packages feed

pandoc 2.2.3.2 → 2.3

raw patch · 98 files changed

+2377/−910 lines, 98 files

Files

AUTHORS.md view
@@ -15,6 +15,7 @@ - Andreas Lööw - Andrew Dunning - Antoine Latter+- Antonio Terceiro - Arata Mizuki - Arlo O'Keeffe - Artyom Kazak@@ -75,6 +76,7 @@ - Igor Khorlo - Ilya V. Portnov - Ivo Clarysse+- J. B. Rainsberger - J. Lewis Muir - Jaime Marquínez Ferrándiz - Jakob Voß@@ -96,6 +98,7 @@ - Jonas Smedegaard - Jonathan Daugherty - Jose Luis Duran+- José de Mattos Neto - Josef Svenningsson - Julien Cretel - Juliusz Gonera
CONTRIBUTING.md view
@@ -189,7 +189,7 @@  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):@@ -302,6 +302,13 @@     identifiers that use accented characters.   - `Text.Pandoc.UUID` contains functions for generating UUIDs.   - `Text.Pandoc.XML` contains functions for formatting XML.++Lua filters+-----------++If you've written a useful pandoc [lua filter](lua-filters.html),+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
INSTALL.md view
@@ -11,6 +11,9 @@     a zip file that contains pandoc's binaries and     documentation.  Simply unzip this file and move the binaries     to a directory of your choice.+    +  - Alternatively, you can install pandoc using+    [chocolatey](https://chocolatey.org): `choco install pandoc`.    - For PDF output, you'll also need to install LaTeX.     We recommend [MiKTeX](http://miktex.org/).@@ -140,14 +143,22 @@  1.  Install the [Haskell platform].  This will give you [GHC] and     the [cabal-install] build tool.  Note that pandoc requires-    GHC >= 7.10.+    GHC >= 7.10 and cabal >= 2.0.  2.  Update your package database:          cabal update -3.  Use `cabal` to install pandoc and its dependencies:+3.  Check your cabal version with +        cabal --version++    If you have a version less than 2.0, install the latest with:++        cabal install cabal-install++4.  Use `cabal` to install pandoc and its dependencies:+         cabal install pandoc      This procedure will install the released version of pandoc,@@ -159,7 +170,7 @@          cabal install -4.  Make sure the `$CABALDIR/bin` directory is in your path.  You should+5.  Make sure the `$CABALDIR/bin` directory is in your path.  You should     now be able to run `pandoc`:          pandoc --help@@ -203,6 +214,7 @@ 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
MANUAL.txt view
@@ -1,6 +1,6 @@ % Pandoc User's Guide % John MacFarlane-% August 7, 2018+% September 16, 2018  Synopsis ========@@ -578,6 +578,16 @@     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 YAML file will always be parsed as Markdown.+    Generally, the input will be handled the same as in+    [YAML metadata blocks][Extension: `yaml_metadata_block`].+    Metadata values specified inside the document, or by using `-M`,+    overwrite values specified with this option.+ `-p`, `--preserve-tabs`  :   Preserve tabs instead of converting them to spaces (the default).@@ -805,6 +815,11 @@     `--resource-path=.:test` will search the working directory     and the `test` subdirectory, in that order. +    `--resource-path` only has an effect if (a) the output+    format embeds images (for example, `docx`, `pdf`, or `html`+    with `--self-contained`) or (b) it is used together with+    `--extract-media`.+ `--request-header=`*NAME*`:`*VAL*  :   Set the request header *NAME* to the value *VAL* when making@@ -901,7 +916,10 @@  `--listings` -:   Use the [`listings`] package for LaTeX code blocks+:   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` @@ -1129,6 +1147,8 @@  [Dublin Core elements]: http://dublincore.org/documents/dces/ [ISO 8601 format]: http://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 ------------------@@ -1211,14 +1231,9 @@ `--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`.+    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` @@ -1352,7 +1367,7 @@  `toc-title` :   title of table of contents (works only with EPUB,-    opendocument, odt, docx, pptx)+    opendocument, odt, docx, pptx, beamer, LaTeX)  `include-before` :   contents specified by `-B/--include-before-body` (may have@@ -1526,12 +1541,14 @@ :    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+:   add color to link text; automatically enabled if any of+    `linkcolor`, `filecolor`, `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+`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@@ -1649,17 +1666,17 @@     from [ConTeXt ICC Profiles].  See also [ConTeXt PDFA] for more     details. -[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-[ConTeXt ICC Profiles]: http://wiki.contextgarden.net/PDFX#ICC_profiles-[ConTeXt PDFA]: http://wiki.contextgarden.net/PDF/A-[`setupwhitespace`]: http://wiki.contextgarden.net/Command/setupwhitespace-[`setupinterlinespace`]: http://wiki.contextgarden.net/Command/setupinterlinespace-[`setuppagenumbering`]: http://wiki.contextgarden.net/Command/setuppagenumbering+[ConTeXt Paper Setup]: https://wiki.contextgarden.net/PaperSetup+[ConTeXt Layout]: https://wiki.contextgarden.net/Layout+[ConTeXt Font Switching]: https://wiki.contextgarden.net/Font_Switching+[ConTeXt Color]: https://wiki.contextgarden.net/Color+[ConTeXt Headers and Footers]: https://wiki.contextgarden.net/Headers_and_Footers+[ConTeXt Indentation]: https://wiki.contextgarden.net/Indentation+[ConTeXt ICC Profiles]: https://wiki.contextgarden.net/PDFX#ICC_profiles+[ConTeXt PDFA]: https://wiki.contextgarden.net/PDF/A+[`setupwhitespace`]: https://wiki.contextgarden.net/Command/setupwhitespace+[`setupinterlinespace`]: https://wiki.contextgarden.net/Command/setupinterlinespace+[`setuppagenumbering`]: https://wiki.contextgarden.net/Command/setuppagenumbering  Variables for man pages -----------------------@@ -1915,7 +1932,8 @@ (in addition to `markdown`):  input formats-:  `latex`, `org`, `textile`+:  `latex`, `org`, `textile`, `html` (environments, `\ref`, and+   `\eqref` only)  output formats :  `textile`, `commonmark`@@ -3053,7 +3071,9 @@     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@@ -3973,11 +3993,12 @@       @*     ... -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 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 respective format (either BibTeX or+BibLaTeX).  For more information, see the [pandoc-citeproc man page]. @@ -4603,6 +4624,46 @@ [MARC relators]: http://loc.gov/marc/relators/relaterm.html [`spine` element]: http://idpf.org/epub/301/spec/epub-publications.html#sec-spine-elem +The `epub:type` attribute+-------------------------++You can mark up the header 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+foreword                          frontmatter+halftitle,                        frontmatter+introduction                      frontmatter+preface                           frontmatter+seriespage                        frontmatter+titlepage                         frontmatter+afterword                         backmatter+appendix                          backmatter+colophon                          backmatter+conclusion                        backmatter+epigraph                          backmatter++[epub-type]: http://www.idpf.org/epub/31/spec/epub-contentdocs.html#sec-epub-type-attribute+ Linked media ------------ @@ -4624,15 +4685,33 @@  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`.+used for highlighting. Currently highlighting is supported only for+HTML, EPUB, 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`.++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 `--highlight-style`. To+get a JSON version of the `pygments` style, for example:++    pandoc --print-highlight-style pygments > my.theme++Then edit `my.theme` and use it like this:++    pandoc --highlight-style my.theme++If you are not satisfied with the built-in highlighting, or you+want 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/applications/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).  To disable highlighting, use the `--no-highlight` option. 
changelog view
@@ -1,3 +1,240 @@+pandoc (2.3)++  * 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)    * Markdown reader: Properly handle boolean values in YAML metadata (#4819).@@ -7304,7 +7541,7 @@  pandoc (1.13.2) -  * TWiki Reader: add new new twiki reader (API change, Alexander Sulfrian).+  * TWiki Reader: add new twiki reader (API change, Alexander Sulfrian).    * Markdown reader: 
data/templates/default.epub3 view
@@ -26,7 +26,7 @@   $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"> $for(title)$
data/templates/default.html5 view
@@ -46,7 +46,7 @@ $include-before$ $endfor$ $if(title)$-<header>+<header id="title-block-header"> <h1 class="title">$title$</h1> $if(subtitle)$ <p class="subtitle">$subtitle$</p>
data/templates/default.latex view
@@ -183,6 +183,7 @@ $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$@@ -359,8 +360,14 @@  $endfor$ $if(toc)$+$if(toc-title)$+\renewcommand*\contentsname{$toc-title$}+$endif$ $if(beamer)$ \begin{frame}+$if(toc-title)$+\frametitle{$toc-title$}+$endif$ \tableofcontents[hideallsubsections] \end{frame} $else$
data/templates/default.opendocument view
@@ -26,9 +26,7 @@ $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: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" />
data/templates/default.tei view
@@ -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>
man/pandoc.1 view
@@ -1,5 +1,5 @@ .\"t-.TH PANDOC 1 "August 7, 2018" "pandoc 2.2.3.2"+.TH PANDOC 1 "September 16, 2018" "pandoc 2.3" .SH NAME pandoc - general markup converter .SH SYNOPSIS@@ -658,6 +658,17 @@ .RS .RE .TP+.B \f[C]\-\-metadata\-file=\f[]\f[I]FILE\f[]+Read metadata from the supplied YAML (or JSON) file.+This option can be used with every input format, but string scalars in+the YAML file will always be parsed as Markdown.+Generally, the input will be handled the same as in YAML metadata+blocks.+Metadata values specified inside the document, or by using \f[C]\-M\f[],+overwrite values specified with this option.+.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@@ -921,6 +932,11 @@ For example: \f[C]\-\-resource\-path=.:test\f[] will search the working directory and the \f[C]test\f[] subdirectory, in that order. .RS+.PP+\f[C]\-\-resource\-path\f[] only has an effect if (a) the output format+embeds images (for example, \f[C]docx\f[], \f[C]pdf\f[], or+\f[C]html\f[] with \f[C]\-\-self\-contained\f[]) or (b) it is used+together with \f[C]\-\-extract\-media\f[]. .RE .TP .B \f[C]\-\-request\-header=\f[]\f[I]NAME\f[]\f[C]:\f[]\f[I]VAL\f[]@@ -1039,7 +1055,11 @@ .RE .TP .B \f[C]\-\-listings\f[]-Use the \f[C]listings\f[] package for LaTeX code blocks+Use the \f[C]listings\f[] 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. .RS .RE .TP@@ -1404,19 +1424,13 @@ .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.+That directory should contain a \f[C]katex.min.js\f[] and a+\f[C]katex.min.css\f[] file. 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]\-\-gladtex\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@@ -1596,7 +1610,7 @@ .TP .B \f[C]toc\-title\f[] title of table of contents (works only with EPUB, opendocument, odt,-docx, pptx)+docx, pptx, beamer, LaTeX) .RS .RE .TP@@ -1827,15 +1841,16 @@ .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+\f[C]linkcolor\f[], \f[C]filecolor\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+.B \f[C]linkcolor\f[], \f[C]filecolor\f[], \f[C]citecolor\f[], \f[C]urlcolor\f[], \f[C]toccolor\f[]+color for internal links, external links, citation links, linked URLs,+and links in table of contents, respectively: 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@@ -2360,7 +2375,8 @@ addition to \f[C]markdown\f[]): .TP .B input formats-\f[C]latex\f[], \f[C]org\f[], \f[C]textile\f[]+\f[C]latex\f[], \f[C]org\f[], \f[C]textile\f[], \f[C]html\f[]+(environments, \f[C]\\ref\f[], and \f[C]\\eqref\f[] only) .RS .RE .TP@@ -3772,7 +3788,10 @@ .fi .PP Just be sure that the YAML file begins with \f[C]\-\-\-\f[] and ends-with \f[C]\-\-\-\f[] or \f[C]\&...\f[].)+with \f[C]\-\-\-\f[] or \f[C]\&...\f[].) Alternatively, you can use the+\f[C]\-\-metadata\-file\f[] option.+Using that approach however, you cannot reference content (like+footnotes) from the main markdown input document. .PP Metadata will be taken from the fields of the YAML object and added to any existing document metadata.@@ -5027,8 +5046,8 @@ \f[] .fi .PP-For LaTeX or PDF output, you can also use \f[C]natbib\f[] or-\f[C]biblatex\f[] to render bibliography.+For LaTeX output, you can also use \f[C]natbib\f[] or \f[C]biblatex\f[]+to render the 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.@@ -5765,6 +5784,123 @@ \f[C]scroll\-axis\f[]: \f[C]vertical\f[]|\f[C]horizontal\f[]|\f[C]default\f[] .RE+.SS The \f[C]epub:type\f[] attribute+.PP+You can mark up the header that corresponds to an EPUB chapter using the+\f[C]epub:type\f[] attribute.+For example, to set the attribute to the value \f[C]prologue\f[], use+this markdown:+.IP+.nf+\f[C]+#\ My\ chapter\ {epub:type=prologue}+\f[]+.fi+.PP+Which will result in:+.IP+.nf+\f[C]+<body\ epub:type="frontmatter">+\ \ <section\ epub:type="prologue">+\ \ \ \ <h1>My\ chapter</h1>+\f[]+.fi+.PP+Pandoc will output \f[C]<body\ epub:type="bodymatter">\f[], unless you+use one of the following values, in which case either+\f[C]frontmatter\f[] or \f[C]backmatter\f[] will be output.+.PP+.TS+tab(@);+l l.+T{+\f[C]epub:type\f[] of first section+T}@T{+\f[C]epub:type\f[] of body+T}+_+T{+prologue+T}@T{+frontmatter+T}+T{+abstract+T}@T{+frontmatter+T}+T{+acknowledgments+T}@T{+frontmatter+T}+T{+copyright\-page+T}@T{+frontmatter+T}+T{+dedication+T}@T{+frontmatter+T}+T{+foreword+T}@T{+frontmatter+T}+T{+halftitle,+T}@T{+frontmatter+T}+T{+introduction+T}@T{+frontmatter+T}+T{+preface+T}@T{+frontmatter+T}+T{+seriespage+T}@T{+frontmatter+T}+T{+titlepage+T}@T{+frontmatter+T}+T{+afterword+T}@T{+backmatter+T}+T{+appendix+T}@T{+backmatter+T}+T{+colophon+T}@T{+backmatter+T}+T{+conclusion+T}@T{+backmatter+T}+T{+epigraph+T}@T{+backmatter+T}+.TE .SS Linked media .PP By default, pandoc will download media referenced from any@@ -5789,8 +5925,9 @@ .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.+The Haskell library skylighting is used for highlighting.+Currently highlighting is supported only for HTML, EPUB, 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@@ -5801,6 +5938,33 @@ 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+If you are not satisfied with the predefined styles, you can use+\f[C]\-\-print\-highlight\-style\f[] to generate a JSON+\f[C]\&.theme\f[] file which can be modified and used as the argument to+\f[C]\-\-highlight\-style\f[].+To get a JSON version of the \f[C]pygments\f[] style, for example:+.IP+.nf+\f[C]+pandoc\ \-\-print\-highlight\-style\ pygments\ >\ my.theme+\f[]+.fi+.PP+Then edit \f[C]my.theme\f[] and use it like this:+.IP+.nf+\f[C]+pandoc\ \-\-highlight\-style\ my.theme+\f[]+.fi+.PP+If you are not satisfied with the built\-in highlighting, or you want+highlight a language that isn\[aq]t supported, you can use the+\f[C]\-\-syntax\-definition\f[] option to load a KDE\-style XML syntax+definition file.+Before writing your own, have a look at KDE\[aq]s repository of syntax+definitions. .PP To disable highlighting, use the \f[C]\-\-no\-highlight\f[] option. .SH CUSTOM STYLES IN DOCX
pandoc.cabal view
@@ -1,5 +1,5 @@ name:            pandoc-version:         2.2.3.2+version:         2.3 cabal-version:   2.0 build-type:      Custom license:         GPL-2@@ -193,6 +193,7 @@                  test/command/sub-file-chapter-1.tex                  test/command/sub-file-chapter-2.tex                  test/command/bar.tex+                 test/command/yaml-metadata.yaml                  test/command/3510-subdoc.org                  test/command/3510-export.latex                  test/command/3510-src.hs
src/Text/Pandoc/App.hs view
@@ -89,6 +89,7 @@ import Text.Pandoc.Filter (Filter (JSONFilter, LuaFilter), applyFilters) import Text.Pandoc.Highlighting (highlightingStyles) import Text.Pandoc.PDF (makePDF)+import Text.Pandoc.Readers.Markdown (yamlToMeta) import Text.Pandoc.SelfContained (makeDataURI, makeSelfContained) import Text.Pandoc.Shared (eastAsianLineBreakFilter, stripEmptyParagraphs,          headerShift, isURI, ordNub, safeRead, tabFilter, uriPathToPath)@@ -399,6 +400,10 @@                                          ("application/xml", jatsCSL)                      return $ ("csl", jatsEncoded) : optMetadata opts                    else return $ optMetadata opts+    metadataFromFile <-+      case optMetadataFile opts of+        Nothing   -> return mempty+        Just file -> readFileLazy file >>= yamlToMeta      case lookup "lang" (optMetadata opts) of            Just l  -> case parseBCP47 l of@@ -491,6 +496,7 @@               (   (if isJust (optExtractMedia opts)                       then fillMediaBag                       else return)+              >=> return . addNonPresentMetadata metadataFromFile               >=> return . addMetadata metadata               >=> applyTransforms transforms               >=> applyFilters readerOpts filters' [format]@@ -556,6 +562,7 @@     , optTemplate              :: Maybe FilePath  -- ^ Custom template     , optVariables             :: [(String,String)] -- ^ Template variables to set     , optMetadata              :: [(String, String)] -- ^ Metadata fields to set+    , optMetadataFile          :: Maybe FilePath  -- ^ Name of YAML metadata file     , optOutputFile            :: Maybe FilePath  -- ^ Name of output file     , optInputFiles            :: [FilePath] -- ^ Names of input files     , optNumberSections        :: Bool    -- ^ Number sections in LaTeX@@ -628,6 +635,7 @@     , optTemplate              = Nothing     , optVariables             = []     , optMetadata              = []+    , optMetadataFile          = Nothing     , optOutputFile            = Nothing     , optInputFiles            = []     , optNumberSections        = False@@ -687,6 +695,9 @@     , optStripComments          = False     } +addNonPresentMetadata :: Text.Pandoc.Meta -> Pandoc -> Pandoc+addNonPresentMetadata newmeta (Pandoc meta bs) = Pandoc (meta <> newmeta) bs+ addMetadata :: [(String, String)] -> Pandoc -> Pandoc addMetadata kvs pdc = foldr addMeta (removeMetaKeys kvs pdc) kvs @@ -961,6 +972,12 @@                      let (key, val) = splitField arg                      return opt{ optMetadata = (key, val) : optMetadata opt })                   "KEY[:VALUE]")+                 ""++    , Option "" ["metadata-file"]+                 (ReqArg+                  (\arg opt -> return opt{ optMetadataFile = Just arg })+                  "FILE")                  ""      , Option "V" ["variable"]
src/Text/Pandoc/Extensions.hs view
@@ -114,7 +114,7 @@     | 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
src/Text/Pandoc/ImageSize.hs view
@@ -319,20 +319,22 @@                     (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''+  (dpix, dpiy) <- findpHYs rest''   return ImageSize { pxX  = x, pxY = y, dpiX = dpix, dpiY = dpiy } -findpHYs :: ByteString -> (Integer, Integer)+findpHYs :: ByteString -> Maybe (Integer, Integer) findpHYs x-  | B.null x || "IDAT" `B.isPrefixOf` x = (72,72)+  | B.null x || "IDAT" `B.isPrefixOf` x = return (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 )+    case map fromIntegral $ unpack $ B.take 9 $ B.drop 4 x of+         [x1,x2,x3,x4,y1,y2,y3,y4,u] -> do+           let factor = if u == 1 -- dots per meter+                          then \z -> z * 254 `div` 10000+                          else const 72+           return+              ( factor $ shift x1 24 + shift x2 16 + shift x3 8 + x4,+                factor $ shift y1 24 + shift y2 16 + shift y3 8 + y4 )+         _ -> mzero   | otherwise = findpHYs $ B.drop 1 x  -- read another byte  gifSize :: ByteString -> Maybe ImageSize@@ -408,20 +410,21 @@  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+  case map fromIntegral $ unpack $ B.take 5 $ B.drop 9 rest of+    [dpiDensity,dpix1,dpix2,dpiy1,dpiy2] ->+      let 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 }+    _ -> Left "unable to determine JFIF size"  findJfifSize :: ByteString -> Either String (Integer,Integer) findJfifSize bs =@@ -541,10 +544,12 @@   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+  let xres = case lookup XResolution allentries of+                  Just (UnsignedRational x) -> floor (x * resfactor)+                  _ -> 72+  let yres = case lookup YResolution allentries of+                  Just (UnsignedRational y) -> floor (y * resfactor)+                  _ -> 72   return ImageSize{                     pxX  = wdth                   , pxY  = hght
src/Text/Pandoc/Lua.hs view
@@ -34,14 +34,14 @@  import Prelude import Control.Monad ((>=>))-import Foreign.Lua (FromLuaStack (peek), Lua, LuaException (..),-                    Status (OK), ToLuaStack (push))+import Foreign.Lua (Lua, LuaException (..)) import Text.Pandoc.Class (PandocIO) import Text.Pandoc.Definition (Pandoc) import Text.Pandoc.Lua.Filter (LuaFilter, walkMWithLuaFilter) import Text.Pandoc.Lua.Init (runPandocLua, registerScriptPath) import Text.Pandoc.Lua.Util (popValue) import Text.Pandoc.Options (ReaderOptions)+ import qualified Foreign.Lua as Lua  -- | Run the Lua filter in @filterPath@ for a transformation to target@@ -60,25 +60,23 @@   registerScriptPath filterPath   top <- Lua.gettop   stat <- Lua.dofile filterPath-  if stat /= OK-    then do-      luaErrMsg <- popValue-      Lua.throwLuaError luaErrMsg+  if stat /= Lua.OK+    then Lua.throwTopMessageAsError     else do       newtop <- Lua.gettop       -- Use the returned filters, or the implicitly defined global filter if       -- nothing was returned.       luaFilters <- if newtop - top >= 1-                    then peek (-1)+                    then Lua.peek Lua.stackTop                     else Lua.getglobal "_G" *> fmap (:[]) popValue       runAll luaFilters pd  where   registerFormat = do-    push format+    Lua.push format     Lua.setglobal "FORMAT"    registerReaderOptions = do-    push ropts+    Lua.push ropts     Lua.setglobal "PANDOC_READER_OPTIONS"  runAll :: [LuaFilter] -> Pandoc -> Lua Pandoc
src/Text/Pandoc/Lua/Module/Pandoc.hs view
@@ -42,7 +42,7 @@ import Text.Pandoc.Definition (Block, Inline) import Text.Pandoc.Lua.Filter (walkInlines, walkBlocks, LuaFilter) import Text.Pandoc.Lua.StackInstances ()-import Text.Pandoc.Lua.Util (addFunction, addValue, loadScriptFromDataDir)+import Text.Pandoc.Lua.Util (addFunction, loadScriptFromDataDir) import Text.Pandoc.Walk (Walkable) import Text.Pandoc.Options (ReaderOptions (readerExtensions)) import Text.Pandoc.Process (pipeProcess)@@ -51,6 +51,7 @@ import qualified Data.ByteString.Lazy as BL import qualified Data.ByteString.Lazy.Char8 as BSL import qualified Foreign.Lua as Lua+import qualified Text.Pandoc.Lua.Util as LuaUtil  -- | Push the "pandoc" on the lua stack. Requires the `list` module to be -- loaded.@@ -114,9 +115,9 @@ instance ToLuaStack PipeError where   push pipeErr = do     Lua.newtable-    addValue "command" (pipeErrorCommand pipeErr)-    addValue "error_code" (pipeErrorCode pipeErr)-    addValue "output" (pipeErrorOutput pipeErr)+    LuaUtil.addField "command" (pipeErrorCommand pipeErr)+    LuaUtil.addField "error_code" (pipeErrorCode pipeErr)+    LuaUtil.addField "output" (pipeErrorOutput pipeErr)     pushPipeErrorMetaTable     Lua.setmetatable (-2)       where
src/Text/Pandoc/Lua/StackInstances.hs view
@@ -44,7 +44,7 @@                     ToLuaStack (push), Type (..), throwLuaError, tryLua) import Text.Pandoc.Definition import Text.Pandoc.Extensions (Extensions)-import Text.Pandoc.Lua.Util (getTable, getTag, pushViaConstructor, typeCheck)+import Text.Pandoc.Lua.Util (pushViaConstructor, typeCheck) import Text.Pandoc.Options (ReaderOptions (..), TrackChanges) import Text.Pandoc.Shared (Element (Blk, Sec), safeRead) @@ -62,7 +62,7 @@ instance FromLuaStack Pandoc where   peek idx = defineHowTo "get Pandoc value" $ do     typeCheck idx Lua.TypeTable-    blocks <- getTable idx "blocks"+    blocks <- LuaUtil.rawField idx "blocks"     meta   <- Lua.getfield idx "meta" *> (Lua.peek Lua.stackTop `finally` Lua.pop 1)     return $ Pandoc meta blocks @@ -99,12 +99,12 @@  instance FromLuaStack Citation where   peek idx = do-    id' <- getTable idx "id"-    prefix <- getTable idx "prefix"-    suffix <- getTable idx "suffix"-    mode <- getTable idx "mode"-    num <- getTable idx "note_num"-    hash <- getTable idx "hash"+    id' <- LuaUtil.rawField idx "id"+    prefix <- LuaUtil.rawField idx "prefix"+    suffix <- LuaUtil.rawField idx "suffix"+    mode <- LuaUtil.rawField idx "mode"+    num <- LuaUtil.rawField idx "note_num"+    hash <- LuaUtil.rawField idx "hash"     return $ Citation id' prefix suffix mode num hash  instance ToLuaStack Alignment where@@ -178,7 +178,7 @@     TypeBoolean -> MetaBool <$> peek idx     TypeString  -> MetaString <$> peek idx     TypeTable   -> do-      tag <- tryLua $ getTag idx+      tag <- tryLua $ LuaUtil.getTag idx       case tag of         Right "MetaBlocks"  -> MetaBlocks  <$> elementContent         Right "MetaBool"    -> MetaBool    <$> elementContent@@ -220,7 +220,7 @@ peekBlock :: StackIndex -> Lua Block peekBlock idx = defineHowTo "get Block value" $ do   typeCheck idx Lua.TypeTable-  tag <- getTag idx+  tag <- LuaUtil.getTag idx   case tag of       "BlockQuote"     -> BlockQuote <$> elementContent       "BulletList"     -> BulletList <$> elementContent@@ -243,7 +243,7 @@  where    -- Get the contents of an AST element.    elementContent :: FromLuaStack a => Lua a-   elementContent = getTable idx "c"+   elementContent = LuaUtil.rawField idx "c"  -- | Push an inline element to the top of the lua stack. pushInline :: Inline -> Lua ()@@ -272,7 +272,7 @@ peekInline :: StackIndex -> Lua Inline peekInline idx = defineHowTo "get Inline value" $ do   typeCheck idx Lua.TypeTable-  tag <- getTag idx+  tag <- LuaUtil.getTag idx   case tag of     "Cite"       -> uncurry Cite <$> elementContent     "Code"       -> withAttr Code <$> elementContent@@ -299,7 +299,7 @@  where    -- Get the contents of an AST element.    elementContent :: FromLuaStack a => Lua a-   elementContent = getTable idx "c"+   elementContent = LuaUtil.rawField idx "c"  withAttr :: (Attr -> a -> b) -> (LuaAttr, a) -> b withAttr f (attributes, x) = f (fromLuaAttr attributes) x@@ -321,11 +321,11 @@   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+    LuaUtil.addField "level" lvl+    LuaUtil.addField "numbering" num+    LuaUtil.addField "attr" (LuaAttr attr)+    LuaUtil.addField "label" label+    LuaUtil.addField "contents" contents     pushSecMetaTable     Lua.setmetatable (-2)       where@@ -333,7 +333,7 @@         pushSecMetaTable = do           inexistant <- Lua.newmetatable "PandocElementSec"           when inexistant $ do-            LuaUtil.addValue "t" "Sec"+            LuaUtil.addField "t" "Sec"             Lua.push "__index"             Lua.pushvalue (-2)             Lua.rawset (-3)@@ -367,12 +367,12 @@           (stripComments         :: Bool)           = ro     Lua.newtable-    LuaUtil.addValue "extensions" extensions-    LuaUtil.addValue "standalone" standalone-    LuaUtil.addValue "columns" columns-    LuaUtil.addValue "tabStop" tabStop-    LuaUtil.addValue "indentedCodeClasses" indentedCodeClasses-    LuaUtil.addValue "abbreviations" abbreviations-    LuaUtil.addValue "defaultImageExtension" defaultImageExtension-    LuaUtil.addValue "trackChanges" trackChanges-    LuaUtil.addValue "stripComments" stripComments+    LuaUtil.addField "extensions" extensions+    LuaUtil.addField "standalone" standalone+    LuaUtil.addField "columns" columns+    LuaUtil.addField "tabStop" tabStop+    LuaUtil.addField "indentedCodeClasses" indentedCodeClasses+    LuaUtil.addField "abbreviations" abbreviations+    LuaUtil.addField "defaultImageExtension" defaultImageExtension+    LuaUtil.addField "trackChanges" trackChanges+    LuaUtil.addField "stripComments" stripComments
src/Text/Pandoc/Lua/Util.hs view
@@ -31,14 +31,11 @@ -} module Text.Pandoc.Lua.Util   ( getTag-  , getTable-  , addValue+  , rawField+  , addField   , addFunction-  , getRawInt-  , setRawInt-  , addRawInt+  , addValue   , typeCheck-  , raiseError   , popValue   , PushViaCall   , pushViaCall@@ -51,34 +48,30 @@ import Control.Monad (when) import Control.Monad.Catch (finally) import Data.ByteString.Char8 (unpack)-import Foreign.Lua (FromLuaStack (..), NumResults, Lua, NumArgs, StackIndex,-                    ToLuaStack (..), ToHaskellFunction)-import Foreign.Lua.Api (Status, call, pop, rawget, rawgeti, rawset, rawseti)+import Foreign.Lua (FromLuaStack, Lua, NumArgs, StackIndex, Status,+                    ToLuaStack, ToHaskellFunction) 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)+rawField :: FromLuaStack a => StackIndex -> String -> Lua a+rawField idx key = do+  absidx <- Lua.absindex idx+  Lua.push key+  Lua.rawget absidx   popValue +-- | Add a value to the table at the top of the stack at a string-index.+addField :: ToLuaStack a => String -> a -> Lua ()+addField = addValue+ -- | 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)+  Lua.push key+  Lua.push value+  Lua.rawset (Lua.nthFromTop 3)  -- | Add a function to the table at the top of the stack, using the given name. addFunction :: ToHaskellFunction a => String -> a -> Lua ()@@ -88,22 +81,6 @@   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)- typeCheck :: StackIndex -> Lua.Type -> Lua () typeCheck idx expected = do   actual <- Lua.ltype idx@@ -112,16 +89,11 @@     actName <- Lua.typename actual     Lua.throwLuaError $ "expected " ++ expName ++ " but got " ++ actName ++ "." -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+  Lua.pop 1   case resOrError of     Left err -> Lua.throwLuaError err     Right x -> return x@@ -136,11 +108,11 @@     Lua.push fn     Lua.rawget Lua.registryindex     pushArgs-    call num 1+    Lua.call num 1  instance (ToLuaStack a, PushViaCall b) => PushViaCall (a -> b) where   pushViaCall' fn pushArgs num x =-    pushViaCall' fn (pushArgs *> push x) (num + 1)+    pushViaCall' fn (pushArgs *> Lua.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@@ -163,9 +135,9 @@       "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+-- important to keep the program from hanging: If the program containes a call+-- to @require@, then a new loader function is created which then becomes+-- garbage. If that function is collected at an inopportune time, i.e. when the -- Lua API is called via a function that doesn't allow calling back into Haskell -- (getraw, setraw, …), then the function's finalizer, and the full program, -- will hang.@@ -182,8 +154,8 @@ -- metatable. 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)-  peek Lua.stackTop `finally` Lua.settop top+  -- push metatable or just the table+  Lua.getmetatable idx >>= \hasMT -> when (not hasMT) (Lua.pushvalue idx)+  Lua.push "tag"+  Lua.rawget (Lua.nthFromTop 2)+  Lua.peek Lua.stackTop `finally` Lua.pop 2
src/Text/Pandoc/PDF.hs view
@@ -188,7 +188,7 @@          then return $ Right pdfOut          else return $ Left "conversion from SVG failed")       (\(e :: E.SomeException) -> return $ Left $-          "check that rsvg2pdf is in path.\n" +++          "check that rsvg-convert is in path.\n" ++           show e)     _ -> JP.readImage fname >>= \res ->           case res of
src/Text/Pandoc/Parsing.hs view
@@ -514,22 +514,19 @@  -- 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+    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
src/Text/Pandoc/Readers/Docx/Lists.hs view
@@ -183,14 +183,13 @@         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
src/Text/Pandoc/Readers/Docx/Parse.hs view
@@ -1153,8 +1153,9 @@ getSymChar ns element   | Just s <- lowerFromPrivate <$> getCodepoint   , Just font <- getFont =-  let [(char, _)] = readLitChar ("\\x" ++ s) in-    TextRun . maybe "" (:[]) $ getUnicode font char+    case readLitChar ("\\x" ++ s) of+         [(char, _)] -> TextRun . maybe "" (:[]) $ getUnicode font char+         _           -> TextRun ""   where     getCodepoint = findAttrByName ns "w" "char" element     getFont = stringToFont =<< findAttrByName ns "w" "font" element
src/Text/Pandoc/Readers/HTML.hs view
@@ -68,11 +68,13 @@ import Text.Pandoc.Class (PandocMonad (..)) import Text.Pandoc.CSS (foldOrElse, pickStyleAttrProps) import Text.Pandoc.Definition+import Text.Pandoc.Readers.LaTeX (rawLaTeXInline)+import Text.Pandoc.Readers.LaTeX.Types (Macro) 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_native_spans, Ext_raw_html, Ext_line_blocks, Ext_raw_tex),     ReaderOptions (readerExtensions, readerStripComments),     extensionEnabled) import Text.Pandoc.Parsing hiding ((<|>))@@ -102,7 +104,8 @@                                          (m:_) -> messageString m   result <- flip runReaderT def $        runParserT parseDoc-       (HTMLState def{ stateOptions = opts } [] Nothing Set.empty M.empty [])+       (HTMLState def{ stateOptions = opts }+         [] Nothing Set.empty M.empty [] M.empty)        "source" tags   case result of     Right doc -> return doc@@ -124,7 +127,8 @@      baseHref    :: Maybe URI,      identifiers :: Set.Set String,      headerMap   :: M.Map Inlines String,-     logMessages :: [LogMessage]+     logMessages :: [LogMessage],+     macros      :: M.Map Text Macro   }  data HTMLLocal = HTMLLocal { quoteContext :: QuoteContext@@ -659,6 +663,7 @@            , pCode            , pSpan            , pMath False+           , pScriptMath            , pRawHtmlInline            ] @@ -745,18 +750,18 @@   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")+  lab <- 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+         return $ extractSpaces (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+         return $ extractSpaces (B.linkWith (uid, cls, []) (escapeURI url) title) lab  pImage :: PandocMonad m => TagParser m Inlines pImage = do@@ -818,6 +823,17 @@ toStringAttr = map go   where go (x,y) = (T.unpack x, T.unpack y) +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 <- T.unpack . innerText <$>+                manyTill pAnyTag (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)@@ -907,9 +923,25 @@   <|> 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" (T.unpack inp)+  case res of+       Left _                -> mzero+       Right (contents, raw) -> do+         _ <- count (length raw) anyChar+         return $ B.rawInline "tex" contents+ pStr :: PandocMonad m => InlinesParser m Inlines pStr = do   result <- many1 $ satisfy $ \c ->@@ -923,6 +955,7 @@ isSpecial '.'     = True isSpecial '-'     = True isSpecial '$'     = True+isSpecial '\\'    = True isSpecial '\8216' = True isSpecial '\8217' = True isSpecial '\8220' = True@@ -1248,6 +1281,10 @@ isSpace _    = False  -- Instances++instance HasMacros HTMLState where+  extractMacros        = macros+  updateMacros f st    = st{ macros = f $ macros st }  instance HasIdentifierList HTMLState where   extractIdentifierList = identifiers
src/Text/Pandoc/Readers/LaTeX.hs view
@@ -71,7 +71,7 @@ import Text.Pandoc.Parsing hiding (blankline, many, mathDisplay, mathInline,                             optional, space, spaces, withRaw, (<|>)) import Text.Pandoc.Readers.LaTeX.Types (ExpansionPoint (..), Macro (..),-                                        Tok (..), TokType (..))+                                        ArgSpec (..), Tok (..), TokType (..)) import Text.Pandoc.Shared import qualified Text.Pandoc.Translations as Translations import Text.Pandoc.Walk@@ -137,15 +137,15 @@ --        Left e  -> error (show e) --        Right r -> return r -newtype HeaderNum = HeaderNum [Int]+newtype DottedNum = DottedNum [Int]   deriving (Show) -renderHeaderNum :: HeaderNum -> String-renderHeaderNum (HeaderNum xs) =+renderDottedNum :: DottedNum -> String+renderDottedNum (DottedNum xs) =   intercalate "." (map show xs) -incrementHeaderNum :: Int -> HeaderNum -> HeaderNum-incrementHeaderNum level (HeaderNum ns) = HeaderNum $+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@@ -162,7 +162,8 @@                             , sCaption       :: (Maybe Inlines, Maybe String)                             , sInListItem    :: Bool                             , sInTableCell   :: Bool-                            , sLastHeaderNum :: HeaderNum+                            , sLastHeaderNum :: DottedNum+                            , sLastFigureNum :: DottedNum                             , sLabels        :: M.Map String [Inline]                             , sHasChapters   :: Bool                             , sToggles       :: M.Map String Bool@@ -182,7 +183,8 @@                               , sCaption       = (Nothing, Nothing)                               , sInListItem    = False                               , sInTableCell   = False-                              , sLastHeaderNum = HeaderNum []+                              , sLastHeaderNum = DottedNum []+                              , sLastFigureNum = DottedNum []                               , sLabels        = M.empty                               , sHasChapters   = False                               , sToggles       = M.empty@@ -473,21 +475,38 @@                 macros <- sMacros <$> getState                 case M.lookup name macros of                      Nothing -> return ()-                     Just (Macro expansionPoint numargs optarg newtoks) -> do+                     Just (Macro expansionPoint argspecs optarg newtoks) -> do                        setInput ts-                       let getarg = try $ spaces >> bracedOrToken+                       let matchTok (Tok _ toktype txt) =+                             satisfyTok (\(Tok _ toktype' txt') ->+                                           toktype == toktype' &&+                                           txt == txt')+                       let matchPattern toks = try $ mapM_ matchTok toks+                       let 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                        args <- case optarg of-                                    Nothing -> count numargs getarg-                                    Just o  ->-                                       (:) <$> option o bracketedToks-                                           <*> count (numargs - 1) getarg+                                    Nothing -> getargs M.empty argspecs+                                    Just o  -> do+                                       x <- option o bracketedToks+                                       getargs (M.singleton 1 x) argspecs                        -- first boolean param is true if we're tokenizing                        -- an argument (in which case we don't want to                        -- expand #1 etc.)-                       let addTok False (Tok _ (Arg i) _) acc | i > 0-                                                              , i <= numargs =-                                 foldr (addTok True) acc (args !! (i - 1))-                           -- add space if needed after control sequence+                       let addTok False (Tok _ (Arg i) _) acc =+                              case M.lookup i args of+                                   Nothing -> mzero+                                   Just xs -> foldr (addTok True) acc xs                            -- see #4007                            addTok _ (Tok _ (CtrlSeq x) txt)                                   acc@(Tok _ Word _ : _)@@ -615,22 +634,29 @@   -- {{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+braced' :: PandocMonad m => LP m Tok -> Int -> LP m [Tok]+braced' getTok n =+  handleEgroup <|> handleBgroup <|> handleOther+  where handleEgroup = do           t <- egroup           if n == 1              then return []-             else (t:) <$> braced' (n - 1)-        handleBgroup n = do+             else (t:) <$> braced' getTok (n - 1)+        handleBgroup = do           t <- bgroup-          (t:) <$> braced' (n + 1)-        handleOther n = do-          t <- anyTok-          (t:) <$> braced' n+          (t:) <$> braced' getTok (n + 1)+        handleOther = do+          t <- getTok+          (t:) <$> braced' getTok n +braced :: PandocMonad m => LP m [Tok]+braced = bgroup *> braced' anyTok 1++-- URLs require special handling, because they can contain %+-- characters.  So we retonenize comments as we go...+bracedUrl :: PandocMonad m => LP m [Tok]+bracedUrl = bgroup *> braced' (retokenizeComment >> anyTok) 1+ bracketed :: PandocMonad m => Monoid a => LP m a -> LP m a bracketed parser = try $ do   symbol '['@@ -711,7 +737,7 @@   skipopts   value <- tok   valueprefix <- option "" $ bracketed tok-  unit <- inlineCommand' <|> tok+  unit <- grouped (mconcat <$> many1 siUnit) <|> siUnit <|> tok   let emptyOr160 "" = ""       emptyOr160 _  = "\160"   return . mconcat $ [valueprefix,@@ -720,12 +746,188 @@                       emptyOr160 unit,                       unit] --- siunitx's \square command-dosquare :: PandocMonad m => LP m Inlines-dosquare = do-  unit <- inlineCommand' <|> tok-  return . mconcat $ [unit, "\178"]+siUnit :: PandocMonad m => LP m Inlines+siUnit = do+  Tok _ (CtrlSeq name) _ <- anyControlSeq+  if name == "square"+     then do+       unit <- grouped (mconcat <$> many1 siUnit) <|> siUnit <|> tok+       return . mconcat $ [unit, "\178"]+     else+       case M.lookup name siUnitMap of+            Just il -> return il+            Nothing -> mzero +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")+  , ("angstrom", str "Å")+  , ("arcmin", str "′")+  , ("arcminute", str "′")+  , ("arcsecond", str "″")+  , ("astronomicalunit", str "ua")+  , ("atomicmassunit", str "u")+  , ("atto", str "a")+  , ("bar", str "bar")+  , ("barn", str "b")+  , ("becquerel", str "Bq")+  , ("bel", str "B")+  , ("candela", str "cd")+  , ("celsius", str "°C")+  , ("centi", str "c")+  , ("coulomb", str "C")+  , ("dalton", str "Da")+  , ("day", str "d")+  , ("deca", str "d")+  , ("deci", str "d")+  , ("decibel", str "db")+  , ("degreeCelsius",str "°C")+  , ("degree", str "°")+  , ("deka", str "d")+  , ("electronvolt", str "eV")+  , ("exa", str "E")+  , ("farad", str "F")+  , ("femto", str "f")+  , ("giga", str "G")+  , ("gram", str "g")+  , ("hectare", str "ha")+  , ("hecto", str "h")+  , ("henry", str "H")+  , ("hertz", str "Hz")+  , ("hour", str "h")+  , ("joule", str "J")+  , ("katal", str "kat")+  , ("kelvin", str "K")+  , ("kilo", str "k")+  , ("kilogram", str "kg")+  , ("knot", str "kn")+  , ("liter", str "L")+  , ("litre", str "l")+  , ("lumen", str "lm")+  , ("lux", str "lx")+  , ("mega", str "M")+  , ("meter", str "m")+  , ("metre", str "m")+  , ("milli", str "m")+  , ("minute", str "min")+  , ("mmHg", str "mmHg")+  , ("mole", str "mol")+  , ("nano", str "n")+  , ("nauticalmile", str "M")+  , ("neper", str "Np")+  , ("newton", str "N")+  , ("ohm", str "Ω")+  , ("Pa", str "Pa")+  , ("pascal", str "Pa")+  , ("percent", str "%")+  , ("per", str "/")+  , ("peta", str "P")+  , ("pico", str "p")+  , ("radian", str "rad")+  , ("second", str "s")+  , ("siemens", str "S")+  , ("sievert", str "Sv")+  , ("steradian", str "sr")+  , ("tera", str "T")+  , ("tesla", str "T")+  , ("tonne", str "t")+  , ("volt", str "V")+  , ("watt", str "W")+  , ("weber", str "Wb")+  , ("yocto", str "y")+  , ("yotta", str "Y")+  , ("zepto", str "z")+  , ("zetta", str "Z")+  ]+ lit :: String -> LP m Inlines lit = pure . str @@ -775,14 +977,32 @@                               cs   -> cs)      else lit startchs -enquote :: PandocMonad m => LP m Inlines-enquote = do+enquote :: PandocMonad m => Bool -> Maybe Text -> LP m Inlines+enquote starred mblang = do   skipopts+  let lang = (T.unpack <$> mblang) >>= babelLangToBCP47+  let langspan = case lang of+                      Nothing -> id+                      Just l  -> spanWith ("",[],[("lang", renderLang l)])   quoteContext <- sQuoteContext <$> getState-  if quoteContext == InDoubleQuote-     then singleQuoted <$> withQuoteContext InSingleQuote tok-     else doubleQuoted <$> withQuoteContext InDoubleQuote tok+  if starred || quoteContext == InDoubleQuote+     then singleQuoted . langspan <$> withQuoteContext InSingleQuote tok+     else doubleQuoted . langspan <$> withQuoteContext InDoubleQuote tok +blockquote :: PandocMonad m => Bool -> Maybe Text -> LP m Blocks+blockquote citations mblang = do+  citePar <- if citations+                then do+                  cs <- cites NormalCitation False+                  return $ para (cite cs mempty)+                else return mempty+  let lang = (T.unpack <$> mblang) >>= babelLangToBCP47+  let langdiv = case lang of+                      Nothing -> id+                      Just l  -> divWith ("",[],[("lang", renderLang l)])+  bs <- grouped block+  return $ blockQuote . langdiv $ (bs <> citePar)+ doAcronym :: PandocMonad m => String -> LP m Inlines doAcronym form = do   acro <- braced@@ -824,6 +1044,16 @@ dolstinline = do   options <- option [] keyvals   let classes = maybeToList $ lookup "language" options >>= fromListingsLanguage+  doinlinecode classes++domintinline :: PandocMonad m => LP m Inlines+domintinline = do+  skipopts+  cls <- toksToString <$> braced+  doinlinecode [cls]++doinlinecode :: PandocMonad m => [String] -> LP m Inlines+doinlinecode classes = do   Tok _ Symbol t <- anySymbol   marker <- case T.uncons t of               Just (c, ts) | T.null ts -> return c@@ -863,7 +1093,10 @@ accent c f = try $ do   ils <- tok   case toList ils of-       (Str (x:xs) : ys) -> return $ fromList (Str (f x ++ xs) : ys)+       (Str (x:xs) : ys) -> return $ fromList $+         case f x of+              [z] | z == x -> Str ([z,c] ++ xs) : ys -- combining accent+              zs           -> Str (zs ++ xs) : ys        [Space]           -> return $ str [c]        []                -> return $ str [c]        _                 -> return ils@@ -1001,6 +1234,84 @@ macron 'u' = "ū" macron c   = [c] +ringabove :: Char -> String+ringabove 'A' = "Å"+ringabove 'a' = "å"+ringabove 'U' = "Ů"+ringabove 'u' = "ů"+ringabove c   = [c]++dotbelow :: Char -> String+dotbelow 'B' = "Ḅ"+dotbelow 'b' = "ḅ"+dotbelow 'D' = "Ḍ"+dotbelow 'd' = "ḍ"+dotbelow 'H' = "Ḥ"+dotbelow 'h' = "ḥ"+dotbelow 'K' = "Ḳ"+dotbelow 'k' = "ḳ"+dotbelow 'L' = "Ḷ"+dotbelow 'l' = "ḷ"+dotbelow 'M' = "Ṃ"+dotbelow 'm' = "ṃ"+dotbelow 'N' = "Ṇ"+dotbelow 'n' = "ṇ"+dotbelow 'R' = "Ṛ"+dotbelow 'r' = "ṛ"+dotbelow 'S' = "Ṣ"+dotbelow 's' = "ṣ"+dotbelow 'T' = "Ṭ"+dotbelow 't' = "ṭ"+dotbelow 'V' = "Ṿ"+dotbelow 'v' = "ṿ"+dotbelow 'W' = "Ẉ"+dotbelow 'w' = "ẉ"+dotbelow 'Z' = "Ẓ"+dotbelow 'z' = "ẓ"+dotbelow 'A' = "Ạ"+dotbelow 'a' = "ạ"+dotbelow 'E' = "Ẹ"+dotbelow 'e' = "ẹ"+dotbelow 'I' = "Ị"+dotbelow 'i' = "ị"+dotbelow 'O' = "Ọ"+dotbelow 'o' = "ọ"+dotbelow 'U' = "Ụ"+dotbelow 'u' = "ụ"+dotbelow 'Y' = "Ỵ"+dotbelow 'y' = "ỵ"+dotbelow c   = [c]++doublegrave :: Char -> String+doublegrave 'A' = "Ȁ"+doublegrave 'a' = "ȁ"+doublegrave 'E' = "Ȅ"+doublegrave 'e' = "ȅ"+doublegrave 'I' = "Ȉ"+doublegrave 'i' = "ȉ"+doublegrave 'O' = "Ȍ"+doublegrave 'o' = "ȍ"+doublegrave 'R' = "Ȑ"+doublegrave 'r' = "ȑ"+doublegrave 'U' = "Ȕ"+doublegrave 'u' = "ȕ"+doublegrave c   = [c]++hookabove :: Char -> String+hookabove 'A' = "Ả"+hookabove 'a' = "ả"+hookabove 'E' = "Ẻ"+hookabove 'e' = "ẻ"+hookabove 'I' = "Ỉ"+hookabove 'i' = "ỉ"+hookabove 'O' = "Ỏ"+hookabove 'o' = "ỏ"+hookabove 'U' = "Ủ"+hookabove 'u' = "ủ"+hookabove 'Y' = "Ỷ"+hookabove 'y' = "ỷ"+hookabove c   = [c]+ cedilla :: Char -> String cedilla 'c' = "ç" cedilla 'C' = "Ç"@@ -1290,6 +1601,17 @@ unescapeURL (x:xs) = x:unescapeURL xs unescapeURL [] = "" +-- 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 (sourceName pos) $ T.tail txt+  getInput >>= setInput . ((Tok pos Symbol "%" : newtoks) ++))+    <|> return ()+ mathEnvWith :: PandocMonad m             => (Inlines -> a) -> Maybe Text -> Text -> LP m a mathEnvWith f innerEnv name = f . mathDisplay . inner <$> mathEnv name@@ -1370,7 +1692,7 @@   , ("(", mathInline . toksToString <$> manyTill anyTok (controlSeq ")"))   , ("[", mathDisplay . toksToString <$> manyTill anyTok (controlSeq "]"))   , ("ensuremath", mathInline . toksToString <$> braced)-  , ("texorpdfstring", (\_ x -> x) <$> tok <*> tok)+  , ("texorpdfstring", (\x _ -> x) <$> tok <*> tok)   , ("P", lit "¶")   , ("S", lit "§")   , ("$", lit "$")@@ -1421,12 +1743,24 @@   , ("\"", accent '\776' umlaut)   , (".", accent '\775' dot)   , ("=", accent '\772' macron)+  , ("|", accent '\781' (:[]))  -- vertical line above+  , ("b", accent '\817' (:[]))  -- macron below   , ("c", accent '\807' cedilla)+  , ("G", accent '\783' doublegrave)+  , ("h", accent '\777' hookabove)+  , ("d", accent '\803' dotbelow)+  , ("f", accent '\785' (:[]))  -- inverted breve+  , ("r", accent '\778' ringabove)+  , ("t", accent '\865' (:[]))  -- double inverted breve+  , ("U", accent '\782' (:[]))  -- double vertical line above   , ("v", accent 'ˇ' hacek)   , ("u", accent '\774' breve)   , ("k", accent '\808' ogonek)   , ("textogonekcentered", accent '\808' ogonek)-  , ("i", lit "i")+  , ("i", lit "ı")  -- dotless i+  , ("j", lit "ȷ")  -- dotless j+  , ("newtie", accent '\785' (:[])) -- inverted breve+  , ("textcircled", accent '\8413' (:[])) -- combining circle   , ("\\", linebreak <$ (do inTableCell <- sInTableCell <$> getState                             guard $ not inTableCell                             optional opt@@ -1444,17 +1778,25 @@   , ("footnote", skipopts >> note <$> grouped block)   , ("verb", doverb)   , ("lstinline", dolstinline)+  , ("mintinline", domintinline)   , ("Verb", doverb)-  , ("url", ((unescapeURL . T.unpack . untokenize) <$> braced) >>= \url ->+  , ("url", ((unescapeURL . T.unpack . untokenize) <$> bracedUrl) >>= \url ->                   pure (link url "" (str url)))   , ("href", (unescapeURL . toksToString <$>-                 braced <* optional sp) >>= \url ->+                 bracedUrl <* 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)+  , ("enquote*", enquote True Nothing)+  , ("enquote", enquote False Nothing)+  -- foreignquote is supposed to use native quote marks+  , ("foreignquote*", braced >>= enquote True . Just . untokenize)+  , ("foreignquote", braced >>= enquote False . Just . untokenize)+  -- hypehnquote uses regular quotes+  , ("hyphenquote*", braced >>= enquote True . Just . untokenize)+  , ("hyphenquote", braced >>= enquote False . Just . untokenize)   , ("figurename", doTerm Translations.Figure)   , ("prefacename", doTerm Translations.Preface)   , ("refname", doTerm Translations.References)@@ -1559,174 +1901,6 @@   , ("acsp", doAcronymPlural "abbrv")   -- siuntix   , ("SI", dosiunitx)-  -- units of siuntix-  , ("fg", lit "fg")-  , ("pg", lit "pg")-  , ("ng", lit "ng")-  , ("ug", lit "μg")-  , ("mg", lit "mg")-  , ("g", lit "g")-  , ("kg", lit "kg")-  , ("amu", lit "u")-  , ("pm", lit "pm")-  , ("nm", lit "nm")-  , ("um", lit "μm")-  , ("mm", lit "mm")-  , ("cm", lit "cm")-  , ("dm", lit "dm")-  , ("m", lit "m")-  , ("km", lit "km")-  , ("as", lit "as")-  , ("fs", lit "fs")-  , ("ps", lit "ps")-  , ("ns", lit "ns")-  , ("us", lit "μs")-  , ("ms", lit "ms")-  , ("s", lit "s")-  , ("fmol", lit "fmol")-  , ("pmol", lit "pmol")-  , ("nmol", lit "nmol")-  , ("umol", lit "μmol")-  , ("mmol", lit "mmol")-  , ("mol", lit "mol")-  , ("kmol", lit "kmol")-  , ("pA", lit "pA")-  , ("nA", lit "nA")-  , ("uA", lit "μA")-  , ("mA", lit "mA")-  , ("A", lit "A")-  , ("kA", lit "kA")-  , ("ul", lit "μl")-  , ("ml", lit "ml")-  , ("l", lit "l")-  , ("hl", lit "hl")-  , ("uL", lit "μL")-  , ("mL", lit "mL")-  , ("L", lit "L")-  , ("hL", lit "hL")-  , ("mHz", lit "mHz")-  , ("Hz", lit "Hz")-  , ("kHz", lit "kHz")-  , ("MHz", lit "MHz")-  , ("GHz", lit "GHz")-  , ("THz", lit "THz")-  , ("mN", lit "mN")-  , ("N", lit "N")-  , ("kN", lit "kN")-  , ("MN", lit "MN")-  , ("Pa", lit "Pa")-  , ("kPa", lit "kPa")-  , ("MPa", lit "MPa")-  , ("GPa", lit "GPa")-  , ("mohm", lit "mΩ")-  , ("kohm", lit "kΩ")-  , ("Mohm", lit "MΩ")-  , ("pV", lit "pV")-  , ("nV", lit "nV")-  , ("uV", lit "μV")-  , ("mV", lit "mV")-  , ("V", lit "V")-  , ("kV", lit "kV")-  , ("W", lit "W")-  , ("uW", lit "μW")-  , ("mW", lit "mW")-  , ("kW", lit "kW")-  , ("MW", lit "MW")-  , ("GW", lit "GW")-  , ("J", lit "J")-  , ("uJ", lit "μJ")-  , ("mJ", lit "mJ")-  , ("kJ", lit "kJ")-  , ("eV", lit "eV")-  , ("meV", lit "meV")-  , ("keV", lit "keV")-  , ("MeV", lit "MeV")-  , ("GeV", lit "GeV")-  , ("TeV", lit "TeV")-  , ("kWh", lit "kWh")-  , ("F", lit "F")-  , ("fF", lit "fF")-  , ("pF", lit "pF")-  , ("K", lit "K")-  , ("dB", lit "dB")-  , ("angstrom", lit "Å")-  , ("arcmin", lit "′")-  , ("arcminute", lit "′")-  , ("arcsecond", lit "″")-  , ("astronomicalunit", lit "ua")-  , ("atomicmassunit", lit "u")-  , ("atto", lit "a")-  , ("bar", lit "bar")-  , ("barn", lit "b")-  , ("becquerel", lit "Bq")-  , ("bel", lit "B")-  , ("candela", lit "cd")-  , ("celsius", lit "°C")-  , ("centi", lit "c")-  , ("coulomb", lit "C")-  , ("dalton", lit "Da")-  , ("day", lit "d")-  , ("deca", lit "d")-  , ("deci", lit "d")-  , ("decibel", lit "db")-  , ("degreeCelsius",lit "°C")-  , ("degree", lit "°")-  , ("deka", lit "d")-  , ("electronvolt", lit "eV")-  , ("exa", lit "E")-  , ("farad", lit "F")-  , ("femto", lit "f")-  , ("giga", lit "G")-  , ("gram", lit "g")-  , ("hectare", lit "ha")-  , ("hecto", lit "h")-  , ("henry", lit "H")-  , ("hertz", lit "Hz")-  , ("hour", lit "h")-  , ("joule", lit "J")-  , ("katal", lit "kat")-  , ("kelvin", lit "K")-  , ("kilo", lit "k")-  , ("kilogram", lit "kg")-  , ("knot", lit "kn")-  , ("liter", lit "L")-  , ("litre", lit "l")-  , ("lumen", lit "lm")-  , ("lux", lit "lx")-  , ("mega", lit "M")-  , ("meter", lit "m")-  , ("metre", lit "m")-  , ("milli", lit "m")-  , ("minute", lit "min")-  , ("mmHg", lit "mmHg")-  , ("mole", lit "mol")-  , ("nano", lit "n")-  , ("nauticalmile", lit "M")-  , ("neper", lit "Np")-  , ("newton", lit "N")-  , ("ohm", lit "Ω")-  , ("Pa", lit "Pa")-  , ("pascal", lit "Pa")-  , ("percent", lit "%")-  , ("per", lit "/")-  , ("peta", lit "P")-  , ("pico", lit "p")-  , ("radian", lit "rad")-  , ("second", lit "s")-  , ("siemens", lit "S")-  , ("sievert", lit "Sv")-  , ("square", dosquare)-  , ("steradian", lit "sr")-  , ("tera", lit "T")-  , ("tesla", lit "T")-  , ("tonne", lit "t")-  , ("volt", lit "V")-  , ("watt", lit "W")-  , ("weber", lit "Wb")-  , ("yocto", lit "y")-  , ("yotta", lit "Y")-  , ("zepto", lit "z")-  , ("zetta", lit "Z")   -- hyphenat   , ("bshyp", lit "\\\173")   , ("fshyp", lit "/\173")@@ -2130,25 +2304,29 @@   optional $ symbol '='   spaces   contents <- bracedOrToken-  return (name, Macro ExpandWhenDefined 0 Nothing contents)+  return (name, Macro ExpandWhenDefined [] Nothing contents)  defmacro :: PandocMonad m => LP m (Text, Macro) defmacro = try $ do   controlSeq "def"   Tok _ (CtrlSeq name) _ <- anyControlSeq-  numargs <- option 0 $ argSeq 1+  argspecs <- many (argspecArg <|> argspecPattern)   -- 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)+  return (name, Macro ExpandWhenUsed argspecs Nothing contents) --- Note: we don't yet support fancy things like #1.#2-argSeq :: PandocMonad m => Int -> LP m Int-argSeq n = do+argspecArg :: PandocMonad m => LP m ArgSpec+argspecArg = do   Tok _ (Arg i) _ <- satisfyTok isArgTok-  guard $ i == n-  argSeq (n+1) <|> return n+  return $ ArgNum i +argspecPattern :: PandocMonad m => LP m ArgSpec+argspecPattern =+  Pattern <$> many1 (satisfyTok (\(Tok _ toktype' txt) ->+                                    (toktype' == Symbol || toktype' == Word) &&+                                    (txt /= "{" && txt /= "\\" && txt /= "}")))+ isArgTok :: Tok -> Bool isArgTok (Tok _ (Arg _) _) = True isArgTok _                 = False@@ -2168,6 +2346,7 @@     (symbol '{' *> spaces *> anyControlSeq <* spaces <* symbol '}')   spaces   numargs <- option 0 $ try bracketedNum+  let argspecs = map (\i -> ArgNum i) [1..numargs]   spaces   optarg <- option Nothing $ Just <$> try bracketedToks   spaces@@ -2177,7 +2356,7 @@     case M.lookup name macros of          Just _  -> report $ MacroAlreadyDefined (T.unpack txt) pos          Nothing -> return ()-  return (name, Macro ExpandWhenUsed numargs optarg contents)+  return (name, Macro ExpandWhenUsed argspecs optarg contents)  newenvironment :: PandocMonad m => LP m (Text, Macro, Macro) newenvironment = do@@ -2190,6 +2369,7 @@   name <- untokenize <$> braced   spaces   numargs <- option 0 $ try bracketedNum+  let argspecs = map (\i -> ArgNum i) [1..numargs]   spaces   optarg <- option Nothing $ Just <$> try bracketedToks   spaces@@ -2201,8 +2381,8 @@     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)+  return (name, Macro ExpandWhenUsed argspecs optarg startcontents,+             Macro ExpandWhenUsed [] Nothing endcontents)  bracketedToks :: PandocMonad m => LP m [Tok] bracketedToks = do@@ -2240,26 +2420,25 @@ resetCaption :: PandocMonad m => LP m () resetCaption = updateState $ \st -> st{ sCaption = (Nothing, Nothing) } -section :: PandocMonad m => Bool -> Attr -> Int -> LP m Blocks-section starred (ident, classes, kvs) lvl = do+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 >> toksToString <$> braced)-  let classes' = if starred then "unnumbered" : classes else classes   when (lvl == 0) $     updateState $ \st -> st{ sHasChapters = True }-  unless starred $ do+  unless ("unnumbered" `elem` classes) $ do     hn <- sLastHeaderNum <$> getState     hasChapters <- sHasChapters <$> getState     let lvl' = lvl + if hasChapters then 1 else 0-    let num = incrementHeaderNum lvl' hn-    updateState $ \st -> st{ sLastHeaderNum = num }-    updateState $ \st -> st{ sLabels = M.insert lab-                            [Str (renderHeaderNum num)]-                            (sLabels st) }-  attr' <- registerHeader (lab, classes', kvs) contents+    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@@ -2320,23 +2499,23 @@    -- 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)+   , ("part", section nullAttr (-1))+   , ("part*", section nullAttr (-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)    -- beamer slides-   , ("frametitle", section False nullAttr 3)-   , ("framesubtitle", section False nullAttr 4)+   , ("frametitle", section nullAttr 3)+   , ("framesubtitle", section nullAttr 4)    -- letters    , ("opening", (para . trimInlines) <$> (skipopts *> tok))    , ("closing", skipopts *> closing)@@ -2372,6 +2551,13 @@    -- 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", include "include")    , ("input", include "input")@@ -2538,6 +2724,33 @@               attr' = case mblab of                         Just lab -> (lab, cls, kvs)                         Nothing  -> attr+          case attr' of+               ("", _, _)    -> return ()+               (ident, _, _) -> do+                  st <- getState+                  let chapnum =+                        case (sHasChapters st, sLastHeaderNum st) of+                             (True, DottedNum (n:_)) -> Just n+                             _                       -> Nothing+                  let num = case sLastFigureNum st of+                       DottedNum [m,n]  ->+                         case chapnum of+                              Just m' | m' == m   -> DottedNum [m, n+1]+                                      | otherwise -> DottedNum [m', 1]+                              Nothing             -> DottedNum [1]+                                                      -- shouldn't happen+                       DottedNum [n]   ->+                         case chapnum of+                              Just m  -> DottedNum [m, 1]+                              Nothing -> DottedNum [n + 1]+                       _               ->+                         case chapnum of+                               Just n  -> DottedNum [n, 1]+                               Nothing -> DottedNum [1]+                  setState $+                    st{ sLastFigureNum = num+                      , sLabels = M.insert ident+                                 [Str (renderDottedNum num)] (sLabels st) }           return $ Image attr' alt' (src, tit')         go x = return x 
src/Text/Pandoc/Readers/LaTeX/Types.hs view
@@ -31,6 +31,7 @@ module Text.Pandoc.Readers.LaTeX.Types ( Tok(..)                                        , TokType(..)                                        , Macro(..)+                                       , ArgSpec(..)                                        , ExpansionPoint(..)                                        , SourcePos                                        )@@ -49,5 +50,8 @@ data ExpansionPoint = ExpandWhenDefined | ExpandWhenUsed      deriving (Eq, Ord, Show) -data Macro = Macro ExpansionPoint Int (Maybe [Tok]) [Tok]+data Macro = Macro ExpansionPoint [ArgSpec] (Maybe [Tok]) [Tok]+     deriving Show++data ArgSpec = ArgNum Int | Pattern [Tok]      deriving Show
src/Text/Pandoc/Readers/Markdown.hs view
@@ -31,11 +31,12 @@  Conversion of markdown-formatted plain text to 'Pandoc' document. -}-module Text.Pandoc.Readers.Markdown ( readMarkdown ) where+module Text.Pandoc.Readers.Markdown ( readMarkdown, yamlToMeta ) where  import Prelude import Control.Monad import Control.Monad.Except (throwError)+import qualified Data.ByteString.Lazy as BS import Data.Char (isAlphaNum, isPunctuation, isSpace, toLower) import Data.List (intercalate, sortBy, transpose, elemIndex) import qualified Data.Map as M@@ -233,7 +234,6 @@ 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@@ -241,47 +241,45 @@   -- by including --- and ..., we allow yaml blocks with just comments:   let rawYaml = unlines ("---" : (rawYamlLines ++ ["..."]))   optional blanklines-  case YAML.decodeNode' YAML.failsafeSchemaResolver False False-               (UTF8.fromStringLazy rawYaml) of-       Right [YAML.Doc (YAML.Mapping _ hashmap)] ->-         mapM_ (\(key, v) -> do-                    k <- nodeToKey key-                    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})-               (M.toList hashmap)-       Right [] -> return ()-       Right [YAML.Doc (YAML.Scalar YAML.SNull)] -> return ()+  newMetaF <- yamlBsToMeta $ UTF8.fromStringLazy rawYaml+  -- Since `<>` is left-biased, existing values are not touched:+  updateState $ \st -> st{ stateMeta' = (stateMeta' st) <> newMetaF }+  return mempty++-- | Read a YAML string and convert it to pandoc metadata.+-- String scalars in the YAML are parsed as Markdown.+yamlToMeta :: PandocMonad m => BS.ByteString -> m Meta+yamlToMeta bstr = do+  let parser = do+        meta <- yamlBsToMeta bstr+        return $ runF meta defaultParserState+  parsed <- readWithM parser def ""+  case parsed of+    Right result -> return result+    Left e       -> throwError e++yamlBsToMeta :: PandocMonad m => BS.ByteString -> MarkdownParser m (F Meta)+yamlBsToMeta bstr = do+  pos <- getPosition+  case YAML.decodeNode' YAML.failsafeSchemaResolver False False bstr of+       Right ((YAML.Doc (YAML.Mapping _ o)):_) -> (fmap Meta) <$> yamlMap o+       Right [] -> return . return $ mempty+       Right [YAML.Doc (YAML.Scalar YAML.SNull)] -> return . return $ mempty        Right _ -> do                   logMessage $                      CouldNotParseYamlMetadata "not an object"                      pos-                  return ()+                  return . return $ mempty        Left err' -> do                     logMessage $ CouldNotParseYamlMetadata                                  err' pos-                    return ()-  return mempty+                    return . return $ mempty  nodeToKey :: Monad m => YAML.Node -> m Text nodeToKey (YAML.Scalar (YAML.SStr t))       = return t nodeToKey (YAML.Scalar (YAML.SUnknown _ t)) = return t nodeToKey _                                 = fail "Non-string key in YAML mapping" --- ignore fields ending with _-ignorable :: Text -> Bool-ignorable t = (T.pack "_") `T.isSuffixOf` t- toMetaValue :: PandocMonad m             => Text -> MarkdownParser m (F MetaValue) toMetaValue x =@@ -309,9 +307,9 @@              then Just False              else Nothing -yamlToMeta :: PandocMonad m-           => YAML.Node -> MarkdownParser m (F MetaValue)-yamlToMeta (YAML.Scalar x) =+yamlToMetaValue :: PandocMonad m+                => YAML.Node -> MarkdownParser m (F MetaValue)+yamlToMetaValue (YAML.Scalar x) =   case x of        YAML.SStr t       -> toMetaValue t        YAML.SBool b      -> return $ return $ MetaBool b@@ -322,26 +320,31 @@            Just b        -> return $ return $ MetaBool b            Nothing       -> toMetaValue t        YAML.SNull        -> return $ return $ MetaString ""-yamlToMeta (YAML.Sequence _ xs) = do-  xs' <- mapM yamlToMeta xs+yamlToMetaValue (YAML.Sequence _ xs) = do+  xs' <- mapM yamlToMetaValue xs   return $ do     xs'' <- sequence xs'     return $ B.toMetaValue xs''-yamlToMeta (YAML.Mapping _ o) =-  foldM (\m (key, v) -> do-          k <- nodeToKey key-          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)-        (M.toList o)-yamlToMeta _ = return $ return $ MetaString ""+yamlToMetaValue (YAML.Mapping _ o) = fmap B.toMetaValue <$> yamlMap o+yamlToMetaValue _ = return $ return $ MetaString "" +yamlMap :: PandocMonad m+        => M.Map YAML.Node YAML.Node+        -> MarkdownParser m (F (M.Map String MetaValue))+yamlMap o = do+    kvs <- forM (M.toList o) $ \(key, v) -> do+             k <- nodeToKey key+             return (k, v)+    let kvs' = filter (not . ignorable . fst) kvs+    (fmap M.fromList . sequence) <$> mapM toMeta kvs'+  where+    ignorable t = (T.pack "_") `T.isSuffixOf` t+    toMeta (k, v) = do+      fv <- yamlToMetaValue v+      return $ do+        v' <- fv+        return (T.unpack k, v')+ stopLine :: PandocMonad m => MarkdownParser m () stopLine = try $ (string "---" <|> string "...") >> blankline >> return () @@ -967,7 +970,9 @@                <|> return (style == Example)   items <- fmap sequence $ many1 $ listItem fourSpaceRule                  (orderedListStart (Just (style, delim)))-  start' <- (start <$ guardEnabled Ext_startnum) <|> return 1+  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)@@ -1143,19 +1148,15 @@ rawTeXBlock = do   guardEnabled Ext_raw_tex   lookAhead $ try $ char '\\' >> letter-  result <- (B.rawBlock "context" . trim . concat <$>-                many1 ((++) <$> (rawConTeXtEnvironment <|> conTeXtCommand)-                            <*> spnl'))-          <|> (B.rawBlock "latex" . trim . concat <$>+  result <- (B.rawBlock "tex" . trim . concat <$>+                many1 ((++) <$> rawConTeXtEnvironment <*> spnl'))+          <|> (B.rawBlock "tex" . trim . concat <$>                 many1 ((++) <$> rawLaTeXBlock <*> spnl'))   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
src/Text/Pandoc/Readers/Muse.hs view
@@ -43,7 +43,7 @@ import Control.Monad import Control.Monad.Except (throwError) import Data.Bifunctor-import Data.Char (isLetter)+import Data.Char (isLetter, isDigit) import Data.Default import Data.List (intercalate) import Data.List.Split (splitOn)@@ -58,7 +58,7 @@ import Text.Pandoc.Definition import Text.Pandoc.Logging import Text.Pandoc.Options-import Text.Pandoc.Parsing hiding (F)+import Text.Pandoc.Parsing hiding (F, enclosed) import Text.Pandoc.Readers.HTML (htmlTag) import Text.Pandoc.Shared (crFilter, underlineSpan) @@ -123,7 +123,9 @@ parseMuse :: PandocMonad m => MuseParser m Pandoc parseMuse = do   many directive-  blocks <- parseBlocks+  firstSection <- parseBlocks+  rest <- many parseSection+  let blocks = mconcat $ (firstSection : rest)   st <- getState   let doc = runF (do Pandoc _ bs <- B.doc <$> blocks                      meta <- museMeta st@@ -252,17 +254,20 @@  -- ** Block parsers +-- | Parse section contents until EOF or next header parseBlocks :: PandocMonad m             => MuseParser m (F Blocks) parseBlocks =   try (parseEnd <|>+       nextSection <|>        blockStart <|>        listStart <|>        paraStart)   where+    nextSection = mempty <$ lookAhead headingStart     parseEnd = mempty <$ eof-    blockStart = ((B.<>) <$> (emacsHeading <|> blockElements <|> emacsNoteBlock)-                         <*> parseBlocks) <|> (uncurry (B.<>) <$> amuseHeadingUntil parseBlocks)+    blockStart = ((B.<>) <$> (blockElements <|> emacsNoteBlock)+                         <*> parseBlocks)     listStart = do       updateState (\st -> st { museInPara = False })       uncurry (B.<>) <$> (anyListUntil parseBlocks <|> amuseNoteBlockUntil parseBlocks)@@ -271,6 +276,13 @@       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)@@ -361,15 +373,20 @@   eol   return $ return B.horizontalRule --- | Parse a single-line heading.-emacsHeading :: PandocMonad m => MuseParser m (F Blocks)-emacsHeading = try $ do-  guardDisabled Ext_amuse+headingStart :: PandocMonad m => MuseParser m (String, Int)+headingStart = try $ do   anchorId <- option "" $ try (parseAnchor <* manyTill spaceChar eol)   getPosition >>= \pos -> guard (sourceColumn pos == 1)   level <- fmap length $ many1 $ char '*'   guard $ level <= 5   spaceChar+  return (anchorId, level)++-- | 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@@ -381,11 +398,7 @@                   -> MuseParser m (F Blocks, a) amuseHeadingUntil end = try $ do   guardEnabled Ext_amuse-  anchorId <- option "" $ try (parseAnchor <* manyTill spaceChar eol)-  getPosition >>= \pos -> guard (sourceColumn pos == 1)-  level <- fmap length $ many1 $ char '*'-  guard $ level <= 5-  spaceChar+  (anchorId, level) <- headingStart   (content, e) <- paraContentsUntil end   attr <- registerHeader (anchorId, [], []) (runF content def)   return (B.headerWith attr level <$> content, e)@@ -462,16 +475,19 @@   rest <- manyTill (choice inlineList) newline   return $ trimInlinesF $ mconcat (pure indent : rest) -verseLines :: PandocMonad m => MuseParser m (F Blocks)-verseLines = do-  lns <- many verseLine-  return $ B.lineBlock <$> sequence lns- -- | Parse @\<verse>@ tag. verseTag :: PandocMonad m => MuseParser m (F Blocks)-verseTag = do-  (_, content) <- htmlBlock "verse"-  parseFromString verseLines (intercalate "\n" $ dropSpacePrefix $ splitOn "\n" $ lchop content)+verseTag = try $ do+  many spaceChar+  pos <- getPosition+  (TagOpen _ _, _) <- htmlTag (~== TagOpen "verse" [])+  manyTill spaceChar eol+  let indent = count (sourceColumn pos - 1) spaceChar+  content <- sequence <$> manyTill (indent >> verseLine) (try $ indent >> endtag)+  manyTill spaceChar eol+  return $ B.lineBlock <$> content+  where+    endtag = void $ htmlTag (~== TagClose "verse")  -- | Parse @\<comment>@ tag. commentTag :: PandocMonad m => MuseParser m (F Blocks)@@ -836,12 +852,20 @@ emphasisBetween :: (PandocMonad m, Show a) => MuseParser m a -> MuseParser m (F Inlines) emphasisBetween c = try $ enclosedInlines c c +-- | 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 spaceChar >> many1Till parser end+ 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))+  trimInlinesF . mconcat <$> (enclosed (atStart start) end inline <* notFollowedBy (satisfy ((||) <$> isLetter <*> isDigit)))  -- | Parse an inline tag, such as @\<em>@ and @\<strong>@. inlineTag :: PandocMonad m@@ -964,11 +988,11 @@ image :: PandocMonad m => MuseParser m (F Inlines) image = try $ do   string "[["-  (url, (ext, width, align)) <- manyUntil (noneOf "]") $ (imageExtensionAndOptions <* char ']')+  (url, (ext, width, align)) <- manyUntil (noneOf "]") (imageExtensionAndOptions <* char ']')   content <- optionMaybe linkContent   char ']'   let widthAttr = case align of-                    Just 'f' -> [("width", (fromMaybe "100" width) ++ "%"), ("height", "75%")]+                    Just 'f' -> [("width", fromMaybe "100" width ++ "%"), ("height", "75%")]                     _ -> maybeToList (("width",) . (++ "%") <$> width)   let alignClass = case align of                      Just 'r' -> ["align-right"]
src/Text/Pandoc/Readers/Odt/Generic/Utils.hs view
@@ -133,9 +133,7 @@ -- 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+                                 a <- maybeToList (lookup word lookupTable)                     ]  -- | Very similar to a simple 'lookup' in the 'lookupTable', but with a lexer.
src/Text/Pandoc/Readers/Odt/StyleReader.hs view
@@ -138,7 +138,7 @@                               lookupDefaultingAttr NsStyle "font-pitch"                             ))                     >>?^ ( M.fromList . foldl accumLegalPitches [] )-                  )+                  ) `ifFailedDo` (returnV (Right M.empty))   where accumLegalPitches ls (Nothing,_) = ls         accumLegalPitches ls (Just n,p)  = (n,p):ls 
src/Text/Pandoc/Readers/Org/DocumentTree.hs view
@@ -1,4 +1,3 @@-{-# LANGUAGE NoImplicitPrelude #-} {- Copyright (C) 2014-2018 Albert Krewinkel <tarleb+pandoc@moltkeplatz.de> @@ -17,8 +16,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA -} {-# LANGUAGE FlexibleContexts #-}-{-# LANGUAGE RecordWildCards  #-}-{-# LANGUAGE ViewPatterns     #-}+{-# LANGUAGE NoImplicitPrelude #-} {- |    Module      : Text.Pandoc.Readers.Org.DocumentTree    Copyright   : Copyright (C) 2014-2018 Albert Krewinkel@@ -70,6 +68,7 @@       , headlineTodoMarker = Nothing       , headlineText = B.fromList title'       , headlineTags = mempty+      , headlinePlanning = emptyPlanning       , headlineProperties = mempty       , headlineContents = initialBlocks'       , headlineChildren = headlines'@@ -117,6 +116,7 @@   , headlineTodoMarker :: Maybe TodoMarker   , headlineText       :: Inlines   , headlineTags       :: [Tag]+  , headlinePlanning   :: PlanningInfo -- ^ subtree planning information   , headlineProperties :: Properties   , headlineContents   :: Blocks   , headlineChildren   :: [Headline]@@ -136,6 +136,7 @@   title <- trimInlinesF . mconcat <$> manyTill inline endOfTitle   tags  <- option [] headerTags   newline+  planning   <- option emptyPlanning planningInfo   properties <- option mempty propertiesDrawer   contents   <- blocks   children   <- many (headline blocks inline (level + 1))@@ -148,6 +149,7 @@       , headlineTodoMarker = todoKw       , headlineText = title'       , headlineTags = tags+      , headlinePlanning = planning       , headlineProperties = properties       , headlineContents = contents'       , headlineChildren = children'@@ -163,14 +165,17 @@  -- | 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 isNoExportTag tags -> return mempty+    _ | any isArchiveTag  tags -> archivedHeadlineToBlocks hdln+    _ | isCommentTitle text    -> return mempty+    _ | maxLevel <= level      -> headlineToHeaderWithList hdln+    _ | otherwise              -> headlineToHeaderWithContents hdln  isNoExportTag :: Tag -> Bool isNoExportTag = (== toTag "noexport")@@ -182,8 +187,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@@ -194,17 +200,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+    , headlineContents hdln+    , planningBlock+    , listBlock+    ]  where    flattenHeader :: Blocks -> Blocks    flattenHeader blks =@@ -213,27 +225,28 @@        _                    -> 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@@ -277,9 +290,60 @@ 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 = String +timestamp :: Monad m => OrgParser m Timestamp+timestamp = try $ do+  openChar <- oneOf "<["+  let isActive = openChar == '<'+  let closeChar = if isActive then '>' else ']'+  content <- many1Till anyChar (char closeChar)+  return (openChar : content ++ [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.
src/Text/Pandoc/Readers/Org/ExportSettings.hs view
@@ -69,7 +69,7 @@   , 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"
src/Text/Pandoc/Readers/Org/ParserState.hs view
@@ -260,6 +260,7 @@   , exportWithAuthor       :: Bool -- ^ Include author in final meta-data   , exportWithCreator      :: Bool -- ^ Include creator in final meta-data   , exportWithEmail        :: Bool -- ^ Include email in final meta-data+  , exportWithPlanning     :: Bool -- ^ Keep planning info after headlines   , exportWithTags         :: Bool -- ^ Keep tags as part of headlines   , exportWithTodoKeywords :: Bool -- ^ Keep TODO keywords in headers   }@@ -280,6 +281,7 @@   , exportWithAuthor = True   , exportWithCreator = True   , exportWithEmail = True+  , exportWithPlanning = False   , exportWithTags = True   , exportWithTodoKeywords = True   }
src/Text/Pandoc/Readers/RST.hs view
@@ -172,6 +172,7 @@   docMinusKeys <- concat <$>                   manyTill (referenceKey <|> anchorDef <|>                             noteBlock <|> citationBlock <|>+                            (snd <$> withRaw comment) <|>                             headerBlock <|> lineClump) eof   setInput docMinusKeys   setPosition startPos
src/Text/Pandoc/Readers/Txt2Tags.hs view
@@ -575,8 +575,10 @@ getTarget :: T2T String 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)
src/Text/Pandoc/UUID.hs view
@@ -67,13 +67,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
src/Text/Pandoc/Writers/AsciiDoc.hs view
@@ -285,7 +285,7 @@   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 <> "]]")+  let identifier = if null ident then empty else "[[" <> text ident <> "]]"   contents <- blockListToAsciiDoc opts bs   return $ identifier $$ contents @@ -492,6 +492,6 @@ -- 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 <> "]]")+  let identifier = if null ident then empty else "[[" <> text ident <> "]]"   contents <- inlineListToAsciiDoc opts ils   return $ identifier <> contents
src/Text/Pandoc/Writers/ConTeXt.hs view
@@ -190,10 +190,9 @@ blockToConTeXt (CodeBlock _ str) =   return $ flush ("\\starttyping" <> cr <> text str <> cr <> "\\stoptyping") $$ blankline   -- 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+blockToConTeXt b@(RawBlock f str)+  | f == Format "context" || f == Format "tex" = return $ text str <> blankline+  | otherwise = empty <$ report (BlockNotRendered b) blockToConTeXt (Div (ident,_,kvs) bs) = do   let align dir txt = "\\startalignment[" <> dir <> "]" $$ txt $$ "\\stopalignment"   mblang <- fromBCP47 (lookup "lang" kvs)@@ -330,8 +329,7 @@                          AlignDefault -> empty  listItemToConTeXt :: PandocMonad m => [Block] -> WM m Doc-listItemToConTeXt list = blockListToConTeXt list >>=-  return . ("\\item" $$) . nest 2+listItemToConTeXt list = (("\\item" $$) . nest 2) <$> blockListToConTeXt list  defListItemToConTeXt :: PandocMonad m => ([Inline], [[Block]]) -> WM m Doc defListItemToConTeXt (term, defs) = do@@ -401,11 +399,9 @@   return $ char '$' <> text 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 il@(RawInline f str)+  | f == Format "tex" || f == Format "context" = return $ text str+  | otherwise = empty <$ report (InlineNotRendered il) inlineToConTeXt LineBreak = return $ text "\\crlf" <> cr inlineToConTeXt SoftBreak = do   wrapText <- gets (writerWrapText . stOptions)
src/Text/Pandoc/Writers/Custom.hs view
@@ -48,7 +48,7 @@ import Text.Pandoc.Error import Text.Pandoc.Lua.Init (runPandocLua, registerScriptPath) import Text.Pandoc.Lua.StackInstances ()-import Text.Pandoc.Lua.Util (addValue, dostring')+import Text.Pandoc.Lua.Util (addField, addValue, dostring') import Text.Pandoc.Options import Text.Pandoc.Templates import qualified Text.Pandoc.UTF8 as UTF8@@ -82,12 +82,12 @@ 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+    addField "citationId" $ citationId cit+    addField "citationPrefix" . Stringify $ citationPrefix cit+    addField "citationSuffix" . Stringify $ citationSuffix cit+    addField "citationMode" $ show (citationMode cit)+    addField "citationNoteNum" $ citationNoteNum cit+    addField "citationHash" $ citationHash cit  -- | Key-value pair, pushed as a table with @a@ as the only key and @v@ as the -- associated value.
src/Text/Pandoc/Writers/Docx.hs view
@@ -66,7 +66,8 @@ import Text.Pandoc.Shared hiding (Element) import Text.Pandoc.Walk import Text.Pandoc.Writers.Math-import Text.Pandoc.Writers.Shared (fixDisplayMath, metaValueToInlines)+import Text.Pandoc.Writers.Shared (isDisplayMath, fixDisplayMath,+                                   metaValueToInlines) import Text.Printf (printf) import Text.TeXMath import Text.XML.Light as XML@@ -762,11 +763,13 @@   let abstract' = case lookupMeta "abstract" meta of                        Just (MetaBlocks bs)   -> bs                        Just (MetaInlines ils) -> [Plain ils]+                       Just (MetaString s)    -> [Plain [Str s]]                        _                      -> []   let subtitle' = case lookupMeta "subtitle" meta of                        Just (MetaBlocks [Plain xs]) -> xs                        Just (MetaBlocks [Para  xs]) -> xs                        Just (MetaInlines xs)        -> xs+                       Just (MetaString s)          -> [Str s]                        _                            -> []   let includeTOC = writerTableOfContents opts ||                    case lookupMeta "toc" meta of@@ -915,9 +918,10 @@   | null lst && not (isEnabled Ext_empty_paragraphs opts) = return []   | otherwise = do       isFirstPara <- gets stFirstPara-      paraProps <- getParaProps $ case lst of-                                   [Math DisplayMath _] -> True-                                   _                    -> False+      let displayMathPara = case lst of+                                 [x] -> isDisplayMath x+                                 _   -> False+      paraProps <- getParaProps displayMathPara       bodyTextStyle <- pStyleM "Body Text"       let paraProps' = case paraProps of             [] | isFirstPara -> [mknode "w:pPr" []
src/Text/Pandoc/Writers/EPUB.hs view
@@ -461,6 +461,7 @@   -- title page   tpContent <- lift $ writeHtml opts'{                                   writerVariables = ("titlepage","true"):+                                  ("body-type", "frontmatter"):                                   ("pagetitle", escapeStringForXML plainTitle):                                   cssvars True ++ vars }                                (Pandoc meta [])@@ -565,13 +566,28 @@   let chapToEntry num (Chapter mbnum bs) =         mkEntry ("text/" ++ showChapter num) =<<         writeHtml opts'{ writerNumberOffset = fromMaybe [] mbnum-                       , writerVariables = cssvars True ++ vars }-                 (case bs of-                     (Header _ _ xs : _) ->+                       , writerVariables = ("body-type", bodyType) :+                                           cssvars True ++ vars } pdoc+         where (pdoc, bodyType) =+                 case bs of+                     (Header _ (_,_,kvs) xs : _) ->                        -- remove notes or we get doubled footnotes-                       Pandoc (setMeta "title" (walk removeNote $ fromList xs)-                                 nullMeta) bs-                     _                   -> Pandoc nullMeta bs)+                       (Pandoc (setMeta "title"+                           (walk removeNote $ fromList xs) nullMeta) bs,+                        case lookup "epub:type" kvs of+                             Nothing -> "bodymatter"+                             Just x+                               | x `elem` frontMatterTypes -> "frontmatter"+                               | x `elem` backMatterTypes  -> "backmatter"+                               | otherwise                 -> "bodymatter")+                     _                   -> (Pandoc nullMeta bs, "bodymatter")+               frontMatterTypes = ["prologue", "abstract", "acknowledgments",+                                   "copyright-page", "dedication",+                                   "foreword", "halftitle",+                                   "introduction", "preface",+                                   "seriespage", "titlepage"]+               backMatterTypes = ["afterword", "appendix", "colophon",+                                  "conclusion", "epigraph"]    chapterEntries <- zipWithM chapToEntry [1..] chapters @@ -785,7 +801,7 @@                                 [ unode "a" ! [("href", "text/cover.xhtml")                                               ,("epub:type", "cover")] $                                   "Cover"] |-                                  epubCoverImage metadata /= Nothing+                                  isJust (epubCoverImage metadata)                               ] ++                               [ unode "li"                                 [ unode "a" ! [("href", "#toc")
src/Text/Pandoc/Writers/FB2.hs view
@@ -119,7 +119,7 @@   let as = authors meta'   dd <- docdate meta'   annotation <- case lookupMeta "abstract" meta' of-                  Just (MetaBlocks bs) -> (list . el "annotation") <$> (cMapM blockToXml $ map unPlain bs)+                  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]@@ -135,8 +135,9 @@                     Just (MetaString s) -> coverimage s                     _       -> return []   return $ el "description"-    [ el "title-info" (genre : (as ++ bt ++ annotation ++ dd ++ lang))-    , el "document-info" (el "program-used" "pandoc" : coverpage)+    [ el "title-info" (genre :+                      (as ++ bt ++ annotation ++ dd ++ coverpage ++ lang))+    , el "document-info" [el "program-used" "pandoc"]     ]  booktitle :: PandocMonad m => Meta -> FBM m [Content]
src/Text/Pandoc/Writers/HTML.hs view
@@ -580,6 +580,7 @@   return $ map (\(x,y) ->      customAttribute         (fromString (if not html5 || x `Set.member` html5Attributes+                                  || "epub:" `isPrefixOf` x                                   || "data-" `isPrefixOf` x                         then x                         else "data-" ++ x)) (toValue y)) kvs@@ -829,9 +830,7 @@   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+                  do term' <- 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 :
src/Text/Pandoc/Writers/Haddock.hs view
@@ -45,7 +45,6 @@ import Text.Pandoc.Pretty import Text.Pandoc.Shared import Text.Pandoc.Templates (renderTemplate')-import Text.Pandoc.Writers.Math (texMathToInlines) import Text.Pandoc.Writers.Shared  type Notes = [[Block]]@@ -208,13 +207,13 @@                    -> [Block]       -- ^ List of block elements                    -> StateT WriterState m Doc blockListToHaddock opts blocks =-  mapM (blockToHaddock opts) blocks >>= return . cat+  cat <$> mapM (blockToHaddock opts) blocks  -- | Convert list of Pandoc inline elements to haddock. inlineListToHaddock :: PandocMonad m                     => WriterOptions -> [Inline] -> StateT WriterState m Doc inlineListToHaddock opts lst =-  mapM (inlineToHaddock opts) lst >>= return . cat+  cat <$> mapM (inlineToHaddock opts) lst  -- | Convert Pandoc inline element to haddock. inlineToHaddock :: PandocMonad m@@ -250,11 +249,10 @@   return $ "@" <> text (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)+inlineToHaddock _ (Math mt str) =+  return $ case mt of+    DisplayMath -> cr <> "\\[" <> text str <> "\\]" <> cr+    InlineMath  -> "\\(" <> text str <> "\\)" inlineToHaddock _ il@(RawInline f str)   | f == "haddock" = return $ text str   | otherwise = do
src/Text/Pandoc/Writers/LaTeX.hs view
@@ -248,7 +248,8 @@                                      defField "biblatex" True                          _        -> id) $                   defField "colorlinks" (any hasStringValue-                           ["citecolor", "urlcolor", "linkcolor", "toccolor"]) $+                           ["citecolor", "urlcolor", "linkcolor", "toccolor",+                            "filecolor"]) $                   (if null dirs                      then id                      else defField "dir" ("ltr" :: String)) $
src/Text/Pandoc/Writers/Man.hs view
@@ -325,11 +325,11 @@                -> [Block]       -- ^ List of block elements                -> StateT WriterState m Doc blockListToMan opts blocks =-  mapM (blockToMan opts) blocks >>= (return . vcat)+  vcat <$> mapM (blockToMan opts) blocks  -- | 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 opts lst = hcat <$> mapM (inlineToMan opts) lst  -- | Convert Pandoc inline element to man. inlineToMan :: PandocMonad m => WriterOptions -> Inline -> StateT WriterState m Doc
src/Text/Pandoc/Writers/Markdown.hs view
@@ -298,7 +298,8 @@               '\\':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_subscript opts ||+             isEnabled Ext_strikeout 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
src/Text/Pandoc/Writers/Ms.hs view
@@ -434,7 +434,7 @@               -> [Block]       -- ^ List of block elements               -> MS m Doc 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
src/Text/Pandoc/Writers/Muse.hs view
@@ -46,7 +46,7 @@ import Prelude import Control.Monad.Reader import Control.Monad.State.Strict-import Data.Char (isSpace, isDigit, isAsciiUpper, isAsciiLower)+import Data.Char (isSpace, isAlphaNum, isDigit, isAsciiUpper, isAsciiLower) import Data.Default import Data.Text (Text) import Data.List (intersperse, transpose, isInfixOf)@@ -70,20 +70,24 @@   WriterEnv { envOptions :: WriterOptions             , envTopLevel :: Bool             , envInsideBlock :: Bool-            , envInlineStart :: Bool+            , envInlineStart :: Bool -- ^ True if there is only whitespace since last newline             , envInsideLinkDescription :: Bool -- ^ Escape ] if True-            , envAfterSpace :: Bool+            , 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               , stIds         :: Set.Set String+              , stUseTags     :: Bool -- ^ Use tags for emphasis, for example because previous character is a letter               }  instance Default WriterState   where def = WriterState { stNotes = []                           , stIds = Set.empty+                          , stUseTags = False                           }  evalMuse :: PandocMonad m => Muse m a -> WriterEnv -> WriterState -> m a@@ -103,6 +107,8 @@                         , envInsideLinkDescription = False                         , envAfterSpace = False                         , envOneLine = False+                        , envInsideAsterisks = False+                        , envNearAsterisks = False                         }  -- | Return Muse representation of document.@@ -212,6 +218,7 @@                              => [Block]                              -> Muse m Doc         bulletListItemToMuse item = do+          modify $ \st -> st { stUseTags = False }           contents <- blockListToMuse item           return $ hang 2 "- " contents blockToMuse (DefinitionList items) = do@@ -223,16 +230,18 @@                                  => ([Inline], [[Block]])                                  -> Muse m Doc         definitionListItemToMuse (label, defs) = do+          modify $ \st -> st { stUseTags = False }           label' <- local (\env -> env { envOneLine = True, envAfterSpace = True }) $ inlineListToMuse' label           contents <- vcat <$> mapM descriptionToMuse defs           let ind = offset label'-          return $ hang ind label' contents+          return $ hang ind (nowrap label') contents         descriptionToMuse :: PandocMonad m                           => [Block]                           -> Muse m Doc         descriptionToMuse desc = hang 4 " :: " <$> blockListToMuse desc blockToMuse (Header level (ident,_,_) inlines) = do   opts <- asks envOptions+  topLevel <- asks envTopLevel   contents <- local (\env -> env { envOneLine = True }) $ inlineListToMuse' inlines   ids <- gets stIds   let autoId = uniqueIdent inlines ids@@ -241,8 +250,8 @@   let attr' = if null ident || (isEnabled Ext_auto_identifiers opts && ident == autoId)                  then empty                  else "#" <> text ident <> cr-  let header' = text $ replicate level '*'-  return $ blankline <> attr' $$ nowrap (header' <> space <> contents) <> blankline+  let header' = if topLevel then (text $ 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@@ -284,7 +293,11 @@            -> [Block]            -> Muse m Doc noteToMuse num note =-  hang (length marker) (text marker) <$> blockListToMuse note+  hang (length marker) (text marker) <$>+    (local (\env -> env { envInsideBlock = True+                        , envInlineStart = True+                        , envAfterSpace = True+                        }) $ blockListToMuse note)   where     marker = "[" ++ show num ++ "] " @@ -295,6 +308,12 @@   substitute "</verbatim>" "<</verbatim><verbatim>/verbatim>" s ++   "</verbatim>" +-- | Replace newlines with spaces+replaceNewlines :: String -> String+replaceNewlines ('\n':xs) = ' ':replaceNewlines xs+replaceNewlines (x:xs) = x:replaceNewlines xs+replaceNewlines [] = []+ startsWithMarker :: (Char -> Bool) -> String -> Bool startsWithMarker f (' ':xs) = startsWithMarker f xs startsWithMarker f (x:xs) =@@ -321,17 +340,29 @@         s (_:xs) = p xs         s [] = False -conditionalEscapeString :: Bool -> String -> String-conditionalEscapeString isInsideLinkDescription s =-  if any (`elem` ("#*<=|" :: String)) s ||-     "::" `isInfixOf` s ||-     "~~" `isInfixOf` s ||-     "[[" `isInfixOf` s ||-     ("]" `isInfixOf` s && isInsideLinkDescription) ||-     containsFootnotes s-    then escapeString s-    else s+-- | Return True if string should be escaped with <verbatim> tags+shouldEscapeString :: PandocMonad m+                   => String+                   -> Muse m Bool+shouldEscapeString s = do+  insideLink <- asks envInsideLinkDescription+  return $ null s ||+           any (`elem` ("#*<=|" :: String)) s ||+           "::" `isInfixOf` s ||+           "~~" `isInfixOf` s ||+           "[[" `isInfixOf` s ||+           ("]" `isInfixOf` s && insideLink) ||+           containsFootnotes s +conditionalEscapeString :: PandocMonad m+                        => String+                        -> Muse m String+conditionalEscapeString s = do+  shouldEscape <- shouldEscapeString s+  return $ if shouldEscape+             then escapeString s+             else s+ -- Expand Math and Cite before normalizing inline list preprocessInlineList :: PandocMonad m                      => [Inline]@@ -389,6 +420,19 @@ fixNotes (SoftBreak : n@Note{} : rest) = Str " " : n : fixNotes rest fixNotes (x:xs) = x : fixNotes xs +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] = stringStartsWithSpace $ reverse s+endsWithSpace (_:xs) = endsWithSpace xs+endsWithSpace [] = False+ urlEscapeBrackets :: String -> String urlEscapeBrackets (']':xs) = '%':'5':'D':urlEscapeBrackets xs urlEscapeBrackets (x:xs) = x:urlEscapeBrackets xs@@ -397,22 +441,33 @@ isHorizontalRule :: String -> Bool isHorizontalRule s = length s >= 4 && all (== '-') s -startsWithSpace :: String -> Bool-startsWithSpace (x:_) = isSpace x-startsWithSpace [] = False+stringStartsWithSpace :: String -> Bool+stringStartsWithSpace (x:_) = isSpace x+stringStartsWithSpace "" = False  fixOrEscape :: Bool -> Inline -> Bool fixOrEscape sp (Str "-") = sp-fixOrEscape sp (Str ";") = not sp-fixOrEscape _ (Str ">") = True+fixOrEscape sp (Str s@('-':x:_)) = (sp && isSpace x) || isHorizontalRule s+fixOrEscape sp (Str (";")) = not sp+fixOrEscape sp (Str (';':x:_)) = not sp && isSpace x+fixOrEscape _ (Str (">")) = True+fixOrEscape _ (Str ('>':x:_)) = isSpace x fixOrEscape sp (Str s) = (sp && (startsWithMarker isDigit s ||                                 startsWithMarker isAsciiLower s ||                                 startsWithMarker isAsciiUpper s))-                         || isHorizontalRule s || startsWithSpace s+                         || stringStartsWithSpace s fixOrEscape _ Space = True fixOrEscape _ SoftBreak = True fixOrEscape _ _ = False +inlineListStartsWithAlnum :: PandocMonad m+                          => [Inline]+                          -> Muse m Bool+inlineListStartsWithAlnum (Str s:_) = do+  esc <- shouldEscapeString s+  return $ esc || isAlphaNum (head s)+inlineListStartsWithAlnum _ = return False+ -- | Convert list of Pandoc inline elements to Muse renderInlineList :: PandocMonad m                  => [Inline]@@ -424,86 +479,159 @@   start <- asks envInlineStart   afterSpace <- asks envAfterSpace   topLevel <- asks envTopLevel-  r <- inlineToMuse x+  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 (text "<verbatim></verbatim>" <> r <> lst')     else pure (r <> lst')  -- | Normalize and convert list of Pandoc inline elements to Muse.-inlineListToMuse'' :: PandocMonad m-                   => Bool-                   -> [Inline]-                   -> Muse m Doc-inlineListToMuse'' start lst = do-  lst' <- (normalizeInlineList . fixNotes) <$> preprocessInlineList (map (removeKeyValues . replaceSmallCaps) lst)-  topLevel <- asks envTopLevel-  afterSpace <- asks envAfterSpace-  local (\env -> env { envInlineStart = start-                     , envAfterSpace = afterSpace || (start && not topLevel)-                     }) $ renderInlineList lst'+inlineListToMuse :: PandocMonad m+                 => [Inline]+                 -> Muse m Doc+inlineListToMuse lst = do+  lst' <- normalizeInlineList . fixNotes <$> preprocessInlineList (map (removeKeyValues . replaceSmallCaps) lst)+  insideAsterisks <- asks envInsideAsterisks+  modify $ \st -> st { stUseTags = False } -- Previous character is likely a '>' or some other markup+  local (\env -> env { envNearAsterisks = insideAsterisks }) $ renderInlineList lst'  inlineListToMuse' :: PandocMonad m => [Inline] -> Muse m Doc-inlineListToMuse' = inlineListToMuse'' True--inlineListToMuse :: PandocMonad m => [Inline] -> Muse m Doc-inlineListToMuse = inlineListToMuse'' False+inlineListToMuse' lst = do+  topLevel <- asks envTopLevel+  afterSpace <- asks envAfterSpace+  local (\env -> env { envInlineStart = True+                     , envAfterSpace = afterSpace || not topLevel+                     }) $ inlineListToMuse lst  -- | Convert Pandoc inline element to Muse. inlineToMuse :: PandocMonad m              => Inline              -> Muse m Doc inlineToMuse (Str str) = do-  insideLink <- asks envInsideLinkDescription-  return $ text $ conditionalEscapeString insideLink str+  escapedStr <- conditionalEscapeString $ replaceNewlines str+  let useTags = isAlphaNum $ last escapedStr -- escapedStr is never empty because empty strings are escaped+  modify $ \st -> st { stUseTags = useTags }+  return $ text escapedStr+inlineToMuse (Emph [Strong lst]) = do+  useTags <- gets stUseTags+  let lst' = normalizeInlineList lst+  if useTags+    then do contents <- local (\env -> env { envInsideAsterisks = True }) $ inlineListToMuse lst'+            modify $ \st -> st { stUseTags = False }+            return $ "<em>**" <> contents <> "**</em>"+    else if null lst' || startsWithSpace lst' || endsWithSpace lst'+           then do+             contents <- local (\env -> env { envInsideAsterisks = False }) $ inlineListToMuse lst'+             modify $ \st -> st { stUseTags = True }+             return $ "*<strong>" <> contents <> "</strong>*"+           else do+             contents <- local (\env -> env { envInsideAsterisks = True }) $ inlineListToMuse lst'+             modify $ \st -> st { stUseTags = True }+             return $ "***" <> contents <> "***" inlineToMuse (Emph lst) = do-  contents <- inlineListToMuse lst-  return $ "<em>" <> contents <> "</em>"+  useTags <- gets stUseTags+  let lst' = normalizeInlineList lst+  if useTags || null lst' || startsWithSpace lst' || endsWithSpace lst'+    then do contents <- inlineListToMuse lst'+            return $ "<em>" <> contents <> "</em>"+    else do contents <- local (\env -> env { envInsideAsterisks = True }) $ inlineListToMuse lst'+            modify $ \st -> st { stUseTags = True }+            return $ "*" <> contents <> "*"+inlineToMuse (Strong [Emph lst]) = do+  useTags <- gets stUseTags+  let lst' = normalizeInlineList lst+  if useTags+    then do contents <- local (\env -> env { envInsideAsterisks = True }) $ inlineListToMuse lst'+            modify $ \st -> st { stUseTags = False }+            return $ "<strong>*" <> contents <> "*</strong>"+    else if null lst' || startsWithSpace lst' || endsWithSpace lst'+           then do+             contents <- local (\env -> env { envInsideAsterisks = False }) $ inlineListToMuse lst'+             modify $ \st -> st { stUseTags = True }+             return $ "**<em>" <> contents <> "</em>**"+           else do+             contents <- local (\env -> env { envInsideAsterisks = True }) $ inlineListToMuse lst'+             modify $ \st -> st { stUseTags = True }+             return $ "***" <> contents <> "***" 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 do contents <- inlineListToMuse lst'+            modify $ \st -> st { stUseTags = False }+            return $ "<strong>" <> contents <> "</strong>"+    else do contents <- local (\env -> env { envInsideAsterisks = True }) $ inlineListToMuse lst'+            modify $ \st -> st { stUseTags = True }+            return $ "**" <> contents <> "**" 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 {} =   fail "SmallCaps should be expanded before normalization" inlineToMuse (Quoted SingleQuote lst) = do   contents <- inlineListToMuse lst+  modify $ \st -> st { stUseTags = False }   return $ "‘" <> contents <> "’" inlineToMuse (Quoted DoubleQuote lst) = do   contents <- inlineListToMuse lst+  modify $ \st -> st { stUseTags = False }   return $ "“" <> contents <> "”" inlineToMuse Cite {} =   fail "Citations should be expanded before normalization"-inlineToMuse (Code _ str) = return $-  "<code>" <> text (substitute "</code>" "<</code><code>/code>" str) <> "</code>"+inlineToMuse (Code _ str) = do+  useTags <- gets stUseTags+  modify $ \st -> st { stUseTags = False }+  return $ if useTags || null str || '=' `elem` str || isSpace (head str) || isSpace (last str)+             then "<code>" <> text (substitute "</code>" "<</code><code>/code>" str) <> "</code>"+             else "=" <> text str <> "=" inlineToMuse Math{} =   fail "Math should be expanded before normalization"-inlineToMuse (RawInline (Format f) str) =+inlineToMuse (RawInline (Format f) str) = do+  modify $ \st -> st { stUseTags = False }   return $ "<literal style=\"" <> text f <> "\">" <> text str <> "</literal>" inlineToMuse LineBreak = do   oneline <- asks envOneLine+  modify $ \st -> st { stUseTags = False }   return $ if oneline then "<br>" else "<br>" <> cr-inlineToMuse Space = return space+inlineToMuse Space = do+  modify $ \st -> st { stUseTags = False }+  return space inlineToMuse SoftBreak = do   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 ->+        [Str x] | escapeURI x == src -> do+             modify $ \st -> st { stUseTags = False }              return $ "[[" <> text (escapeLink x) <> "]]"         _ -> do contents <- local (\env -> env { envInsideLinkDescription = True }) $ inlineListToMuse txt+                modify $ \st -> st { stUseTags = False }                 return $ "[[" <> text (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@@ -514,11 +642,12 @@ inlineToMuse (Image attr@(_, classes, _) inlines (source, title)) = do   opts <- asks envOptions   alt <- local (\env -> env { envInsideLinkDescription = True }) $ inlineListToMuse inlines-  let title' = if null title-                  then if null inlines-                          then ""-                          else "[" <> alt <> "]"-                  else "[" <> text (conditionalEscapeString True title) <> "]"+  title' <- if null title+            then if null inlines+                 then return ""+                 else return $ "[" <> alt <> "]"+            else do s <- local (\env -> env { envInsideLinkDescription = True }) $ conditionalEscapeString title+                    return $ "[" <> text s <> "]"   let width = case dimension Width attr of                 Just (Percent x) | isEnabled Ext_amuse opts -> " " ++ show (round x :: Integer)                 _ -> ""@@ -528,11 +657,14 @@   let rightalign = if "align-right" `elem` classes                    then " r"                    else ""+  modify $ \st -> st { stUseTags = False }   return $ "[[" <> text (urlEscapeBrackets source ++ width ++ leftalign ++ rightalign) <> "]" <> title' <> "]" inlineToMuse (Note contents) = do   -- add to notes in state   notes <- gets stNotes-  modify $ \st -> st { stNotes = contents:notes }+  modify $ \st -> st { stNotes = contents:notes+                     , stUseTags = False+                     }   let ref = show $ length notes + 1   return $ "[" <> text ref <> "]" inlineToMuse (Span (anchor,names,_) inlines) = do@@ -540,6 +672,7 @@   let anchorDoc = if null anchor                      then mempty                      else text ('#':anchor) <> space+  modify $ \st -> st { stUseTags = False }   return $ anchorDoc <> (if null inlines && not (null anchor)                          then mempty                          else (if null names
src/Text/Pandoc/Writers/ODT.hs view
@@ -189,8 +189,8 @@        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@(Percent _), Nothing) -> [("rel-width", show w),("rel-height", "scale"),("width", show ptX ++ "pt"),("height", show ptY ++ "pt")]+               (Nothing, Just h@(Percent _)) -> [("rel-width", "scale"),("rel-height", show h),("width", show ptX ++ "pt"),("height", show ptY ++ "pt")]                (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")]
src/Text/Pandoc/Writers/OpenDocument.hs view
@@ -506,7 +506,9 @@                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" ++ show id') : getDims kvs) $
src/Text/Pandoc/Writers/Org.hs view
@@ -109,7 +109,7 @@                , ('\x2013',"--")                , ('\x2019',"'")                , ('\x2026',"...")-               ] ++ backslashEscapes "^_"+               ]  isRawFormat :: Format -> Bool isRawFormat f =
src/Text/Pandoc/Writers/RST.hs view
@@ -211,11 +211,26 @@            => Block         -- ^ Block element            -> RST m Doc blockToRST Null = return empty-blockToRST (Div attr bs) = do+blockToRST (Div ("",["admonition-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+                          -> ".. " <> text cl <> "::"+                        cls -> ".. container::" <> space <>+                                   text (unwords (filter (/= "container") cls))+  return $ blankline $$+           admonition $$+           (if null ident+               then blankline+               else "   :name: " <> text 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@@ -238,6 +253,7 @@   linesToLineBlock lns blockToRST (RawBlock f@(Format f') str)   | f == "rst" = return $ text str+  | f == "tex" = blockToRST (RawBlock (Format "latex") str)   | otherwise  = return $ blankline <> ".. raw:: " <>                     text (map toLower f') $+$                     nest 3 (text str) $$ blankline
src/Text/Pandoc/Writers/Shared.hs view
@@ -38,6 +38,7 @@                      , resetField                      , defField                      , tagWithAttrs+                     , isDisplayMath                      , fixDisplayMath                      , unsmartify                      , gridTable@@ -187,8 +188,9 @@   ] <> ">"  isDisplayMath :: Inline -> Bool-isDisplayMath (Math DisplayMath _) = True-isDisplayMath _                    = False+isDisplayMath (Math DisplayMath _)          = True+isDisplayMath (Span _ [Math DisplayMath _]) = True+isDisplayMath _                             = False  stripLeadingTrailingSpace :: [Inline] -> [Inline] stripLeadingTrailingSpace = go . reverse . go . reverse
src/Text/Pandoc/Writers/TEI.hs view
@@ -35,7 +35,6 @@ 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 Text.Pandoc.Definition import Text.Pandoc.Highlighting (languages, languagesByExtension)@@ -48,16 +47,6 @@ 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. writeTEI :: PandocMonad m => WriterOptions -> Pandoc -> m Text writeTEI opts (Pandoc meta blocks) = do@@ -72,13 +61,11 @@                    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'+                 meta   main    <- (render' . vcat) <$> mapM (elementToTEI opts startLvl) elements   let context = defField "body" main               $
src/Text/Pandoc/Writers/Texinfo.hs view
@@ -346,12 +346,9 @@ 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 @@ -389,7 +386,7 @@ inlineListToTexinfo :: PandocMonad m                     => [Inline]  -- ^ Inlines to convert                     -> TI m Doc-inlineListToTexinfo lst = mapM inlineToTexinfo lst >>= return . hcat+inlineListToTexinfo lst = hcat <$> mapM inlineToTexinfo lst  -- | Convert list of inline elements to Texinfo acceptable for a node name. inlineListForNode :: PandocMonad m@@ -411,10 +408,10 @@   inlineListToTexinfo lst  inlineToTexinfo (Emph lst) =-  inlineListToTexinfo lst >>= return . inCmd "emph"+  inCmd "emph" <$> inlineListToTexinfo lst  inlineToTexinfo (Strong lst) =-  inlineListToTexinfo lst >>= return . inCmd "strong"+  inCmd "strong" <$> inlineListToTexinfo lst  inlineToTexinfo (Strikeout lst) = do   modify $ \st -> st{ stStrikeout = True }@@ -430,7 +427,7 @@   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 ++ "}"
src/Text/Pandoc/Writers/Textile.hs view
@@ -73,7 +73,7 @@                  (inlineListToTextile opts) meta   body <- blockListToTextile opts blocks   notes <- gets $ unlines . reverse . stNotes-  let main = pack $ body ++ if null notes then "" else ("\n\n" ++ notes)+  let main = pack $ body ++ if null notes then "" else "\n\n" ++ notes   let context = defField "body" main metadata   case writerTemplate opts of          Nothing  -> return main@@ -154,7 +154,7 @@  blockToTextile opts (Header level (ident,classes,keyvals) inlines) = do   contents <- inlineListToTextile opts inlines-  let identAttr = if null ident then "" else ('#':ident)+  let identAttr = if null ident then "" else '#':ident   let attribs = if null identAttr && null classes                    then ""                    else "(" ++ unwords classes ++ identAttr ++ ")"@@ -382,13 +382,13 @@                    -> [Block]       -- ^ List of block elements                    -> TW m String 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 inlineListToTextile opts lst =-  mapM (inlineToTextile opts) lst >>= return . concat+  concat <$> mapM (inlineToTextile opts) lst  -- | Convert Pandoc inline element to Textile. inlineToTextile :: PandocMonad m => WriterOptions -> Inline -> TW m String
stack.yaml view
@@ -10,11 +10,20 @@     debug: false packages: - '.'+# See https://github.com/haskell-foundation/foundation/pull/503+# We can go back to released foundation when this is fixed.+- location:+    git: https://github.com/jgm/foundation+    commit: '4294e39'+  subdirs:+  - foundation+  extra-dep: true extra-deps:-- pandoc-citeproc-0.14.3.1+- pandoc-citeproc-0.14.4 - haddock-library-1.6.0 - HsYAML-0.1.1.1-- network-2.7.0.2+- texmath-0.11.1+- yaml-0.9.0 ghc-options:    "$locals": -fhide-source-paths -XNoImplicitPrelude-resolver: lts-12.0+resolver: lts-12.6
test/Tests/Readers/HTML.hs view
@@ -4,11 +4,14 @@  import Prelude import Data.Text (Text)+import qualified Data.Text as T import Test.Tasty+import Test.Tasty.QuickCheck import Tests.Helpers import Text.Pandoc import Text.Pandoc.Arbitrary () import Text.Pandoc.Builder+import Text.Pandoc.Walk (walk)  html :: Text -> Pandoc html = purely $ readHtml def@@ -16,6 +19,25 @@ 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 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.pack . (++ "\n") . T.unpack .+                  purely (writeHtml5String def { writerWrapText = WrapPreserve })+ tests :: [TestTree] tests = [ testGroup "base tag"           [ test html "simple" $@@ -53,4 +75,5 @@           , 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"))           ]+        , testProperty "Round trip" roundTrip         ]
test/Tests/Readers/Muse.hs view
@@ -39,9 +39,9 @@  -- Demand that any AST produced by Muse reader and written by Muse writer can be read back exactly the same way. -- Currently we remove tables and compare first rewrite to the second.-roundTrip :: Block -> Bool+roundTrip :: Blocks -> Bool roundTrip b = d' == d''-  where d = walk makeRoundTrip $ Pandoc nullMeta [b]+  where d = walk makeRoundTrip $ Pandoc nullMeta $ toList b         d' = rewrite d         d'' = rewrite d'         rewrite = amuse . T.pack . (++ "\n") . T.unpack .@@ -62,6 +62,14 @@         "*Foo bar*" =?>         para (emph . spcSep $ ["Foo", "bar"]) +      -- Emacs Muse allows this+      , "Newline in the beginning of emphasis" =:+        "*\nFoo bar*" =?>+        para (emph ("Foo" <> space <> "bar"))+      , "Newline in the end of emphasis" =:+        "*Foo bar\n*" =?>+        para (emph ("Foo" <> space <> "bar"))+       , "Comma after closing *" =:         "Foo *bar*, baz" =?>         para ("Foo " <> emph "bar" <> ", baz")@@ -74,6 +82,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"])@@ -243,7 +255,7 @@         ]       ] -  , testGroup "Blocks" $+  , testGroup "Blocks"       [ testProperty "Round trip" roundTrip       , "Block elements end paragraphs" =:         T.unlines [ "First paragraph"@@ -403,6 +415,12 @@                   , "</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 [ "{{{"@@ -607,6 +625,18 @@           T.unlines [ "* Foo"                     , "bar"                     ] =?> header 1 "Foo\nbar"+        , 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" =:@@ -990,7 +1020,7 @@                               , para "c"                               ]                     ]-      , "List continuation afeter nested list" =:+      , "List continuation after nested list" =:          T.unlines            [ " - - foo"            , ""@@ -1353,7 +1383,8 @@           , "   <verse>"           , "   </quote>"           , "   </verse>"+          , "</quote>"           ] =?>-        para "<quote>" <> bulletList [ para "Foo" <> para "</quote>" <> para "bar" <> lineBlock [ "</quote>" ] ]+        blockQuote (bulletList [ para "Foo" <> para "</quote>" <> para "bar" <> lineBlock [ "</quote>" ] ])       ]   ]
test/Tests/Readers/Org/Block/Header.hs view
@@ -181,4 +181,42 @@                 , "  :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"+    ]   ]
test/Tests/Readers/Org/Directive.hs view
@@ -150,6 +150,29 @@                   , "* Headline :hello:world:"                   ] =?>         headerWith ("headline", [], mempty) 1 "Headline"++    , 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 "Include"
test/Tests/Writers/HTML.hs view
@@ -43,4 +43,9 @@             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><dt></dt><dd><p>foo bar</p></dd></dl>"+          ]         ]
test/Tests/Writers/Muse.hs view
@@ -275,7 +275,7 @@                unlines [ "#bar"                        , "** Foo"                       ]-            , "empty heading" =: header 4 (mempty) =?> "**** <verbatim></verbatim>"+            , "empty heading" =: header 4 mempty =?> "**** <verbatim></verbatim>"             ]           , "horizontal rule" =: horizontalRule =?> "----"           , "escape horizontal rule" =: para (text "----") =?> "<verbatim></verbatim>----"@@ -283,6 +283,7 @@           , "don't escape horizontal inside paragraph" =: para (text "foo ---- bar") =?> "foo ---- bar"           , "escape nonbreaking space" =: para (text "~~") =?> "<verbatim>~~</verbatim>"           , "escape > in the beginning of line" =: para (text "> foo bar") =?> "<verbatim></verbatim>> foo bar"+          , "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"]@@ -341,36 +342,95 @@             , "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 $ text "foo") <>-                           (para $ text "- bar")+              bulletList [ para (text "foo") <>+                           para (text "- 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 (text "- 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" =: text "foo" <> softbreak <> text "; bar" =?> "foo\n<verbatim></verbatim>; bar"             , "escape ; after linebreak" =: text "foo" <> linebreak <> text "; bar" =?> "foo<br>\n<verbatim></verbatim>; bar"             , "do not escape ; inside paragraph" =: text "foo ; bar" =?> "foo ; bar"+            , "escape newlines" =: str "foo\nbar" =?> "foo bar"             ]           , testGroup "emphasis"-            [ "emph" =: emph (text "foo") =?> "<em>foo</em>"-            , "strong" =: strong (text "foo") =?> "<strong>foo</strong>"+            [ "emphasis" =: emph (text "foo") =?> "*foo*"+            , "emphasis inside word" =: text "foo" <> emph (text "bar") <> text "baz" =?> "foo<em>bar</em>baz"+            , "emphasis before comma" =: emph (text "foo") <> text ", bar" =?> "*foo*, bar"+            , "emphasis before period" =: emph (text "foobar") <> text "." =?> "*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 (text "foo") =?> "**foo**"+            , "strong inside word" =: text "foo" <> strong (text "bar") <> text "baz" =?> "foo<strong>bar</strong>baz"+            , "strong emphasis" =: strong (emph (text "foo")) =?> "***foo***"+            , "strong after emphasis" =: emph (text "foo") <> strong (text "bar") =?> "*foo*<strong>bar</strong>"+            , "strong emphasis after emphasis" =: emph (text "foo") <> strong (emph (text "bar")) =?> "*foo*<strong>*bar*</strong>"+            , "strong in the end of emphasis" =: emph (text "foo" <> strong (text "bar")) =?> "*foo<strong>bar</strong>*"             , "strikeout" =: strikeout (text "foo") =?> "<del>foo</del>"+            , "space at the beginning of emphasis" =: emph (text " foo") =?> "<em> foo</em>"+            , "space at the end of emphasis" =: emph (text "foo ") =?> "<em>foo </em>"+            , "space at the beginning of strong" =: strong (text " foo") =?> "<strong> foo</strong>"+            , "space at the end of strong" =: strong (text "foo ") =?> "<strong>foo </strong>"+            , "space at the beginning of strong emphasis" =: strong (emph (text " foo")) =?> "**<em> foo</em>**"+            , "space at the end of strong emphasis" =: strong (emph (text "foo ")) =?> "**<em>foo </em>**"+            , "space at the beginning of emphasiszed strong" =: emph (strong (text " foo")) =?> "*<strong> foo</strong>*"+            , "space at the end of emphasized strong" =: emph (strong (text "foo ")) =?> "*<strong>foo </strong>*"             ]           , "superscript" =: superscript (text "foo") =?> "<sup>foo</sup>"           , "subscript" =: subscript (text "foo") =?> "<sub>foo</sub>"-          , "smallcaps" =: smallcaps (text "foo") =?> "<em>foo</em>"-          , "smallcaps near emphasis" =: emph (str "foo") <> smallcaps (str "bar") =?> "<em>foobar</em>"+          , "smallcaps" =: smallcaps (text "foo") =?> "*foo*"+          , "smallcaps near emphasis" =: emph (str "foo") <> smallcaps (str "bar") =?> "*foobar*"           , "single quoted" =: singleQuoted (text "foo") =?> "‘foo’"           , "double quoted" =: doubleQuoted (text "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 with attributes" =: codeWith ("",["haskell"],[]) "foo" <> code "bar" =?> "<code>foobar</code>"-            , "normalization" =: code "</co" <> code "de>" =?> "<code><</code><code>/code></code>"-            , "normalization with empty string" =: code "</co" <> str "" <> 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"@@ -385,7 +445,7 @@           , testGroup "math"             [ "inline math" =: math "2^3" =?> "2<sup>3</sup>"             , "display math" =: displayMath "2^3" =?> "2<sup>3</sup>"-            , "multiple letters in inline math" =: math "abc" =?> "<em>abc</em>"+            , "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" <> text ", " <> displayMath "3^2" =?> "5<sub>4</sub>, 3<sup>2</sup>"             ]@@ -441,11 +501,11 @@                               =?> "<class name=\"foobar\">Some text</class>"           , "span without class" =: spanWith ("",[],[]) (text "Some text")                                  =?> "<class>Some text</class>"-          , "span with anchor" =: spanWith ("anchor", [], []) (mempty) <> (text "Foo bar")+          , "span with anchor" =: spanWith ("anchor", [], []) mempty <> text "Foo bar"                                =?> "#anchor Foo bar"-          , "empty span with anchor" =: spanWith ("anchor", [], []) (mempty)+          , "empty span with anchor" =: spanWith ("anchor", [], []) mempty                                      =?> "#anchor"-          , "empty span without class and anchor" =: spanWith ("", [], []) (mempty)+          , "empty span without class and anchor" =: spanWith ("", [], []) mempty                                                   =?> "<class></class>"           , "span with class and anchor" =: spanWith ("anchor", ["foo"], []) (text "bar")                                          =?> "#anchor <class name=\"foo\">bar</class>"@@ -461,7 +521,7 @@                     "<em>foo</em>bar"             , "emph quoted" =:                 para (doubleQuoted (emph (text "foo"))) =?>-                    "“<em>foo</em>”"+                    "“*foo*”"             , "strong word before" =:                 para (text "foo" <> strong (text "bar")) =?>                     "foo<strong>bar</strong>"@@ -470,7 +530,7 @@                     "<strong>foo</strong>bar"             , "strong quoted" =:                 para (singleQuoted (strong (text "foo"))) =?>-                    "‘<strong>foo</strong>’"+                    "‘**foo**’"             ]          ]        ]
+ test/command/1126.md view
@@ -0,0 +1,29 @@+```+% 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}+```
test/command/3534.md view
@@ -21,3 +21,25 @@ [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 "."]]+```
test/command/3558.md view
@@ -6,7 +6,7 @@  \endmulti ^D-[RawBlock (Format "latex") "\\multi"+[RawBlock (Format "tex") "\\multi" ,Para [Str "hello"]-,RawBlock (Format "latex") "\\endmulti"]+,RawBlock (Format "tex") "\\endmulti"] ```
test/command/3804.md view
@@ -2,5 +2,5 @@ % 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}"] ```
test/command/3947.md view
@@ -6,6 +6,6 @@  	Another Code block ^D-[RawBlock (Format "latex") "\\newpage"+[RawBlock (Format "tex") "\\newpage" ,CodeBlock ("",[],[]) "Code block\n\nAnother Code block"] ```
test/command/4056.md view
@@ -5,7 +5,7 @@ \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}"] ```  ```
test/command/4159.md view
@@ -3,6 +3,6 @@ \newcommand{\gen}{a\ Gen\ b} abc ^D-[RawBlock (Format "latex") "\\newcommand{\\gen}{a\\ Gen\\ b}"+[RawBlock (Format "tex") "\\newcommand{\\gen}{a\\ Gen\\ b}" ,Para [Str "abc"]] ```
+ test/command/4768.md view
@@ -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+```
test/command/4781.md view
@@ -7,7 +7,7 @@ *But not here* ^D [Para [Str "Markdown",Space,Str "parsed",Space,Emph [Str "here"]]-,RawBlock (Format "latex") "\\include{command/bar}"+,RawBlock (Format "tex") "\\include{command/bar}" ,Para [Emph [Str "But",Space,Str "not",Space,Str "here"]]] ``` 
+ test/command/4832.md view
@@ -0,0 +1,21 @@+```+% pandoc -f latex -t native+\url{http://example.com/foo%20bar.htm}+^D+[Para [Link ("",[],[]) [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 ("",[],[]) [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","")]]+```+
+ test/command/4833.md view
@@ -0,0 +1,20 @@+```+pandoc -f native -t rst+[Div ("",["warning"],[])+ [Div ("",["admonition-title"],[])+  [Para [Str "Warning"]]+ ,Para [Str "Hi"]]]+^D+.. warning::++   Hi+```+```+pandoc -f native -t rst+[Div ("",["unknown"],[])+ [Para [Str "Hi"]]]+^D+.. container:: unknown++   Hi+```
+ test/command/4842.md view
@@ -0,0 +1,6 @@+```+pandoc -f latex -t native+\l+^D+[Para [Str "\322"]]+```
+ test/command/4845.md view
@@ -0,0 +1,6 @@+```+% 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"]]+```
+ test/command/4848.md view
@@ -0,0 +1,59 @@+```+% 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."]]+```+
+ test/command/4860.md view
@@ -0,0 +1,9 @@+```+% 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 "."]]+```
+ test/command/4877.md view
@@ -0,0 +1,13 @@+```+% 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}"]]+```
+ test/command/4908.md view
@@ -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+```
test/command/adjacent_latex_blocks.md view
@@ -4,6 +4,6 @@  \listoftables ^D-[RawBlock (Format "latex") "\\listoffigures"-,RawBlock (Format "latex") "\\listoftables"]+[RawBlock (Format "tex") "\\listoffigures"+,RawBlock (Format "tex") "\\listoftables"] ```
test/command/hspace.md view
@@ -8,7 +8,7 @@ \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,7 +32,7 @@ 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}"] ```  ```@@ -51,6 +51,6 @@ there ^D [Para [Str "hi"]-,RawBlock (Format "latex") "\\hspace{1em}"+,RawBlock (Format "tex") "\\hspace{1em}" ,Para [Str "there"]] ```
test/command/macros.md view
@@ -24,18 +24,18 @@ % pandoc -f latex -t latex \let\a\b \newcommand{\b}{\emph{ouk}}-\a+\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 ```  ```
test/command/refs.md view
@@ -43,8 +43,51 @@ Figure \ref{fig:Logo} illustrated the SVG logo ^D [Para [Image ("fig:Logo",[],[]) [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"]]+,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"]+,Para [Image ("fig:Logo",[],[]) [Str "Logo",Span ("",[],[("label","fig:Logo")]) []] ("command/SVG_logo.svg","fig:")]+,Para [Image ("fig:Logo2",[],[]) [Str "Logo2",Span ("",[],[("label","fig:Logo2")]) []] ("command/SVG_logo2.svg","fig:")]+,Header 1 ("two",[],[]) [Str "Two"]+,Header 2 ("subone",[],[]) [Str "Subone"]+,Para [Image ("fig:Logo3",[],[]) [Str "Logo3",Span ("",[],[("label","fig:Logo3")]) []] ("command/SVG_logo3.svg","fig:")]+,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
test/command/write18.md view
@@ -3,7 +3,7 @@ % pandoc -t native \write18{git --version} ^D-[RawBlock (Format "latex") "\\write18{git --version}"]+[RawBlock (Format "tex") "\\write18{git --version}"] ```  ```
+ test/command/yaml-metadata-blocks.md view
@@ -0,0 +1,63 @@+```+% 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+emtpy: []+nested:+  int: 8+  float: 2.5+  bool: true+  more: False+  nothing: null+  emtpy: []+  scientific: 3.7e-5+---+^D+Pandoc (Meta {unMeta = fromList [("bool",MetaBool True),("emtpy",MetaList []),("float",MetaInlines [Str "1.5"]),("int",MetaInlines [Str "7"]),("more",MetaBool False),("nested",MetaMap (fromList [("bool",MetaBool True),("emtpy",MetaList []),("float",MetaInlines [Str "2.5"]),("int",MetaInlines [Str "8"]),("more",MetaBool False),("nothing",MetaInlines [Str "null"]),("scientific",MetaInlines [Str "3.7e-5"])])),("nothing",MetaInlines [Str "null"]),("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")]})+[]+```
+ test/command/yaml-metadata.yaml view
@@ -0,0 +1,4 @@+---+title: file+other: _markdown_ value+---
test/markdown-reader-more.native view
@@ -3,10 +3,11 @@ ,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"-,RawBlock (Format "context") "\\start[a2]\n\\start[a2]\n\\stop[a2]\n\\stop[a2]"+,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 "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}"+,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")]@@ -55,7 +56,7 @@ ,OrderedList (3,Example,TwoParens)  [[Plain [Str "Third",Space,Str "example."]]] ,Header 2 ("macros",[],[]) [Str "Macros"]-,RawBlock (Format "latex") "\\newcommand{\\tuple}[1]{\\langle #1 \\rangle}"+,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","")]
test/testsuite.native view
@@ -324,7 +324,7 @@  ,[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}"+,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:"]
test/writer.context view
@@ -706,6 +706,12 @@  Here's a LaTeX table: +\begin{tabular}{|l|l|}\hline+Animal & Number \\ \hline+Dog    & 2      \\+Cat    & 1      \\ \hline+\end{tabular}+ \thinrule  \section[title={Special Characters},reference={special-characters}]
test/writer.haddock view
@@ -455,14 +455,14 @@ #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: 
test/writer.html5 view
@@ -19,7 +19,7 @@   <![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>
test/writer.muse view
@@ -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 @@ -271,18 +271,18 @@  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: @@ -331,7 +331,7 @@ <td> </literal> -This is <em>emphasized</em>+This is *emphasized*  <literal style="html"> </td>@@ -341,7 +341,7 @@ <td> </literal> -And this is <strong>strong</strong>+And this is **strong**  <literal style="html"> </td>@@ -461,27 +461,25 @@  * 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. @@ -500,8 +498,8 @@  ‘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. @@ -515,26 +513,25 @@   - <literal style="tex">\cite[22-23]{smith.1899}</literal>  - <verbatim>2 + 2 = 4</verbatim>- - <em>x</em> ∈ <em>y</em>- - <em>α</em> ∧ <em>ω</em>+ - *x* ∈ *y*+ - *α* ∧ *ω*  - 223- - <em>p</em>-Tree+ - *p*-Tree  - Here’s some display math:    <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:-   <em>α</em> + <em>ω</em> × <em>x</em><sup>2</sup>.+ - 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      \\@@ -669,7 +666,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/>@@ -689,7 +686,7 @@  * Footnotes -Here is a footnote reference,[1] and another.[2] This should <em>not</em> be a+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] @@ -716,9 +713,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 [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. 
test/writer.native view
@@ -324,7 +324,7 @@  ,[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}"+,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:"]
test/writer.org view
@@ -584,7 +584,7 @@ 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.+spaces: a^b c^d, a~b c~d.  -------------- @@ -674,7 +674,7 @@  Asterisk: * -Underscore: \_+Underscore: _  Left brace: { @@ -724,7 +724,7 @@  [[/url/][URL and title]] -[[/url/with_underscore][with\_underscore]]+[[/url/with_underscore][with_underscore]]  [[mailto:nobody@nowhere.net][Email link]] @@ -816,7 +816,7 @@   :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
test/writer.rst view
@@ -385,53 +385,23 @@  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: @@ -477,15 +447,9 @@  Here’s a simple block: -.. raw:: html--   <div>--foo--.. raw:: html+.. container:: -   </div>+   foo  This should be a code block, though: @@ -503,31 +467,13 @@  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: 
test/writer.tei view
@@ -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>