git.iko.soy/typeable/pandoc
on master help sign in
382 files changed+12228−8471
since splitsnapshots
unifiedsplit
.circleci/config.yml+1−1 .editorconfig+8 .github/ISSUE_TEMPLATE−11 .github/ISSUE_TEMPLATE/bug_report.md+25 .github/ISSUE_TEMPLATE/config.yml+9 .github/ISSUE_TEMPLATE/feature_request.md+21 .github/workflows/ci.yml+33−8 .github/workflows/nightly.yml+9−2 .github/workflows/release-candidate.yml−1 .hlint.yaml+3−5 AUTHORS.md+18 CONTRIBUTING.md+16−11 INSTALL.md+4 MANUAL.txt+218−71 Makefile+28−15 README.md+6−6 RELEASE-CHECKLIST+1 SECURITY.md+12 benchmark/benchmark-pandoc.hs+13−12 cabal.project+9−8 changelog.md+982−105 data/docx/word/settings.xml+6−16 data/templates/article.jats_publishing+1−1 data/templates/default.context+7−3 data/templates/default.dzslides+1−1 data/templates/default.jats_articleauthoring+1−1 data/templates/default.latex+50−25 data/templates/default.revealjs+79−129 data/templates/default.s5+3 data/templates/default.slideous+7 data/templates/default.slidy+5 data/templates/styles.html+2−1 doc/epub.md+9−2 doc/faqs.md+128 doc/filters.md+2 doc/jats.md+9 doc/libraries.md+63 doc/lua-filters.md+2−2 doc/org.md+16−2 doc/using-the-pandoc-api.md+25−12 linux/make_artifacts.sh+19−7 man/pandoc.1+286−61 pandoc.cabal+52−32 src/Text/Pandoc/App.hs+40−21 src/Text/Pandoc/App/CommandLineOptions.hs+30−8 src/Text/Pandoc/App/FormatHeuristics.hs+13−7 src/Text/Pandoc/App/Opt.hs+145−57 src/Text/Pandoc/Asciify.hs+13−390 src/Text/Pandoc/BCP47.hs−112 src/Text/Pandoc/Citeproc.hs+75−56 src/Text/Pandoc/Citeproc/BibTeX.hs+25−15 src/Text/Pandoc/Citeproc/Data.hs+7−6 src/Text/Pandoc/Citeproc/Locator.hs+20−4 src/Text/Pandoc/Class/CommonState.hs+1−1 src/Text/Pandoc/Class/IO.hs+21−22 src/Text/Pandoc/Class/PandocMonad.hs+24−34 src/Text/Pandoc/Error.hs+23−16 src/Text/Pandoc/Extensions.hs+9−1 src/Text/Pandoc/Highlighting.hs+5−5 src/Text/Pandoc/ImageSize.hs+5−1 src/Text/Pandoc/Logging.hs+32−9 src/Text/Pandoc/Lua/Filter.hs+4−1 src/Text/Pandoc/Lua/Marshaling/AST.hs+77−79 src/Text/Pandoc/Lua/Module/MediaBag.hs+3−3 src/Text/Pandoc/Lua/Module/Pandoc.hs+8−3 src/Text/Pandoc/Lua/Module/Utils.hs+1−1 src/Text/Pandoc/MIME.hs+10 src/Text/Pandoc/MediaBag.hs+45−14 src/Text/Pandoc/Options.hs+17−17 src/Text/Pandoc/PDF.hs+16−3 src/Text/Pandoc/Parsing.hs+360−242 src/Text/Pandoc/Readers.hs+55−48 src/Text/Pandoc/Readers/BibTeX.hs+14−8 src/Text/Pandoc/Readers/CSV.hs+7−7 src/Text/Pandoc/Readers/CommonMark.hs+46−4 src/Text/Pandoc/Readers/Creole.hs+5−6 src/Text/Pandoc/Readers/CslJson.hs+5−4 src/Text/Pandoc/Readers/DocBook.hs+30−15 src/Text/Pandoc/Readers/Docx.hs+59−42 src/Text/Pandoc/Readers/Docx/Combine.hs+5−5 src/Text/Pandoc/Readers/Docx/Parse.hs+121−21 src/Text/Pandoc/Readers/Docx/Util.hs+7 src/Text/Pandoc/Readers/DokuWiki.hs+9−8 src/Text/Pandoc/Readers/FB2.hs+6−3 src/Text/Pandoc/Readers/HTML.hs+48−28 src/Text/Pandoc/Readers/HTML/Table.hs+35−15 src/Text/Pandoc/Readers/Haddock.hs+11−7 src/Text/Pandoc/Readers/Ipynb.hs+5−3 src/Text/Pandoc/Readers/JATS.hs+13−6 src/Text/Pandoc/Readers/Jira.hs+13−9 src/Text/Pandoc/Readers/LaTeX.hs+223−1424 src/Text/Pandoc/Readers/LaTeX/Citation.hs+210 src/Text/Pandoc/Readers/LaTeX/Inline.hs+397 src/Text/Pandoc/Readers/LaTeX/Lang.hs+199−120 src/Text/Pandoc/Readers/LaTeX/Macro.hs+184 src/Text/Pandoc/Readers/LaTeX/Math.hs+221 src/Text/Pandoc/Readers/LaTeX/Parsing.hs+95−7 src/Text/Pandoc/Readers/LaTeX/SIunitx.hs+152−71 src/Text/Pandoc/Readers/LaTeX/Table.hs+378 src/Text/Pandoc/Readers/LaTeX/Types.hs+14−1 src/Text/Pandoc/Readers/Man.hs+18−11 src/Text/Pandoc/Readers/Markdown.hs+284−238 src/Text/Pandoc/Readers/MediaWiki.hs+16−7 src/Text/Pandoc/Readers/Metadata.hs+44−17 src/Text/Pandoc/Readers/Muse.hs+10−9 src/Text/Pandoc/Readers/Native.hs+7−5 src/Text/Pandoc/Readers/OPML.hs+9−4 src/Text/Pandoc/Readers/Odt/Arrows/State.hs+2−2 src/Text/Pandoc/Readers/Odt/ContentReader.hs+12−7 src/Text/Pandoc/Readers/Odt/Generic/XMLConverter.hs+2−2 src/Text/Pandoc/Readers/Odt/StyleReader.hs+8−7 src/Text/Pandoc/Readers/Org.hs+4−7 src/Text/Pandoc/Readers/Org/Blocks.hs+7−4 src/Text/Pandoc/Readers/Org/Inlines.hs+6−5 src/Text/Pandoc/Readers/Org/Parsing.hs+5−5 src/Text/Pandoc/Readers/RST.hs+78−110 src/Text/Pandoc/Readers/Roff.hs+16−18 src/Text/Pandoc/Readers/TWiki.hs+7−27 src/Text/Pandoc/Readers/Textile.hs+94−88 src/Text/Pandoc/Readers/TikiWiki.hs+6−6 src/Text/Pandoc/Readers/Txt2Tags.hs+47−21 src/Text/Pandoc/Readers/Vimwiki.hs+12−7 src/Text/Pandoc/SelfContained.hs+4−7 src/Text/Pandoc/Shared.hs+41−64 src/Text/Pandoc/Sources.hs+195 src/Text/Pandoc/Templates.hs+4 src/Text/Pandoc/Writers.hs+3−3 src/Text/Pandoc/Writers/AsciiDoc.hs+10−4 src/Text/Pandoc/Writers/BibTeX.hs+1−1 src/Text/Pandoc/Writers/ConTeXt.hs+44−38 src/Text/Pandoc/Writers/CslJson.hs+4−3 src/Text/Pandoc/Writers/Docbook.hs+50−7 src/Text/Pandoc/Writers/Docx.hs+60−244 src/Text/Pandoc/Writers/Docx/Table.hs+227 src/Text/Pandoc/Writers/Docx/Types.hs+185 src/Text/Pandoc/Writers/DokuWiki.hs+3−1 src/Text/Pandoc/Writers/EPUB.hs+3−3 src/Text/Pandoc/Writers/GridTable.hs+157 src/Text/Pandoc/Writers/HTML.hs+107−34 src/Text/Pandoc/Writers/Haddock.hs+13−2 src/Text/Pandoc/Writers/JATS.hs+67−44 src/Text/Pandoc/Writers/JATS/References.hs+3−2 src/Text/Pandoc/Writers/JATS/Table.hs+25−5 src/Text/Pandoc/Writers/JATS/Types.hs+12−3 src/Text/Pandoc/Writers/Jira.hs+41−16 src/Text/Pandoc/Writers/LaTeX.hs+50−563 src/Text/Pandoc/Writers/LaTeX/Caption.hs−1 src/Text/Pandoc/Writers/LaTeX/Citation.hs+181 src/Text/Pandoc/Writers/LaTeX/Lang.hs+192 src/Text/Pandoc/Writers/LaTeX/Table.hs+21−8 src/Text/Pandoc/Writers/LaTeX/Types.hs+2−1 src/Text/Pandoc/Writers/LaTeX/Util.hs+275 src/Text/Pandoc/Writers/Man.hs+2−2 src/Text/Pandoc/Writers/Markdown.hs+59−646 src/Text/Pandoc/Writers/Markdown/Inline.hs+616 src/Text/Pandoc/Writers/Markdown/Types.hs+81 src/Text/Pandoc/Writers/Ms.hs+24−8 src/Text/Pandoc/Writers/Muse.hs+6−3 src/Text/Pandoc/Writers/ODT.hs+4−3 src/Text/Pandoc/Writers/OpenDocument.hs+50−54 src/Text/Pandoc/Writers/Org.hs+24−14 src/Text/Pandoc/Writers/Powerpoint.hs+1−1 src/Text/Pandoc/Writers/Powerpoint/Output.hs+43−31 src/Text/Pandoc/Writers/Powerpoint/Presentation.hs+2−3 src/Text/Pandoc/Writers/RST.hs+14−10 src/Text/Pandoc/Writers/RTF.hs+16−10 src/Text/Pandoc/Writers/Shared.hs+18−3 src/Text/Pandoc/Writers/TEI.hs+4−3 src/Text/Pandoc/Writers/Texinfo.hs+22−15 src/Text/Pandoc/Writers/ZimWiki.hs+4−2 src/Text/Pandoc/XML.hs+28−2 src/Text/Pandoc/XML/Light/Proc.hs−1 src/Text/Pandoc/XML/Light/Types.hs+4−4 stack.yaml+11−14 test/Tests/Command.hs+7−14 test/Tests/Helpers.hs+23 test/Tests/Old.hs+3−12 test/Tests/Readers/Docx.hs+25−5 test/Tests/Readers/EPUB.hs+1−1 test/Tests/Readers/HTML.hs+20−5 test/Tests/Readers/Jira.hs+14 test/Tests/Readers/LaTeX.hs+1−18 test/Tests/Readers/Markdown.hs+3−3 test/Tests/Readers/Odt.hs+1 test/Tests/Writers/ConTeXt.hs+122−113 test/Tests/Writers/Docbook.hs+43−6 test/Tests/Writers/Docx.hs+5 test/Tests/Writers/HTML.hs+57−52 test/Tests/Writers/JATS.hs+135−91 test/Tests/Writers/Jira.hs+60−1 test/Tests/Writers/OOXML.hs+3−1 test/command/1279.md+1−1 test/command/2103.md+8 test/command/2874.md+2−2 test/command/3752.md+60 test/command/3792.md+1−1 test/command/4063.md+29 test/command/4164.md+1−1 test/command/4442.md+1−1 test/command/4465.md+15 test/command/5304.md+1−1 test/command/5367.md+6−2 test/command/5519.md+1−1 test/command/6026.md+19 test/command/6541.md+27 test/command/6620.md+3 test/command/6658.md+75 test/command/6709.md+11 test/command/6890.md+2−2 test/command/6925.md+2−2 test/command/6958.md+10 test/command/7041.md+23 test/command/7099.md+1−1 test/command/7129.md+27 test/command/7132.md+10 test/command/7134.md+16 test/command/7145.md+12 test/command/7155.md+15 test/command/7173.md+137 test/command/7208.md+6 test/command/7214.md+28 test/command/7216.md+19 test/command/7266.md+10 test/command/7272.md+27 test/command/7278.md+38 test/command/7282.md+7 test/command/7288.md+40 test/command/7299.md+23 test/command/7321.md+24 test/command/7323.md+29 test/command/7324.md+25 test/command/7339.md+11 test/command/7340.md+6 test/command/7376.md+16 test/command/7394.md+85 test/command/7397.md+14 test/command/7400.md+9 test/command/7416.md+19 test/command/averroes.bib+95 test/command/biblatex-baez-article.md+1−1 test/command/biblatex-baez-online.md+1−1 test/command/biblatex-basic.md+5−3 test/command/biblatex-examples.bib−1674 test/command/biblatex-inproceedings.md+1−1 test/command/biblatex-itzhaki.md+1−1 test/command/biblatex-jaffe.md+2−2 test/command/biblatex-moraux.md+1−1 test/command/biblatex-nussbaum.md−63 test/command/biblatex-quotes.md+1−1 test/command/biblatex-sigfridsson.md+1−1 test/command/biblatex-spiegelberg.md+2−2 test/command/biblatex-test-case-conversion.md+2−2 test/command/biblatex-textnormal.md+1−1 test/command/biblatex-wassenberg.md+1−1 test/command/biblatex-wilde.md+1−1 test/command/chap1/spider.png test/command/chap1/text.md+17 test/command/chap2/spider.png test/command/chap2/text.md+5 test/command/defaults-inheritance-2.md+1−1 test/command/duplicate_attributes.md+7 test/command/mmd-metadata.md+20 test/command/newif.md+55 test/command/pandoc-citeproc-119.md+1−1 test/command/pandoc-citeproc-320a.md+3−3 test/command/pandoc-citeproc-322.md+1−1 test/command/pandoc-citeproc-356.md+2−7 test/command/pandoc-citeproc-65.md+1−1 test/command/pandoc-citeproc-70.md+2−2 test/command/pandoc-citeproc-chicago-author-date.md+7−7 test/command/pandoc-citeproc-chicago-fullnote-bibliography.md+6−7 test/command/svg.md+1−1 test/command/toc.md+2−2 test/command/unicode-collation.md+130 test/docbook-reader.docbook+3−1 test/docx/0_level_headers.native+2−2 test/docx/golden/block_quotes.docx test/docx/golden/codeblock.docx test/docx/golden/comments.docx test/docx/golden/custom_style_no_reference.docx test/docx/golden/custom_style_preserve.docx test/docx/golden/custom_style_reference.docx test/docx/golden/definition_list.docx test/docx/golden/document-properties-short-desc.docx test/docx/golden/document-properties.docx test/docx/golden/headers.docx test/docx/golden/image.docx test/docx/golden/inline_code.docx test/docx/golden/inline_formatting.docx test/docx/golden/inline_images.docx test/docx/golden/link_in_notes.docx test/docx/golden/links.docx test/docx/golden/lists.docx test/docx/golden/lists_continuing.docx test/docx/golden/lists_multiple_initial.docx test/docx/golden/lists_restarting.docx test/docx/golden/nested_anchors_in_header.docx test/docx/golden/notes.docx test/docx/golden/raw-blocks.docx test/docx/golden/raw-bookmarks.docx test/docx/golden/table_one_row.docx test/docx/golden/table_with_list_cell.docx test/docx/golden/tables-default-widths.docx test/docx/golden/tables.docx test/docx/golden/track_changes_deletion.docx test/docx/golden/track_changes_insertion.docx test/docx/golden/track_changes_move.docx test/docx/golden/track_changes_scrubbed_metadata.docx test/docx/golden/unicode.docx test/docx/golden/verbatim_subsuper.docx test/docx/image_vml_as_object.docx test/docx/image_vml_as_object.native+2 test/docx/sdt_elements.native+9−10 test/docx/table_captions_no_field.docx test/docx/table_captions_no_field.native+34 test/docx/table_captions_with_field.docx test/docx/table_captions_with_field.native+54 test/docx/table_header_rowspan.docx test/docx/table_header_rowspan.native+189 test/docx/table_one_header_row.docx test/docx/table_one_header_row.native+18 test/docx/table_one_row.docx test/docx/table_one_row.native+4−4 test/docx/table_variable_width.native+12−17 test/docx/table_with_list_cell.native+3−3 test/docx/tables-default-widths.native+92 test/docx/tables.native+9−9 test/epub/features.native+2−2 test/epub/wasteland.epub test/fb2/images.fb2+1−1 test/fb2/test.jpg test/html-reader.native+2−1 test/jira-reader.native+1−1 test/lhs-test.html+2−1 test/lhs-test.html+lhs+2−1 test/odt/native/tab.native+1 test/odt/odt/tab.odt test/pipe-tables.native+2−10 test/pptx/code-custom_templated.pptx test/pptx/code_templated.pptx test/pptx/document-properties-short-desc_templated.pptx test/pptx/document-properties_templated.pptx test/pptx/endnotes_templated.pptx test/pptx/endnotes_toc_templated.pptx test/pptx/images_templated.pptx test/pptx/inline_formatting_templated.pptx test/pptx/lists_templated.pptx test/pptx/raw_ooxml_templated.pptx test/pptx/reference_depth.pptx test/pptx/remove_empty_slides_templated.pptx test/pptx/slide_breaks_slide_level_1_templated.pptx test/pptx/slide_breaks_templated.pptx test/pptx/slide_breaks_toc_templated.pptx test/pptx/speaker_notes_after_metadata_templated.pptx test/pptx/speaker_notes_afterheader_templated.pptx test/pptx/speaker_notes_afterseps_templated.pptx test/pptx/speaker_notes_templated.pptx test/pptx/start_numbering_at_templated.pptx test/pptx/tables_templated.pptx test/pptx/two_column_templated.pptx test/tables.latex+27−3 test/tables.ms+30 test/tables/nordics.latex+22−4 test/tables/planets.latex+4−4 test/tables/students.latex+10−2 test/test-pandoc.hs+1−2 test/txt2tags.native+1−1 test/writer.context+42−38 test/writer.html4+2−1 test/writer.html5+2−1 test/writer.jats_archiving+37−47 test/writer.jats_articleauthoring+41−49 test/writer.jats_publishing+37−47 test/writer.jira+23−35 test/writer.ms+1−1 test/writer.opml+1−1 test/writer.org+7−7 test/writer.zimwiki+3−3 test/writers-lang-and-dir.context+4 tools/build-arm.sh+110 tools/parseTimings.pl+33 trypandoc/trypandoc.hs+2−5
.circleci/config.yml+1−1
@@ -2,7 +2,7 @@ version: "2.1"
22jobs:
33 build:
44 macos:
5− xcode: 9.4.1
5+ xcode: 11.1.0
66 environment:
77 HOMEBREW_NO_AUTO_UPDATE: 1
88 steps:
.editorconfig+8
@@ -8,6 +8,14 @@ indent_size = 2
88insert_final_newline = true
99trim_trailing_whitespace = true
1010
11+[*.{zip,docx}]
12+charset =
13+end_of_line =
14+indent_style =
15+indent_size =
16+insert_final_newline =
17+trim_trailing_whitespace =
18+
1119[*.{markdown,md}]
1220trim_trailing_whitespace = false
1321
.github/ISSUE_TEMPLATEdeleted−11
@@ -1,11 +0,0 @@
1−Asking a question?
2−Please use the pandoc-discuss mailing list instead:
3−https://groups.google.com/forum/#!forum/pandoc-discuss
4−This tracker is for bug reports and enhancement requests.
5−
6−Reporting a bug?
7−Please include your pandoc version and an example that allows us
8−to reproduce the problem (complete input, exact command line
9−used, expected and actual output). The smaller the example, the
10−better.
11−
.github/ISSUE_TEMPLATE/bug_report.mdnew file+25
@@ -0,0 +1,25 @@
1+---
2+name: Bug report
3+about: Create a report to help us improve
4+title: ''
5+labels: 'bug'
6+assignees: ''
7+
8+---
9+
10+<!--
11+Thank you for reporting an issue! Before you continue, please make sure that you have
12+
13+- searched the issue tracker for similar issues (including closed issues): https://github.com/jgm/pandoc/issues
14+- searched the pandoc-discuss mailing list for solutions: https://groups.google.com/forum/#!forum/pandoc-discuss
15+- reproduced your issue on the latest release of pandoc, or on https://pandoc.org/try
16+
17+Note that this bug tracker is for reporting bugs, not asking questions. For questions, use the pandoc-discuss mailing list.
18+-->
19+
20+**Explain the problem.**
21+Include the exact command line you used and all inputs necessary to reproduce the issue. Please create as minimal an example as possible, to help the maintainers isolate the problem. Explain the output you received and how it differs from what you expected.
22+
23+**Pandoc version?**
24+What version of pandoc are you using, on what OS?
25+
.github/ISSUE_TEMPLATE/config.ymlnew file+9
@@ -0,0 +1,9 @@
1+blank_issues_enabled: false
2+contact_links:
3+ - name: Ask a question
4+ url: https://groups.google.com/forum/#!forum/pandoc-discuss
5+ about: "Discussion forum for pandoc (may be used as an email list)"
6+ - name: Contributing Guidelines
7+ url: https://pandoc.org/CONTRIBUTING.html
8+ about: "Guidelines for submitting bug reports and code improvements"
9+
.github/ISSUE_TEMPLATE/feature_request.mdnew file+21
@@ -0,0 +1,21 @@
1+---
2+name: Feature request
3+about: Suggest an idea for this project
4+title: ''
5+labels: 'enhancement'
6+assignees: ''
7+
8+---
9+
10+<!--
11+Thank you for suggesting a feature! Before you continue, please make sure that you have
12+
13+- read the contributing guidelines: https://pandoc.org/CONTRIBUTING.html
14+- searched the issue tracker for similar issues (including closed issues): https://github.com/jgm/pandoc/issues
15+- searched the pandoc-discuss mailing list for relevant discussions: https://groups.google.com/forum/#!forum/pandoc-discuss
16+-->
17+
18+**Describe your proposed improvement and the problem it solves.**
19+
20+**Describe alternatives you've considered.**
21+
.github/workflows/ci.yml+33−8
@@ -44,20 +44,47 @@ jobs:
4444 matrix:
4545 versions:
4646 - ghc: '8.0.2'
47− cabal: '2.2'
47+ cabal: '2.4'
48+ prefix: 'v2-'
49+ cabalopts: ''
50+ testopts: ''
4851 - ghc: '8.2.2'
4952 cabal: '2.4'
53+ prefix: 'v2-'
54+ cabalopts: ''
55+ testopts: ''
5056 - ghc: '8.4.4'
5157 cabal: '2.4'
58+ prefix: 'v2-'
59+ cabalopts: '-f-embed_data_files'
60+ testopts: ''
5261 - ghc: '8.6.5'
5362 cabal: '3.2'
63+ prefix: ''
64+ cabalopts: ''
65+ testopts: '--test-option=--hide-successes'
5466 - ghc: '8.8.4'
5567 cabal: '3.2'
56− - ghc: '8.10.2'
68+ prefix: ''
69+ cabalopts: ''
70+ testopts: '--test-option=--hide-successes'
71+ - ghc: '8.10.4'
5772 cabal: '3.2'
73+ prefix: ''
74+ cabalopts: '-ftrypandoc'
75+ testopts: '--test-option=--hide-successes'
76+ - ghc: '9.0.1'
77+ cabal: '3.4'
78+ prefix: ''
79+ cabalopts: ''
80+ testopts: '--test-option=--hide-successes'
5881 steps:
5982 - uses: actions/checkout@v2
6083
84+ # needed by memory
85+ - name: Install numa
86+ run: sudo apt-get install libnuma-dev
87+
6188 # need to install older cabal/ghc versions from ppa repository
6289
6390 - name: Install recent cabal/ghc
@@ -88,17 +115,15 @@ jobs:
88115
89116 - name: Install dependencies
90117 run: |
91− v2=$([ "${{ matrix.versions.cabal }}" = "2.2" ] && printf 'new' || printf 'v2')
92− cabal $v2-update
93− cabal $v2-build --dependencies-only --enable-tests --disable-optimization
118+ cabal ${{ matrix.versions.prefix }}update
119+ cabal ${{ matrix.versions.prefix }}build ${{ matrix.versions.cabalopts }} --dependencies-only --enable-tests --disable-optimization
94120
95121 - name: Build and test
96122 run: |
97− v2=$([ "${{ matrix.versions.cabal }}" = "2.2" ] && printf 'new' || printf 'v2')
98− cabal $v2-build --enable-tests --disable-optimization 2>&1 | tee build.log
123+ cabal ${{ matrix.versions.prefix }}build ${{ matrix.versions.cabalopts }} --enable-tests --disable-optimization 2>&1 | tee build.log
99124 # fail if warnings in local build
100125 ! grep -q ": *[Ww]arning:" build.log || exit 1
101− cabal $v2-test --disable-optimization
126+ cabal ${{ matrix.versions.prefix }}test ${{ matrix.versions.cabalopts }} --disable-optimization ${{ matrix.versions.testopts }}
102127
103128 windows:
104129
.github/workflows/nightly.yml+9−2
@@ -10,15 +10,22 @@ jobs:
1010 runs-on: ubuntu-18.04
1111 steps:
1212 - uses: actions/checkout@v2
13+
14+ - name: Install recent cabal/ghc
15+ uses: haskell/actions/setup@v1
16+ with:
17+ ghc-version: '8.10.3'
18+ cabal-version: '3.2'
19+
1320 - name: Install dependencies
1421 run: |
1522 ghc --version
1623 cabal --version
1724 cabal v2-update
18− cabal v2-build --dependencies-only all
25+ cabal v2-build --dependencies-only
1926 - name: Build
2027 run: |
21− cabal v2-install all
28+ cabal v2-install
2229 strip $HOME/.cabal/bin/pandoc
2330 - name: Install artifact
2431 run: |
.github/workflows/release-candidate.yml−1
@@ -32,7 +32,6 @@ jobs:
3232 - osarch: "windows-x86_64"
3333 arch: "x64"
3434 stack_opts: "-j1"
35−
3635 steps:
3736 - uses: actions/checkout@v1
3837 - name: Install dependencies
.hlint.yaml+3−5
@@ -9,6 +9,7 @@
99# Ignore some builtin hints
1010#
1111- ignore: {name: "Avoid lambda"}
12+- ignore: {name: "Use bimap"}
1213- ignore: {name: "Eta reduce"}
1314- ignore: {name: "Evaluate"}
1415- ignore: {name: "Reduce duplication"} # TODO: could be more fine-grained
@@ -39,13 +40,10 @@
3940 name: "Redundant return"
4041 within: Text.Pandoc.Citeproc.BibTeX
4142
42−# TODO: check
43+# With recent hlint this rule has given false positives on TH
4344- ignore:
4445 name: "Redundant bracket"
45− within:
46− - Text.Pandoc.Citeproc
47− - Text.Pandoc.Citeproc.BibTeX
48− - Text.Pandoc.Citeproc.MetaValue
46+
4947
5048- ignore:
5149 name: "Use <$>"
AUTHORS.md+18
@@ -20,6 +20,7 @@
2020- Andreas Lööw
2121- Andrew Dunning
2222- Andy Morris
23+- Anti-Distinctlyminty
2324- Antoine Latter
2425- Antonio Terceiro
2526- Arata Mizuki
@@ -35,6 +36,7 @@
3536- Benoit Schweblin
3637- Bjorn Buckwalter
3738- Blake Eryx
39+- Bodigrim
3840- Bradley Kuhn
3941- Brent Yorgey
4042- Brian Leung
@@ -45,6 +47,7 @@
4547- Carlos Sosa
4648- Cécile Chemin
4749- Cédric Couralet
50+- Charanjit Singh
4851- Chris Black
4952- Christian Conkle
5053- Christian Despres
@@ -75,8 +78,10 @@
7578- Eigil Rischel
7679- Emanuel Evans
7780- Emerson Harkin
81+- Emily Bourke
7882- Emily Eisenberg
7983- Eric Kow
84+- Erik Rask
8085- Eric Seidel
8186- Eric Schrijver
8287- Ethan Riley
@@ -86,6 +91,7 @@
8691- Florian Beeres
8792- Florian Eitel
8893- Florian Klink
94+- Florian Kohrt
8995- Francesco Occhipinti
9096- François Gannaz
9197- Frederik Elwert
@@ -146,6 +152,7 @@
146152- Josef Svenningsson
147153- Joseph C. Sible
148154- Julien Cretel
155+- Julien Dutant
149156- Juliette Fourcot
150157- Juliusz Gonera
151158- Justin Bogner
@@ -163,6 +170,8 @@
163170- Leif Metcalf
164171- Leonard Rosenthol
165172- Lila
173+- Loïc Grobol
174+- Lorenzo
166175- Lucas Escot
167176- Luke Plant
168177- Marc Schreiber
@@ -196,10 +205,12 @@
196205- Nathan Gass
197206- Neil Mayhew
198207- Nick Bart
208+- Nick Berendsen
199209- Nick Fleisher
200210- Nicolas Kaiser
201211- Nikolay Yakimov
202212- Nils Carlson
213+- Nixon Enraght-Moony
203214- Nokome Bentley
204215- Ole Martin Ruud
205216- Oliver Matthews
@@ -224,6 +235,7 @@
224235- Raymond Ehlers
225236- Recai Oktaş
226237- Roland Hieber
238+- Roman Beránek
227239- RyanGlScott
228240- Salim B
229241- Sascha Wilde
@@ -241,6 +253,7 @@
241253- Stefan Dresselhaus
242254- Sumit Sahrawat
243255- Tarik Graba
256+- Tatiana Porras
244257- Thenaesh Elango
245258- Thomas Hodgson
246259- Thomas Weißschuh
@@ -274,6 +287,7 @@
274287- a-vrma
275288- andrebauer
276289- argent0
290+- badumont
277291- blmage
278292- bucklereed
279293- bumper314
@@ -289,8 +303,11 @@
289303- kaizshang91
290304- lux-lth
291305- lwolfsonkin
306+- mbrackeantidot
292307- nkalvi
293308- niszet
309+- nuew
310+- obcat
294311- oltolm
295312- oquechy
296313- quasicomputational
@@ -302,6 +319,7 @@
302319- shreevatsa.public
303320- takahashim
304321- taotieren
322+- tecosaur
305323- TEC
306324- tgkokk
307325- the-solipsist
CONTRIBUTING.md+16−11
@@ -244,9 +244,16 @@ Or with stack:
244244
245245 stack test --test-arguments='-p markdown'
246246
247−It is often helpful to add `-j4` (run tests in parallel)
248−and `--hide-successes` (don't clutter output with successes)
249−to the test arguments as well.
247+It is often helpful to add `-j4` (run tests in parallel) and
248+`--hide-successes` (don't clutter output with successes) to the test
249+arguments as well. Collecting all options in a `cabal.project.local`
250+file in the project's root directory can help to keep `cabal`
251+commands short. E.g.:
252+
253+ flags: +embed_data_files
254+ tests: True
255+ test-show-details: direct
256+ test-options: -j4 --hide-successes
250257
251258If you add a new feature to pandoc, please add tests as well, following
252259the pattern of the existing tests. The test suite code is in
@@ -311,9 +318,6 @@ With stack:
311318
312319 stack bench
313320
314−You can also build `weigh-pandoc` (`stack build pandoc:weigh-pandoc`)
315−to get some statistics on memory usage. (Eventually this should
316−be incorporated into the benchmark suite.)
317321
318322Using the REPL
319323--------------
@@ -402,11 +406,11 @@ The library is structured as follows:
402406 tree automatically.
403407 - `Text.Pandoc.Readers.*` are the readers, and `Text.Pandoc.Writers.*`
404408 are the writers.
405− - `Text.Pandoc.Biblio` is a utility module for formatting citations
406− using citeproc-hs.
409+ - `Text.Pandoc.Citeproc.*` contain the code for citation handling,
410+ including an interface to the [citeproc] library.
407411 - `Text.Pandoc.Data` is used to embed data files when the `embed_data_files`
408− cabal flag is used. It is generated from `src/Text/Pandoc/Data.hsb` using
409− the preprocessor [hsb2hs].
412+ cabal flag is used.
413+ - `Text.Pandoc.Emoji` is a thin wrapper around [emojis].
410414 - `Text.Pandoc.Highlighting` contains the interface to the
411415 skylighting library, which is used for code syntax highlighting.
412416 - `Text.Pandoc.ImageSize` is a utility module containing functions for
@@ -417,7 +421,6 @@ The library is structured as follows:
417421 - `Text.Pandoc.PDF` contains functions for producing a PDF from a
418422 LaTeX source.
419423 - `Text.Pandoc.Parsing` contains parsing functions used in multiple readers.
420− - `Text.Pandoc.Pretty` is a pretty-printing library specialized to
421424 the needs of pandoc.
422425 - `Text.Pandoc.SelfContained` contains functions for making an HTML
423426 file "self-contained," by importing remotely linked images, CSS,
@@ -452,6 +455,8 @@ you may want to consider submitting a pull request to the
452455[EditorConfig]: https://editorconfig.org/
453456[Haskell platform]: https://www.haskell.org/platform/
454457[hlint]: https://hackage.haskell.org/package/hlint
458+[citeproc]: https://hackage.haskell.org/package/citeproc
459+[emojis]: https://hackage.haskell.org/package/emojis
455460[hsb2hs]: https://hackage.haskell.org/package/hsb2hs
456461[pre-commit hook]: https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks
457462[GitHub labels]: https://github.com/jgm/pandoc/labels
INSTALL.md+4
@@ -34,6 +34,10 @@ without SVG support), [Python] (to use Pandoc filters), and
3434
3535 choco install rsvg-convert python miktex
3636
37+Using multiple installation methods can result in two separate
38+installations of pandoc; it is recommended to properly uninstall
39+pandoc before switching to an alternative installation method.
40+
3741By default, Pandoc creates PDFs using LaTeX.
3842We recommend installing it via [MiKTeX].
3943
MANUAL.txt+218−71
@@ -1,7 +1,7 @@
11---
22title: Pandoc User's Guide
33author: John MacFarlane
4−date: January 21, 2021
4+date: June 20, 2021
55---
66
77# Synopsis
@@ -361,15 +361,15 @@ header when requesting a document from a URL:
361361 will be used. On \*nix and macOS systems this will be the `pandoc`
362362 subdirectory of the XDG data directory (by default,
363363 `$HOME/.local/share`, overridable by setting the `XDG_DATA_HOME`
364− environment variable). If that directory does not exist,
365− `$HOME/.pandoc` will be used (for backwards compatibility).
366− In Windows the default user data directory is
364+ environment variable). If that directory does not exist and
365+ `$HOME/.pandoc` exists, it will be used (for backwards compatibility).
366+ On Windows the default user data directory is
367367 `C:\Users\USERNAME\AppData\Roaming\pandoc`.
368368 You can find the default user data directory on your system by
369369 looking at the output of `pandoc --version`.
370− A `reference.odt`, `reference.docx`, `epub.css`, `templates`,
371− `slidy`, `slideous`, or `s5` directory
372− placed in this directory will override pandoc's normal defaults.
370+ Data files placed in this directory (for example, `reference.odt`,
371+ `reference.docx`, `epub.css`, `templates`) will override
372+ pandoc's normal defaults.
373373
374374`-d` *FILE*, `--defaults=`*FILE*
375375
@@ -675,12 +675,12 @@ header when requesting a document from a URL:
675675: Extract images and other media contained in or linked from
676676 the source document to the path *DIR*, creating it if
677677 necessary, and adjust the images references in the document
678− so they point to the extracted files. If the source format is
679− a binary container (docx, epub, or odt), the media is
680− extracted from the container and the original
681− filenames are used. Otherwise the media is read from the
682− file system or downloaded, and new filenames are constructed
683− based on SHA1 hashes of the contents.
678+ so they point to the extracted files. Media are downloaded,
679+ read from the file system, or extracted from a binary
680+ container (e.g. docx), as needed. The original file paths
681+ are used if they are relative paths not containing `..`.
682+ Otherwise filenames are constructed from the SHA1 hash of
683+ the contents.
684684
685685`--abbreviations=`*FILE*
686686
@@ -691,9 +691,9 @@ header when requesting a document from a URL:
691691 system default, use
692692 `pandoc --print-default-data-file=abbreviations`. The only
693693 use pandoc makes of this list is in the Markdown reader.
694− Strings ending in a period that are found in this list will
695− be followed by a nonbreaking space, so that the period will
696− not produce sentence-ending space in formats like LaTeX.
694+ Strings found in this list will be followed by a nonbreaking
695+ space, and the period will not produce sentence-ending space
696+ in formats like LaTeX. The strings may not contain spaces.
697697
698698[`pandocfilters`]: https://github.com/jgm/pandocfilters
699699[PHP]: https://github.com/vinai/pandocfilters-php
@@ -891,6 +891,11 @@ header when requesting a document from a URL:
891891 will not be searched. For example:
892892 `--resource-path=.:test` will search the working directory
893893 and the `test` subdirectory, in that order.
894+ This option can be used repeatedly. Search path components
895+ that come later on the command line will be searched before
896+ those that come earlier, so
897+ `--resource-path foo:bar --resource-path baz:bim` is
898+ equivalent to `--resource-path baz:bim:foo:bar`.
894899
895900`--request-header=`*NAME*`:`*VAL*
896901
@@ -1410,13 +1415,12 @@ results only for basic math, usually you will want to use
14101415`--gladtex`
14111416
14121417: Enclose TeX math in `<eq>` tags in HTML output. The resulting HTML
1413− can then be processed by [GladTeX] to produce images of the typeset
1414− formulas and an HTML file with links to these images.
1415− So, the procedure is:
1418+ can then be processed by [GladTeX] to produce SVG images of the typeset
1419+ formulas and an HTML file with these images embedded.
14161420
14171421 pandoc -s --gladtex input.md -o myfile.htex
1418− gladtex -d myfile-images myfile.htex
1419− # produces myfile.html and images in myfile-images
1422+ gladtex -d image_dir myfile.htex
1423+ # produces myfile.html and images in image_dir
14201424
14211425[MathML]: https://www.w3.org/Math/
14221426[MathJax]: https://www.mathjax.org
@@ -1672,6 +1676,34 @@ one line:
16721676verbosity: INFO
16731677```
16741678
1679+In fields that expect a file path (or list of file paths), the
1680+following syntax may be used to interpolate environment variables:
1681+
1682+``` yaml
1683+csl: ${HOME}/mycsldir/special.csl
1684+```
1685+
1686+`${USERDATA}` may also be used; this will always resolve to the
1687+user data directory that is current when the defaults file is
1688+parsed, regardless of the setting of the environment
1689+variable `USERDATA`.
1690+
1691+`${.}` will resolve to the directory containing the default
1692+file itself. This allows you to refer to resources contained
1693+in that directory:
1694+
1695+``` yaml
1696+epub-cover-image: ${.}/cover.jpg
1697+epub-metadata: ${.}/meta.xml
1698+resource-path:
1699+- . # the working directory from which pandoc is run
1700+- ${.}/images # the images subdirectory of the directory
1701+ # containing this defaults file
1702+```
1703+
1704+This environment variable interpolation syntax *only* works in
1705+fields that expect file paths.
1706+
16751707Default files can be placed in the `defaults` subdirectory of
16761708the user data directory and used from any directory. For
16771709example, one could create a file specifying defaults for writing
@@ -2282,8 +2314,8 @@ math equations flush left using [YAML metadata](#layout) or with
22822314
22832315These affect HTML output when [producing slide shows with pandoc].
22842316
2285−All [reveal.js configuration options] are available as variables.
2286−To turn off boolean flags that default to true in reveal.js, use `0`.
2317+`institute`
2318+: author affiliations: can be a list when there are multiple authors
22872319
22882320`revealjs-url`
22892321: base URL for reveal.js documents (defaults to
@@ -2303,6 +2335,9 @@ To turn off boolean flags that default to true in reveal.js, use `0`.
23032335: additional attributes for the title slide of reveal.js slide shows.
23042336 See [background in reveal.js and beamer] for an example.
23052337
2338+All [reveal.js configuration options] are available as variables.
2339+To turn off boolean flags that default to true in reveal.js, use `0`.
2340+
23062341[reveal.js configuration options]: https://revealjs.com/config/
23072342
23082343### Variables for Beamer slides
@@ -3719,7 +3754,7 @@ definition:
37193754Note that space between items in a definition list is required.
37203755(A variant that loosens this requirement, but disallows "lazy"
37213756hard wrapping, can be activated with `compact_definition_lists`: see
3722−[Non-pandoc extensions], below.)
3757+[Non-default extensions], below.)
37233758
37243759[^3]: I have been influenced by the suggestions of [David
37253760 Wheeler](https://justatheory.com/2009/02/modest-markdown-proposal/).
@@ -4144,10 +4179,12 @@ option is used. All of the metadata will appear in a single block
41444179at the beginning of the document.
41454180
41464181Note that [YAML] escaping rules must be followed. Thus, for example,
4147−if a title contains a colon, it must be quoted. The pipe character
4148−(`|`) can be used to begin an indented block that will be interpreted
4149−literally, without need for escaping. This form is necessary
4150−when the field contains blank lines or block-level formatting:
4182+if a title contains a colon, it must be quoted, and if it contains a
4183+backslash escape, then it must be ensured that it is not treated as a
4184+[YAML escape sequence]. The pipe character (`|`) can be used to begin
4185+an indented block that will be interpreted literally, without need for
4186+escaping. This form is necessary when the field contains blank lines
4187+or block-level formatting:
41514188
41524189 ---
41534190 title: 'This is the title: it contains a colon'
@@ -4161,6 +4198,12 @@ when the field contains blank lines or block-level formatting:
41614198 It consists of two paragraphs.
41624199 ...
41634200
4201+The literal block after the `|` must be indented relative to the
4202+line containing the `|`. If it is not, the YAML will be invalid
4203+and pandoc will not interpret it as metadata. For an overview
4204+of the complex rules governing YAML, see the [Wikipedia entry on
4205+YAML syntax].
4206+
41644207Template variables will be set automatically from the metadata. Thus, for
41654208example, in writing HTML, the variable `abstract` will be set to the HTML
41664209equivalent of the Markdown in the `abstract` field:
@@ -4207,6 +4250,24 @@ will be interpreted as markdown. For example:
42074250 \renewcommand{\section}[1]{\clearpage\oldsection{#1}}
42084251 ```
42094252
4253+Note: the `yaml_metadata_block` extension works with
4254+`commonmark` as well as `markdown` (and it is enabled by default
4255+in `gfm` and `commonmark_x`). However, in these formats the
4256+following restrictions apply:
4257+
4258+- The YAML metadata block must occur at the beginning of the
4259+ document (and there can be only one). If multiple files are
4260+ given as arguments to pandoc, only the first can be a YAML
4261+ metadata block.
4262+
4263+- The leaf nodes of the YAML structure are parsed in isolation from
4264+ each other and from the rest of the document. So, for
4265+ example, you can't use a reference link in these contexts
4266+ if the link definition is somewhere else in the document.
4267+
4268+[YAML escape sequence]: https://yaml.org/spec/1.2/spec.html#id2776092
4269+[Wikipedia entry on YAML syntax]: https://en.m.wikipedia.org/wiki/YAML#Syntax
4270+
42104271## Backslash escapes
42114272
42124273#### Extension: `all_symbols_escapable` ####
@@ -4899,37 +4960,68 @@ Inline and regular footnotes may be mixed freely.
48994960
49004961#### Extension: `citations` ####
49014962
4902−Markdown citations go inside square brackets and are separated
4903−by semicolons. Each citation must have a key, composed of '@' +
4904−the citation identifier from the database, and may optionally
4905−have a prefix, a locator, and a suffix. The citation key must
4906−begin with a letter, digit, or `_`, and may contain
4907−alphanumerics, `_`, and internal punctuation characters
4908−(`:.#$%&-+?<>~/`). Here are some examples:
4909−
4910− Blah blah [see @doe99, pp. 33-35; also @smith04, chap. 1].
4911−
4912− Blah blah [@doe99, pp. 33-35, 38-39 and *passim*].
4913−
4914− Blah blah [@smith04; @doe99].
4915−
4916−`pandoc` detects locator terms in the [CSL locale files].
4917−Either abbreviated or unabbreviated forms are accepted. In the `en-US`
4918−locale, locator terms can be written in either singular or plural forms,
4919−as `book`, `bk.`/`bks.`; `chapter`, `chap.`/`chaps.`; `column`,
4920−`col.`/`cols.`; `figure`, `fig.`/`figs.`; `folio`, `fol.`/`fols.`;
4921−`number`, `no.`/`nos.`; `line`, `l.`/`ll.`; `note`, `n.`/`nn.`; `opus`,
4922−`op.`/`opp.`; `page`, `p.`/`pp.`; `paragraph`, `para.`/`paras.`; `part`,
4923−`pt.`/`pts.`; `section`, `sec.`/`secs.`; `sub verbo`, `s.v.`/`s.vv.`;
4924−`verse`, `v.`/`vv.`; `volume`, `vol.`/`vols.`; `¶`/`¶¶`; `§`/`§§`. If no
4963+To cite a bibliographic item with an identifier foo, use the
4964+syntax `@foo`. Normal citations should be included in square
4965+brackets, with semicolons separating distinct items:
4966+
4967+ Blah blah [@doe99; @smith2000; @smith2004].
4968+
4969+How this is rendered depends on the citation style. In an
4970+author-date style, it might render as
4971+
4972+ Blah blah (Doe 1999, Smith 2000, 2004).
4973+
4974+In a footnote style, it might render as
4975+
4976+ Blah blah.[^1]
4977+
4978+ [^1]: John Doe, "Frogs," *Journal of Amphibians* 44 (1999);
4979+ Susan Smith, "Flies," *Journal of Insects* (2000);
4980+ Susan Smith, "Bees," *Journal of Insects* (2004).
4981+
4982+See the [CSL user documentation] for more information about CSL
4983+styles and how they affect rendering.
4984+
4985+Unless a citation key start with a letter, digit, or `_`,
4986+and contains only alphanumerics and internal punctuation
4987+characters (`:.#$%&-+?<>~/`), it must be surrounded
4988+by curly braces, which are not considered part of the key.
4989+In `@Foo_bar.baz.`, the key is `Foo_bar.baz`. The final
4990+period is not *internal* punctuation, so it is not included in
4991+the key. In `@{Foo_bar.baz.}`, the key is `Foo_bar.baz.`, including
4992+the final period. The curly braces are recommended if you use URLs as
4993+keys: `[@{https://example.com/bib?name=foobar&date=2000}, p. 33]`.
4994+
4995+Citation items may optionally include a prefix, a locator, and
4996+a suffix. In
4997+
4998+ Blah blah [see @doe99, pp. 33-35 and *passim*; @smith04, chap. 1].
4999+
5000+The first item (`doe99`) has prefix `see `, locator `pp. 33-35`,
5001+and suffix `and *passim*`. The second item (`smith04`) has
5002+locator `chap. 1` and no prefix or suffix.
5003+
5004+Pandoc uses some heuristics to separate the locator from the
5005+rest of the subject. It is sensitive to the locator terms
5006+defined in the [CSL locale files]. Either abbreviated or
5007+unabbreviated forms are accepted. In the `en-US` locale, locator
5008+terms can be written in either singular or plural forms, as
5009+`book`, `bk.`/`bks.`; `chapter`, `chap.`/`chaps.`; `column`,
5010+`col.`/`cols.`; `figure`, `fig.`/`figs.`; `folio`,
5011+`fol.`/`fols.`; `number`, `no.`/`nos.`; `line`, `l.`/`ll.`;
5012+`note`, `n.`/`nn.`; `opus`, `op.`/`opp.`; `page`, `p.`/`pp.`;
5013+`paragraph`, `para.`/`paras.`; `part`, `pt.`/`pts.`; `section`,
5014+`sec.`/`secs.`; `sub verbo`, `s.v.`/`s.vv.`; `verse`,
5015+`v.`/`vv.`; `volume`, `vol.`/`vols.`; `¶`/`¶¶`; `§`/`§§`. If no
49255016locator term is used, "page" is assumed.
49265017
4927−`pandoc` will use heuristics to distinguish the locator
4928−from the suffix. In complex cases, the locator can be enclosed
4929−in curly braces:
5018+In complex cases, you can force something to be treated as
5019+a locator by enclosing it in curly braces or prevent parsing
5020+the suffix as locator by prepending curly braces:
49305021
49315022 [@smith{ii, A, D-Z}, with a suffix]
49325023 [@smith, {pp. iv, vi-xi, (xv)-(xvii)} with suffix here]
5024+ [@smith{}, 99 years later]
49335025
49345026A minus sign (`-`) before the `@` will suppress mention of
49355027the author in the citation. This can be useful when the
@@ -4937,13 +5029,26 @@ author is already mentioned in the text:
49375029
49385030 Smith says blah [-@smith04].
49395031
4940−You can also write an in-text citation, as follows:
5032+You can also write an author-in-text citation, by omitting the
5033+square brackets:
49415034
49425035 @smith04 says blah.
49435036
49445037 @smith04 [p. 33] says blah.
49455038
5039+This will cause the author's name to be rendered, followed by
5040+the bibliographical details. Use this form when you want to
5041+make the citation the subject of a sentence.
5042+
5043+When you are using a note style, it is usually better to let
5044+citeproc create the footnotes from citations rather than writing
5045+an explicit note. If you do write an explicit note that
5046+contains a citation, note that normal citations will be put in
5047+parentheses, while author-in-text citations will not. For
5048+this reason, it is sometimes preferable to use the
5049+author-in-text style inside notes when using a note style.
49465050
5051+[CSL user documentation]: https://citationstyles.org/authors/
49475052[CSL]: https://docs.citationstyles.org/en/stable/specification.html
49485053[CSL markup specs]: https://docs.citationstyles.org/en/1.0/release-notes.html#rich-text-markup-within-fields
49495054[Chicago Manual of Style]: https://chicagomanualofstyle.org
@@ -4952,13 +5057,44 @@ You can also write an in-text citation, as follows:
49525057[finding and editing styles]: https://citationstyles.org/authors/
49535058[CSL locale files]: https://github.com/citation-style-language/locales
49545059
4955−## Non-pandoc extensions
5060+## Non-default extensions
49565061
49575062The following Markdown syntax extensions are not enabled by default
49585063in pandoc, but may be enabled by adding `+EXTENSION` to the format
49595064name, where `EXTENSION` is the name of the extension. Thus, for
49605065example, `markdown+hard_line_breaks` is Markdown with hard line breaks.
49615066
5067+#### Extension: `rebase_relative_paths` ####
5068+
5069+Rewrite relative paths for Markdown links and images, depending
5070+on the path of the file containing the link or image link. For
5071+each link or image, pandoc will compute the directory of the
5072+containing file, relative to the working directory, and prepend
5073+the resulting path to the link or image path.
5074+
5075+The use of this extension is best understood by example.
5076+Suppose you have a a subdirectory for each chapter of a book,
5077+`chap1`, `chap2`, `chap3`. Each contains a file `text.md` and a
5078+number of images used in the chapter. You would like to have
5079+`![image](spider.jpg)` in `chap1/text.md` refer to
5080+`chap1/spider.jpg` and `![image](spider.jpg)` in `chap2/text.md`
5081+refer to `chap2/spider.jpg`. To do this, use
5082+
5083+ pandoc chap*/*.md -f markdown+rebase_relative_paths
5084+
5085+Without this extension, you would have to use
5086+`![image](chap1/spider.jpg)` in `chap1/text.md` and
5087+`![image](chap2/spider.jpg)` in `chap2/text.md`. Links with
5088+relative paths will be rewritten in the same way as images.
5089+
5090+Absolute paths and URLs are not changed. Neither are empty
5091+paths or paths consisting entirely of a fragment, e.g., `#foo`.
5092+
5093+Note that relative paths in reference links and images will
5094+be rewritten relative to the file containing the link
5095+reference definition, not the file containing the reference link
5096+or image itself, if these differ.
5097+
49625098#### Extension: `attributes` ####
49635099
49645100Allows attributes to be attached to any inline or block-level
@@ -5492,10 +5628,23 @@ A few other metadata fields affect bibliography formatting:
54925628
54935629`lang`
54945630: The `lang` field will affect how the style is localized,
5495− for example in the translation of labels and the use
5496− of quotation marks. (For backwards compatibility,
5497− `locale` may be used instead of `lang`, but this use
5498− is deprecated.)
5631+ for example in the translation of labels, the use
5632+ of quotation marks, and the way items are sorted.
5633+ (For backwards compatibility, `locale` may be used instead
5634+ of `lang`, but this use is deprecated.)
5635+
5636+ A BCP 47 language tag is expected: for example, `en`,
5637+ `de`, `en-US`, `fr-CA`, `ug-Cyrl`. The unicode extension
5638+ syntax (after `-u-`) may be used to specify options for
5639+ collation (sorting) more precisely. Here are some examples:
5640+
5641+ - `zh-u-co-pinyin` -- Chinese with the Pinyin collation.
5642+ - `es-u-co-trad` -- Spanish with the traditional collation
5643+ (with `Ch` sorting after `C`).
5644+ - `fr-u-kb` -- French with "backwards" accent sorting
5645+ (with `coté` sorting after `côte`).
5646+ - `en-US-u-kf-upper` -- English with uppercase letters sorting
5647+ before lower (default is lower before upper).
54995648
55005649`notes-after-punctuation`
55015650: If true (the default), pandoc will put footnote citations
@@ -5507,12 +5656,6 @@ A few other metadata fields affect bibliography formatting:
55075656 punctuation.
55085657
55095658
5510−
5511−
5512−
5513−
5514−
5515−
55165659# Slide shows
55175660
55185661You can use pandoc to produce an HTML + JavaScript slide presentation
@@ -5605,7 +5748,11 @@ rules:
56055748 * A heading at the slide level always starts a new slide.
56065749
56075750 * Headings *below* the slide level in the hierarchy create
5608− headings *within* a slide.
5751+ headings *within* a slide. (In beamer, a "block" will be
5752+ created. If the heading has the class `example`, an
5753+ `exampleblock` environment will be used; if it has the class
5754+ `alert`, an `alertblock` will be used; otherwise a regular
5755+ `block` will be used.)
56095756
56105757 * Headings *above* the slide level in the hierarchy create
56115758 "title slides," which just contain the section title
@@ -6183,7 +6330,7 @@ Then edit `my.theme` and use it like this:
61836330If you are not satisfied with the built-in highlighting, or you
61846331want highlight a language that isn't supported, you can use the
61856332`--syntax-definition` option to load a [KDE-style XML syntax definition
6186−file](https://docs.kde.org/stable5/en/applications/katepart/highlight.html).
6333+file](https://docs.kde.org/stable5/en/kate/katepart/highlight.html).
61876334Before writing your own, have a look at KDE's [repository of syntax
61886335definitions](https://github.com/KDE/syntax-highlighting/tree/master/data/syntax).
61896336
@@ -6357,9 +6504,9 @@ application, here are some things to keep in mind:
635765044. The HTML generated by pandoc is not guaranteed to be safe.
63586505 If `raw_html` is enabled for the Markdown input, users can
63596506 inject arbitrary HTML. Even if `raw_html` is disabled,
6360− users can include dangerous content in attributes for
6361− headings, spans, and code blocks. To be safe, you should
6362− run all the generated HTML through an HTML sanitizer.
6507+ users can include dangerous content in URLs and attributes.
6508+ To be safe, you should run all the generated HTML through
6509+ an HTML sanitizer.
63636510
63646511# Authors
63656512
Makefile+28−15
@@ -2,25 +2,31 @@ version?=$(shell grep '^[Vv]ersion:' pandoc.cabal | awk '{print $$2;}')
22pandoc=$(shell find dist -name pandoc -type f -exec ls -t {} \; | head -1)
33SOURCEFILES?=$(shell git ls-tree -r master --name-only | grep "\.hs$$")
44BRANCH?=master
5+ARCH=$(shell uname -m)
6+DOCKERIMAGE=registry.gitlab.b-data.ch/ghc/ghc4pandoc:8.10.4
57COMMIT=$(shell git rev-parse --short HEAD)
68TIMESTAMP=$(shell date "+%Y%m%d_%H%M")
7−LATESTBENCH=$(word 1,$(shell ls -t bench_*.csv))
8−ifeq ($(LATESTBENCH),)
9−BASELINE=
9+LATESTBENCH=$(word 1,$(shell ls -t bench_*.csv 2>/dev/null))
10+BASELINE?=$(LATESTBENCH)
11+ifeq ($(BASELINE),)
12+BASELINECMD=
1013else
11−BASELINE=--baseline $(LATESTBENCH)
14+BASELINECMD=--baseline $(BASELINE)
1215endif
13−GHCOPTS=-fdiagnostics-color=always
16+GHCOPTS=-fdiagnostics-color=always -j4 +RTS -A8m -RTS
1417WEBSITE=../../web/pandoc.org
1518REVISION?=1
16−BENCHARGS?=--timeout=6 +RTS -T -RTS $(if $(PATTERN),--pattern "$(PATTERN)",)
19+# For gauge:
20+# BENCHARGS?=--small --ci=0.90 --match=pattern $(PATTERN)
21+# For tasty-bench:
22+BENCHARGS?=--csv bench_$(TIMESTAMP).csv $(BASELINECMD) --timeout=6 +RTS -T -RTS $(if $(PATTERN),--pattern "$(PATTERN)",)
1723
1824quick:
19− stack install --ghc-options='$(GHCOPTS)' --install-ghc --flag 'pandoc:embed_data_files' --fast --test --ghc-options='-j +RTS -A64m -RTS' --test-arguments='-j4 --hide-successes $(TESTARGS)'
25+ stack install --ghc-options='$(GHCOPTS)' --install-ghc --flag 'pandoc:embed_data_files' --fast --test --ghc-options='$(GHCOPTS)' --test-arguments='-j4 --hide-successes $(TESTARGS)'
2026
2127quick-cabal:
2228 cabal new-configure . --ghc-options '$(GHCOPTS)' --disable-optimization --enable-tests
23− cabal new-build . --disable-optimization
29+ cabal new-build -j4 . --disable-optimization
2430 cabal new-run test-pandoc --disable-optimization -- --hide-successes $(TESTARGS)
2531
2632full-cabal:
@@ -29,7 +35,7 @@ full-cabal:
2935 cabal new-run test-pandoc --disable-optimization -- --hide-successes $(TESTARGS)
3036
3137full:
32− stack install --flag 'pandoc:embed_data_files' --flag 'pandoc:trypandoc' --bench --no-run-benchmarks --test --test-arguments='-j4 --hide-successes' --ghc-options '-Wall -Werror -fno-warn-unused-do-bind -O0 -j4 $(GHCOPTS)'
38+ stack install --flag 'pandoc:embed_data_files' --flag 'pandoc:trypandoc' --bench --no-run-benchmarks --test --test-arguments='-j4 --hide-successes' --ghc-options '-Wall -Werror -fno-warn-unused-do-bind -O0 $(GHCOPTS)'
3339
3440ghci:
3541 stack ghci --flag 'pandoc:embed_data_files'
@@ -45,11 +51,14 @@ test:
4551ghcid:
4652 ghcid -c "stack repl --flag 'pandoc:embed_data_files'"
4753
48−bench:
49− stack bench --benchmark-arguments='$(BENCHARGS) $(BASELINE) --csv bench_$(TIMESTAMP).csv' --ghc-options '$(GHCOPTS)'
54+ghcid-test:
55+ ghcid -c "stack repl --ghc-options=-XNoImplicitPrelude --flag 'pandoc:embed_data_files' --ghci-options=-fobject-code pandoc:lib pandoc:test-pandoc"
5056
51−weigh:
52− stack build --ghc-options '$(GHCOPTS)' pandoc:weigh-pandoc && stack exec weigh-pandoc
57+bench:
58+ stack bench \
59+ --ghc-options '$(GHCOPTS)' \
60+ --benchmark-arguments='$(BENCHARGS)' 2>&1 | \
61+ tee "bench_latest.txt"
5362
5463reformat:
5564 for f in $(SOURCEFILES); do echo $$f; stylish-haskell -i $$f ; done
@@ -81,10 +90,14 @@ checkdocs:
8190debpkg: man/pandoc.1
8291 docker run -v `pwd`:/mnt \
8392 -v `pwd`/linux/artifacts:/artifacts \
93+ --user $(id -u):$(id -g) \
8494 -e REVISION=$(REVISION) \
8595 -w /mnt \
86− utdemir/ghc-musl:v12-libgmp-ghc8101 bash \
87− /mnt/linux/make_artifacts.sh
96+ --memory=0 \
97+ --rm \
98+ $(DOCKERIMAGE) \
99+ bash \
100+ /mnt/linux/make_artifacts.sh 2>&1 > docker.log
88101
89102man/pandoc.1: MANUAL.txt man/pandoc.1.before man/pandoc.1.after
90103 pandoc $< -f markdown -t man -s \
README.md+6−6
@@ -8,10 +8,10 @@ pandoc --lua-filter tools/update-readme.lua README.template -o README.md
88[![github
99release](https://img.shields.io/github/release/jgm/pandoc.svg?label=current+release)](https://github.com/jgm/pandoc/releases)
1010[![hackage
11−release](https://img.shields.io/hackage/v/pandoc.svg?label=hackage)](http://hackage.haskell.org/package/pandoc)
12−[![homebrew](https://img.shields.io/homebrew/v/pandoc.svg)](http://brewformulas.org/Pandoc)
11+release](https://img.shields.io/hackage/v/pandoc.svg?label=hackage)](https://hackage.haskell.org/package/pandoc)
12+[![homebrew](https://img.shields.io/homebrew/v/pandoc.svg)](https://formulae.brew.sh/formula/pandoc)
1313[![stackage LTS
14−package](http://stackage.org/package/pandoc/badge/lts)](http://stackage.org/lts/package/pandoc)
14+package](https://stackage.org/package/pandoc/badge/lts)](https://www.stackage.org/lts/package/pandoc-types)
1515[![CI
1616tests](https://github.com/jgm/pandoc/workflows/CI%20tests/badge.svg)](https://github.com/jgm/pandoc/actions)
1717[![license](https://img.shields.io/badge/license-GPLv2+-lightgray.svg)](https://www.gnu.org/licenses/gpl.html)
@@ -20,7 +20,7 @@ groups](https://img.shields.io/badge/pandoc-discuss-red.svg?style=social)](https
2020
2121## The universal markup converter
2222
23−Pandoc is a [Haskell](http://haskell.org) library for converting from
23+Pandoc is a [Haskell](https://haskell.org) library for converting from
2424one markup format to another, and a command-line tool that uses this
2525library. It can convert *from*
2626
@@ -175,7 +175,7 @@ It can convert *to*
175175 and JavaScript slide show)
176176- `slidy` ([Slidy](https://www.w3.org/Talks/Tools/Slidy2/) HTML and
177177 JavaScript slide show)
178−- `dzslides` ([DZSlides](http://paulrouget.com/dzslides/) HTML5 +
178+- `dzslides` ([DZSlides](https://paulrouget.com/dzslides/) HTML5 +
179179 JavaScript slide show),
180180- `revealjs` ([reveal.js](https://revealjs.com/) HTML5 + JavaScript
181181 slide show)
@@ -239,6 +239,6 @@ opening a new issue.
239239## License
240240
241241© 2006-2021 John MacFarlane (jgm@berkeley.edu). Released under the
242−[GPL](http://www.gnu.org/copyleft/gpl.html "GNU General Public License"),
242+[GPL](https://www.gnu.org/licenses/old-licenses/gpl-2.0.html "GNU General Public License"),
243243version 2 or greater. This software carries no warranty of any kind.
244244(See COPYRIGHT for full copyright and warranty notices.)
RELEASE-CHECKLIST+1
@@ -4,6 +4,7 @@
44[ ] Finalize changelog
55[ ] push release candidate branch rc/VERSION and (if it builds
66 successfully) download artifacts
7+[ ] run tools/build-arm.sh to create and download arm64 linux package
78[ ] download macos artifacts from CircleCI
89[ ] Use 'make' in macos and windows artifacts to sign code
910[ ] make update-website
SECURITY.mdnew file+12
@@ -0,0 +1,12 @@
1+# Security Policy
2+
3+## Supported Versions
4+
5+Only the most recent version of pandoc is supported with security updates.
6+
7+## Reporting a Vulnerability
8+
9+To report a vulnerability, email the maintainer, jgm@berkeley.edu.
10+But first please read the section of the manual entitled
11+[A note on security](https://pandoc.org/MANUAL.html#a-note-on-security),
12+which describes some security guarantees pandoc does NOT make.
benchmark/benchmark-pandoc.hs+13−12
@@ -18,12 +18,13 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
1818-}
1919import Text.Pandoc
2020import Text.Pandoc.MIME
21−import Control.Monad (when)
21+import Control.DeepSeq (force)
2222import Control.Monad.Except (throwError)
2323import qualified Text.Pandoc.UTF8 as UTF8
2424import qualified Data.ByteString as B
2525import qualified Data.Text as T
2626import Test.Tasty.Bench
27+-- import Gauge
2728import qualified Data.ByteString.Lazy as BL
2829import Data.Maybe (mapMaybe)
2930import Data.List (sortOn)
@@ -31,10 +32,10 @@ import Data.List (sortOn)
3132readerBench :: Pandoc
3233 -> T.Text
3334 -> Maybe Benchmark
35+readerBench _ name
36+ | name `elem` ["bibtex", "biblatex", "csljson"] = Nothing
3437readerBench doc name = either (const Nothing) Just $
3538 runPure $ do
36− when (name `elem` ["bibtex", "biblatex", "csljson"]) $
37− throwError $ PandocSomeError $ name <> " not supported for benchmark"
3839 (rdr, rexts) <- getReader name
3940 (wtr, wexts) <- getWriter name
4041 case (rdr, wtr) of
@@ -56,19 +57,19 @@ readerBench doc name = either (const Nothing) Just $
5657
5758getImages :: IO [(FilePath, MimeType, BL.ByteString)]
5859getImages = do
59− ll <- BL.readFile "test/lalune.jpg"
60− mv <- BL.readFile "test/movie.jpg"
61− return [("lalune.jpg", "image/jpg", ll)
62− ,("movie.jpg", "image/jpg", mv)]
60+ ll <- B.readFile "test/lalune.jpg"
61+ mv <- B.readFile "test/movie.jpg"
62+ return [("lalune.jpg", "image/jpg", BL.fromStrict ll)
63+ ,("movie.jpg", "image/jpg", BL.fromStrict mv)]
6364
6465writerBench :: [(FilePath, MimeType, BL.ByteString)]
6566 -> Pandoc
6667 -> T.Text
6768 -> Maybe Benchmark
69+writerBench _ _ name
70+ | name `elem` ["bibtex", "biblatex", "csljson"] = Nothing
6871writerBench imgs doc name = either (const Nothing) Just $
6972 runPure $ do
70− when (name `elem` ["bibtex", "biblatex", "csljson"]) $
71− throwError $ PandocSomeError $ name <> " not supported for benchmark"
7273 (wtr, wexts) <- getWriter name
7374 case wtr of
7475 TextWriter writerFun ->
@@ -90,10 +91,10 @@ main :: IO ()
9091main = do
9192 inp <- UTF8.toText <$> B.readFile "test/testsuite.txt"
9293 let opts = def
93− let doc = either (error . show) id $ runPure $ readMarkdown opts inp
94− imgs <- getImages
94+ let doc = either (error . show) force $ runPure $ readMarkdown opts inp
9595 defaultMain
96− [ bgroup "writers" $ mapMaybe (writerBench imgs doc . fst)
96+ [ env getImages $ \imgs ->
97+ bgroup "writers" $ mapMaybe (writerBench imgs doc . fst)
9798 (sortOn fst
9899 writers :: [(T.Text, Writer PandocPure)])
99100 , bgroup "readers" $ mapMaybe (readerBench doc . fst)
cabal.project+9−8
@@ -1,12 +1,13 @@
11packages: pandoc.cabal
2−
32tests: True
3+flags: +embed_data_files
44
5−package pandoc
6− flags: +embed_data_files -trypandoc
7− ghc-options: -j +RTS -A256m -RTS
5+source-repository-package
6+ type: git
7+ location: https://github.com/jgm/doctemplates
8+ tag: 428c26d5303cf7a2b1051fe1ffd9aafe9ba71c81
89
9−-- source-repository-package
10−-- type: git
11−-- location: https://github.com/jgm/citeproc
12−-- tag: d44e24696ab444090d0e63e321c3a573f68b2e74
10+source-repository-package
11+ type: git
12+ location: https://github.com/jgm/citeproc
13+ tag: 4ce0501cd6f9c86eee087afcf878c256e49b9615
changelog.md+982−105
@@ -1,6 +1,782 @@
11# Revision history for pandoc
22
3−## pandoc 2.12 (UNRELEASED -- PROVISIONAL)
3+## pandoc 2.14.0.3 (2021-06-22)
4+
5+ * Text.Pandoc.MediaBag `insertMediaBag`: ensure we get a sane mediaPath
6+ for URLs (#7391). In earlier 2.14.x versions, we'd get
7+ incorrect paths for resources downloaded from URLs when the
8+ media are extracted (including in PDF production).
9+ * Text.Pandoc.Parsing: improve `emailAddress` (#7398).
10+ Previously the parser would accept characters in domains
11+ that are illegal in domains, and this sometimes caused it
12+ to gobble bits of the following text.
13+ * txt2tags reader: modify the email address parser so
14+ it still includes form parameters, even after the change to
15+ `emailAddress` in Text.Pandoc.Parsing.
16+ * Text.Pandoc.Readers.Metadata: Fix regression with comment-only YAML
17+ metadata blocks (#7400).
18+ * reveal.js writer and template: better handling of options. Previously
19+ it was impossible to specify false values for options that default to
20+ true (e.g. `center`); setting the option to false just caused the portion
21+ of the template setting the option to be omitted. Now we prepopulate
22+ all the variables with their default values, including them all
23+ unconditionally and allowing them to be overridden.
24+ * Markdown writer: Fix regression in code blocks with attributes (#7397).
25+ Code blocks with a single class but nonempty attributes
26+ were having attributes drop as a result of #7242.
27+ * LaTeX writer:
28+ + Add strut at end of minipage if it contains line breaks.
29+ Without them, the last line is not as tall as it should be in
30+ some cases.
31+ + Always use a minipage for cells with line breaks, when
32+ width information is available (#7393). Otherwise the way we treat them
33+ can lead to content that overflows a cell.
34+ + Use `\strut` instead of `~` before `\\` in empty line.
35+ * Use lts-18.0 stack resolver.
36+ * Require skylighting 0.10.5.2 (adding support for Swift).
37+ * Require commonmark 0.2.1.
38+ * Rephrase section on unsafe HTML in manual.
39+ * Create SECURITY.md
40+
41+## pandoc 2.14.0.2 (2021-06-13)
42+
43+ * Fix MediaBag regressions (#7345). iIn the 2.14 release `--extract-media`
44+ stopped working as before; there could be mismatches between the
45+ paths in the rendered document and the extracted media.
46+ This patch makes several changes that restore the earlier behavior
47+ (while keeping the same API). The `mediaPath` in 2.14 was always
48+ constructed from the SHA1 hash of the media contents. Now, we
49+ preserve the original path unless it's an absolute path or contains
50+ `..` segments (in that case we use a path based on the SHA1 hash of
51+ the contents).
52+
53+ In Text.Pandoc.MediaBag, `mediaDirectory` and `mediaItems` now use the
54+ `mediaPath`, rather than the mediabag key, for the first component of the
55+ tuple. This makes more sense, I think, and fits with the documentation of
56+ these functions; eventually, though, we should rework the API so that
57+ `mediaItems` returns both the keys and the MediaItems.
58+
59+ In Text.Pandoc.Class.IO, rewriting of source paths in `extractMedia` has
60+ been fixed.
61+
62+ In Text.Pandoc.Class.PandocMonad, `fillMediaBag` has been modified so that
63+ it doesn't modify image paths (that was part of the problem in #7345).
64+
65+ We now do path normalization (e.g. `\` separators on Windows) in
66+ writing the media.
67+
68+ * Text.Pandoc.PDF:
69+
70+ + Text.Pandoc.PDF: Fix regression in 2.14 for generation of PDFs with
71+ SVGs (#7344).
72+ + Only print relevant part of environment on `--verbose`. Since
73+ `--verbose` output might be put in an issue, we want to avoid
74+ spilling out secrets in environment variables.
75+
76+ * Markdown reader: fix pipe table regression in 2.11.4 (#7343).
77+ Previously pipe tables with empty headers (that is, a header
78+ line with all empty cells) would be rendered as headerless
79+ tables. This broke in 2.11.4. The fix here is to produce an
80+ AST with an empty table head when a pipe table has all empty
81+ header cells.
82+
83+ * LaTeX reader: don't allow optional `*` on symbol control sequences
84+ (#7340). Generally we allow optional starred variants of LaTeX commands
85+ (since many allow them, and if we don't accept these explicitly,
86+ ignoring the star usually gives acceptable results). But we
87+ don't want to do this for `\(*\)` and similar cases.
88+
89+ * Docx reader: handle absolute URIs in Relationship Target (#7374).
90+
91+ * Docx writer: fix handling of empty table headers (Albert Krewinkel,
92+ #7369). A table header which does not contain any cells is now treated as
93+ an empty header.
94+
95+ * LaTeX writer: Fix regression in table header position (#7347).
96+ In recent versions the table headers were no longer bottom-aligned
97+ (if more than one line). This patch fixes that by using minipages
98+ for table headers in non-simple tables.
99+
100+ * CommonMark writer:
101+
102+ + Do not use simple class for fenced-divs (Jan Tojnar, amends #7242.)
103+ + Do not throw away attributes when `Ext_attributes` is enabled.
104+ `Ext_attributes` covers at least the following:
105+ `Ext_fenced_code_attributes`, `Ext_header_attributes`,
106+ `Ext_inline_code_attributes`, `Ext_link_attributes`.
107+
108+ * Markdown writer:
109+
110+ + Allow `pipe_tables` to be disabled for commonmark formats
111+ (`commonmark_x`, `gfm`) (#7375).
112+ + Re-use functions from Text.Pandoc.Markdown.Inline (Jan Tojnar).
113+
114+ * DocBook writer: Remove non-existent admonitions (Jan Tojnar).
115+ `attention`, `error` and `hint` are reStructuredText specific.
116+
117+ * HTML writer: Don't omit width attribute on div (#7342).
118+
119+ * Text.Pandoc.MIME, `extensionFromMimeType`: add a few special cases.
120+ When we do a reverse lookup in the MIME table, we just get the
121+ last match, so when the same mime type is associated with several
122+ different extensions, we sometimes got weird results, e.g. `.vs`
123+ for `text/plain`. These special cases help us get the most standard
124+ extensions for mime types like `text/plain`.
125+
126+ * Lua utils: fix handling of table headers in `from_simple_table` (Albert
127+ Krewinkel, #7369). Passing an empty list of header cells now results
128+ in an empty table header.
129+
130+ * Text.Pandoc.Citeproc:
131+
132+ + Avoid duplicate classes and attributes on references div.
133+ + Fix regression in citeproc processing (#7376). If inline
134+ references are used (in the metadata `references` field), we
135+ should still only include in the bibliography items that are
136+ actually cited (unless `nocite` is used).
137+
138+ * Require citeproc 0.4.0.1. This fixes a bug which led to doubled
139+ "et al." in some (rare) circumstances.
140+
141+ * MANUAL.txt:
142+
143+ + Mention GladTeX for EPUB export (Sebastian Humenda).
144+ This updates the manual and the web site about the GladTeX usage.
145+ + More details and a useful link for YAML syntax.
146+
147+ * CONTRIBUTING.md: update modules overview (Albert Krewinkel).
148+
149+ * using-the-pandoc-api.md: switch from String to Text (Albert Krewinkel).
150+
151+
152+## pandoc 2.14.0.1 (2021-06-01)
153+
154+ * Commonmark reader: Fix regression in 2.14 with YAML metdata block parsing,
155+ which could cause the document body to be omitted after metadata (#7339).
156+
157+ * HTML reader: fix column width regression in 2.14 (#7334).
158+ Column widths specified with a style attribute were off by a factor of 100.
159+
160+ * Markdown reader: in `rebasePaths`, check for both Windows and Posix
161+ absolute paths. Previously Windows pandoc was treating
162+ `/foo/bar.jpg` as non-absolute.
163+
164+ * Text.Pandoc.Logging: In rendering `LoadedResource`, use relative paths.
165+
166+ * Docx writer: fix regression on captions (#7328). The "Table Caption"
167+ style was no longer getting applied. (It was overwritten by "Compact.")
168+
169+ * Use commonmark-extensions 0.2.1.2
170+
171+## pandoc 2.14 (2021-05-28)
172+
173+ * Change reader types, allowing better tracking of source positions
174+ [API change]. Previously, when multiple file arguments were provided,
175+ pandoc simply concatenated them and passed the contents to the readers,
176+ which took a Text argument. As a result, the readers had no way of knowing
177+ which file was the source of any particular bit of text. This meant that
178+ we couldn't report accurate source positions on errors or include accurate
179+ source positions as attributes in the AST. More seriously, it meant that
180+ we couldn't resolve resource paths relative to the files containing them
181+ (see e.g. #5501, #6632, #6384, #3752).
182+
183+ * Add `rebase_relative_paths` extension (#3752). When enabled, this
184+ extension rewrites relative image and link paths by prepending
185+ the (relative) directory of the containing file. This
186+ behavior is useful when your input sources are split
187+ into multiple files, across several directories, with files
188+ referring to images stored in the same directory. The
189+ extension can be enabled for all markdown and commonmark-based formats.
190+
191+ * Add Text.Pandoc.Sources (exported module), with a `Sources` type and a
192+ `ToSources` class. A `Sources` wraps a list of `(SourcePos, Text)` pairs
193+ [API change]. A parsec `Stream` instance is provided for `Sources`. The
194+ module also exports versions of parsec's `satisfy` and other Char parsers
195+ that track source positions accurately from a `Sources` stream (or any
196+ instance of the new `UpdateSourcePos` class).
197+
198+ * Text.Pandoc.Parsing
199+
200+ + Export the modified Char parsers defined in Text.Pandoc.Sources
201+ instead of the ones parsec provides. Modified parsers to use a
202+ `Sources` as stream [API change].
203+ + Improve include file functions [API change]. Remove old
204+ `insertIncludedFileF`. Give `insertIncludedFile` a more general type,
205+ allowing it to be used where `insertIncludedFileF` was.
206+ + Add parameter to the `citeKey` parser from
207+ Text.Pandoc.Parsing, which controls whether the `@{..}`
208+ syntax is allowed [API change].
209+
210+ * Text.Pandoc.Error: Modified the constructor `PandocParsecError` to take a
211+ `Sources` rather than a `Text` as first argument, so parse error locations
212+ can be accurately reported.
213+
214+ * Fix source position reporting for YAML bibliographies (#7273).
215+
216+ * Issue error message when reader or writer format is malformed
217+ (#7231). Previously we exited with an error status but (due to a bug)
218+ no message.
219+
220+ * Smarter smart quotes (#7216, #2103). Treat a leading `"` with no
221+ closing `"` as a left curly quote. This supports the practice, in
222+ fiction, of continuing paragraphs quoting the same speaker without an
223+ end quote. It also helps with quotes that break over lines in line blocks.
224+
225+ * Markdown reader:
226+
227+ + Use MetaInlines not MetaBlocks for multimarkdown metadata fields.
228+ This gives better results in converting to e.g. pandoc markdown.
229+ + Implement curly-brace syntax for Markdown citation keys (#6026).
230+ The change provides a way to use citation keys that contain
231+ special characters not usable with the standard citation key syntax.
232+ Example: `@{foo_bar{x}'}` for the key `foo_bar{x}`. It also allows
233+ separating citation keys from immediately following text, e.g. `@{foo}A`.
234+
235+ * RST reader:
236+
237+ + Seek include files in the directory of the file
238+ containing the include directive, as RST requires (#6632).
239+ + Use `insertIncludedFile` from Text.Pandoc.Parsing
240+ instead of reproducing much of its code.
241+
242+ * Org reader: Resolve org includes relative to the directory containing the
243+ file containing the INCLUDE directive (#5501).
244+
245+ * ODT reader: Treat tabs as spaces (#7185, niszet).
246+
247+ * Docx reader:
248+
249+ + Add handling of vml image objects (#7257, mbrackeantidot).
250+ + Support new table features (Emily Bourke, #6316): column
251+ spans, row spans, multiple header rows, table description
252+ (parsed as a simple caption), captions, column widths.
253+
254+ * LaTeX reader:
255+
256+ + Improved siunitx support (#6658, #6620).
257+ + Better support for `\xspace` (#7299).
258+ + Improve parsing of `\def` macros. We previously set "verbatim mode"
259+ even for parsing the initial `\def`; this caused problems
260+ for `\def` nested inside another `\def`.
261+ + Implement `\newif`.
262+
263+ * ConTeXt writer: improve ordered lists (#5016, Denis Maier).
264+ Change ordered list from itemize to enumerate. Add new
265+ itemgroup for ordered lists. Remove manual insertion of
266+ width attributes. Use tabular figures in ordered list
267+ enumerators.
268+
269+ * HTML reader:
270+
271+ + Don't fail on unmatched closing "script" tag (Albert Krenkel, #7282).
272+ + Keep h1 tags as normal headers (#2293, Albert Krewinkel).
273+ The tags `<title>` and `<h1 class="title">` often contain the same
274+ information, so the latter was dropped from the document. However, as
275+ this can lead to loss of information, the heading is now always
276+ retained. Use `--shift-heading-level-by=-1` to turn the `<h1>`
277+ into the document title, or a filter to restore the previous behavior.
278+ + Handle relative lengths (e.g. `2*`) in HTML column widths (#4063).
279+ See <https://www.w3.org/TR/html4/types.html#h-6.6>.
280+
281+ * DocBook/JATS readers:
282+
283+ + Fix mathml regression caused by the switch in XML libraries (#7173).
284+ + Fix "phrase" in DocBook: take classes from "role" not "class" (#7195).
285+
286+ * DocBook reader: ensure that first and last names are separated (#6541).
287+
288+ * Jira reader (Albert Krewinkel, #7218):
289+
290+ + Support "smart" links: `[alias|https://example.com|smart-card]` syntax.
291+ + Allow spaces and most unicode characters in attachment links.
292+ + No longer require a newline character after `{noformat}`.
293+ + Only allow URI path segment characters in bare links.
294+ + The `file:` schema is no longer allowed in bare links; these
295+ rarely make sense.
296+
297+ * Plain writer: handle superscript unicode minus (#7276).
298+
299+ * LaTeX writer:
300+
301+ + Better handling of line breaks in simple tables (#7272).
302+ Now we also handle the case where they're embedded in other elements,
303+ e.g. spans.
304+ + For beamer output, support `exampleblock` and `alertblock` (#7278).
305+ A block will be rendered as an `exampleblock` if the heading
306+ has class `example` and an `alertblock` if it has class `alert`.
307+ + Separate successive quote chars with thin space (#6958,
308+ Albert Krewinkel). Successive quote characters are separated with
309+ a thin space to improve readability and to prevent unwanted ligatures.
310+ Detection of these quotes sometimes had failed if the second quote
311+ was nested in a span element.
312+ + Separate successive quote chars with thin space (#6958, Albert
313+ Krewinkel).
314+
315+ * EPUB Writer: Fix belongs-to-collection XML id choice (#7267, nuew).
316+ The epub writer previously used the same XML id for both the book
317+ identifier and the epub collection. This causes an error on epubcheck.
318+
319+ * BibTeX/BibLaTeX writer: Handle `annote` field (#7266).
320+
321+ * ZimWiki writer: allow links and emphasis in headers (#6605,
322+ Albert Krewinkel).
323+
324+ * ConTeXt writer:
325+
326+ + Support blank lines in line blocks (#6564, Albert Krewinkel,
327+ thanks to @denismaier).
328+ + Use span identifiers as reference anchors (#7246, Albert Krewinkel).
329+
330+ * HTML writer:
331+
332+ + Keep attributes from code nested below `pre` tag (#7221,
333+ Albert Krewinkel). If a code block is defined with `<pre><code
334+ class="language-x">…</code></pre>`, where the `<pre>` element has no
335+ attributes, then the attributes from the `<code>` element are used
336+ instead. Any leading `language-` prefix is dropped in the code's
337+ `class` attribute are dropped to improve syntax highlighting.
338+ + Ensure headings only have valid attribs in HTML4 (#5944, Albert
339+ Krewinkel).
340+ + Parse `<header>` as a Div (Albert Krewinkel).
341+
342+ * Org writer:
343+
344+ + Inline latex envs need newlines (#7252, tecosaur).
345+ As specified in https://orgmode.org/manual/LaTeX-fragments.html, an
346+ inline \begin{}...\end{} LaTeX block must start on a new line.
347+ + Use LaTeX style maths deliminators (#7196, tecosaur).
348+
349+ * JATS writer (Albert Krewinkel):
350+
351+ + Use either styled-content or named-content for spans (#7211).
352+ If the element has a content-type attribute, or at least one class,
353+ then that value is used as `content-type` and the span is put inside
354+ a `<named-content>` element. Otherwise a `<styled-content>` element
355+ is used instead.
356+ + Reduce unnecessary use of `<p>` elements for wrapping (#7227).
357+ The `<p>` element is used for wrapping in cases were the contents
358+ would otherwise not be allowed in a certain context. Unnecessary
359+ wrapping is avoided, especially around quotes (`<disp-quote>` elements).
360+ + Convert spans to `<named-content>` elements (#7211). Spans with
361+ attributes are converted to `<named-content>` elements instead of
362+ being wrapped with `<milestone-start/>` and `<milestone-end>`
363+ elements. Milestone elements are not allowed in documents using the
364+ articleauthoring tag set, so this change ensures the creation of valid
365+ documents.
366+ + Add footnote number as label in backmatter (#7210). Footnotes in the
367+ backmatter are given the footnote's number as a label. The
368+ articleauthoring output is unaffected from this change, as footnotes
369+ are placed inline there.
370+ + Escape disallows chars in identifiers. XML identifiers must start
371+ with an underscore or letter, and can contain only a limited set
372+ of punctuation characters. Any IDs not adhering to these rules are
373+ rewritten by writing the offending characters as `Uxxxx`,
374+ where `xxxx` is the character's hex code.
375+
376+ * Jira writer: use `{color}` when span has a color attribute
377+ (Albert Krewinkel, tarleb/jira-wiki-markup#10).
378+
379+ * Docx writer:
380+
381+ + Autoset table width if no column has an explicit width (Albert
382+ Krewinkel).
383+ + Extract Table handling into separate module (Albert Krewinkel).
384+ + Support colspans and rowspans in tables (Albert Krewinkel, #6315).
385+ + Support multirow table headers (Albert Krewinkel).
386+ + Improve integration of settings from reference.docx (#1209).
387+ This change allows users to create a reference.docx that
388+ sets `w:proofState` for spelling or grammar to `dirty`,
389+ so that spell/grammar checking will be triggered on the
390+ generated docx.
391+ + Copy over more settings from reference.docx (#7240). From settings.xml
392+ in the reference-doc, we now include: `zoom`, `embedSystemFonts`,
393+ `doNotTrackMoves`, `defaultTabStop`, `drawingGridHorizontalSpacing`,
394+ `drawingGridVerticalSpacing`, `displayHorizontalDrawingGridEvery`,
395+ `displayVerticalDrawingGridEvery`, `characterSpacingControl`,
396+ `savePreviewPicture`, `mathPr`, `themeFontLang`, `decimalSymbol`,
397+ `listSeparator`, `autoHyphenation`, `compat`.
398+ + Set zoom to 100% by default in settings.xml.
399+ + Align math options more with current Word defaults (e.g. Cambria Math
400+ font).
401+ + Remove `rsid`s from default settings.xml. Word will add these
402+ when revisions are made.
403+
404+ * Ms writer: Handle tables with multiple paragraphs (#7288).
405+ Previously they overflowed the table cell width. We now set line lengths
406+ per-cell and restore them after the table has been written.
407+
408+ * Markdown writer:
409+
410+ + Use cleaner braceless syntax for code blocks with a
411+ single class (#7242, Jan Tojnar).
412+ + Add quotes properly in markdown YAML metadata fields (#7245).
413+ This fixes a bug, which caused the writer to look at the *last*
414+ rather than the *first* character in determining whether quotes
415+ were needed. So we got spurious quotes in some cases and
416+ didn't get necessary quotes in others.
417+ + Use `@{..}` syntax for citations when needed.
418+ + Use fewer unneeded escapes for `#` (see #6259).
419+ + Improve escaping of `@`. We need to escape literal `@` before
420+ `{` because of the new citation syntax.
421+
422+ * Commonmark writer: Use backslash escapes for `<` and `|`...
423+ instead of entities (#7208).
424+
425+ * Powerpoint writer: allow `monofont` to be specified in metadata
426+ (#7187).
427+
428+ * LaTeX template:
429+
430+ + Use non-starred names for xcolor color names (#6109).
431+ This should make svgnames and x11names work properly.
432+ + Fix bad vertical spacing after bibliography (#7234, badumont).
433+ + List of figures before list of tables (#7235, Julien Dutant).
434+ + Move CSL macro definitions before header-includes so they can be
435+ overridden (#7286).
436+ + Improve treatment of CSL `entry-spacing` (#7296).
437+ Previously with the default template settings (`indent` variable
438+ not set), we would get interparagraph spaces separating bib
439+ entries even with `entry-spacing="0"`. On the other hand,
440+ setting `entry-spacing="2"` gave ridiculously large spacing.
441+ This change makes the spacing caused by `entry-spacing` a multiple
442+ of `\parskip` by default, which gives aesthetically reasonable
443+ output. Those who want a larger or smaller unit (e.g. because
444+ they use `indent` which sets `\parskip` to 0) may
445+ `\setlength{\cslentryspacingunit}{10pt}` in header-includes
446+ to override the defaults.
447+ + Move title, author, date up to top of preamble (#7295).
448+ This allows header-includes to use them, and puts them
449+ in a position where you can see them immediately.
450+ + Define commands for zero width non-joiner character
451+ (#6639, Albert Krewinkel). The zero-width non-joiner character
452+ is used to avoid ligatures (e.g. in German).
453+
454+ * ConTeXt template:
455+
456+ + Define `enumerate` itemgroup (#5016, Denis Maier).
457+ + List of figures before list of tables (#7235, Julien Dutant).
458+
459+ * reveal.js template:
460+
461+ + Support `toc-title` (#7171, Florian Kohrt).
462+ + Use `hash: true` by default rather than `history: true` (#6968).
463+
464+ * HTML-based slide shows: add support for `institute` (#7289, Thomas
465+ Hodgson).
466+
467+ * Text.Pandoc.Extensions: Add constructor `Ext_rebase_relative_paths` to
468+ `Extensions` [API change].
469+
470+ * Text.Pandoc.XML.Light: add Eq, Ord instances for Content,
471+ Element, Attr, CDataKind [API change].
472+
473+ * Text.Pandoc.MediaBag:
474+
475+ + Change type to use a `Text` key instead of `[FilePath]`.
476+ We normalize the path and use `/` separators for consistency.
477+ + Export `MediaItem` type [API change].
478+ + Change `MediaBag` type to a map from Text to MediaItem [API change].
479+ + `lookupMedia` now returns a `MediaItem` [API change].
480+ + Change `insertMedia` so it sets the `mediaPath` to a filename based on
481+ the SHA1 hash of the contents. This will be used when contents
482+ are extracted.
483+
484+ * Text.Pandoc.Class.PandocMonad:
485+
486+ + Remove `fetchMediaResource` [API change]. Use `fetchItem` to get
487+ resources in `fillMediaBag`.
488+ + Add informational message in `downloadOrRead` indicating what path
489+ local resources have been loaded from.
490+
491+ * Text.Pandoc.Logging:
492+
493+ + Remove single quotes around paths in messages.
494+ + Add LoadedResource constructor to LogMessage [API change].
495+ This is for INFO-level messages telling where image data has been
496+ loaded from. (This can vary because of the resource path.)
497+
498+ * Text.Pandoc.Asciify: simplify code and export `toAsciiText` [API change].
499+ Instead of encoding a giant (and incomplete) map, we now
500+ just use unicode-transforms to normalize the text to
501+ a canonical decomposition, and manipulate the result.
502+
503+ * App: allow tabs expansion even if file-scope is used (Albert Krewinkel,
504+ #6709). Tabs in plain-text inputs are now handled correctly, even if
505+ the `--file-scope` flag is used.
506+
507+ * Add new internal module Text.Pandoc.Writers.GridTable (Albert Krewinkel).
508+
509+ * Text.Pandoc.Highlighting: Change type of `languagesByExtension`, adding
510+ a parameter for a `SyntaxMap` [API change] (Jan Tojnar, #7241).
511+ Languages defined using `--syntax-definition` were not recognized by
512+ `languagesByExtension`. This patch corrects that, allowing the writers
513+ to see all custom definitions. The LaTeX writer still uses the default
514+ syntax map, but that's okay in that context, since
515+ `--syntax-definition` won't create new listings styles.
516+
517+ * Text.Pandoc.Citeproc:
518+
519+ + Ensure that CSL-related attributes are passed on to a Div with id
520+ 'refs'. Otherwise things like `entry-spacing` won't work when
521+ such Divs are used.
522+ + Use metadata's `lang` for the lang parameter of citeproc, overriding
523+ `localeLanguage`.
524+ + Recognize locators spelled with a capital letter (#7323).
525+ + Add a comma and a space in front of the suffix if it doesn't start
526+ with space or punctuation (#7324).
527+ + Don't detect math elements as locators (#7321).
528+
529+ * Remove Text.Pandoc.BCP47 module [API change]. Use types and functions
530+ from UnicodeCollation.Lang instead. This is a richer implementation
531+ of BCP 47.
532+
533+ * Text.Pandoc.Shared:
534+
535+ + Fix regression in grid tables for wide characters (#7214).
536+ In the translation from String to Text, a char-width-sensitive
537+ `splitAt'` was dropped. This commit reinstates it and uses it to make
538+ `splitTextByInstances` char-width sensitive.
539+ + Add `getLang` (formerly in the now-removed BCP47) [API change].
540+
541+ * Text.Pandoc.SelfContained: use `application/octet-stream`
542+ for unknown mime types instead of halting with an error (#7202).
543+
544+ * Lua filters: respect Inlines/Blocks filter functions in `pandoc.walk_*`
545+ (Albert Krewinkel).
546+
547+ * Add text as build-depend for trypandoc (#7193, Roman Beránek).
548+
549+ * Bump upper-bounds for network-uri, time, attoparsec.
550+
551+ * Use citeproc 0.4.
552+
553+ * Use texmath 0.12.3.
554+
555+ * Use jira-wiki-markup 1.3.5 (Albert Krewinkel).
556+
557+ * Require latest skylighting (fixes a bug in XML syntax highlighting).
558+
559+ * Use latest xml-conduit.
560+
561+ * Use latest commonmark, commonmark-extensions, commonmark-pandoc.
562+
563+ * Use haddock-library-1.10.0 (Albert Krewinkel).
564+
565+ * Allow compilation with base 4.15 (Albert Krewinkel).
566+
567+ * MANUAL:
568+
569+ + Add information about `lang` and bibliography sorting.
570+ + Add info about YAML escape sequences, link to spec (#7152,
571+ Albert Krewinkel).
572+ + Note that `institute` variable works for HTML-based slides.
573+ + Update documentation on citation syntax.
574+ + Add citation example for locators and suffixes (Tristan Stenner)
575+
576+ * Updated and fixed typos in documentation (Charanjit Singh,
577+ Anti-Distinctlyminty, Tatiana Porras, obcat).
578+
579+ * Add instructions for installing pandoc-types before compiling filter.
580+
581+ * INSTALL: add note that parallel installations should be avoided
582+ (#6865).
583+
584+ * Remove `biblatex-nussbaum.md` test. It is basically the same
585+ as `biblaetx-quotes.md`.
586+
587+ * Command tests: fail if a file contains no tests---and fix a
588+ test that failed in that way!
589+
590+ * Use smaller images in tests, reducing the size of the source tarball by 8 MB.
591+
592+
593+## pandoc 2.13 (2021-03-21)
594+
595+ * Support `yaml_metadata_block` extension for `commonmark`, `gfm` (#6537).
596+ This supported is a bit more limited than with pandoc's
597+ `markdown`. The YAML block must be the first thing in the input,
598+ and the leaf notes are parsed in isolation from the rest of
599+ the document. So, for example, you can't use reference
600+ links if the references are defined later in the document.
601+
602+ * Fix fallback to default partials when custom templates are used.
603+ If the directory containing a template does not contain the partial,
604+ it should be sought in the default templates, but this was not
605+ working properly (#7164).
606+
607+ * Handle `nocite` better with `--biblatex` and `--natbib` (#4585).
608+ Previously the nocite metadata field was ignored with these formats.
609+ Now it populates a `nocite-ids` template variable and causes a
610+ `\nocite` command to be issued.
611+
612+ * Text.Pandoc.Citeproc: apply `fixLinks` correctly (#7130). This is code
613+ that incorporates a prefix like `https://doi.org/` into a following link
614+ when appropriate.
615+
616+ * Text.Pandoc.Shared:
617+
618+ + Remove `backslashEscapes`, `escapeStringUsing` [API change]. Replace
619+ these inefficient association list lookups with more efficient escaping
620+ functions in the writers that used them (for a 10-25% performance boost
621+ in org, haddock, rtf, texinfo writers).
622+ + Remove `ToString`, `ToText` typeclasses [API change]. These were needed
623+ for the transition from String to Text, but they are no longer used and
624+ may clash with other things.
625+ + Simplify `compactDL`.
626+
627+ * Text.Pandoc.Parsing:
628+
629+ + Change type of `readWithM` so that it is no longer polymorphic
630+ [API change]. The `ToText` class has been removed, and now that we've
631+ completed the transition to Text we no longer need this to operate
632+ on Strings.
633+ + Remove `F` type synonym [API change]. Muse and Org were defining their
634+ own `F` anyway.
635+
636+ * Text.Pandoc.Readers.Metadata:
637+
638+ + Export `yamlMetaBlock` [API change].
639+ + Make `yamlBsToMeta`, `yamlBsToRefs` polymorphic on the parser state
640+ [API change].
641+
642+ * Markdown reader: Fix regression with `tex_math_backslash` (#7155).
643+
644+ * MediaWiki reader: Allow block-level content in notes (ref) (#7145).
645+
646+ * Jira reader (Albert Krewinkel):
647+
648+ + Fixed parsing of autolinks (i.e., of bare URLs in the text).
649+ Previously an autolink would take up the rest of a line, as spaces
650+ were allowed characters in these items.
651+ + Emoji character sequences no longer cause parsing failures. This was
652+ due to missing backtracking when emoji parsing fails.
653+ + Mark divs created from panels with class "panel".
654+
655+ * RST reader: fix logic for ending comments (#7134). Previously comments
656+ sometimes got extended too far.
657+
658+ * DocBook writer: include Header attributes as XML attributes on
659+ section (Erik Rask). Attributes with key names that are not allowed
660+ as XML attributes are dropped, as are attributes with invalid values
661+ and `xml:id` (DocBook 5) and `id` (DocBook 4).
662+
663+ * Docx writer:
664+
665+ + Make `nsid` in `abstractNum` deterministic. Previously we assigned
666+ a random number, but we don't need random values, so now we just
667+ assign a value based on the list marker.
668+ + Use integral values for `w:tblW` (#7141).
669+
670+ * Jira writer (Albert Krewinkel):
671+
672+ + Block quotes are only rendered as `bq.` if they do not contain a
673+ linebreak.
674+ + Jira writer: improve div/panel handling. Include div attributes in
675+ panels, always render divs with class `panel` as panels, and
676+ avoid nesting of panels.
677+
678+ * HTML writer: Add warnings on duplicate attribute values.
679+ This prevents emitting invalid HTML. Ultimately it would be good to
680+ prevent this in the types themselves, but this is better for now.
681+
682+ * Org writer: Prevent unintended creation of ordered list items (#7132,
683+ Albert Krewinkel). Adjust line wrapping if default wrapping would cause
684+ a line to be read as an ordered list item.
685+
686+ * JATS templates: support 'equal-contrib' attrib for authors (Albert
687+ Krewinkel). Authors who contributed equally to a paper may be marked
688+ with `equal-contrib`.
689+
690+ * reveal.js template: replace JS comment with HTML (#7154, Florian Kohrt).
691+
692+ * Text.Pandoc.Logging: Add `DuplicateAttribute` constructor to `LogMessage`.
693+ [API change]
694+
695+ * Use `-j4` for linux release build. This speeds up the build dramatically
696+ on arm.
697+
698+ * cabal.project: remove ghcoptions. Move flags to top level, so they can
699+ be set differently on the command line.
700+
701+ * Require latest texmath, skylighting, citeproc, jira-wiki-markup.
702+ (The latest skylighting fixes a bad bug with Haskell syntax highlighting.)
703+ Narrow version bounds for texmath, skylighting, and citeproc, since
704+ the test output depend on them.
705+
706+ * Use doclayout 0.3.0.2. This significantly reduces the time and memory
707+ needed to compile pandoc.
708+
709+ * Use `foldl'` instead of `foldl` everywhere.
710+
711+ * Update bounds for random (#7156, Alexey Kuleshevich).
712+
713+ * Remove uses of some partial functions.
714+
715+ * Don't bake in a larger stack size for the executable.
716+
717+ * Test improvements:
718+
719+ + Use `getExecutablePath` from base, avoiding the dependency on
720+ `executable-path`.
721+ + Factor out `setupEnvironment` in Helpers, to avoid code duplication.
722+ + Fix finding of data files by setting teh `pandoc_datadir` environment
723+ variable when we shell out to pandoc. This avoids the need to use
724+ `--data-dir` for the tests, which caused problems finding `pandoc.lua`
725+ when compiling without the `embed_data_files` flag (#7163).
726+
727+ * Benchmark improvements:
728+
729+ + Build `+RTS -A8m -RTS` into default ghc-options for benchmark.
730+ This is necessary to get accurate benchmark results; otherwise we
731+ are largely measuring garbage collecting, some not related to the
732+ current benchmark.
733+ + Allow specifying BASELINE file in 'make bench' for comparison
734+ (otherwise the latest benchmark is chosen by default).
735+ + Force `readFile` in benchmarks early (Bodigrim).
736+
737+ * CONTRIBUTING: suggest using a `cabal.project.local` file (#7153,
738+ Albert Krewinkel).
739+
740+ * Add ghcid-test to Makefile. This loads the test suite in ghcid.
741+
742+
743+## pandoc 2.12 (2021-03-08)
744+
745+ * `--resource-path` now accumulates if specified multiple
746+ times (#6152). Resource paths specified later on the command line are
747+ prepended to those specified earlier. Thus,
748+ `--resource-path foo --resource-path bar:baz` is equivalent to
749+ `--resource-path bar:bas:foo`. (The previous behavior was
750+ for the last `--resource-path` to replace all the rest.)
751+ `resource-path` in defaults files behaves the same way: it
752+ will be prepended to the resource path set by earlier
753+ command line options or defaults files. This change
754+ facilitates the use of multiple defaults files: each can
755+ specify a directory containing resources it refers to
756+ without clobbering the resource paths set by the others.
757+
758+ * Allow defaults files to refer to the home directory, the
759+ user data directory, and the directory containing the defaults file
760+ itself (#5871, #5982, #5977). In fields that expect file paths
761+ (and only in these fields),
762+
763+ + `${VARIABLE}` will expand to the value of the environment variable
764+ `VARIABLE` (and in particular `${HOME}` will expand to the path
765+ of the home directory). A warning will be raised for undefined
766+ variables.
767+ + `${USERDATA}` will expand to the path of the user data
768+ directory in force when the defaults file is being processed.
769+ + `${.}` will expand to the directory containing the defaults file.
770+ (This allows default files to be placed in a directory containing
771+ resources they make use of.)
772+
773+ * When downloading content from URL arguments, be sensitive to
774+ the character encoding (#5600). We can properly handle UTF-8 and latin1
775+ (ISO-8859-1); for others we raise an error. Fall back to latin1 if
776+ no charset is given in the mime type and UTF-8 decoding fails.
777+
778+ * Allow abbreviations that don't end in a period to be
779+ specified using `--abbreviations` (#7124).
4780
5781 * Add new unexported module Text.Pandoc.XML.Light, as well
6782 as Text.Pandoc.XML.Light.Types, Text.Pantoc.XML.Light.Proc,
@@ -34,75 +810,6 @@
34810 these have been added. And the docx golden tests have been updated,
35811 because the new parser does not preserve the order of attributes.
36812
37− * Text.Pandoc.App
38−
39− + Add `parseOptionsFromArgs` [API change, new exported function].
40−
41− * Text.Pandoc.Citeproc.BibTeX
42−
43− + `Text.Pandoc.Citeproc.writeBibTeXString` now returns
44− `Doc Text` instead of `Text` (#7068).
45− + Correctly handle `pages` (= `page` in CSL) (#7067).
46− + Correctly handle BibLaTeX `langid` (= `language` in CSL, #7067).
47− + In BibTeX output, protect foreign titles since there's no language
48− field (#7067).
49− + Clean up BibTeX parsing (#7049). Previously there was a messy code
50− path that gave strange results in some cases, not passing through raw
51− tex but trying to extract a string content. This was an artefact of
52− trying to handle some special bibtex-specific commands in the BibTeX
53− reader. Now we just handle these in the LaTeX reader and simplify
54− parsing in the BibTeX reader. This does mean that more raw tex will
55− be passed through (and currently this is not sensitive to the
56− `raw_tex` extension; this should be fixed).
57−
58− * Text.Pandoc.Citeproc.MetaValue
59−
60− + Correctly parse "raw" date value in markdown references metadata.
61− (See jgm/citeproc#53.)
62−
63− * Text.Pandoc.Class
64−
65− + Add `getTimestamp` [API change]. This attempts to read the
66− `SOURCE_DATE_EPOCH` environment variable and parse a UTC time
67− from it (treating it as a unix date stamp, see
68− https://reproducible-builds.org/specs/source-date-epoch/). If the
69− variable is not set or can't be parsed as a unix date stamp, then the
70− function returns the current date.
71−
72− * Text.Pandoc.Error
73−
74− + Remove unused variables (Albert Krewinkel)
75− + Export `renderError` [API change].
76− + Refactor `handleError` to use `renderError`. This allows us render
77− error messages without exiting.
78−
79− * Text.Pandoc.Extensions
80−
81− + `Ext_task_lists` is now supported by org (and turned
82− on by default) (Albert Krewinkel, #6336).
83− + Remove `Ext_fenced_code_attributes` from allowed commonmark attributes
84− (#7097). This attribute was listed as allowed, but it didn't actually
85− do anything. Use `attributes` for code attributes and more.
86−
87− * Lua subsystem:
88−
89− + Always load built-in Lua scripts from default data-dir (Albert
90− Krewinkel). The Lua modules `pandoc` and `pandoc.List` are now always
91− loaded from the system's default data directory. Loading from a
92− different directory by overriding the default path, e.g. via
93− `--data-dir`, is no longer supported to avoid unexpected behavior
94− and to address security concerns.
95− + Add module "pandoc.path" (Albert Krewinkel, #6001, #6565).
96− The module allows to work with file paths in a convenient and
97− platform-independent manner.
98−
99− * Text.Pandoc.PDF
100−
101− + Disable `smart` extension when building PDF via LaTeX.
102− This is to prevent accidental creation of ligatures like
103− `` ?` `` and `` !` `` (especially in languages with quotations like
104− German), and similar ligature issues. (See jgm/citeproc#54.)
105−
106813 * DocBook reader:
107814
108815 + Avoid expensive tree normalization step, as it is not necessary
@@ -137,6 +844,11 @@
137844
138845 * LaTeX reader:
139846
847+ + Don't export `tokenize`, `untokenize` [API change]. These are internal
848+ implementation details, which were only exported for testing.
849+ They don't belong in the public API.
850+ + Improved efficiency of the parser. With these changes the reader
851+ is almost twice as fast as in the last release in our benchmarks.
140852 + Code cleanup, removing some unnecessary things.
141853 + Rewrite `withRaw` so it doesn't rely on fragile assumptions
142854 about token positions (which break when macros are expanded)
@@ -156,11 +868,20 @@
156868 it doesn't change anything.
157869 + Improve `braced'`. Remove the parameter, have it parse the
158870 opening brace, and make it more efficient.
871+ + Factor out pieces of the LaTeX reader to make the module smaller.
872+ This reduces memory demands when compiling. Created
873+ Text.Pandoc.Readers.{LaTeX,Math,Citation,Table,Macro,Inline}.
874+ Changed Text.Pandoc.Readers.LaTeX.SIunitx to export a command map
875+ instead of individual commands.
876+ + Handle table cells containing `&` in `\verb` (#7129).
877+
878+ * Make Text.Pandoc.Readers.LaTeX.Types an unexported module [API change].
159879
160880 * Markdown reader:
161881
162882 + Improved handling of mmd link attributes in references (#7080).
163883 Previously they only worked for links that had titles.
884+ + Improved efficiency of the parser (benchmarks show a 15% speedup).
164885
165886 * OPML reader:
166887
@@ -190,9 +911,10 @@
190911 * Jira reader:
191912
192913 + Modified the Doc parser to skip leading blank lines. This fixes
193− parsing of documents which start with multiple blank lines (#7095).
194− + Prevent URLs within link aliases to be treated as autolinks
195− (#6944).
914+ parsing of documents which start with multiple blank lines (Albert
915+ Krewinkel, #7095).
916+ + Prevent URLs within link aliases to be treated as autolinks (Albert
917+ Krewinkel, #6944).
196918
197919 * Text.Pandoc.Shared
198920
@@ -201,6 +923,10 @@
201923 and `underlineSpan` (which had been deprecated in April 2020)
202924 [API change].
203925 + Export `handleTaskListItem` (Albert Krewinkel) [API change].
926+ + Change `defaultUserDataDirs` to `defaultUserDataDir` [API
927+ change]. We determine what is the default user data directory
928+ by seeing whether the XDG directory and/or legacy
929+ directory exist.
204930
205931 * BibTeX writer:
206932
@@ -218,7 +944,7 @@
218944 + Use `getTimestamp` instead of `getCurrentTime` for timestamp.
219945 Setting `SOURCE_DATE_EPOCH` will allow reproducible builds.
220946
221− * Text.Pandoc.Writers.EPUB
947+ * EPUB writer:
222948
223949 + Use `getTimestamp` instead of `getCurrentTime` for timestamp.
224950 Setting `SOURCE_DATE_EPOCH` will allow reproducible builds (#7093).
@@ -233,6 +959,13 @@
233959 contains an ampersand or another character with a special meaning
234960 in XML.
235961
962+ * Jira writer:
963+
964+ + Use Span identifiers as anchors (Albert Krewinkel).
965+ + Use `{noformat}` instead of `{code}` for unknown languages (Albert
966+ Krewinkel). Code blocks which are not marked as a language supported
967+ by Jira are rendered as preformatted text via `{noformat}` blocks.
968+
236969 * LaTeX writer:
237970
238971 + Adjust hypertargets to beginnings of paragraphs (#7078).
@@ -241,12 +974,18 @@
241974 This makes a particular difference for links to citations using
242975 `--citeproc` and `link-citations: true`.
243976 + Change BCP47 lang tag from `jp` to `ja` (Mauro Bieg, #7047).
977+ + Use function instead of map for accent lookup (should be
978+ more efficient).
979+ + Split the module to make it easier to compile on low-memory
980+ systems: added Text.Pandoc.Writers.LaTeX.{Util,Citation,Lang}.
244981
245982 * Markdown writer:
246983
247984 + Handle math right before digit. We insert an HTML comment to
248985 avoid a `$` right before a digit, which pandoc will not recognize
249986 as a math delimiter.
987+ + Split the module to make it easier to compile on low-memory
988+ systems: added Text.Pandoc.Writers.Markdown.{Types,Inline}.
250989
251990 * ODT writer:
252991
@@ -279,40 +1018,154 @@
2791018 `--include-in-header`, `--include-before-body`, `--include-after-body`)
2801019 may be used.
2811020
282− * LaTeX template: Update to iftex package (#7073) (Andrew Dunning)
1021+ * LaTeX template:
1022+
1023+ + Update to iftex package (#7073) (Andrew Dunning)
1024+ + Wrap url colours in braces (#7121) (Loïc Grobol).
2831025
2841026 * revealjs template: Add 'center' option for vertical slide centering.
2851027 (maurerle, #7104).
2861028
2871029 * Text.Pandoc.XML: Improve efficiency of `fromEntities`.
2881030
289− * Test suite: a more robust way of testing the executable.
290− Many of our tests require running the pandoc executable. This is
291− problematic for a few different reasons. First, cabal-install will
292− sometimes run the test suite after building the library but before
293− building the executable, which means the executable isn't in place for
294− the tests. One can work around that by first building, then building and
295− running the tests, but that's fragile. Second, we have to find the
296− executable. So far, we've done that using a function `findPandoc` that
297− attempts to locate it relative to the test executable (which can be
298− located using findExecutablePath). But the logic here is delicate and
299− work with every combination of options. To solve both problems, we add
300− an `--emulate` option to the `test-pandoc` executable. When `--emulate`
301− occurs as the first argument passed to `test-pandoc`, the program simply
302− emulates the regular pandoc executable, using the rest of the arguments
303− (after `--emulate`). Thus, `test-pandoc --emulate -f markdown -t latex`
304− is just like `pandoc -f markdown -t latex`.
305− Since all the work is done by library functions, implementing this
306− emulation just takes a couple lines of code and should be entirely
307− reliable. With this change, we can test the pandoc executable by running
308− the test program itself (locatable using `findExecutablePath`) with the
309− `--emulate` option. This removes the need for the fragile `findPandoc`
310− step, and it means we can run our integration tests even when we're just
311− building the library, not the executable. [Note: part of this change
312− involved simplifying some complex handling to set environment variables
313− for dynamic library paths. I have tested a build with
314− `--enable-dynamic-executable`, and it works, but further testing may be
315− needed.]
1031+ * Text.Pandoc.MIME
1032+
1033+ + Add exported function `getCharset` [API change].
1034+
1035+ * Text.Pandoc.UTF8: change IO functions to return Text, not String
1036+ [API change]. This affects `readFile`, `getContents`, `writeFileWith`,
1037+ `writeFile`, `putStrWith`, `putStr`, `putStrLnWith`, `putStrLn`.
1038+ `hPutStrWith`, `hPutStr`, `hPutStrLnWith`, `hPutStrLn`, `hGetContents`.
1039+ This avoids the need to uselessly create a linked list of characters
1040+ when emiting output.
1041+
1042+ * Text.Pandoc.App
1043+
1044+ + Add `parseOptionsFromArgs` [API change, new exported function].
1045+ + Add fields for CSL options to `Opt` [API change]:
1046+ `optCSL`, `optbibliography`, `optCitationAbbreviations`.
1047+
1048+ * Text.Pandoc.Citeproc.BibTeX
1049+
1050+ + `Text.Pandoc.Citeproc.writeBibTeXString` now returns
1051+ `Doc Text` instead of `Text` (#7068).
1052+ + Correctly handle `pages` (= `page` in CSL) (#7067).
1053+ + Correctly handle BibLaTeX `langid` (= `language` in CSL, #7067).
1054+ + In BibTeX output, protect foreign titles since there's no language
1055+ field (#7067).
1056+ + Clean up BibTeX parsing (#7049). Previously there was a messy code
1057+ path that gave strange results in some cases, not passing through raw
1058+ tex but trying to extract a string content. This was an artefact of
1059+ trying to handle some special bibtex-specific commands in the BibTeX
1060+ reader. Now we just handle these in the LaTeX reader and simplify
1061+ parsing in the BibTeX reader. This does mean that more raw tex will
1062+ be passed through (and currently this is not sensitive to the
1063+ `raw_tex` extension; this should be fixed).
1064+
1065+ * Text.Pandoc.Citeproc.MetaValue
1066+
1067+ + Correctly parse "raw" date value in markdown references metadata.
1068+ (See jgm/citeproc#53.)
1069+
1070+ * Text.Pandoc.Citeproc
1071+
1072+ + Use https URLs for links (Salim B, #7122).
1073+
1074+ * Text.Pandoc.Class
1075+
1076+ + Add `getTimestamp` [API change]. This attempts to read the
1077+ `SOURCE_DATE_EPOCH` environment variable and parse a UTC time
1078+ from it (treating it as a unix date stamp, see
1079+ https://reproducible-builds.org/specs/source-date-epoch/). If the
1080+ variable is not set or can't be parsed as a unix date stamp, then the
1081+ function returns the current date.
1082+
1083+ * Text.Pandoc.Error
1084+
1085+ + Add `PandocUnsupportedCharsetError` constructor for
1086+ `PandocError` [API change].
1087+ + Export `renderError` [API change].
1088+ + Refactor `handleError` to use `renderError`. This allows us render
1089+ error messages without exiting.
1090+
1091+ * Text.Pandoc.Extensions
1092+
1093+ + `Ext_task_lists` is now supported by org (and turned
1094+ on by default) (Albert Krewinkel, #6336).
1095+ + Remove `Ext_fenced_code_attributes` from allowed commonmark attributes
1096+ (#7097). This attribute was listed as allowed, but it didn't actually
1097+ do anything. Use `attributes` for code attributes and more.
1098+
1099+ * Lua subsystem:
1100+
1101+ + Always load built-in Lua scripts from default data-dir (Albert
1102+ Krewinkel). The Lua modules `pandoc` and `pandoc.List` are now always
1103+ loaded from the system's default data directory. Loading from a
1104+ different directory by overriding the default path, e.g. via
1105+ `--data-dir`, is no longer supported to avoid unexpected behavior
1106+ and to address security concerns.
1107+ + Add module "pandoc.path" (Albert Krewinkel, #6001, #6565).
1108+ The module allows to work with file paths in a convenient and
1109+ platform-independent manner.
1110+ + Use strict evaluation when retrieving AST value from the stack
1111+ (Albert Krewinkel, #6674).
1112+
1113+ * Text.Pandoc.PDF
1114+
1115+ + Disable `smart` extension when building PDF via LaTeX.
1116+ This is to prevent accidental creation of ligatures like
1117+ `` ?` `` and `` !` `` (especially in languages with quotations like
1118+ German), and similar ligature issues. (See jgm/citeproc#54.)
1119+
1120+ * Text.Pandoc.CSV:
1121+
1122+ + Fix parsing of unquoted values (#7112). Previously we didn't allow
1123+ unescaped quotes in unquoted values, but they are allowed
1124+ in CSV.
1125+
1126+ * Test suite:
1127+
1128+ + Use a more robust method for testing the executable. Many
1129+ of our tests require running the pandoc executable. This
1130+ is problematic for a few different reasons. First,
1131+ cabal-install will sometimes run the test suite after
1132+ building the library but before building the executable,
1133+ which means the executable isn't in place for the tests.
1134+ One can work around that by first building, then building
1135+ and running the tests, but that's fragile. Second, we
1136+ have to find the executable. So far, we've done that using
1137+ a function `findPandoc` that attempts to locate it
1138+ relative to the test executable (which can be located
1139+ using findExecutablePath). But the logic here is delicate
1140+ and work with every combination of options. To solve both
1141+ problems, we add an `--emulate` option to the
1142+ `test-pandoc` executable. When `--emulate` occurs as the
1143+ first argument passed to `test-pandoc`, the program simply
1144+ emulates the regular pandoc executable, using the rest of
1145+ the arguments (after `--emulate`). Thus, `test-pandoc
1146+ --emulate -f markdown -t latex` is just like `pandoc -f
1147+ markdown -t latex`. Since all the work is done by library
1148+ functions, implementing this emulation just takes a couple
1149+ lines of code and should be entirely reliable. With this
1150+ change, we can test the pandoc executable by running the
1151+ test program itself (locatable using `findExecutablePath`)
1152+ with the `--emulate` option. This removes the need for the
1153+ fragile `findPandoc` step, and it means we can run our
1154+ integration tests even when we're just building the
1155+ library, not the executable. [Note: part of this change
1156+ involved simplifying some complex handling to set
1157+ environment variables for dynamic library paths. I have
1158+ tested a build with `--enable-dynamic-executable`, and it
1159+ works, but further testing may be needed.]
1160+ + Print accurate location if a test fails (Albert
1161+ Krewinkel). Ensures that tasty-hunit reports the location
1162+ of the failing test instead of the location of the helper
1163+ `test` function.
1164+
1165+ * Documentation: Update URLs and use `https` where possible (#7122,
1166+ Salim B).
1167+
1168+ * Add `doc/libraries.md`, a description of libraries that support pandoc.
3161169
3171170 * MANUAL.txt
3181171
@@ -328,6 +1181,9 @@
3281181 * Makefile: in `make bench`, create CSV files for comparison and compare
3291182 against previous benchmark run. Add timestamp to CSV filenames.
3301183
1184+ * cabal.project: don't explicitly set -trypandoc.
1185+ If we do, this can't be overridden on the cabal command line.
1186+
3311187 * doc/lua-filters.md: improve documentation for
3321188 `pandoc.mediabag.insert`, `pandoc.mediabag.fetch`,
3331189 `directory`, `normalize` (Albert Krewinkel).
@@ -336,9 +1192,17 @@
3361192
3371193 * Require jira-wiki-markup 1.3.3 (Albert Krewinkel)
3381194
339− * Require citeproc 0.3.0.7, which correctly titlecases when titles
1195+ * Require citeproc 0.3.0.8, which correctly titlecases when titles
3401196 contain non-ASCII characters.
3411197
1198+ * Use skylighting 0.10.4. This version of skylighting uses xml-conduit
1199+ rather than hxt. This speeds up parsing of XML syntax definitions
1200+ fourfold, and removes four packages from pandoc's dependency graph:
1201+ hxt-charproperties, hxt-unicode, hxt-regex-xmlschema, hxt.
1202+
1203+ * Add script `tools/parseTimings.pl` to help pin down which
1204+ modules take the most time and memory to compile.
1205+
3421206 * Avoid unnecessary use of NoImplicitPrelude pragma (#7089) (Albert
3431207 Krewinkel)
3441208
@@ -353,6 +1217,16 @@
3531217 + Clean up benchmark code.
3541218 + Allow specifying patterns using `-p blah'.
3551219
1220+ * trypandoc: add 2 second timeout.
1221+
1222+ * Use `-split-sections` in creating linux release binary.
1223+ This reduces executable size significantly (by about 30%).
1224+
1225+ * Remove `weigh-pandoc`. It's not really useful any more, now that our
1226+ regular benchmarks include data on allocation.
1227+
1228+ * Improve linux package build process and add script to
1229+ automate building an arm64 binary package.
3561230
3571231
3581232## pandoc 2.11.4 (2021-01-22)
@@ -946,8 +1820,11 @@
9461820 translated to `C:\/foo/bar`, which caused problems.
9471821 With this fix, the backslashes are removed.
9481822
949− * Text.Pandoc.Logging: Add constructor `ATXHeadingInLHS` constructor
950− to `LogMessage` [API change].
1823+ * Text.Pandoc.Logging:
1824+
1825+ + Add constructor `ATXHeadingInLHS` to `LogMessage` [API change].
1826+ + Add constructor `EnvironmentVariableUndefined` to
1827+ `LogMessage` [API change].
9511828
9521829 * Fix error that is given when people specify `doc` output (#6834,
9531830 gison93).
data/docx/word/settings.xml+6−16
@@ -1,6 +1,6 @@
11<?xml version="1.0" encoding="UTF-8"?>
22<w:settings xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:w10="urn:schemas-microsoft-com:office:word" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:sl="http://schemas.openxmlformats.org/schemaLibrary/2006/main">
3− <w:zoom w:percent="90" />
3+ <w:zoom w:percent="100" />
44 <w:embedSystemFonts />
55 <w:proofState w:spelling="clean" w:grammar="clean" />
66 <w:stylePaneFormatFilter w:val="0004" />
@@ -17,31 +17,21 @@
1717 <w:characterSpacingControl w:val="doNotCompress" />
1818 <w:savePreviewPicture />
1919 <w:rsids>
20− <w:rsidRoot w:val="00590D07" />
21− <w:rsid w:val="00011C8B" />
22− <w:rsid w:val="004E29B3" />
23− <w:rsid w:val="00590D07" />
24− <w:rsid w:val="00784D58" />
25− <w:rsid w:val="008D6863" />
26− <w:rsid w:val="00B86B75" />
27− <w:rsid w:val="00BC48D5" />
28− <w:rsid w:val="00C36279" />
29− <w:rsid w:val="00E315A3" />
3020 </w:rsids>
3121 <m:mathPr>
32− <m:mathFont m:val="Lucida Grande" />
22+ <m:mathFont m:val="Cambria Math" />
3323 <m:brkBin m:val="before" />
3424 <m:brkBinSub m:val="--" />
35− <m:smallFrac m:val="false" />
36− <m:dispDef m:val="false" />
25+ <m:smallFrac m:val="0" />
26+ <m:dispDef />
3727 <m:lMargin m:val="0" />
3828 <m:rMargin m:val="0" />
3929 <m:wrapRight />
4030 <m:intLim m:val="subSup" />
41− <m:naryLim m:val="subSup" />
31+ <m:naryLim m:val="undOvr" />
4232 </m:mathPr>
4333 <w:themeFontLang w:val="en-US" />
4434 <w:clrSchemeMapping w:bg1="light1" w:t1="dark1" w:bg2="light2" w:t2="dark2" w:accent1="accent1" w:accent2="accent2" w:accent3="accent3" w:accent4="accent4" w:accent5="accent5" w:accent6="accent6" w:hyperlink="hyperlink" w:followedHyperlink="followedHyperlink" />
4535 <w:decimalSymbol w:val="." />
4636 <w:listSeparator w:val="," />
47−</w:settings>
37+</w:settings>
data/templates/article.jats_publishing+1−1
@@ -86,7 +86,7 @@ $endif$
8686$if(author)$
8787<contrib-group>
8888$for(author)$
89−<contrib contrib-type="author">
89+<contrib contrib-type="author"$if(author.equal-contrib)$ equal-contrib="true"$endif$>
9090$if(author.orcid)$
9191<contrib-id contrib-id-type="orcid">$author.orcid$</contrib-id>
9292$endif$
data/templates/default.context+7−3
@@ -51,6 +51,7 @@ $endif$
5151
5252% use microtypography
5353\definefontfeature[default][default][script=latn, protrusion=quality, expansion=quality, itlc=yes, textitalics=yes, onum=yes, pnum=yes]
54+\definefontfeature[default:tnum][default][tnum=yes, pnum=no]
5455\definefontfeature[smallcaps][script=latn, protrusion=quality, expansion=quality, smcp=yes, onum=yes, pnum=yes]
5556\setupalign[hz,hanging]
5657\setupitaliccorrection[global, always]
@@ -97,6 +98,9 @@ $endif$
9798\setupitemize[autointro] % prevent orphan list intro
9899\setupitemize[indentnext=no]
99100
101+\defineitemgroup[enumerate]
102+\setupenumerate[each][fit][itemalign=left,distance=.5em,style={\feature[+][default:tnum]}]
103+
100104\setupfloat[figure][default={here,nonumber}]
101105\setupfloat[table][default={here,nonumber}]
102106
@@ -160,12 +164,12 @@ $endfor$
160164$if(toc)$
161165\completecontent
162166$endif$
163−$if(lot)$
164−\completelistoftables
165−$endif$
166167$if(lof)$
167168\completelistoffigures
168169$endif$
170+$if(lot)$
171+\completelistoftables
172+$endif$
169173
170174$body$
171175
data/templates/default.dzslides+1−1
@@ -171,7 +171,7 @@ $if(subtitle)$
171171 <h1 class="subtitle">$subtitle$</h1>
172172$endif$
173173 <footer>
174− $if(author)$<span class="author">$for(author)$$author$$sep$, $endfor$</span>$endif$ · $if(date)$<span class="date">$date$</span>$endif$
174+ $if(author)$<span class="author">$for(author)$$author$$sep$, $endfor$</span> · $endif$$if(institute)$<span class="institute">$for(institute)$$institute$$sep$, $endfor$</span> · $endif$$if(date)$<span class="date">$date$</span>$endif$
175175 </footer>
176176</section>
177177$endif$
data/templates/default.jats_articleauthoring+1−1
@@ -19,7 +19,7 @@ $endif$
1919$if(author)$
2020<contrib-group>
2121$for(author)$
22−<contrib contrib-type="author">
22+<contrib contrib-type="author"$if(author.equal-contrib)$ equal-contrib="true"$endif$>
2323$if(author.orcid)$
2424<contrib-id contrib-id-type="orcid">$author.orcid$</contrib-id>
2525$endif$
data/templates/default.latex+50−25
@@ -2,7 +2,7 @@
22\PassOptionsToPackage{unicode$for(hyperrefoptions)$,$hyperrefoptions$$endfor$}{hyperref}
33\PassOptionsToPackage{hyphens}{url}
44$if(colorlinks)$
5−\PassOptionsToPackage{dvipsnames,svgnames*,x11names*}{xcolor}
5+\PassOptionsToPackage{dvipsnames,svgnames,x11names}{xcolor}
66$endif$
77$if(dir)$
88$if(latex-dir-rtl)$
@@ -156,6 +156,25 @@ $if(CJKmainfont)$
156156 \fi
157157$endif$
158158\fi
159+$if(zero-width-non-joiner)$
160+%% Support for zero-width non-joiner characters.
161+\makeatletter
162+\def\zerowidthnonjoiner{%
163+ % Prevent ligatures and adjust kerning, but still support hyphenating.
164+ \texorpdfstring{%
165+ \textormath{\nobreak\discretionary{-}{}{\kern.03em}%
166+ \ifvmode\else\nobreak\hskip\z@skip\fi}{}%
167+ }{}%
168+}
169+\makeatother
170+\ifPDFTeX
171+ \DeclareUnicodeCharacter{200C}{\zerowidthnonjoiner}
172+\else
173+ \catcode`^^^^200c=\active
174+ \protected\def ^^^^200c{\zerowidthnonjoiner}
175+\fi
176+%% End of ZWNJ support
177+$endif$
159178$if(beamer)$
160179$if(theme)$
161180\usetheme[$for(themeoptions)$$themeoptions$$sep$,$endfor$]{$theme$}
@@ -325,6 +344,31 @@ $endif$
325344$if(pagestyle)$
326345\pagestyle{$pagestyle$}
327346$endif$
347+$if(csl-refs)$
348+\newlength{\cslhangindent}
349+\setlength{\cslhangindent}{1.5em}
350+\newlength{\csllabelwidth}
351+\setlength{\csllabelwidth}{3em}
352+\newlength{\cslentryspacingunit} % times entry-spacing
353+\setlength{\cslentryspacingunit}{\parskip}
354+\newenvironment{CSLReferences}[2] % #1 hanging-ident, #2 entry spacing
355+ {% don't indent paragraphs
356+ \setlength{\parindent}{0pt}
357+ % turn on hanging indent if param 1 is 1
358+ \ifodd #1
359+ \let\oldpar\par
360+ \def\par{\hangindent=\cslhangindent\oldpar}
361+ \fi
362+ % set entry spacing
363+ \setlength{\parskip}{#2\cslentryspacingunit}
364+ }%
365+ {}
366+\usepackage{calc}
367+\newcommand{\CSLBlock}[1]{#1\hfill\break}
368+\newcommand{\CSLLeftMargin}[1]{\parbox[t]{\csllabelwidth}{#1}}
369+\newcommand{\CSLRightInline}[1]{\parbox[t]{\linewidth - \csllabelwidth}{#1}\break}
370+\newcommand{\CSLIndent}[1]{\hspace{\cslhangindent}#1}
371+$endif$
328372$for(header-includes)$
329373$header-includes$
330374$endfor$
@@ -372,27 +416,8 @@ $for(bibliography)$
372416\addbibresource{$bibliography$}
373417$endfor$
374418$endif$
375−$if(csl-refs)$
376−\newlength{\cslhangindent}
377−\setlength{\cslhangindent}{1.5em}
378−\newlength{\csllabelwidth}
379−\setlength{\csllabelwidth}{3em}
380−\newenvironment{CSLReferences}[2] % #1 hanging-ident, #2 entry spacing
381− {% don't indent paragraphs
382− \setlength{\parindent}{0pt}
383− % turn on hanging indent if param 1 is 1
384− \ifodd #1 \everypar{\setlength{\hangindent}{\cslhangindent}}\ignorespaces\fi
385− % set entry spacing
386− \ifnum #2 > 0
387− \setlength{\parskip}{#2\baselineskip}
388− \fi
389− }%
390− {}
391−\usepackage{calc}
392−\newcommand{\CSLBlock}[1]{#1\hfill\break}
393−\newcommand{\CSLLeftMargin}[1]{\parbox[t]{\csllabelwidth}{#1}}
394−\newcommand{\CSLRightInline}[1]{\parbox[t]{\linewidth - \csllabelwidth}{#1}\break}
395−\newcommand{\CSLIndent}[1]{\hspace{\cslhangindent}#1}
419+$if(nocite-ids)$
420+\nocite{$for(nocite-ids)$$it$$sep$, $endfor$}
396421$endif$
397422$if(csquotes)$
398423\usepackage{csquotes}
@@ -469,12 +494,12 @@ $endif$
469494}
470495$endif$
471496$endif$
472−$if(lot)$
473−\listoftables
474−$endif$
475497$if(lof)$
476498\listoffigures
477499$endif$
500+$if(lot)$
501+\listoftables
502+$endif$
478503$if(linestretch)$
479504\setstretch{$linestretch$}
480505$endif$
data/templates/default.revealjs+79−129
@@ -52,6 +52,9 @@ $endif$
5252$for(author)$
5353 <p class="author">$author$</p>
5454$endfor$
55+$for(institute)$
56+ <p class="institute">$institute$</p>
57+$endfor$
5558$if(date)$
5659 <p class="date">$date$</p>
5760$endif$
@@ -59,7 +62,12 @@ $endif$
5962$endif$
6063$if(toc)$
6164<section id="$idprefix$TOC">
65+<nav role="doc-toc">
66+$if(toc-title)$
67+<h2 id="$idprefix$toc-title">$toc-title$</h2>
68+$endif$
6269$table-of-contents$
70+</nav>
6371</section>
6472$endif$
6573
@@ -69,7 +77,7 @@ $body$
6977
7078 <script src="$revealjs-url$/dist/reveal.js"></script>
7179
72− // reveal.js plugins
80+ <!-- reveal.js plugins -->
7381 <script src="$revealjs-url$/plugin/notes/notes.js"></script>
7482 <script src="$revealjs-url$/plugin/search/search.js"></script>
7583 <script src="$revealjs-url$/plugin/zoom/zoom.js"></script>
@@ -82,256 +90,198 @@ $endif$
8290 // Full list of configuration options available at:
8391 // https://revealjs.com/config/
8492 Reveal.initialize({
85−$if(center)$
86− // Determines whether slide content should be vertically centered
87− center: $center$,
88−$endif$
89−$if(controls)$
9093 // Display controls in the bottom right corner
9194 controls: $controls$,
92−$endif$
93−$if(controlsTutorial)$
95+
9496 // Help the user learn the controls by providing hints, for example by
9597 // bouncing the down arrow when they first encounter a vertical slide
9698 controlsTutorial: $controlsTutorial$,
97−$endif$
98−$if(controlsLayout)$
99+
99100 // Determines where controls appear, "edges" or "bottom-right"
100101 controlsLayout: '$controlsLayout$',
101−$endif$
102−$if(controlsBackArrows)$
102+
103103 // Visibility rule for backwards navigation arrows; "faded", "hidden"
104104 // or "visible"
105105 controlsBackArrows: '$controlsBackArrows$',
106−$endif$
107−$if(progress)$
106+
108107 // Display a presentation progress bar
109108 progress: $progress$,
110−$endif$
111−$if(slideNumber)$
109+
112110 // Display the page number of the current slide
113111 slideNumber: $slideNumber$,
114−$endif$
115−$if(showSlideNumber)$
112+
116113 // 'all', 'print', or 'speaker'
117114 showSlideNumber: '$showSlideNumber$',
118−$endif$
119−$if(hash)$
115+
120116 // Add the current slide number to the URL hash so that reloading the
121117 // page/copying the URL will return you to the same slide
122118 hash: $hash$,
123−$endif$
124−$if(hashOneBasedIndex)$
119+
125120 // Start with 1 for the hash rather than 0
126121 hashOneBasedIndex: $hashOneBasedIndex$,
127−$endif$
122+
123+ // Flags if we should monitor the hash and change slides accordingly
124+ respondToHashChanges: $respondToHashChanges$,
125+
128126 // Push each slide change to the browser history
129− history: $if(history)$$history$$else$true$endif$,
130−$if(keyboard)$
127+ history: $history$,
128+
131129 // Enable keyboard shortcuts for navigation
132130 keyboard: $keyboard$,
133−$endif$
134−$if(overview)$
131+
135132 // Enable the slide overview mode
136133 overview: $overview$,
137−$endif$
138−$if(center)$
134+
135+ // Disables the default reveal.js slide layout (scaling and centering)
136+ // so that you can use custom CSS layout
137+ disableLayout: false,
138+
139139 // Vertical centering of slides
140140 center: $center$,
141−$endif$
142−$if(touch)$
141+
143142 // Enables touch navigation on devices with touch input
144143 touch: $touch$,
145−$endif$
146−$if(loop)$
144+
147145 // Loop the presentation
148146 loop: $loop$,
149−$endif$
150−$if(rtl)$
147+
151148 // Change the presentation direction to be RTL
152149 rtl: $rtl$,
153−$endif$
154−$if(navigationMode)$
150+
155151 // see https://revealjs.com/vertical-slides/#navigation-mode
156152 navigationMode: '$navigationMode$',
157−$endif$
158−$if(shuffle)$
153+
159154 // Randomizes the order of slides each time the presentation loads
160155 shuffle: $shuffle$,
161−$endif$
162−$if(fragments)$
156+
163157 // Turns fragments on and off globally
164158 fragments: $fragments$,
165−$endif$
166−$if(fragmentInURL)$
159+
167160 // Flags whether to include the current fragment in the URL,
168161 // so that reloading brings you to the same fragment position
169162 fragmentInURL: $fragmentInURL$,
170−$endif$
171−$if(embedded)$
163+
172164 // Flags if the presentation is running in an embedded mode,
173165 // i.e. contained within a limited portion of the screen
174166 embedded: $embedded$,
175−$endif$
176−$if(help)$
167+
177168 // Flags if we should show a help overlay when the questionmark
178169 // key is pressed
179170 help: $help$,
180−$endif$
181−$if(pause)$
182− // Flags if it should be possible to pause the presentation (blackout)
183− pause: $pause$,
184−$endif$
185−$if(showNotes)$
171+
172+ // Flags if it should be possible to pause the presentation (blackout)
173+ pause: $pause$,
174+
186175 // Flags if speaker notes should be visible to all viewers
187176 showNotes: $showNotes$,
188−$endif$
189−$if(autoPlayMedia)$
190− // Global override for autoplaying embedded media (video/audio/iframe)
191− // - null: Media will only autoplay if data-autoplay is present
192− // - true: All media will autoplay, regardless of individual setting
193− // - false: No media will autoplay, regardless of individual setting
177+
178+ // Global override for autoplaying embedded media (null/true/false)
194179 autoPlayMedia: $autoPlayMedia$,
195−$endif$
196−$if(preloadIframes)$
197− // Global override for preloading lazy-loaded iframes
198− // - null: Iframes with data-src AND data-preload will be loaded when within
199− // the viewDistance, iframes with only data-src will be loaded when visible
200− // - true: All iframes with data-src will be loaded when within the viewDistance
201− // - false: All iframes with data-src will be loaded only when visible
180+
181+ // Global override for preloading lazy-loaded iframes (null/true/false)
202182 preloadIframes: $preloadIframes$,
203−$endif$
204−$if(autoSlide)$
183+
205184 // Number of milliseconds between automatically proceeding to the
206185 // next slide, disabled when set to 0, this value can be overwritten
207186 // by using a data-autoslide attribute on your slides
208187 autoSlide: $autoSlide$,
209−$endif$
210−$if(autoSlideStoppable)$
188+
211189 // Stop auto-sliding after user input
212190 autoSlideStoppable: $autoSlideStoppable$,
213−$endif$
214−$if(autoSlideMethod)$
191+
215192 // Use this method for navigation when auto-sliding
216193 autoSlideMethod: $autoSlideMethod$,
217−$endif$
218−$if(defaultTiming)$
194+
219195 // Specify the average time in seconds that you think you will spend
220196 // presenting each slide. This is used to show a pacing timer in the
221197 // speaker view
222198 defaultTiming: $defaultTiming$,
223−$endif$
224−$if(totalTime)$
225− // Specify the total time in seconds that is available to
226− // present. If this is set to a nonzero value, the pacing
227− // timer will work out the time available for each slide,
228− // instead of using the defaultTiming value
229− totalTime: $totalTime$,
230−$endif$
231−$if(minimumTimePerSlide)$
232− // Specify the minimum amount of time you want to allot to
233− // each slide, if using the totalTime calculation method. If
234− // the automated time allocation causes slide pacing to fall
235− // below this threshold, then you will see an alert in the
236− // speaker notes window
237− minimumTimePerSlide: $minimumTimePerSlide$,
238−$endif$
239−$if(mouseWheel)$
199+
240200 // Enable slide navigation via mouse wheel
241201 mouseWheel: $mouseWheel$,
242−$endif$
243−$if(rollingLinks)$
244− // Apply a 3D roll to links on hover
245− rollingLinks: $rollingLinks$,
246−$endif$
247−$if(hideInactiveCursor)$
202+
203+ // The display mode that will be used to show slides
204+ display: '$display$',
205+
248206 // Hide cursor if inactive
249207 hideInactiveCursor: $hideInactiveCursor$,
250−$endif$
251−$if(hideCursorTime)$
208+
252209 // Time before the cursor is hidden (in ms)
253210 hideCursorTime: $hideCursorTime$,
254−$endif$
255−$if(hideAddressBar)$
256− // Hides the address bar on mobile devices
257− hideAddressBar: $hideAddressBar$,
258−$endif$
259−$if(previewLinks)$
211+
260212 // Opens links in an iframe preview overlay
261213 previewLinks: $previewLinks$,
262−$endif$
263−$if(transition)$
264− // Transition style
265− transition: '$transition$', // none/fade/slide/convex/concave/zoom
266−$endif$
267−$if(transitionSpeed)$
268− // Transition speed
269− transitionSpeed: '$transitionSpeed$', // default/fast/slow
270−$endif$
271−$if(backgroundTransition)$
214+
215+ // Transition style (none/fade/slide/convex/concave/zoom)
216+ transition: '$transition$',
217+
218+ // Transition speed (default/fast/slow)
219+ transitionSpeed: '$transitionSpeed$',
220+
272221 // Transition style for full page slide backgrounds
273− backgroundTransition: '$backgroundTransition$', // none/fade/slide/convex/concave/zoom
274−$endif$
275−$if(viewDistance)$
222+ // (none/fade/slide/convex/concave/zoom)
223+ backgroundTransition: '$backgroundTransition$',
224+
276225 // Number of slides away from the current that are visible
277226 viewDistance: $viewDistance$,
278−$endif$
279−$if(mobileViewDistance)$
227+
280228 // Number of slides away from the current that are visible on mobile
281229 // devices. It is advisable to set this to a lower number than
282230 // viewDistance in order to save resources.
283231 mobileViewDistance: $mobileViewDistance$,
284−$endif$
285232$if(parallaxBackgroundImage)$
233+
286234 // Parallax background image
287235 parallaxBackgroundImage: '$parallaxBackgroundImage$', // e.g. "'https://s3.amazonaws.com/hakim-static/reveal-js/reveal-parallax-1.jpg'"
288236$else$
289237$if(background-image)$
238+
290239 // Parallax background image
291240 parallaxBackgroundImage: '$background-image$', // e.g. "'https://s3.amazonaws.com/hakim-static/reveal-js/reveal-parallax-1.jpg'"
292241$endif$
293242$endif$
294243$if(parallaxBackgroundSize)$
244+
295245 // Parallax background size
296246 parallaxBackgroundSize: '$parallaxBackgroundSize$', // CSS syntax, e.g. "2100px 900px"
297247$endif$
298248$if(parallaxBackgroundHorizontal)$
249+
299250 // Amount to move parallax background (horizontal and vertical) on slide change
300251 // Number, e.g. 100
301252 parallaxBackgroundHorizontal: $parallaxBackgroundHorizontal$,
302253$endif$
303254$if(parallaxBackgroundVertical)$
255+
304256 parallaxBackgroundVertical: $parallaxBackgroundVertical$,
305257$endif$
306258$if(width)$
259+
307260 // The "normal" size of the presentation, aspect ratio will be preserved
308261 // when the presentation is scaled to fit different resolutions. Can be
309262 // specified using percentage units.
310263 width: $width$,
311264$endif$
312265$if(height)$
266+
313267 height: $height$,
314268$endif$
315269$if(margin)$
270+
316271 // Factor of the display size that should remain empty around the content
317272 margin: $margin$,
318273$endif$
319274$if(minScale)$
275+
320276 // Bounds for smallest/largest possible scale to apply to content
321277 minScale: $minScale$,
322278$endif$
323279$if(maxScale)$
280+
324281 maxScale: $maxScale$,
325282$endif$
326−$if(zoomKey)$
327− // Modifier key used to click-zoom to part of the slide
328− zoomKey: '$zoomKey$',
329−$endif$
330−$if(display)$
331− // The display mode that will be used to show slides
332− display: '$display$',
333−$endif$
334283$if(mathjax)$
284+
335285 math: {
336286 mathjax: '$mathjaxurl$',
337287 config: 'TeX-AMS_HTML-full',
data/templates/default.s5+3
@@ -61,6 +61,9 @@ $endif$
6161$if(author)$
6262 <h3 class="author">$for(author)$$author$$sep$<br/>$endfor$</h3>
6363$endif$
64+$if(institute)$
65+ <h3 class="institute">$for(institute)$$institute$$sep$<br/>$endfor$</h3>
66+$endif$
6467$if(date)$
6568 <h4 class="date">$date$</h4>
6669$endif$
data/templates/default.slideous+7
@@ -63,9 +63,16 @@ $if(title)$
6363$if(subtitle)$
6464 <h1 class="subtitle">$subtitle$</h1>
6565$endif$
66+$if(author)$
6667 <p class="author">
6768$for(author)$$author$$sep$<br/>$endfor$
6869 </p>
70+$endif$
71+$if(institute)$
72+ <p class="institute">
73+$for(institute)$$institute$$sep$<br/>$endfor$
74+ </p>
75+$endif$
6976$if(date)$
7077 <p class="date">$date$</p>
7178$endif$
data/templates/default.slidy+5
@@ -52,6 +52,11 @@ $if(author)$
5252$for(author)$$author$$sep$<br/>$endfor$
5353 </p>
5454$endif$
55+$if(institute)$
56+ <p class="institute">
57+$for(institute)$$institute$$sep$<br/>$endfor$
58+ </p>
59+$endif$
5560$if(date)$
5661 <p class="date">$date$</p>
5762$endif$
data/templates/styles.html+2−1
@@ -14,7 +14,7 @@ body {
1414 padding-top: $if(margin-top)$$margin-top$$else$50px$endif$;
1515 padding-bottom: $if(margin-bottom)$$margin-bottom$$else$50px$endif$;
1616 hyphens: auto;
17− word-wrap: break-word;
17+ overflow-wrap: break-word;
1818 text-rendering: optimizeLegibility;
1919 font-kerning: normal;
2020}
@@ -93,6 +93,7 @@ $endif$
9393pre code {
9494 padding: 0;
9595 overflow: visible;
96+ overflow-wrap: normal;
9697}
9798.sourceCode {
9899 background-color: transparent;
doc/epub.md+9−2
@@ -141,8 +141,15 @@ Pandoc has an EPUB3 writer. It renders LaTeX math into MathML, which
141141EPUB3 readers are supposed to support (but unfortunately few do).
142142
143143Of course, this isn't much help if you want EPUB2 output (`pandoc -t epub2`)
144−or target readers that don't support MathML. Then you should try using the
145−`--webtex` option, which will use a web service to convert the TeX to an image.
144+or target readers that don't support MathML. Then you have two options:
145+
146+1. Use the [`--webtex`](https://pandoc.org/MANUAL.html#option--webtex) option,
147+ which will use a web service to convert the TeX to an image.
148+2. Use the [`--gladtex`](https://pandoc.org/MANUAL.html#option--gladtex) option
149+ to convert maths into SVG images on your local machine.
150+
151+Both GladTeX and WebTeX add the LaTeX source of the formula as alternative text
152+of the image, increasing accessibility for blind users.
146153
147154[KindleGen]: https://www.amazon.com/gp/feature.html?ie=UTF8&docId=1000765211
148155[EPUB]: https://en.wikipedia.org/wiki/EPUB
doc/faqs.mdnew file+128
@@ -0,0 +1,128 @@
1+% FAQs
2+
3+::: faqs
4+
5+## How can I convert a whole directory of files from Markdown to RTF?
6+
7+On linux or OSX:
8+
9+ for f in *.txt; do pandoc "$f" -s -o "${f%.txt}.rtf"; done
10+
11+
12+In Windows Powershell:
13+
14+ gci -r -i *.txt |foreach{$rtf=$_.directoryname+"\"+$_.basename+".rtf";pandoc -f markdown -s $_.name -o $rtf}
15+
16+## I used pandoc to convert a document to ICML (or OPML or RTF), and when I try to open it I'm told it's invalid. What have I done wrong?
17+
18+Be sure to use the `-s` or `--standalone` flag, or you just get a
19+fragment, not a full document with the required header:
20+
21+ pandoc -s -f markdown -t icml -o my.icml my.md
22+
23+## I get a blank document when I try to convert a markdown document in Chinese to PDF.
24+
25+By default, pandoc uses pdflatex to generate the PDF, and pdflatex
26+doesn't handle Chinese characters. But you can change the default to
27+use xelatex instead. You should also make sure you're using a font
28+with Chinese glyphs. For example:
29+
30+ pandoc -o c.pdf --pdf-engine=xelatex -V mainfont='Adobe Ming Std'
31+
32+## The Windows installer does a single user install, rather than installing pandoc for all users. How can I install pandoc for all users?
33+
34+Run the following command as admin:
35+
36+ msiexec /i pandoc-VERSION.msi ALLUSERS=1
37+
38+This will put pandoc in `C:\Program Files\Pandoc`.
39+You can install Pandoc to a different directory by setting APPLICATIONFOLDER parameter,
40+for example:
41+
42+ msiexec /i pandoc-1.11.1.msi ALLUSERS=1 APPLICATIONFOLDER="C:\Pandoc"
43+
44+## How do I change the margins in PDF output?
45+
46+The option
47+
48+ -V geometry:margin=1in
49+
50+will set the margins to one inch on each side. If you don't want uniform
51+margins, you can do something like
52+
53+ -V geometry:"top=2cm, bottom=1.5cm, left=1cm, right=1cm"
54+
55+Or
56+
57+ -V geometry:"left=3cm, width=10cm"
58+
59+For more options, see the documentation for the LaTeX [geometry
60+package](https://www.ctan.org/pkg/geometry).
61+
62+## How does pandoc compare to multimarkdown?
63+
64+Here is a [wiki
65+page](https://github.com/jgm/pandoc/wiki/Pandoc-vs-Multimarkdown)
66+comparing the two.
67+
68+## When I specify an image width of 50% and convert to LaTeX, pandoc sets the height to textheight and the aspect ratio isn't preserved. How can I prevent this?
69+
70+For example, if you convert an image with `{width="50%"}`, the LaTeX produced
71+will be `\includegraphics[width=0.5\textwidth,height=\textheight]`.
72+
73+This output presupposes the following code in pandoc's default latex
74+template:
75+
76+```
77+% Scale images if necessary, so that they will not overflow the page
78+% margins by default, and it is still possible to overwrite the defaults
79+% using explicit options in \includegraphics[width, height, ...]{}
80+\setkeys{Gin}{width=\maxwidth,height=\maxheight,keepaspectratio}
81+```
82+
83+If you don't have this in your custom template, you should
84+add it. If we didn't set the `height` explicitly in this way,
85+the image would not be resized correctly unless it was
86+being resized to smaller than its original size.
87+
88+## Pandoc sometimes uses too much memory. How can I limit the memory used by pandoc?
89+
90+`pandoc +RTS -M30m -RTS` will limit heap memory to 30MB.
91+When converting a document requires more than this, an out of
92+memory error will be issued.
93+
94+## When using `--include-in-header` with PDF or LaTeX output, how do I reference tex declarations coming after `$header-includes$` in the default template?
95+
96+For various reasons, the `$header-includes$` are not at the very
97+end of the LaTeX preamble. This poses a problem when the code
98+you are inserting depends on declarations in the preamble coming
99+after the `$header-includes$` location. For example, you might
100+want to reference the `\author` and `\title` metadata values
101+(set at the very bottom of the preamble) and present them in
102+margins. In that case you can wrap your code in `etoolbox`'s
103+`\AtEndPreamble`. The technique is demonstrated in [this
104+gist](https://gist.github.com/JohnLukeBentley/9dda6166b9ee5c4127afd2b8cd16b70a).
105+When using `\AtEndPreamble`, keep any `makeatletter` or
106+`makeatother` outside of the `\AtEndPreamble`, as shown in the
107+example.
108+
109+## How can I convert PDFs to other formats using pandoc?
110+
111+You can't. You can try opening the PDF in Word or Google Docs
112+and saving in a format from which pandoc can convert directly.
113+
114+## Do I really need to install a 1 GB TeX installation to produce a PDF using pandoc?
115+
116+No. You can get by with a relatively small TeX installation,
117+for example, by starting with MacTeX's Basic TeX distribution
118+and using the `tlmgr` tool to install a few packages required by pandoc
119+(see https://pandoc.org/MANUAL.html#creating-a-pdf).
120+
121+Or, you can produce PDFs via HTML and `wkhtmltopdf`,
122+or via groff ms and `pdfroff`. (These don't produce as nice
123+topography as TeX, particularly when it comes to math, but they
124+may be fine for many purposes.)
125+
126+
127+:::
128+
doc/filters.md+2
@@ -394,6 +394,8 @@ automatically assign it `Just` the target format or `Nothing`.
394394
395395We compile our script:
396396
397+ # first, make sure pandoc-types is installed:
398+ cabal install --lib pandoc-types --package-env .
397399 ghc --make handleRuby
398400
399401Then run it:
doc/jats.md+9
@@ -50,6 +50,13 @@ Metadata Values
5050 list must also occur as the `id` of an affiliation listed in
5151 the top-level `affiliation` list.
5252
53+ `equal-contrib`
54+ : boolean attribute used to mark authors who contributed
55+ equally to the work. The
56+ [`equal-contrib`][attr:equal-contrib] attribute is added
57+ to the author's [`<contrib>`] element if this is set to a
58+ truthy value.
59+
5360 `cor-id`
5461 : identifier linking to the contributor's correspondence
5562 information. The info itself must be stored in as an item in
@@ -355,6 +362,7 @@ Required metadata values:
355362[Ringgold]: https://ringgold.com/
356363[attr:content-type]: https://jats.nlm.nih.gov/publishing/tag-library/1.2/attribute/content-type.html
357364[attr:date-type]: https://jats.nlm.nih.gov/publishing/tag-library/1.2/attribute/date-type.html
365+[attr:equal-contrib]: https://jats.nlm.nih.gov/publishing/tag-library/1.2/attribute/equal-contrib.html
358366[attr:fn-type]: https://jats.nlm.nih.gov/publishing/tag-library/1.2/attribute/fn-type.html
359367[attr:institution-id-type]: https://jats.nlm.nih.gov/publishing/tag-library/1.2/attribute/institution-id-type.html
360368[attr:iso-8601-date]: https://jats.nlm.nih.gov/publishing/tag-library/1.2/attribute/iso-8601-date.html
@@ -398,6 +406,7 @@ Required metadata values:
398406[`<addr-line>`]: https://jats.nlm.nih.gov/publishing/tag-library/1.2/element/addr-line.html
399407[`<aff>`]: https://jats.nlm.nih.gov/publishing/tag-library/1.2/element/aff.html
400408[`<city>`]: https://jats.nlm.nih.gov/publishing/tag-library/1.2/element/city.html
409+[`<contrib>`]: https://jats.nlm.nih.gov/publishing/tag-library/1.2/element/contrib.html
401410[`<country>`]: https://jats.nlm.nih.gov/publishing/tag-library/1.2/element/country.html
402411[`<institution-id>`]: https://jats.nlm.nih.gov/publishing/tag-library/1.2/element/institution-id.html
403412[`<institution-wrap>`]: https://jats.nlm.nih.gov/publishing/tag-library/1.2/element/institution-wrap.html
doc/libraries.mdnew file+63
@@ -0,0 +1,63 @@
1+---
2+title: The pandoc family of libraries
3+author: John MacFarlane
4+---
5+
6+The following Haskell libraries have been developed to support
7+pandoc:
8+
9+[skylighting-core] and [skylighting]
10+: Syntax highlighting engine supporting over 140 languages.
11+
12+[citeproc]
13+: Citation processing using CSL stylesheets.
14+
15+[texmath]
16+: Conversion of math between tex, Word equation, MathML, and GNU eqn.
17+
18+[unicode-collation]
19+: Proper Unicode collation (sorting).
20+
21+[doclayout]
22+: Combinators for laying out a textual document, with support
23+ for line wrapping, tabular layout, and more.
24+
25+[doctemplates]
26+: Supports pandoc's templates.
27+
28+[commonmark], [commonmark-extensions], and [commonmark-pandoc]
29+: Efficient, standards-compliant parser for commonmark and extensions.
30+
31+[ipynb]
32+: Representation of Jupyter notebooks and conversion to and
33+ from JSON.
34+
35+[zip-archive]
36+: A pure zip file creator and extractor, used by pandoc for
37+ docx, ODT, and EPUB.
38+
39+[rfc5051]
40+: Simple unicode collation (used for citation sorting).
41+
42+[emojis]
43+: Conversion between emoji characters and aliases.
44+
45+[jira-wiki-markup]
46+: Support for parsing Jira wiki syntax.
47+
48+[skylighting]: https://hackage.haskell.org/package/skylighting
49+[skylighting-core]: https://hackage.haskell.org/package/skylighting-core
50+[citeproc]: https://hackage.haskell.org/package/citeproc
51+[texmath]: https://hackage.haskell.org/package/texmath
52+[doclayout]: https://hackage.haskell.org/package/doclayout
53+[doctemplates]: https://hackage.haskell.org/package/doctemplates
54+[commonmark]: https://hackage.haskell.org/package/commonmark
55+[commonmark-extensions]: https://hackage.haskell.org/package/commonmark-extensions
56+[commonmark-pandoc]: https://hackage.haskell.org/package/commonmark-pandoc
57+[ipynb]: https://hackage.haskell.org/package/ipynb
58+[zip-archive]: https://hackage.haskell.org/package/zip-archive
59+[rfc5051]: https://hackage.haskell.org/package/rfc5051
60+[emojis]: https://hackage.haskell.org/package/emojis
61+[jira-wiki-markup]: https://hackage.haskell.org/package/jira-wiki-markup
62+[unicode-collation]: https://hackage.haskell.org/package/unicode-collation
63+
doc/lua-filters.md+2−2
@@ -109,7 +109,7 @@ element filtering function. In other words, filter entries will
109109be called for each corresponding element in the document,
110110getting the respective element as input.
111111
112−The return of a filter function must one of the following:
112+The return of a filter function must be one of the following:
113113
114114- nil: this means that the object should remain unchanged.
115115- a pandoc object: this must be of the same type as the input
@@ -3205,7 +3205,7 @@ Usage:
32053205
32063206# Module pandoc.List
32073207
3208−The this module defines pandoc's list type. It comes with useful
3208+This module defines pandoc's list type. It comes with useful
32093209methods and convenience functions.
32103210
32113211## Constructor
doc/org.md+16−2
@@ -25,8 +25,7 @@ The following export keywords are supported:
2525- LANGUAGE: document language; included as plain-text metadata
2626 field `lang`. The value should be a [BCP47 language tag].
2727
28−- SELECT_TAGS: tags which select a tree for export. Currently
29− *unsupported*.
28+- SELECT_TAGS: tags which select a tree for export.
3029
3130- EXCLUDE\_TAGS: tags which prevent a subtree from being
3231 exported. Fully supported.
@@ -37,6 +36,21 @@ The following export keywords are supported:
3736 defaults to stdout unless a target has to be given as a command
3837 line option.
3938
39+::: {.alert .alert-info}
40+Pandoc tries to be compatible with org-mode when exporting an org document. If
41+you find some behavior confusing, please do refer to org-mode
42+[Export-Settings](https://orgmode.org/manual/Export-Settings.html)
43+documentation. For example, a common confusion
44+([#3214](https://github.com/jgm/pandoc/issues/3214 "Problem with headers lower
45+then 3 in org-mode reader"), [#5169](https://github.com/jgm/pandoc/issues/5169
46+"org mode headings past level three converted to numbered outline list"),
47+[#6145](https://github.com/jgm/pandoc/issues/6145 "Headers 4 levels deep render
48+differently"), [#7236](https://github.com/jgm/pandoc/issues/7236 "In Org mode,
49+Header with level > 3 are not recognized as headers")) is treatment of headers
50+with level > 3 differently because org-mode sets `org-export-headline-levels`
51+(configurable with `#+OPTIONS: H:3`) to 3 by default.
52+:::
53+
4054[BCP47 language tag]: https://tools.ietf.org/html/bcp47
4155
4256Format-specific options
doc/using-the-pandoc-api.md+25−12
@@ -14,7 +14,7 @@ and types is available at
1414Pandoc is structured as a set of *readers*, which translate
1515various input formats into an abstract syntax tree (the
1616Pandoc AST) representing a structured document, and a set of
17−*writers*, which render this AST into various input formats.
17+*writers*, which render this AST into various output formats.
1818Pictorially:
1919
2020```
@@ -90,8 +90,14 @@ Some notes:
9090Let's look at the types of `readMarkdown` and `writeRST`:
9191
9292```haskell
93−readMarkdown :: PandocMonad m => ReaderOptions -> Text -> m Pandoc
94−writeRST :: PandocMonad m => WriterOptions -> Pandoc -> m Text
93+readMarkdown :: (PandocMonad m, ToSources a)
94+ => ReaderOptions
95+ -> a
96+ -> m Pandoc
97+writeRST :: PandocMonad m
98+ => WriterOptions
99+ -> Pandoc
100+ -> m Text
95101```
96102
97103The `PandocMonad m =>` part is a typeclass constraint.
@@ -133,7 +139,7 @@ report :: PandocMonad m => LogMessage -> m ()
133139-- | Fetch an image or other item from the local filesystem or the net.
134140-- Returns raw content and maybe mime type.
135141fetchItem :: PandocMonad m
136− => String
142+ => Text
137143 -> m (B.ByteString, Maybe MimeType)
138144
139145-- Set the resource path searched by 'fetchItem'.
@@ -155,6 +161,13 @@ Note that `PandocIO` is an instance of `MonadIO`, so you can
155161use `liftIO` to perform arbitrary IO operations inside a pandoc
156162conversion chain.
157163
164+`readMarkdown` is polymorphic in its second argument, which
165+can be any type that is an instance of the `ToSources`
166+typeclass. You can use `Text`, as in the example above.
167+But you can also use `[(FilePath, Text)]`, if the input comes
168+from multiple files and you want to track source positions
169+accurately.
170+
158171# Options
159172
160173The first argument of each reader or writer is for
@@ -200,8 +213,8 @@ of the Monoid typeclass and can easily be concatenated:
200213import Text.Pandoc.Builder
201214
202215mydoc :: Pandoc
203−mydoc = doc $ header 1 (text "Hello!")
204− <> para (emph (text "hello world") <> text ".")
216+mydoc = doc $ header 1 (text (T.pack "Hello!"))
217+ <> para (emph (text (T.pack "hello world")) <> text (T.pack "."))
205218
206219main :: IO ()
207220main = print mydoc
@@ -248,16 +261,16 @@ import qualified Data.Text as T
248261import Data.List (intersperse)
249262
250263data Station = Station{
251− address :: String
252− , name :: String
253− , cardsAccepted :: [String]
264+ address :: T.Text
265+ , name :: T.Text
266+ , cardsAccepted :: [T.Text]
254267 } deriving Show
255268
256269instance FromJSON Station where
257270 parseJSON (Object v) = Station <$>
258271 v .: "street_address" <*>
259272 v .: "station_name" <*>
260− (words <$> (v .:? "cards_accepted" .!= ""))
273+ (T.words <$> (v .:? "cards_accepted" .!= ""))
261274 parseJSON _ = mzero
262275
263276createLetter :: [Station] -> Pandoc
@@ -315,7 +328,7 @@ users to override the system defaults. If you want to disable
315328this behavior, use `setUserDataDir Nothing`.
316329
317330To render a template, use `renderTemplate'`, which takes two
318−arguments, a template (String) and a context (any instance
331+arguments, a template (Text) and a context (any instance
319332of ToJSON). If you want to create a context from the metadata
320333part of a Pandoc document, use `metaToJSON'` from
321334[Text.Pandoc.Writers.Shared]. If you also want to incorporate
@@ -413,7 +426,7 @@ concatenated together. Here's an example that returns a
413426list of the URLs linked to in a document:
414427
415428```haskell
416−listURLs :: Pandoc -> [String]
429+listURLs :: Pandoc -> [Text]
417430listURLs = query urls
418431 where urls (Link _ _ (src, _)) = [src]
419432 urls _ = []
linux/make_artifacts.sh+19−7
@@ -2,13 +2,23 @@ set -e
22
33MACHINE=$(uname -m)
44case "$MACHINE" in
5− x86_64) ARCHITECTURE=amd64;;
6− i686) ARCHITECTURE=i386;;
7− i386) ARCHITECTURE=i386;;
5+ x86_64) ARCHITECTURE=amd64;;
6+ i686) ARCHITECTURE=i386;;
7+ i386) ARCHITECTURE=i386;;
8+ aarch64) ARCHITECTURE=arm64;;
9+ *) ARCHITECTURE=unknown;;
810esac
911
1012ARTIFACTS="${ARTIFACTS:-/artifacts}"
1113
14+# This is our sentinel that tells us when we're done.
15+rm -f $ARTIFACTS/DONE
16+
17+clean_up() {
18+ echo "All done!" > "$ARTIFACTS/DONE"
19+}
20+trap clean_up EXIT
21+
1222# build binaries
1323
1424cabal --version
@@ -16,9 +26,9 @@ ghc --version
1626
1727cabal v2-update
1828cabal v2-clean
19−cabal v2-configure --enable-tests -f-export-dynamic -fembed_data_files --enable-executable-static --ghc-options '-optc-Os -optl=-pthread' pandoc
20−cabal v2-build
21−cabal v2-test -j1
29+cabal v2-configure --enable-tests -f-export-dynamic -fembed_data_files --enable-executable-static --ghc-options '-j4 +RTS -A256m -RTS -split-sections -optc-Os -optl=-pthread' pandoc
30+cabal v2-build -j4
31+cabal v2-test -j4
2232for f in $(find dist-newstyle -name 'pandoc' -type f -perm /400); do cp $f /artifacts/; done
2333
2434# make deb
@@ -68,5 +78,7 @@ mv pandoc $TARGET/bin
6878strip $TARGET/bin/pandoc
6979gzip -9 $TARGET/share/man/man1/pandoc.1
7080
71−tar cvzf $TARGET-linux-amd64.tar.gz $TARGET
81+tar cvzf $TARGET-linux-$ARCHITECTURE.tar.gz $TARGET
7282rm -r $TARGET
83+
84+exit 0
man/pandoc.1+286−61
@@ -1,7 +1,7 @@
11'\" t
2−.\" Automatically generated by Pandoc 2.11.4
2+.\" Automatically generated by Pandoc 2.14.0.1
33.\"
4−.TH "Pandoc User\[cq]s Guide" "" "January 21, 2021" "pandoc 2.11.4" ""
4+.TH "Pandoc User\[cq]s Guide" "" "June 20, 2021" "pandoc 2.14.0.3" ""
55.hy
66.SH NAME
77pandoc - general markup converter
@@ -172,13 +172,12 @@ You can then test it with \f[C]pdflatex test.tex\f[R].
172172When using LaTeX, the following packages need to be available (they are
173173included with all recent versions of TeX Live): \f[C]amsfonts\f[R],
174174\f[C]amsmath\f[R], \f[C]lm\f[R], \f[C]unicode-math\f[R],
175−\f[C]ifxetex\f[R], \f[C]ifluatex\f[R], \f[C]listings\f[R] (if the
176−\f[C]--listings\f[R] option is used), \f[C]fancyvrb\f[R],
177−\f[C]longtable\f[R], \f[C]booktabs\f[R], \f[C]graphicx\f[R] (if the
178−document contains images), \f[C]hyperref\f[R], \f[C]xcolor\f[R],
179−\f[C]ulem\f[R], \f[C]geometry\f[R] (with the \f[C]geometry\f[R] variable
180−set), \f[C]setspace\f[R] (with \f[C]linestretch\f[R]), and
181−\f[C]babel\f[R] (with \f[C]lang\f[R]).
175+\f[C]iftex\f[R], \f[C]listings\f[R] (if the \f[C]--listings\f[R] option
176+is used), \f[C]fancyvrb\f[R], \f[C]longtable\f[R], \f[C]booktabs\f[R],
177+\f[C]graphicx\f[R] (if the document contains images),
178+\f[C]hyperref\f[R], \f[C]xcolor\f[R], \f[C]ulem\f[R], \f[C]geometry\f[R]
179+(with the \f[C]geometry\f[R] variable set), \f[C]setspace\f[R] (with
180+\f[C]linestretch\f[R]), and \f[C]babel\f[R] (with \f[C]lang\f[R]).
182181The use of \f[C]xelatex\f[R] or \f[C]lualatex\f[R] as the PDF engine
183182requires \f[C]fontspec\f[R].
184183\f[C]lualatex\f[R] uses \f[C]selnolig\f[R].
@@ -458,16 +457,15 @@ On *nix and macOS systems this will be the \f[C]pandoc\f[R] subdirectory
458457of the XDG data directory (by default, \f[C]$HOME/.local/share\f[R],
459458overridable by setting the \f[C]XDG_DATA_HOME\f[R] environment
460459variable).
461−If that directory does not exist, \f[C]$HOME/.pandoc\f[R] will be used
462−(for backwards compatibility).
463−In Windows the default user data directory is
460+If that directory does not exist and \f[C]$HOME/.pandoc\f[R] exists, it
461+will be used (for backwards compatibility).
462+On Windows the default user data directory is
464463\f[C]C:\[rs]Users\[rs]USERNAME\[rs]AppData\[rs]Roaming\[rs]pandoc\f[R].
465464You can find the default user data directory on your system by looking
466465at the output of \f[C]pandoc --version\f[R].
467−A \f[C]reference.odt\f[R], \f[C]reference.docx\f[R], \f[C]epub.css\f[R],
468−\f[C]templates\f[R], \f[C]slidy\f[R], \f[C]slideous\f[R], or
469−\f[C]s5\f[R] directory placed in this directory will override
470−pandoc\[cq]s normal defaults.
466+Data files placed in this directory (for example,
467+\f[C]reference.odt\f[R], \f[C]reference.docx\f[R], \f[C]epub.css\f[R],
468+\f[C]templates\f[R]) will override pandoc\[cq]s normal defaults.
471469.TP
472470\f[B]\f[CB]-d\f[B]\f[R] \f[I]FILE\f[R], \f[B]\f[CB]--defaults=\f[B]\f[R]\f[I]FILE\f[R]
473471Specify a set of default option settings.
@@ -718,11 +716,11 @@ Extract images and other media contained in or linked from the source
718716document to the path \f[I]DIR\f[R], creating it if necessary, and adjust
719717the images references in the document so they point to the extracted
720718files.
721−If the source format is a binary container (docx, epub, or odt), the
722−media is extracted from the container and the original filenames are
723−used.
724−Otherwise the media is read from the file system or downloaded, and new
725−filenames are constructed based on SHA1 hashes of the contents.
719+Media are downloaded, read from the file system, or extracted from a
720+binary container (e.g.\ docx), as needed.
721+The original file paths are used if they are relative paths not
722+containing \f[C]..\f[R].
723+Otherwise filenames are constructed from the SHA1 hash of the contents.
726724.TP
727725\f[B]\f[CB]--abbreviations=\f[B]\f[R]\f[I]FILE\f[R]
728726Specifies a custom abbreviations file, with abbreviations one to a line.
@@ -732,9 +730,9 @@ system default.
732730To see the system default, use
733731\f[C]pandoc --print-default-data-file=abbreviations\f[R].
734732The only use pandoc makes of this list is in the Markdown reader.
735−Strings ending in a period that are found in this list will be followed
736−by a nonbreaking space, so that the period will not produce
737−sentence-ending space in formats like LaTeX.
733+Strings found in this list will be followed by a nonbreaking space, and
734+the period will not produce sentence-ending space in formats like LaTeX.
735+The strings may not contain spaces.
738736.SS General writer options
739737.TP
740738\f[B]\f[CB]-s\f[B]\f[R], \f[B]\f[CB]--standalone\f[B]\f[R]
@@ -925,6 +923,11 @@ Note that, if \f[C]--resource-path\f[R] is specified, the working
925923directory must be explicitly listed or it will not be searched.
926924For example: \f[C]--resource-path=.:test\f[R] will search the working
927925directory and the \f[C]test\f[R] subdirectory, in that order.
926+This option can be used repeatedly.
927+Search path components that come later on the command line will be
928+searched before those that come earlier, so
929+\f[C]--resource-path foo:bar --resource-path baz:bim\f[R] is equivalent
930+to \f[C]--resource-path baz:bim:foo:bar\f[R].
928931.TP
929932\f[B]\f[CB]--request-header=\f[B]\f[R]\f[I]NAME\f[R]\f[B]\f[CB]:\f[B]\f[R]\f[I]VAL\f[R]
930933Set the request header \f[I]NAME\f[R] to the value \f[I]VAL\f[R] when
@@ -1501,16 +1504,16 @@ inserted.
15011504.TP
15021505\f[B]\f[CB]--gladtex\f[B]\f[R]
15031506Enclose TeX math in \f[C]<eq>\f[R] tags in HTML output.
1504−The resulting HTML can then be processed by GladTeX to produce images of
1505−the typeset formulas and an HTML file with links to these images.
1506−So, the procedure is:
1507+The resulting HTML can then be processed by GladTeX to produce SVG
1508+images of the typeset formulas and an HTML file with these images
1509+embedded.
15071510.RS
15081511.IP
15091512.nf
15101513\f[C]
15111514pandoc -s --gladtex input.md -o myfile.htex
1512−gladtex -d myfile-images myfile.htex
1513−# produces myfile.html and images in myfile-images
1515+gladtex -d image_dir myfile.htex
1516+# produces myfile.html and images in image_dir
15141517\f[R]
15151518.fi
15161519.RE
@@ -1614,6 +1617,11 @@ T}@T{
16141617PandocPDFError
16151618T}
16161619T{
1620+44
1621+T}@T{
1622+PandocXMLError
1623+T}
1624+T{
1617162547
16181626T}@T{
16191627PandocPDFProgramNotFoundError
@@ -1674,6 +1682,11 @@ T}@T{
16741682PandocIpynbDecodingError
16751683T}
16761684T{
1685+94
1686+T}@T{
1687+PandocUnsupportedCharsetError
1688+T}
1689+T{
1677169097
16781691T}@T{
16791692PandocCouldNotFindDataFileError
@@ -1773,8 +1786,11 @@ data-dir:
17731786verbosity: INFO
17741787log-file: log.json
17751788
1776−# citeproc, natbib, or biblatex
1789+# citeproc, natbib, or biblatex. This only affects LaTeX
1790+# output. If you want to use citeproc to format citations,
1791+# you should also set \[aq]citeproc: true\[aq] (see above).
17771792cite-method: citeproc
1793+
17781794# part, chapter, section, or default:
17791795top-level-division: chapter
17801796abbreviations:
@@ -1875,6 +1891,38 @@ verbosity: INFO
18751891\f[R]
18761892.fi
18771893.PP
1894+In fields that expect a file path (or list of file paths), the following
1895+syntax may be used to interpolate environment variables:
1896+.IP
1897+.nf
1898+\f[C]
1899+csl: ${HOME}/mycsldir/special.csl
1900+\f[R]
1901+.fi
1902+.PP
1903+\f[C]${USERDATA}\f[R] may also be used; this will always resolve to the
1904+user data directory that is current when the defaults file is parsed,
1905+regardless of the setting of the environment variable
1906+\f[C]USERDATA\f[R].
1907+.PP
1908+\f[C]${.}\f[R] will resolve to the directory containing the default file
1909+itself.
1910+This allows you to refer to resources contained in that directory:
1911+.IP
1912+.nf
1913+\f[C]
1914+epub-cover-image: ${.}/cover.jpg
1915+epub-metadata: ${.}/meta.xml
1916+resource-path:
1917+- . # the working directory from which pandoc is run
1918+- ${.}/images # the images subdirectory of the directory
1919+ # containing this defaults file
1920+\f[R]
1921+.fi
1922+.PP
1923+This environment variable interpolation syntax \f[I]only\f[R] works in
1924+fields that expect file paths.
1925+.PP
18781926Default files can be placed in the \f[C]defaults\f[R] subdirectory of
18791927the user data directory and used from any directory.
18801928For example, one could create a file specifying defaults for writing
@@ -2134,9 +2182,9 @@ ${ styles.html() }
21342182\f[R]
21352183.fi
21362184.PP
2137−(If a partial is not found in the directory of the template, it will
2138−also be sought in the \f[C]templates\f[R] subdirectory of the user data
2139−directory.)
2185+(If a partial is not found in the directory of the template and the
2186+template path is given as a relative path, it will also be sought in the
2187+\f[C]templates\f[R] subdirectory of the user data directory.)
21402188.PP
21412189Partials may optionally be applied to variables using a colon:
21422190.IP
@@ -2543,10 +2591,9 @@ YAML metadata or with \f[C]-M classoption=fleqn\f[R].
25432591.SS Variables for HTML slides
25442592.PP
25452593These affect HTML output when [producing slide shows with pandoc].
2546−.PP
2547−All reveal.js configuration options are available as variables.
2548−To turn off boolean flags that default to true in reveal.js, use
2549−\f[C]0\f[R].
2594+.TP
2595+\f[B]\f[CB]institute\f[B]\f[R]
2596+author affiliations: can be a list when there are multiple authors
25502597.TP
25512598\f[B]\f[CB]revealjs-url\f[B]\f[R]
25522599base URL for reveal.js documents (defaults to
@@ -2565,6 +2612,10 @@ base URL for Slideous documents (defaults to \f[C]slideous\f[R])
25652612\f[B]\f[CB]title-slide-attributes\f[B]\f[R]
25662613additional attributes for the title slide of reveal.js slide shows.
25672614See background in reveal.js and beamer for an example.
2615+.PP
2616+All reveal.js configuration options are available as variables.
2617+To turn off boolean flags that default to true in reveal.js, use
2618+\f[C]0\f[R].
25682619.SS Variables for Beamer slides
25692620.PP
25702621These variables change the appearance of PDF slides using
@@ -3928,6 +3979,9 @@ begin with a space.
39283979\f[R]
39293980.fi
39303981.PP
3982+Inline formatting (such as emphasis) is allowed in the content, but not
3983+block-level formatting (such as block quotes or lists).
3984+.PP
39313985This syntax is borrowed from reStructuredText.
39323986.SS Lists
39333987.SS Bullet lists
@@ -4221,7 +4275,7 @@ Term 2
42214275Note that space between items in a definition list is required.
42224276(A variant that loosens this requirement, but disallows \[lq]lazy\[rq]
42234277hard wrapping, can be activated with \f[C]compact_definition_lists\f[R]:
4224−see Non-pandoc extensions, below.)
4278+see Non-default extensions, below.)
42254279.SS Numbered example lists
42264280.SS Extension: \f[C]example_lists\f[R]
42274281.PP
@@ -4742,7 +4796,9 @@ All of the metadata will appear in a single block at the beginning of
47424796the document.
47434797.PP
47444798Note that YAML escaping rules must be followed.
4745−Thus, for example, if a title contains a colon, it must be quoted.
4799+Thus, for example, if a title contains a colon, it must be quoted, and
4800+if it contains a backslash escape, then it must be ensured that it is
4801+not treated as a YAML escape sequence.
47464802The pipe character (\f[C]|\f[R]) can be used to begin an indented block
47474803that will be interpreted literally, without need for escaping.
47484804This form is necessary when the field contains blank lines or
@@ -4764,6 +4820,13 @@ abstract: |
47644820\f[R]
47654821.fi
47664822.PP
4823+The literal block after the \f[C]|\f[R] must be indented relative to the
4824+line containing the \f[C]|\f[R].
4825+If it is not, the YAML will be invalid and pandoc will not interpret it
4826+as metadata.
4827+For an overview of the complex rules governing YAML, see the Wikipedia
4828+entry on YAML syntax.
4829+.PP
47674830Template variables will be set automatically from the metadata.
47684831Thus, for example, in writing HTML, the variable \f[C]abstract\f[R] will
47694832be set to the HTML equivalent of the Markdown in the \f[C]abstract\f[R]
@@ -4829,6 +4892,21 @@ header-includes:
48294892 \[ga]\[ga]\[ga]
48304893\f[R]
48314894.fi
4895+.PP
4896+Note: the \f[C]yaml_metadata_block\f[R] extension works with
4897+\f[C]commonmark\f[R] as well as \f[C]markdown\f[R] (and it is enabled by
4898+default in \f[C]gfm\f[R] and \f[C]commonmark_x\f[R]).
4899+However, in these formats the following restrictions apply:
4900+.IP \[bu] 2
4901+The YAML metadata block must occur at the beginning of the document (and
4902+there can be only one).
4903+If multiple files are given as arguments to pandoc, only the first can
4904+be a YAML metadata block.
4905+.IP \[bu] 2
4906+The leaf nodes of the YAML structure are parsed in isolation from each
4907+other and from the rest of the document.
4908+So, for example, you can\[cq]t use a reference link in these contexts if
4909+the link definition is somewhere else in the document.
48324910.SS Backslash escapes
48334911.SS Extension: \f[C]all_symbols_escapable\f[R]
48344912.PP
@@ -5048,7 +5126,9 @@ delimiters.
50485126.PP
50495127For display math, use \f[C]$$\f[R] delimiters.
50505128(In this case, the delimiters may be separated from the formula by
5051−whitespace.)
5129+whitespace.
5130+However, there can be no blank lines betwen the opening and closing
5131+\f[C]$$\f[R] delimiters.)
50525132.PP
50535133TeX math will be printed in all output formats.
50545134How it is rendered depends on the output format:
@@ -5707,27 +5787,70 @@ Inline and regular footnotes may be mixed freely.
57075787.SS Citation syntax
57085788.SS Extension: \f[C]citations\f[R]
57095789.PP
5710−Markdown citations go inside square brackets and are separated by
5711−semicolons.
5712−Each citation must have a key, composed of `\[at]' + the citation
5713−identifier from the database, and may optionally have a prefix, a
5714−locator, and a suffix.
5715−The citation key must begin with a letter, digit, or \f[C]_\f[R], and
5716−may contain alphanumerics, \f[C]_\f[R], and internal punctuation
5717−characters (\f[C]:.#$%&-+?<>\[ti]/\f[R]).
5718−Here are some examples:
5790+To cite a bibliographic item with an identifier foo, use the syntax
5791+\f[C]\[at]foo\f[R].
5792+Normal citations should be included in square brackets, with semicolons
5793+separating distinct items:
57195794.IP
57205795.nf
57215796\f[C]
5722−Blah blah [see \[at]doe99, pp. 33-35; also \[at]smith04, chap. 1].
5723−
5724−Blah blah [\[at]doe99, pp. 33-35, 38-39 and *passim*].
5797+Blah blah [\[at]doe99; \[at]smith2000; \[at]smith2004].
5798+\f[R]
5799+.fi
5800+.PP
5801+How this is rendered depends on the citation style.
5802+In an author-date style, it might render as
5803+.IP
5804+.nf
5805+\f[C]
5806+Blah blah (Doe 1999, Smith 2000, 2004).
5807+\f[R]
5808+.fi
5809+.PP
5810+In a footnote style, it might render as
5811+.IP
5812+.nf
5813+\f[C]
5814+Blah blah.[\[ha]1]
57255815
5726−Blah blah [\[at]smith04; \[at]doe99].
5816+[\[ha]1]: John Doe, \[dq]Frogs,\[dq] *Journal of Amphibians* 44 (1999);
5817+Susan Smith, \[dq]Flies,\[dq] *Journal of Insects* (2000);
5818+Susan Smith, \[dq]Bees,\[dq] *Journal of Insects* (2004).
57275819\f[R]
57285820.fi
57295821.PP
5730−\f[C]pandoc\f[R] detects locator terms in the CSL locale files.
5822+See the CSL user documentation for more information about CSL styles and
5823+how they affect rendering.
5824+.PP
5825+Unless a citation key start with a letter, digit, or \f[C]_\f[R], and
5826+contains only alphanumerics and internal punctuation characters
5827+(\f[C]:.#$%&-+?<>\[ti]/\f[R]), it must be surrounded by curly braces,
5828+which are not considered part of the key.
5829+In \f[C]\[at]Foo_bar.baz.\f[R], the key is \f[C]Foo_bar.baz\f[R].
5830+The final period is not \f[I]internal\f[R] punctuation, so it is not
5831+included in the key.
5832+In \f[C]\[at]{Foo_bar.baz.}\f[R], the key is \f[C]Foo_bar.baz.\f[R],
5833+including the final period.
5834+The curly braces are recommended if you use URLs as keys:
5835+\f[C][\[at]{https://example.com/bib?name=foobar&date=2000}, p. 33]\f[R].
5836+.PP
5837+Citation items may optionally include a prefix, a locator, and a suffix.
5838+In
5839+.IP
5840+.nf
5841+\f[C]
5842+Blah blah [see \[at]doe99, pp. 33-35 and *passim*; \[at]smith04, chap. 1].
5843+\f[R]
5844+.fi
5845+.PP
5846+The first item (\f[C]doe99\f[R]) has prefix \f[C]see\f[R], locator
5847+\f[C]pp. 33-35\f[R], and suffix \f[C]and *passim*\f[R].
5848+The second item (\f[C]smith04\f[R]) has locator \f[C]chap. 1\f[R] and no
5849+prefix or suffix.
5850+.PP
5851+Pandoc uses some heuristics to separate the locator from the rest of the
5852+subject.
5853+It is sensitive to the locator terms defined in the CSL locale files.
57315854Either abbreviated or unabbreviated forms are accepted.
57325855In the \f[C]en-US\f[R] locale, locator terms can be written in either
57335856singular or plural forms, as \f[C]book\f[R],
@@ -5749,14 +5872,15 @@ singular or plural forms, as \f[C]book\f[R],
57495872\f[C]\[sc]\f[R]/\f[C]\[sc]\[sc]\f[R].
57505873If no locator term is used, \[lq]page\[rq] is assumed.
57515874.PP
5752−\f[C]pandoc\f[R] will use heuristics to distinguish the locator from the
5753−suffix.
5754−In complex cases, the locator can be enclosed in curly braces:
5875+In complex cases, you can force something to be treated as a locator by
5876+enclosing it in curly braces or prevent parsing the suffix as locator by
5877+prepending curly braces:
57555878.IP
57565879.nf
57575880\f[C]
57585881[\[at]smith{ii, A, D-Z}, with a suffix]
57595882[\[at]smith, {pp. iv, vi-xi, (xv)-(xvii)} with suffix here]
5883+[\[at]smith{}, 99 years later]
57605884\f[R]
57615885.fi
57625886.PP
@@ -5770,7 +5894,8 @@ Smith says blah [-\[at]smith04].
57705894\f[R]
57715895.fi
57725896.PP
5773−You can also write an in-text citation, as follows:
5897+You can also write an author-in-text citation, by omitting the square
5898+brackets:
57745899.IP
57755900.nf
57765901\f[C]
@@ -5779,13 +5904,64 @@ You can also write an in-text citation, as follows:
57795904\[at]smith04 [p. 33] says blah.
57805905\f[R]
57815906.fi
5782−.SS Non-pandoc extensions
5907+.PP
5908+This will cause the author\[cq]s name to be rendered, followed by the
5909+bibliographical details.
5910+Use this form when you want to make the citation the subject of a
5911+sentence.
5912+.PP
5913+When you are using a note style, it is usually better to let citeproc
5914+create the footnotes from citations rather than writing an explicit
5915+note.
5916+If you do write an explicit note that contains a citation, note that
5917+normal citations will be put in parentheses, while author-in-text
5918+citations will not.
5919+For this reason, it is sometimes preferable to use the author-in-text
5920+style inside notes when using a note style.
5921+.SS Non-default extensions
57835922.PP
57845923The following Markdown syntax extensions are not enabled by default in
57855924pandoc, but may be enabled by adding \f[C]+EXTENSION\f[R] to the format
57865925name, where \f[C]EXTENSION\f[R] is the name of the extension.
57875926Thus, for example, \f[C]markdown+hard_line_breaks\f[R] is Markdown with
57885927hard line breaks.
5928+.SS Extension: \f[C]rebase_relative_paths\f[R]
5929+.PP
5930+Rewrite relative paths for Markdown links and images, depending on the
5931+path of the file containing the link or image link.
5932+For each link or image, pandoc will compute the directory of the
5933+containing file, relative to the working directory, and prepend the
5934+resulting path to the link or image path.
5935+.PP
5936+The use of this extension is best understood by example.
5937+Suppose you have a a subdirectory for each chapter of a book,
5938+\f[C]chap1\f[R], \f[C]chap2\f[R], \f[C]chap3\f[R].
5939+Each contains a file \f[C]text.md\f[R] and a number of images used in
5940+the chapter.
5941+You would like to have \f[C]![image](spider.jpg)\f[R] in
5942+\f[C]chap1/text.md\f[R] refer to \f[C]chap1/spider.jpg\f[R] and
5943+\f[C]![image](spider.jpg)\f[R] in \f[C]chap2/text.md\f[R] refer to
5944+\f[C]chap2/spider.jpg\f[R].
5945+To do this, use
5946+.IP
5947+.nf
5948+\f[C]
5949+pandoc chap*/*.md -f markdown+rebase_relative_paths
5950+\f[R]
5951+.fi
5952+.PP
5953+Without this extension, you would have to use
5954+\f[C]![image](chap1/spider.jpg)\f[R] in \f[C]chap1/text.md\f[R] and
5955+\f[C]![image](chap2/spider.jpg)\f[R] in \f[C]chap2/text.md\f[R].
5956+Links with relative paths will be rewritten in the same way as images.
5957+.PP
5958+Absolute paths and URLs are not changed.
5959+Neither are empty paths or paths consisting entirely of a fragment,
5960+e.g., \f[C]#foo\f[R].
5961+.PP
5962+Note that relative paths in reference links and images will be rewritten
5963+relative to the file containing the link reference definition, not the
5964+file containing the reference link or image itself, if these differ.
57895965.SS Extension: \f[C]attributes\f[R]
57905966.PP
57915967Allows attributes to be attached to any inline or block-level element.
@@ -6415,9 +6591,29 @@ entries (for author-date and numerical styles only).
64156591.TP
64166592\f[B]\f[CB]lang\f[B]\f[R]
64176593The \f[C]lang\f[R] field will affect how the style is localized, for
6418−example in the translation of labels and the use of quotation marks.
6594+example in the translation of labels, the use of quotation marks, and
6595+the way items are sorted.
64196596(For backwards compatibility, \f[C]locale\f[R] may be used instead of
64206597\f[C]lang\f[R], but this use is deprecated.)
6598+.RS
6599+.PP
6600+A BCP 47 language tag is expected: for example, \f[C]en\f[R],
6601+\f[C]de\f[R], \f[C]en-US\f[R], \f[C]fr-CA\f[R], \f[C]ug-Cyrl\f[R].
6602+The unicode extension syntax (after \f[C]-u-\f[R]) may be used to
6603+specify options for collation (sorting) more precisely.
6604+Here are some examples:
6605+.IP \[bu] 2
6606+\f[C]zh-u-co-pinyin\f[R] \[en] Chinese with the Pinyin collation.
6607+.IP \[bu] 2
6608+\f[C]es-u-co-trad\f[R] \[en] Spanish with the traditional collation
6609+(with \f[C]Ch\f[R] sorting after \f[C]C\f[R]).
6610+.IP \[bu] 2
6611+\f[C]fr-u-kb\f[R] \[en] French with \[lq]backwards\[rq] accent sorting
6612+(with \f[C]cot\['e]\f[R] sorting after \f[C]c\[^o]te\f[R]).
6613+.IP \[bu] 2
6614+\f[C]en-US-u-kf-upper\f[R] \[en] English with uppercase letters sorting
6615+before lower (default is lower before upper).
6616+.RE
64216617.TP
64226618\f[B]\f[CB]notes-after-punctuation\f[B]\f[R]
64236619If true (the default), pandoc will put footnote citations after
@@ -6538,6 +6734,11 @@ A heading at the slide level always starts a new slide.
65386734.IP \[bu] 2
65396735Headings \f[I]below\f[R] the slide level in the hierarchy create
65406736headings \f[I]within\f[R] a slide.
6737+(In beamer, a \[lq]block\[rq] will be created.
6738+If the heading has the class \f[C]example\f[R], an
6739+\f[C]exampleblock\f[R] environment will be used; if it has the class
6740+\f[C]alert\f[R], an \f[C]alertblock\f[R] will be used; otherwise a
6741+regular \f[C]block\f[R] will be used.)
65416742.IP \[bu] 2
65426743Headings \f[I]above\f[R] the slide level in the hierarchy create
65436744\[lq]title slides,\[rq] which just contain the section title and help to
@@ -6938,6 +7139,16 @@ A string value.
69387139\f[B]\f[CB]rights\f[B]\f[R]
69397140A string value.
69407141.TP
7142+\f[B]\f[CB]belongs-to-collection\f[B]\f[R]
7143+A string value.
7144+identifies the name of a collection to which the EPUB Publication
7145+belongs.
7146+.TP
7147+\f[B]\f[CB]group-position\f[B]\f[R]
7148+The \f[C]group-position\f[R] field indicates the numeric position in
7149+which the EPUB Publication belongs relative to other works belonging to
7150+the same \f[C]belongs-to-collection\f[R] field.
7151+.TP
69417152\f[B]\f[CB]cover-image\f[B]\f[R]
69427153A string value (path to cover image).
69437154.TP
@@ -7453,6 +7664,20 @@ need to specify a template manually using \f[C]--template\f[R] or add a
74537664new default template with the name
74547665\f[C]default.NAME_OF_CUSTOM_WRITER.lua\f[R] to the \f[C]templates\f[R]
74557666subdirectory of your user data directory (see Templates).
7667+.SH REPRODUCIBLE BUILDS
7668+.PP
7669+Some of the document formats pandoc targets (such as EPUB, docx, and
7670+ODT) include build timestamps in the generated document.
7671+That means that the files generated on successive builds will differ,
7672+even if the source does not.
7673+To avoid this, set the \f[C]SOURCE_DATE_EPOCH\f[R] environment variable,
7674+and the timestamp will be taken from it instead of the current time.
7675+\f[C]SOURCE_DATE_EPOCH\f[R] should contain an integer unix timestamp
7676+(specifying the number of second since midnight UTC January 1, 1970).
7677+.PP
7678+Some document formats also include a unique identifier.
7679+For EPUB, this can be set explicitly by setting the \f[C]identifier\f[R]
7680+metadata field (see EPUB Metadata, above).
74567681.SH A NOTE ON SECURITY
74577682.PP
74587683If you use pandoc to convert user-contributed content in a web
@@ -7483,7 +7708,7 @@ The HTML generated by pandoc is not guaranteed to be safe.
74837708If \f[C]raw_html\f[R] is enabled for the Markdown input, users can
74847709inject arbitrary HTML.
74857710Even if \f[C]raw_html\f[R] is disabled, users can include dangerous
7486−content in attributes for headings, spans, and code blocks.
7711+content in URLs and attributes.
74877712To be safe, you should run all the generated HTML through an HTML
74887713sanitizer.
74897714.SH AUTHORS
pandoc.cabal+52−32
@@ -1,6 +1,6 @@
11cabal-version: 2.2
22name: pandoc
3−version: 2.11.4
3+version: 2.14.0.3
44build-type: Simple
55license: GPL-2.0-or-later
66license-file: COPYING.md
@@ -12,7 +12,7 @@ stability: alpha
1212homepage: https://pandoc.org
1313category: Text
1414tested-with: GHC == 8.2.2, GHC == 8.4.4, GHC == 8.6.5,
15− GHC == 8.8.4, GHC == 8.10.2
15+ GHC == 8.8.4, GHC == 8.10.2, GHC == 9.0.1
1616synopsis: Conversion between markup formats
1717description: Pandoc is a Haskell library for converting from one markup
1818 format to another, and a command-line tool that uses
@@ -208,12 +208,16 @@ extra-source-files:
208208 test/command/*.md
209209 test/command/*.csl
210210 test/command/biblio.bib
211− test/command/biblatex-examples.bib
211+ test/command/averroes.bib
212212 test/command/A.txt
213213 test/command/B.txt
214214 test/command/C.txt
215215 test/command/D.txt
216216 test/command/01.csv
217+ test/command/chap1/spider.png
218+ test/command/chap2/spider.png
219+ test/command/chap1/text.md
220+ test/command/chap2/text.md
217221 test/command/defaults1.yaml
218222 test/command/defaults2.yaml
219223 test/command/defaults3.yaml
@@ -398,8 +402,7 @@ flag trypandoc
398402
399403common common-options
400404 default-language: Haskell2010
401− build-depends: base >= 4.9 && < 5,
402− text >= 1.1.1.0 && < 1.3
405+ build-depends: base >= 4.9 && < 5
403406 ghc-options: -Wall -fno-warn-unused-do-bind
404407 -Wincomplete-record-updates
405408 -Wnoncanonical-monad-instances
@@ -427,7 +430,7 @@ common common-options
427430common common-executable
428431 import: common-options
429432 build-depends: pandoc
430− ghc-options: -rtsopts -with-rtsopts=-K16m -threaded
433+ ghc-options: -rtsopts -with-rtsopts=-A8m -threaded
431434
432435
433436library
@@ -439,29 +442,30 @@ library
439442 SHA >= 1.6 && < 1.7,
440443 aeson >= 0.7 && < 1.6,
441444 aeson-pretty >= 0.8.5 && < 0.9,
442− attoparsec >= 0.12 && < 0.14,
445+ array >= 0.5 && < 0.6,
446+ attoparsec >= 0.12 && < 0.15,
443447 base64-bytestring >= 0.1 && < 1.3,
444448 binary >= 0.7 && < 0.11,
445449 blaze-html >= 0.9 && < 0.10,
446450 blaze-markup >= 0.8 && < 0.9,
447451 bytestring >= 0.9 && < 0.12,
448452 case-insensitive >= 1.2 && < 1.3,
449− citeproc >= 0.3.0.7 && < 0.4,
450− commonmark >= 0.1.1.3 && < 0.2,
451− commonmark-extensions >= 0.2.0.4 && < 0.3,
452− commonmark-pandoc >= 0.2 && < 0.3,
453+ citeproc >= 0.4.0.1 && < 0.4.1,
454+ commonmark >= 0.2.1 && < 0.3,
455+ commonmark-extensions >= 0.2.1.2 && < 0.3,
456+ commonmark-pandoc >= 0.2.1.1 && < 0.3,
453457 connection >= 0.3.1,
454458 containers >= 0.4.2.1 && < 0.7,
455459 data-default >= 0.4 && < 0.8,
456460 deepseq >= 1.3 && < 1.5,
457461 directory >= 1.2.3 && < 1.4,
458− doclayout >= 0.3 && < 0.4,
462+ doclayout >= 0.3.0.1 && < 0.4,
459463 doctemplates >= 0.9 && < 0.10,
460464 emojis >= 0.1 && < 0.2,
461465 exceptions >= 0.8 && < 0.11,
462466 file-embed >= 0.0 && < 0.1,
463467 filepath >= 1.1 && < 1.5,
464− haddock-library >= 1.8 && < 1.10,
468+ haddock-library >= 1.10 && < 1.11,
465469 hslua >= 1.1 && < 1.4,
466470 hslua-module-path >= 0.1.0 && < 0.2.0,
467471 hslua-module-system >= 0.2 && < 0.3,
@@ -470,30 +474,31 @@ library
470474 http-client-tls >= 0.2.4 && < 0.4,
471475 http-types >= 0.8 && < 0.13,
472476 ipynb >= 0.1 && < 0.2,
473− jira-wiki-markup >= 1.3.3 && < 1.4,
477+ jira-wiki-markup >= 1.4 && < 1.5,
474478 mtl >= 2.2 && < 2.3,
475479 network >= 2.6,
476− network-uri >= 2.6 && < 2.7,
480+ network-uri >= 2.6 && < 2.8,
477481 pandoc-types >= 1.22 && < 1.23,
478482 parsec >= 3.1 && < 3.2,
479483 process >= 1.2.3 && < 1.7,
480− random >= 1 && < 1.2,
481− safe >= 0.3 && < 0.4,
484+ random >= 1 && < 1.3,
485+ safe >= 0.3.18 && < 0.4,
482486 scientific >= 0.3 && < 0.4,
483− skylighting >= 0.10.3 && < 0.11,
484− skylighting-core >= 0.10.3 && < 0.11,
487+ skylighting >= 0.10.5.2 && < 0.10.6,
488+ skylighting-core >= 0.10.5.2 && < 0.10.6,
485489 split >= 0.2 && < 0.3,
486490 syb >= 0.1 && < 0.8,
487491 tagsoup >= 0.14.6 && < 0.15,
488492 temporary >= 1.1 && < 1.4,
489− texmath >= 0.12.1 && < 0.13,
493+ texmath >= 0.12.3 && < 0.12.4,
490494 text >= 1.1.1.0 && < 1.3,
491495 text-conversions >= 0.3 && < 0.4,
492− time >= 1.5 && < 1.10,
496+ time >= 1.5 && < 1.12,
493497 unicode-transforms >= 0.3 && < 0.4,
494498 unordered-containers >= 0.2 && < 0.3,
495499 xml >= 1.3.12 && < 1.4,
496− xml-conduit >= 1.7 && < 1.10,
500+ xml-conduit >= 1.9.1.1 && < 1.10,
501+ unicode-collation >= 0.1.1 && < 0.2,
497502 zip-archive >= 0.2.3.4 && < 0.5,
498503 zlib >= 0.5 && < 0.7
499504 if os(windows) && arch(i386)
@@ -512,13 +517,13 @@ library
512517 Text.Pandoc.Options,
513518 Text.Pandoc.Extensions,
514519 Text.Pandoc.Shared,
520+ Text.Pandoc.Sources,
515521 Text.Pandoc.MediaBag,
516522 Text.Pandoc.Error,
517523 Text.Pandoc.Filter,
518524 Text.Pandoc.Readers,
519525 Text.Pandoc.Readers.HTML,
520526 Text.Pandoc.Readers.LaTeX,
521− Text.Pandoc.Readers.LaTeX.Types,
522527 Text.Pandoc.Readers.Markdown,
523528 Text.Pandoc.Readers.CommonMark,
524529 Text.Pandoc.Readers.Creole,
@@ -602,7 +607,6 @@ library
602607 Text.Pandoc.Asciify,
603608 Text.Pandoc.Emoji,
604609 Text.Pandoc.ImageSize,
605− Text.Pandoc.BCP47,
606610 Text.Pandoc.Class,
607611 Text.Pandoc.Citeproc
608612 other-modules: Text.Pandoc.App.CommandLineOptions,
@@ -627,9 +631,15 @@ library
627631 Text.Pandoc.Readers.HTML.Table,
628632 Text.Pandoc.Readers.HTML.TagCategories,
629633 Text.Pandoc.Readers.HTML.Types,
630− Text.Pandoc.Readers.LaTeX.Parsing,
634+ Text.Pandoc.Readers.LaTeX.Inline,
635+ Text.Pandoc.Readers.LaTeX.Citation,
631636 Text.Pandoc.Readers.LaTeX.Lang,
637+ Text.Pandoc.Readers.LaTeX.Macro,
638+ Text.Pandoc.Readers.LaTeX.Math,
639+ Text.Pandoc.Readers.LaTeX.Parsing,
632640 Text.Pandoc.Readers.LaTeX.SIunitx,
641+ Text.Pandoc.Readers.LaTeX.Table,
642+ Text.Pandoc.Readers.LaTeX.Types,
633643 Text.Pandoc.Readers.Odt.Base,
634644 Text.Pandoc.Readers.Odt.Namespaces,
635645 Text.Pandoc.Readers.Odt.StyleReader,
@@ -653,13 +663,21 @@ library
653663 Text.Pandoc.Readers.Metadata,
654664 Text.Pandoc.Readers.Roff,
655665 Text.Pandoc.Writers.Docx.StyleMap,
666+ Text.Pandoc.Writers.Docx.Table,
667+ Text.Pandoc.Writers.Docx.Types,
668+ Text.Pandoc.Writers.GridTable
656669 Text.Pandoc.Writers.JATS.References,
657670 Text.Pandoc.Writers.JATS.Table,
658671 Text.Pandoc.Writers.JATS.Types,
659672 Text.Pandoc.Writers.LaTeX.Caption,
660673 Text.Pandoc.Writers.LaTeX.Notes,
661674 Text.Pandoc.Writers.LaTeX.Table,
675+ Text.Pandoc.Writers.LaTeX.Lang,
662676 Text.Pandoc.Writers.LaTeX.Types,
677+ Text.Pandoc.Writers.LaTeX.Citation,
678+ Text.Pandoc.Writers.LaTeX.Util,
679+ Text.Pandoc.Writers.Markdown.Types,
680+ Text.Pandoc.Writers.Markdown.Inline,
663681 Text.Pandoc.Writers.Roff,
664682 Text.Pandoc.Writers.Powerpoint.Presentation,
665683 Text.Pandoc.Writers.Powerpoint.Output,
@@ -720,7 +738,7 @@ executable trypandoc
720738 main-is: trypandoc.hs
721739 hs-source-dirs: trypandoc
722740 if flag(trypandoc)
723− build-depends: aeson, http-types, wai >= 0.3, wai-extra
741+ build-depends: aeson, http-types, text, wai >= 0.3, wai-extra >= 3.0.24
724742 buildable: True
725743 else
726744 buildable: False
@@ -734,13 +752,11 @@ test-suite test-pandoc
734752 Diff >= 0.2 && < 0.5,
735753 Glob >= 0.7 && < 0.11,
736754 QuickCheck >= 2.4 && < 2.15,
737− base64-bytestring >= 0.1 && < 1.3,
738755 bytestring >= 0.9 && < 0.12,
739756 containers >= 0.4.2.1 && < 0.7,
740757 directory >= 1.2.3 && < 1.4,
741758 doctemplates >= 0.9 && < 0.10,
742759 exceptions >= 0.8 && < 0.11,
743− executable-path >= 0.0 && < 0.1,
744760 filepath >= 1.1 && < 1.5,
745761 hslua >= 1.1 && < 1.4,
746762 mtl >= 2.2 && < 2.3,
@@ -751,8 +767,8 @@ test-suite test-pandoc
751767 tasty-hunit >= 0.9 && < 0.11,
752768 tasty-lua >= 0.2 && < 0.3,
753769 tasty-quickcheck >= 0.8 && < 0.11,
754− temporary >= 1.1 && < 1.4,
755− time >= 1.5 && < 1.10,
770+ text >= 1.1.1.0 && < 1.3,
771+ time >= 1.5 && < 1.12,
756772 xml >= 1.3.12 && < 1.4,
757773 zip-archive >= 0.2.3.4 && < 0.5
758774 other-modules: Tests.Old
@@ -818,7 +834,11 @@ benchmark benchmark-pandoc
818834 hs-source-dirs: benchmark
819835 build-depends: bytestring,
820836 containers,
821− tasty,
837+ -- gauge >= 0.2 && < 0.3,
822838 tasty-bench >= 0.2 && <= 0.3,
823839 mtl >= 2.2 && < 2.3,
824− time
840+ text >= 1.1.1.0 && < 1.3,
841+ time,
842+ deepseq
843+ -- we increase heap size to avoid benchmarking garbage collection:
844+ ghc-options: -rtsopts -with-rtsopts=-A8m -threaded
src/Text/Pandoc/App.hs+40−21
@@ -47,20 +47,21 @@ import System.FilePath ( takeBaseName, takeExtension )
4747import System.IO (nativeNewline, stdout)
4848import qualified System.IO as IO (Newline (..))
4949import Text.Pandoc
50+import Text.Pandoc.Builder (setMeta)
5051import Text.Pandoc.MIME (getCharset)
5152import Text.Pandoc.App.FormatHeuristics (formatFromFilePaths)
5253import Text.Pandoc.App.Opt (Opt (..), LineEnding (..), defaultOpts,
53− IpynbOutput (..) )
54+ IpynbOutput (..))
5455import Text.Pandoc.App.CommandLineOptions (parseOptions, parseOptionsFromArgs,
5556 options)
5657import Text.Pandoc.App.OutputSettings (OutputSettings (..), optToOutputSettings)
57−import Text.Pandoc.BCP47 (Lang (..), parseBCP47)
58+import Text.Collate.Lang (Lang (..), parseLang)
5859import Text.Pandoc.Filter (Filter (JSONFilter, LuaFilter), applyFilters)
5960import Text.Pandoc.PDF (makePDF)
6061import Text.Pandoc.SelfContained (makeSelfContained)
6162import Text.Pandoc.Shared (eastAsianLineBreakFilter, stripEmptyParagraphs,
6263 headerShift, isURI, tabFilter, uriPathToPath, filterIpynbOutput,
63− defaultUserDataDirs, tshow, findM)
64+ defaultUserDataDir, tshow)
6465import Text.Pandoc.Writers.Shared (lookupMetaString)
6566import Text.Pandoc.Readers.Markdown (yamlToMeta)
6667import qualified Text.Pandoc.UTF8 as UTF8
@@ -71,6 +72,15 @@ import System.Posix.Terminal (queryTerminal)
7172
7273convertWithOpts :: Opt -> IO ()
7374convertWithOpts opts = do
75+ datadir <- case optDataDir opts of
76+ Nothing -> do
77+ d <- defaultUserDataDir
78+ exists <- doesDirectoryExist d
79+ return $ if exists
80+ then Just d
81+ else Nothing
82+ Just _ -> return $ optDataDir opts
83+
7484 let outputFile = fromMaybe "-" (optOutputFile opts)
7585 let filters = optFilters opts
7686 let verbosity = optVerbosity opts
@@ -85,12 +95,6 @@ convertWithOpts opts = do
8595 Just xs | not (optIgnoreArgs opts) -> xs
8696 _ -> ["-"]
8797
88− datadir <- case optDataDir opts of
89− Nothing -> do
90− ds <- defaultUserDataDirs
91− findM doesDirectoryExist ds
92− Just _ -> return $ optDataDir opts
93−
9498 let runIO' :: PandocIO a -> IO a
9599 runIO' f = do
96100 (res, reports) <- runIOorExplode $ do
@@ -156,9 +160,11 @@ convertWithOpts opts = do
156160 else optTabStop opts)
157161
158162
159− let readSources :: [FilePath] -> PandocIO Text
160− readSources srcs = convertTabs . T.intercalate (T.pack "\n") <$>
161− mapM readSource srcs
163+ let readSources :: [FilePath] -> PandocIO [(FilePath, Text)]
164+ readSources srcs =
165+ mapM (\fp -> do
166+ t <- readSource fp
167+ return (if fp == "-" then "" else fp, convertTabs t)) srcs
162168
163169
164170 outputSettings <- optToOutputSettings opts
@@ -196,8 +202,8 @@ convertWithOpts opts = do
196202 Just f -> readFileStrict f
197203
198204 case lookupMetaString "lang" (optMetadata opts) of
199− "" -> setTranslations $ Lang "en" "" "US" []
200− l -> case parseBCP47 l of
205+ "" -> setTranslations $ Lang "en" Nothing (Just "US") [] [] []
206+ l -> case parseLang l of
201207 Left _ -> report $ InvalidLang l
202208 Right l' -> setTranslations l'
203209
@@ -251,13 +257,17 @@ convertWithOpts opts = do
251257 let sourceToDoc :: [FilePath] -> PandocIO Pandoc
252258 sourceToDoc sources' =
253259 case reader of
254− TextReader r
255− | optFileScope opts || readerNameBase == "json" ->
256− mconcat <$> mapM (readSource >=> r readerOpts) sources'
257− | otherwise ->
258− readSources sources' >>= r readerOpts
259− ByteStringReader r ->
260− mconcat <$> mapM (readFile' >=> r readerOpts) sources'
260+ TextReader r
261+ | readerNameBase == "json" ->
262+ mconcat <$> mapM (readSource >=> r readerOpts) sources'
263+ | optFileScope opts ->
264+ -- Read source and convert tabs (see #6709)
265+ let readSource' = fmap convertTabs . readSource
266+ in mconcat <$> mapM (readSource' >=> r readerOpts) sources'
267+ | otherwise ->
268+ readSources sources' >>= r readerOpts
269+ ByteStringReader r ->
270+ mconcat <$> mapM (readFile' >=> r readerOpts) sources'
261271
262272
263273 when (readerNameBase == "markdown_github" ||
@@ -275,12 +285,21 @@ convertWithOpts opts = do
275285 report $ Deprecated "pandoc-citeproc filter"
276286 "Use --citeproc instead."
277287
288+ let cslMetadata =
289+ maybe id (setMeta "csl") (optCSL opts) .
290+ (case optBibliography opts of
291+ [] -> id
292+ xs -> setMeta "bibliography" xs) .
293+ maybe id (setMeta "citation-abbreviations")
294+ (optCitationAbbreviations opts) $ mempty
295+
278296 doc <- sourceToDoc sources >>=
279297 ( (if isJust (optExtractMedia opts)
280298 then fillMediaBag
281299 else return)
282300 >=> return . adjustMetadata (metadataFromFile <>)
283301 >=> return . adjustMetadata (<> optMetadata opts)
302+ >=> return . adjustMetadata (<> cslMetadata)
284303 >=> applyTransforms transforms
285304 >=> applyFilters readerOpts filters [T.unpack format]
286305 >=> maybe return extractMedia (optExtractMedia opts)
src/Text/Pandoc/App/CommandLineOptions.hs+30−8
@@ -31,7 +31,7 @@ import Data.Aeson.Encode.Pretty (encodePretty', Config(..), keyOrder,
3131 defConfig, Indent(..), NumberFormat(..))
3232import Data.Bifunctor (second)
3333import Data.Char (toLower)
34−import Data.List (intercalate, sort)
34+import Data.List (intercalate, sort, foldl')
3535#ifdef _WINDOWS
3636#if MIN_VERSION_base(4,12,0)
3737import Data.List (isPrefixOf)
@@ -48,12 +48,13 @@ import System.FilePath
4848import System.IO (stdout)
4949import Text.DocTemplates (Context (..), ToContext (toVal), Val (..))
5050import Text.Pandoc
51+import Text.Pandoc.Builder (setMeta)
5152import Text.Pandoc.App.Opt (Opt (..), LineEnding (..), IpynbOutput (..),
52− DefaultsState (..), addMeta, applyDefaults,
53+ DefaultsState (..), applyDefaults,
5354 fullDefaultsPath)
5455import Text.Pandoc.Filter (Filter (..))
5556import Text.Pandoc.Highlighting (highlightingStyles)
56−import Text.Pandoc.Shared (ordNub, elemText, safeStrRead, defaultUserDataDirs)
57+import Text.Pandoc.Shared (ordNub, elemText, safeStrRead, defaultUserDataDir)
5758import Text.Printf
5859
5960#ifdef EMBED_DATA_FILES
@@ -92,7 +93,7 @@ parseOptionsFromArgs options' defaults prg rawArgs = do
9293 ("Try " ++ prg ++ " --help for more information.")
9394
9495 -- thread option data structure through all supplied option actions
95− opts <- foldl (>>=) (return defaults) actions
96+ opts <- foldl' (>>=) (return defaults) actions
9697 let mbArgs = case args of
9798 [] -> Nothing
9899 xs -> Just xs
@@ -287,7 +288,8 @@ options =
287288 , Option "" ["resource-path"]
288289 (ReqArg
289290 (\arg opt -> return opt { optResourcePath =
290− splitSearchPath arg })
291+ splitSearchPath arg ++
292+ optResourcePath opt })
291293 "SEARCHPATH")
292294 "" -- "Paths to search for images and other resources"
293295
@@ -939,13 +941,12 @@ options =
939941 (NoArg
940942 (\_ -> do
941943 prg <- getProgName
942− defaultDatadirs <- defaultUserDataDirs
944+ defaultDatadir <- defaultUserDataDir
943945 UTF8.hPutStrLn stdout
944946 $ T.pack
945947 $ prg ++ " " ++ T.unpack pandocVersion ++
946948 compileInfo ++
947− "\nUser data directory: " ++
948− intercalate " or " defaultDatadirs ++
949+ "\nUser data directory: " ++ defaultDatadir ++
949950 ('\n':copyrightMessage)
950951 exitSuccess ))
951952 "" -- "Print version"
@@ -1053,6 +1054,27 @@ setVariable key val (Context ctx) = Context $ M.alter go key ctx
10531054 go (Just (ListVal xs)) = Just $ ListVal $ xs ++ [toVal val]
10541055 go (Just x) = Just $ ListVal [x, toVal val]
10551056
1057+addMeta :: String -> String -> Meta -> Meta
1058+addMeta k v meta =
1059+ case lookupMeta k' meta of
1060+ Nothing -> setMeta k' v' meta
1061+ Just (MetaList xs) ->
1062+ setMeta k' (MetaList (xs ++ [v'])) meta
1063+ Just x -> setMeta k' (MetaList [x, v']) meta
1064+ where
1065+ v' = readMetaValue v
1066+ k' = T.pack k
1067+
1068+readMetaValue :: String -> MetaValue
1069+readMetaValue s
1070+ | s == "true" = MetaBool True
1071+ | s == "True" = MetaBool True
1072+ | s == "TRUE" = MetaBool True
1073+ | s == "false" = MetaBool False
1074+ | s == "False" = MetaBool False
1075+ | s == "FALSE" = MetaBool False
1076+ | otherwise = MetaString $ T.pack s
1077+
10561078-- On Windows with ghc 8.6+, we need to rewrite paths
10571079-- beginning with \\ to \\?\UNC\. -- See #5127.
10581080normalizePath :: FilePath -> FilePath
src/Text/Pandoc/App/FormatHeuristics.hs+13−7
@@ -15,18 +15,24 @@ module Text.Pandoc.App.FormatHeuristics
1515 ) where
1616
1717import Data.Char (toLower)
18+import Data.Foldable (asum)
1819import Data.Text (Text)
1920import System.FilePath (takeExtension)
2021
21−-- Determine default format based on file extensions.
22+-- | Determines default format based on file extensions; uses the format
23+-- of the first extension that's associated with a format.
24+--
25+-- Examples:
26+--
27+-- > formatFromFilePaths ["text.unknown", "no-extension"]
28+-- Nothing
29+--
30+-- > formatFromFilePaths ["my.md", "other.rst"]
31+-- Just "markdown"
2232formatFromFilePaths :: [FilePath] -> Maybe Text
23−formatFromFilePaths [] = Nothing
24−formatFromFilePaths (x:xs) =
25− case formatFromFilePath x of
26− Just f -> Just f
27− Nothing -> formatFromFilePaths xs
33+formatFromFilePaths = asum . map formatFromFilePath
2834
29−-- Determine format based on file extension
35+-- | Determines format based on file extension.
3036formatFromFilePath :: FilePath -> Maybe Text
3137formatFromFilePath x =
3238 case takeExtension (map toLower x) of
src/Text/Pandoc/App/Opt.hs+145−57
@@ -22,28 +22,29 @@ module Text.Pandoc.App.Opt (
2222 , IpynbOutput (..)
2323 , DefaultsState (..)
2424 , defaultOpts
25− , addMeta
2625 , applyDefaults
2726 , fullDefaultsPath
2827 ) where
2928import Control.Monad.Except (MonadIO, liftIO, throwError, (>=>), foldM)
3029import Control.Monad.State.Strict (StateT, modify, gets)
31−import System.FilePath ( addExtension, (</>), takeExtension )
30+import System.FilePath ( addExtension, (</>), takeExtension, takeDirectory )
31+import System.Directory ( canonicalizePath )
3232import Data.Char (isLower, toLower)
3333import Data.Maybe (fromMaybe)
3434import GHC.Generics hiding (Meta)
35−import Text.Pandoc.Builder (setMeta)
3635import Text.Pandoc.Filter (Filter (..))
37−import Text.Pandoc.Logging (Verbosity (WARNING))
36+import Text.Pandoc.Logging (Verbosity (WARNING), LogMessage(..))
3837import Text.Pandoc.Options (TopLevelDivision (TopLevelDefault),
3938 TrackChanges (AcceptChanges),
4039 WrapOption (WrapAuto), HTMLMathMethod (PlainMath),
4140 ReferenceLocation (EndOfDocument),
4241 ObfuscationMethod (NoObfuscation),
4342 CiteMethod (Citeproc))
44−import Text.Pandoc.Class (readFileLazy, fileExists, setVerbosity, PandocMonad)
43+import Text.Pandoc.Class (readFileLazy, fileExists, setVerbosity, report,
44+ PandocMonad(lookupEnv), getUserDataDir)
4545import Text.Pandoc.Error (PandocError (PandocParseError, PandocSomeError))
46−import Text.Pandoc.Shared (camelCaseStrToHyphenated, defaultUserDataDirs, findM, ordNub)
46+import Text.Pandoc.Shared (camelCaseStrToHyphenated, defaultUserDataDir,
47+ findM, ordNub)
4748import qualified Text.Pandoc.Parsing as P
4849import Text.Pandoc.Readers.Metadata (yamlMap)
4950import Text.Pandoc.Class.PandocPure
@@ -52,7 +53,7 @@ import Data.Text (Text, unpack)
5253import Data.Default (def)
5354import qualified Data.Text as T
5455import qualified Data.Map as M
55−import Text.Pandoc.Definition (Meta(..), MetaValue(..), lookupMeta)
56+import Text.Pandoc.Definition (Meta(..), MetaValue(..))
5657import Data.Aeson (defaultOptions, Options(..))
5758import Data.Aeson.TH (deriveJSON)
5859import Control.Applicative ((<|>))
@@ -156,6 +157,9 @@ data Opt = Opt
156157 , optNoCheckCertificate :: Bool -- ^ Disable certificate validation
157158 , optEol :: LineEnding -- ^ Style of line-endings to use
158159 , optStripComments :: Bool -- ^ Skip HTML comments
160+ , optCSL :: Maybe FilePath -- ^ CSL stylesheet
161+ , optBibliography :: [FilePath] -- ^ Bibliography files
162+ , optCitationAbbreviations :: Maybe FilePath -- ^ Citation abbreviations
159163 } deriving (Generic, Show)
160164
161165instance FromYAML (Opt -> Opt) where
@@ -175,17 +179,128 @@ instance (PandocMonad m, MonadIO m)
175179 dataDir <- case M.lookup "data-dir" opts of
176180 Nothing -> return Nothing
177181 Just v -> Just . unpack <$> parseYAML v
178− f <- parseOptions $ M.toList m
182+ f <- parseOptions (M.toList m)
179183 case M.lookup "defaults" opts of
180184 Just v -> do
181185 g <- parseDefaults v dataDir
182− return $ g >=> f
183− Nothing -> return f
186+ return $ g >=> f >=> resolveVarsInOpt
187+ Nothing -> return $ f >=> resolveVarsInOpt
184188 where
185189 toText (Scalar _ (SStr s)) = s
186190 toText _ = ""
187191 parseYAML n = failAtNode n "Expected a mapping"
188192
193+resolveVarsInOpt :: forall m. (PandocMonad m, MonadIO m)
194+ => Opt -> StateT DefaultsState m Opt
195+resolveVarsInOpt
196+ opt@Opt
197+ { optTemplate = oTemplate
198+ , optMetadataFiles = oMetadataFiles
199+ , optOutputFile = oOutputFile
200+ , optInputFiles = oInputFiles
201+ , optSyntaxDefinitions = oSyntaxDefinitions
202+ , optAbbreviations = oAbbreviations
203+ , optReferenceDoc = oReferenceDoc
204+ , optEpubMetadata = oEpubMetadata
205+ , optEpubFonts = oEpubFonts
206+ , optEpubCoverImage = oEpubCoverImage
207+ , optLogFile = oLogFile
208+ , optFilters = oFilters
209+ , optDataDir = oDataDir
210+ , optExtractMedia = oExtractMedia
211+ , optCss = oCss
212+ , optIncludeBeforeBody = oIncludeBeforeBody
213+ , optIncludeAfterBody = oIncludeAfterBody
214+ , optIncludeInHeader = oIncludeInHeader
215+ , optResourcePath = oResourcePath
216+ , optCSL = oCSL
217+ , optBibliography = oBibliography
218+ , optCitationAbbreviations = oCitationAbbreviations
219+ }
220+ = do
221+ oTemplate' <- mapM resolveVars oTemplate
222+ oMetadataFiles' <- mapM resolveVars oMetadataFiles
223+ oOutputFile' <- mapM resolveVars oOutputFile
224+ oInputFiles' <- mapM (mapM resolveVars) oInputFiles
225+ oSyntaxDefinitions' <- mapM resolveVars oSyntaxDefinitions
226+ oAbbreviations' <- mapM resolveVars oAbbreviations
227+ oReferenceDoc' <- mapM resolveVars oReferenceDoc
228+ oEpubMetadata' <- mapM resolveVars oEpubMetadata
229+ oEpubFonts' <- mapM resolveVars oEpubFonts
230+ oEpubCoverImage' <- mapM resolveVars oEpubCoverImage
231+ oLogFile' <- mapM resolveVars oLogFile
232+ oFilters' <- mapM resolveVarsInFilter oFilters
233+ oDataDir' <- mapM resolveVars oDataDir
234+ oExtractMedia' <- mapM resolveVars oExtractMedia
235+ oCss' <- mapM resolveVars oCss
236+ oIncludeBeforeBody' <- mapM resolveVars oIncludeBeforeBody
237+ oIncludeAfterBody' <- mapM resolveVars oIncludeAfterBody
238+ oIncludeInHeader' <- mapM resolveVars oIncludeInHeader
239+ oResourcePath' <- mapM resolveVars oResourcePath
240+ oCSL' <- mapM resolveVars oCSL
241+ oBibliography' <- mapM resolveVars oBibliography
242+ oCitationAbbreviations' <- mapM resolveVars oCitationAbbreviations
243+ return opt{ optTemplate = oTemplate'
244+ , optMetadataFiles = oMetadataFiles'
245+ , optOutputFile = oOutputFile'
246+ , optInputFiles = oInputFiles'
247+ , optSyntaxDefinitions = oSyntaxDefinitions'
248+ , optAbbreviations = oAbbreviations'
249+ , optReferenceDoc = oReferenceDoc'
250+ , optEpubMetadata = oEpubMetadata'
251+ , optEpubFonts = oEpubFonts'
252+ , optEpubCoverImage = oEpubCoverImage'
253+ , optLogFile = oLogFile'
254+ , optFilters = oFilters'
255+ , optDataDir = oDataDir'
256+ , optExtractMedia = oExtractMedia'
257+ , optCss = oCss'
258+ , optIncludeBeforeBody = oIncludeBeforeBody'
259+ , optIncludeAfterBody = oIncludeAfterBody'
260+ , optIncludeInHeader = oIncludeInHeader'
261+ , optResourcePath = oResourcePath'
262+ , optCSL = oCSL'
263+ , optBibliography = oBibliography'
264+ , optCitationAbbreviations = oCitationAbbreviations'
265+ }
266+
267+ where
268+ resolveVars :: FilePath -> StateT DefaultsState m FilePath
269+ resolveVars [] = return []
270+ resolveVars ('$':'{':xs) =
271+ let (ys, zs) = break (=='}') xs
272+ in if null zs
273+ then return $ '$':'{':xs
274+ else do
275+ val <- lookupEnv' ys
276+ (val ++) <$> resolveVars (drop 1 zs)
277+ resolveVars (c:cs) = (c:) <$> resolveVars cs
278+ lookupEnv' :: String -> StateT DefaultsState m String
279+ lookupEnv' "." = do
280+ mbCurDefaults <- gets curDefaults
281+ maybe (return "")
282+ (fmap takeDirectory . liftIO . canonicalizePath)
283+ mbCurDefaults
284+ lookupEnv' "USERDATA" = do
285+ mbodatadir <- mapM resolveVars oDataDir
286+ mbdatadir <- getUserDataDir
287+ defdatadir <- liftIO defaultUserDataDir
288+ return $ fromMaybe defdatadir (mbodatadir <|> mbdatadir)
289+ lookupEnv' v = do
290+ mbval <- fmap T.unpack <$> lookupEnv (T.pack v)
291+ case mbval of
292+ Nothing -> do
293+ report $ EnvironmentVariableUndefined (T.pack v)
294+ return mempty
295+ Just x -> return x
296+ resolveVarsInFilter (JSONFilter fp) =
297+ JSONFilter <$> resolveVars fp
298+ resolveVarsInFilter (LuaFilter fp) =
299+ LuaFilter <$> resolveVars fp
300+ resolveVarsInFilter CiteprocFilter = return CiteprocFilter
301+
302+
303+
189304parseDefaults :: (PandocMonad m, MonadIO m)
190305 => Node Pos
191306 -> Maybe FilePath
@@ -428,26 +543,18 @@ doOpt (k',v) = do
428543 (parseYAML v >>= \x -> return (\o -> o{ optCss = optCss o <>
429544 [unpack x] }))
430545 "bibliography" ->
431− do let addItem x o = o{ optMetadata =
432− addMeta "bibliography" (T.unpack x)
433− (optMetadata o) }
434− (parseYAML v >>= \(xs :: [Text]) -> return $ \o ->
435− foldr addItem o xs)
436− <|>
437− (parseYAML v >>= \(x :: Text) -> return $ \o -> addItem x o)
546+ (parseYAML v >>= \x -> return (\o ->
547+ o{ optBibliography = optBibliography o <>
548+ map unpack x }))
549+ <|>
550+ (parseYAML v >>= \x -> return (\o ->
551+ o{ optBibliography = optBibliography o <>
552+ [unpack x] }))
438553 "csl" ->
439− do let addItem x o = o{ optMetadata =
440− addMeta "csl" (T.unpack x)
441− (optMetadata o) }
442− (parseYAML v >>= \(xs :: [Text]) -> return $ \o ->
443− foldr addItem o xs)
444− <|>
445− (parseYAML v >>= \(x :: Text) -> return $ \o -> addItem x o)
554+ parseYAML v >>= \x -> return (\o -> o{ optCSL = unpack <$> x })
446555 "citation-abbreviations" ->
447− parseYAML v >>= \x ->
448− return (\o -> o{ optMetadata =
449− addMeta "citation-abbreviations" (T.unpack x)
450− (optMetadata o) })
556+ parseYAML v >>= \x -> return (\o -> o{ optCitationAbbreviations =
557+ unpack <$> x })
451558 "ipynb-output" ->
452559 parseYAML v >>= \x -> return (\o -> o{ optIpynbOutput = x })
453560 "include-before-body" ->
@@ -476,7 +583,8 @@ doOpt (k',v) = do
476583 optIncludeInHeader o <> [unpack x] }))
477584 "resource-path" ->
478585 parseYAML v >>= \x ->
479− return (\o -> o{ optResourcePath = map unpack x })
586+ return (\o -> o{ optResourcePath = map unpack x <>
587+ optResourcePath o })
480588 "request-headers" ->
481589 parseYAML v >>= \x ->
482590 return (\o -> o{ optRequestHeaders = x })
@@ -562,6 +670,9 @@ defaultOpts = Opt
562670 , optNoCheckCertificate = False
563671 , optEol = Native
564672 , optStripComments = False
673+ , optCSL = Nothing
674+ , optBibliography = []
675+ , optCitationAbbreviations = Nothing
565676 }
566677
567678parseStringKey :: Node Pos -> Parser Text
@@ -575,31 +686,11 @@ yamlToMeta (Mapping _ _ m) =
575686 either (fail . show) return $ runEverything (yamlMap pMetaString m)
576687 where
577688 pMetaString = pure . MetaString <$> P.manyChar P.anyChar
578− runEverything p = runPure (P.readWithM p def "")
689+ runEverything p =
690+ runPure (P.readWithM p (def :: P.ParserState) ("" :: Text))
579691 >>= fmap (Meta . flip P.runF def)
580692yamlToMeta _ = return mempty
581693
582−addMeta :: String -> String -> Meta -> Meta
583−addMeta k v meta =
584− case lookupMeta k' meta of
585− Nothing -> setMeta k' v' meta
586− Just (MetaList xs) ->
587− setMeta k' (MetaList (xs ++ [v'])) meta
588− Just x -> setMeta k' (MetaList [x, v']) meta
589− where
590− v' = readMetaValue v
591− k' = T.pack k
592−
593−readMetaValue :: String -> MetaValue
594−readMetaValue s
595− | s == "true" = MetaBool True
596− | s == "True" = MetaBool True
597− | s == "TRUE" = MetaBool True
598− | s == "false" = MetaBool False
599− | s == "False" = MetaBool False
600− | s == "FALSE" = MetaBool False
601− | otherwise = MetaString $ T.pack s
602−
603694-- | Apply defaults from --defaults file.
604695applyDefaults :: (PandocMonad m, MonadIO m)
605696 => Opt
@@ -625,12 +716,9 @@ fullDefaultsPath dataDir file = do
625716 let fp = if null (takeExtension file)
626717 then addExtension file "yaml"
627718 else file
628− dataDirs <- liftIO defaultUserDataDirs
629− let fps = fp : case dataDir of
630− Nothing -> map (</> ("defaults" </> fp))
631− dataDirs
632− Just dd -> [dd </> "defaults" </> fp]
633− fromMaybe fp <$> findM fileExists fps
719+ defaultDataDir <- liftIO defaultUserDataDir
720+ let defaultFp = fromMaybe defaultDataDir dataDir </> "defaults" </> fp
721+ fromMaybe fp <$> findM fileExists [fp, defaultFp]
634722
635723-- | In a list of lists, append another list in front of every list which
636724-- starts with specific element.
src/Text/Pandoc/Asciify.hs+13−390
@@ -10,396 +10,19 @@
1010Function to convert accented latin letters to their unaccented
1111ascii equivalents (used in constructing HTML identifiers).
1212-}
13−module Text.Pandoc.Asciify (toAsciiChar)
13+module Text.Pandoc.Asciify (toAsciiChar, toAsciiText)
1414where
15−import Data.Char (isAscii)
16−import qualified Data.Map as M
15+import Data.Char (isAscii, isMark)
16+import qualified Data.Text.Normalize as TN
17+import Data.Text (Text)
18+import qualified Data.Text as T
1719
18−toAsciiChar :: Char -> Maybe Char
19−toAsciiChar c | isAscii c = Just c
20− | otherwise = M.lookup c asciiMap
20+toAsciiText :: Text -> Text
21+toAsciiText = T.filter isAscii . TN.normalize (TN.NFD)
2122
22−asciiMap :: M.Map Char Char
23−asciiMap = M.fromList
24− [('\192','A')
25− ,('\193','A')
26− ,('\194','A')
27− ,('\195','A')
28− ,('\196','A')
29− ,('\197','A')
30− ,('\199','C')
31− ,('\200','E')
32− ,('\201','E')
33− ,('\202','E')
34− ,('\203','E')
35− ,('\204','I')
36− ,('\205','I')
37− ,('\206','I')
38− ,('\207','I')
39− ,('\209','N')
40− ,('\210','O')
41− ,('\211','O')
42− ,('\212','O')
43− ,('\213','O')
44− ,('\214','O')
45− ,('\217','U')
46− ,('\218','U')
47− ,('\219','U')
48− ,('\220','U')
49− ,('\221','Y')
50− ,('\224','a')
51− ,('\225','a')
52− ,('\226','a')
53− ,('\227','a')
54− ,('\228','a')
55− ,('\229','a')
56− ,('\231','c')
57− ,('\232','e')
58− ,('\233','e')
59− ,('\234','e')
60− ,('\235','e')
61− ,('\236','i')
62− ,('\237','i')
63− ,('\238','i')
64− ,('\239','i')
65− ,('\241','n')
66− ,('\242','o')
67− ,('\243','o')
68− ,('\244','o')
69− ,('\245','o')
70− ,('\246','o')
71− ,('\249','u')
72− ,('\250','u')
73− ,('\251','u')
74− ,('\252','u')
75− ,('\253','y')
76− ,('\255','y')
77− ,('\256','A')
78− ,('\257','a')
79− ,('\258','A')
80− ,('\259','a')
81− ,('\260','A')
82− ,('\261','a')
83− ,('\262','C')
84− ,('\263','c')
85− ,('\264','C')
86− ,('\265','c')
87− ,('\266','C')
88− ,('\267','c')
89− ,('\268','C')
90− ,('\269','c')
91− ,('\270','D')
92− ,('\271','d')
93− ,('\274','E')
94− ,('\275','e')
95− ,('\276','E')
96− ,('\277','e')
97− ,('\278','E')
98− ,('\279','e')
99− ,('\280','E')
100− ,('\281','e')
101− ,('\282','E')
102− ,('\283','e')
103− ,('\284','G')
104− ,('\285','g')
105− ,('\286','G')
106− ,('\287','g')
107− ,('\288','G')
108− ,('\289','g')
109− ,('\290','G')
110− ,('\291','g')
111− ,('\292','H')
112− ,('\293','h')
113− ,('\296','I')
114− ,('\297','i')
115− ,('\298','I')
116− ,('\299','i')
117− ,('\300','I')
118− ,('\301','i')
119− ,('\302','I')
120− ,('\303','i')
121− ,('\304','I')
122− ,('\305','i')
123− ,('\308','J')
124− ,('\309','j')
125− ,('\310','K')
126− ,('\311','k')
127− ,('\313','L')
128− ,('\314','l')
129− ,('\315','L')
130− ,('\316','l')
131− ,('\317','L')
132− ,('\318','l')
133− ,('\323','N')
134− ,('\324','n')
135− ,('\325','N')
136− ,('\326','n')
137− ,('\327','N')
138− ,('\328','n')
139− ,('\332','O')
140− ,('\333','o')
141− ,('\334','O')
142− ,('\335','o')
143− ,('\336','O')
144− ,('\337','o')
145− ,('\340','R')
146− ,('\341','r')
147− ,('\342','R')
148− ,('\343','r')
149− ,('\344','R')
150− ,('\345','r')
151− ,('\346','S')
152− ,('\347','s')
153− ,('\348','S')
154− ,('\349','s')
155− ,('\350','S')
156− ,('\351','s')
157− ,('\352','S')
158− ,('\353','s')
159− ,('\354','T')
160− ,('\355','t')
161− ,('\356','T')
162− ,('\357','t')
163− ,('\360','U')
164− ,('\361','u')
165− ,('\362','U')
166− ,('\363','u')
167− ,('\364','U')
168− ,('\365','u')
169− ,('\366','U')
170− ,('\367','u')
171− ,('\368','U')
172− ,('\369','u')
173− ,('\370','U')
174− ,('\371','u')
175− ,('\372','W')
176− ,('\373','w')
177− ,('\374','Y')
178− ,('\375','y')
179− ,('\376','Y')
180− ,('\377','Z')
181− ,('\378','z')
182− ,('\379','Z')
183− ,('\380','z')
184− ,('\381','Z')
185− ,('\382','z')
186− ,('\416','O')
187− ,('\417','o')
188− ,('\431','U')
189− ,('\432','u')
190− ,('\461','A')
191− ,('\462','a')
192− ,('\463','I')
193− ,('\464','i')
194− ,('\465','O')
195− ,('\466','o')
196− ,('\467','U')
197− ,('\468','u')
198− ,('\486','G')
199− ,('\487','g')
200− ,('\488','K')
201− ,('\489','k')
202− ,('\490','O')
203− ,('\491','o')
204− ,('\496','j')
205− ,('\500','G')
206− ,('\501','g')
207− ,('\504','N')
208− ,('\505','n')
209− ,('\512','A')
210− ,('\513','a')
211− ,('\514','A')
212− ,('\515','a')
213− ,('\516','E')
214− ,('\517','e')
215− ,('\518','E')
216− ,('\519','e')
217− ,('\520','I')
218− ,('\521','i')
219− ,('\522','I')
220− ,('\523','i')
221− ,('\524','O')
222− ,('\525','o')
223− ,('\526','O')
224− ,('\527','o')
225− ,('\528','R')
226− ,('\529','r')
227− ,('\530','R')
228− ,('\531','r')
229− ,('\532','U')
230− ,('\533','u')
231− ,('\534','U')
232− ,('\535','u')
233− ,('\536','S')
234− ,('\537','s')
235− ,('\538','T')
236− ,('\539','t')
237− ,('\542','H')
238− ,('\543','h')
239− ,('\550','A')
240− ,('\551','a')
241− ,('\552','E')
242− ,('\553','e')
243− ,('\558','O')
244− ,('\559','o')
245− ,('\562','Y')
246− ,('\563','y')
247− ,('\894',';')
248− ,('\7680','A')
249− ,('\7681','a')
250− ,('\7682','B')
251− ,('\7683','b')
252− ,('\7684','B')
253− ,('\7685','b')
254− ,('\7686','B')
255− ,('\7687','b')
256− ,('\7690','D')
257− ,('\7691','d')
258− ,('\7692','D')
259− ,('\7693','d')
260− ,('\7694','D')
261− ,('\7695','d')
262− ,('\7696','D')
263− ,('\7697','d')
264− ,('\7698','D')
265− ,('\7699','d')
266− ,('\7704','E')
267− ,('\7705','e')
268− ,('\7706','E')
269− ,('\7707','e')
270− ,('\7710','F')
271− ,('\7711','f')
272− ,('\7712','G')
273− ,('\7713','g')
274− ,('\7714','H')
275− ,('\7715','h')
276− ,('\7716','H')
277− ,('\7717','h')
278− ,('\7718','H')
279− ,('\7719','h')
280− ,('\7720','H')
281− ,('\7721','h')
282− ,('\7722','H')
283− ,('\7723','h')
284− ,('\7724','I')
285− ,('\7725','i')
286− ,('\7728','K')
287− ,('\7729','k')
288− ,('\7730','K')
289− ,('\7731','k')
290− ,('\7732','K')
291− ,('\7733','k')
292− ,('\7734','L')
293− ,('\7735','l')
294− ,('\7738','L')
295− ,('\7739','l')
296− ,('\7740','L')
297− ,('\7741','l')
298− ,('\7742','M')
299− ,('\7743','m')
300− ,('\7744','M')
301− ,('\7745','m')
302− ,('\7746','M')
303− ,('\7747','m')
304− ,('\7748','N')
305− ,('\7749','n')
306− ,('\7750','N')
307− ,('\7751','n')
308− ,('\7752','N')
309− ,('\7753','n')
310− ,('\7754','N')
311− ,('\7755','n')
312− ,('\7764','P')
313− ,('\7765','p')
314− ,('\7766','P')
315− ,('\7767','p')
316− ,('\7768','R')
317− ,('\7769','r')
318− ,('\7770','R')
319− ,('\7771','r')
320− ,('\7774','R')
321− ,('\7775','r')
322− ,('\7776','S')
323− ,('\7777','s')
324− ,('\7778','S')
325− ,('\7779','s')
326− ,('\7786','T')
327− ,('\7787','t')
328− ,('\7788','T')
329− ,('\7789','t')
330− ,('\7790','T')
331− ,('\7791','t')
332− ,('\7792','T')
333− ,('\7793','t')
334− ,('\7794','U')
335− ,('\7795','u')
336− ,('\7796','U')
337− ,('\7797','u')
338− ,('\7798','U')
339− ,('\7799','u')
340− ,('\7804','V')
341− ,('\7805','v')
342− ,('\7806','V')
343− ,('\7807','v')
344− ,('\7808','W')
345− ,('\7809','w')
346− ,('\7810','W')
347− ,('\7811','w')
348− ,('\7812','W')
349− ,('\7813','w')
350− ,('\7814','W')
351− ,('\7815','w')
352− ,('\7816','W')
353− ,('\7817','w')
354− ,('\7818','X')
355− ,('\7819','x')
356− ,('\7820','X')
357− ,('\7821','x')
358− ,('\7822','Y')
359− ,('\7823','y')
360− ,('\7824','Z')
361− ,('\7825','z')
362− ,('\7826','Z')
363− ,('\7827','z')
364− ,('\7828','Z')
365− ,('\7829','z')
366− ,('\7830','h')
367− ,('\7831','t')
368− ,('\7832','w')
369− ,('\7833','y')
370− ,('\7840','A')
371− ,('\7841','a')
372− ,('\7842','A')
373− ,('\7843','a')
374− ,('\7864','E')
375− ,('\7865','e')
376− ,('\7866','E')
377− ,('\7867','e')
378− ,('\7868','E')
379− ,('\7869','e')
380− ,('\7880','I')
381− ,('\7881','i')
382− ,('\7882','I')
383− ,('\7883','i')
384− ,('\7884','O')
385− ,('\7885','o')
386− ,('\7886','O')
387− ,('\7887','o')
388− ,('\7908','U')
389− ,('\7909','u')
390− ,('\7910','U')
391− ,('\7911','u')
392− ,('\7922','Y')
393− ,('\7923','y')
394− ,('\7924','Y')
395− ,('\7925','y')
396− ,('\7926','Y')
397− ,('\7927','y')
398− ,('\7928','Y')
399− ,('\7929','y')
400− ,('\8175','`')
401− ,('\8490','K')
402− ,('\8800','=')
403− ,('\8814','<')
404− ,('\8815','>')
405− ]
23+toAsciiChar :: Char -> Maybe Char
24+toAsciiChar c = case T.unpack (TN.normalize TN.NFD (T.singleton c)) of
25+ (x:xs) | isAscii x
26+ , all isMark xs
27+ -> Just x
28+ _ -> Nothing
src/Text/Pandoc/BCP47.hsdeleted−112
@@ -1,112 +0,0 @@
1−{-# LANGUAGE OverloadedStrings #-}
2−{- |
3− Module : Text.Pandoc.BCP47
4− Copyright : Copyright (C) 2017-2021 John MacFarlane
5− License : GNU GPL, version 2 or above
6−
7− Maintainer : John MacFarlane <jgm@berkeley.edu>
8− Stability : alpha
9− Portability : portable
10−
11−Functions for parsing and rendering BCP47 language identifiers.
12−-}
13−module Text.Pandoc.BCP47 (
14− getLang
15− , parseBCP47
16− , Lang(..)
17− , renderLang
18− )
19−where
20−import Control.Monad (guard)
21−import Data.Char (isAlphaNum, isAscii, isLetter, isLower, isUpper)
22−import Text.Pandoc.Definition
23−import Text.Pandoc.Options
24−import Text.DocTemplates (FromContext(..))
25−import qualified Data.Text as T
26−import qualified Text.Parsec as P
27−
28−-- | Represents BCP 47 language/country code.
29−data Lang = Lang{ langLanguage :: T.Text
30− , langScript :: T.Text
31− , langRegion :: T.Text
32− , langVariants :: [T.Text] }
33− deriving (Eq, Ord, Show)
34−
35−-- | Render a Lang as BCP 47.
36−renderLang :: Lang -> T.Text
37−renderLang lang = T.intercalate "-" (langLanguage lang : filter (not . T.null)
38− ([langScript lang, langRegion lang] ++ langVariants lang))
39−
40−-- | Get the contents of the `lang` metadata field or variable.
41−getLang :: WriterOptions -> Meta -> Maybe T.Text
42−getLang opts meta =
43− case lookupContext "lang" (writerVariables opts) of
44− Just s -> Just s
45− _ ->
46− case lookupMeta "lang" meta of
47− Just (MetaBlocks [Para [Str s]]) -> Just s
48− Just (MetaBlocks [Plain [Str s]]) -> Just s
49− Just (MetaInlines [Str s]) -> Just s
50− Just (MetaString s) -> Just s
51− _ -> Nothing
52−
53−-- | Parse a BCP 47 string as a Lang. Currently we parse
54−-- extensions and private-use fields as "variants," even
55−-- though officially they aren't.
56−parseBCP47 :: T.Text -> Either T.Text Lang
57−parseBCP47 lang =
58− case P.parse bcp47 "lang" lang of
59− Right r -> Right r
60− Left e -> Left $ T.pack $ show e
61− where bcp47 = do
62− language <- pLanguage
63− script <- P.option "" pScript
64− region <- P.option "" pRegion
65− variants <- P.many (pVariant P.<|> pExtension P.<|> pPrivateUse)
66− P.eof
67− return Lang{ langLanguage = language
68− , langScript = script
69− , langRegion = region
70− , langVariants = variants }
71− asciiLetter = P.satisfy (\c -> isAscii c && isLetter c)
72− pLanguage = do
73− cs <- P.many1 asciiLetter
74− let lcs = length cs
75− guard $ lcs == 2 || lcs == 3
76− return $ T.toLower $ T.pack cs
77− pScript = P.try $ do
78− P.char '-'
79− x <- P.satisfy (\c -> isAscii c && isLetter c && isUpper c)
80− xs <- P.count 3
81− (P.satisfy (\c -> isAscii c && isLetter c && isLower c))
82− return $ T.toLower $ T.pack (x:xs)
83− pRegion = P.try $ do
84− P.char '-'
85− cs <- P.many1 asciiLetter
86− let lcs = length cs
87− guard $ lcs == 2 || lcs == 3
88− return $ T.toUpper $ T.pack cs
89− pVariant = P.try $ do
90− P.char '-'
91− ds <- P.option "" (P.count 1 P.digit)
92− cs <- P.many1 asciiLetter
93− let var = ds ++ cs
94− lv = length var
95− guard $ if null ds
96− then lv >= 5 && lv <= 8
97− else lv == 4
98− return $ T.toLower $ T.pack var
99− pExtension = P.try $ do
100− P.char '-'
101− cs <- P.many1 $ P.satisfy (\c -> isAscii c && isAlphaNum c)
102− let lcs = length cs
103− guard $ lcs >= 2 && lcs <= 8
104− return $ T.toLower $ T.pack cs
105− pPrivateUse = P.try $ do
106− P.char '-'
107− P.char 'x'
108− P.char '-'
109− cs <- P.many1 $ P.satisfy (\c -> isAscii c && isAlphaNum c)
110− guard $ not (null cs) && length cs <= 8
111− let var = "x-" ++ cs
112− return $ T.toLower $ T.pack var
src/Text/Pandoc/Citeproc.hs+75−56
@@ -18,7 +18,6 @@ import Text.Pandoc.Citeproc.CslJson (cslJsonToReferences)
1818import Text.Pandoc.Citeproc.BibTeX (readBibtexString, Variant(..))
1919import Text.Pandoc.Citeproc.MetaValue (metaValueToReference, metaValueToText)
2020import Text.Pandoc.Readers.Markdown (yamlToRefs)
21−import qualified Text.Pandoc.BCP47 as BCP47
2221import Text.Pandoc.Builder (Inlines, Many(..), deleteMeta, setMeta)
2322import qualified Text.Pandoc.Builder as B
2423import Text.Pandoc.Definition as Pandoc
@@ -28,7 +27,7 @@ import Text.Pandoc.Error (PandocError(..))
2827import Text.Pandoc.Extensions (pandocExtensions)
2928import Text.Pandoc.Logging (LogMessage(..))
3029import Text.Pandoc.Options (ReaderOptions(..))
31−import Text.Pandoc.Shared (stringify, ordNub, blocksToInlines, tshow)
30+import Text.Pandoc.Shared (stringify, ordNub, tshow)
3231import qualified Text.Pandoc.UTF8 as UTF8
3332import Text.Pandoc.Walk (query, walk, walkM)
3433import Control.Applicative ((<|>))
@@ -49,7 +48,6 @@ import Data.Text (Text)
4948import qualified Data.Text as T
5049import System.FilePath (takeExtension)
5150import Safe (lastMay, initSafe)
52−-- import Debug.Trace as Trace (trace, traceShowId)
5351
5452
5553processCitations :: PandocMonad m => Pandoc -> m Pandoc
@@ -76,8 +74,7 @@ processCitations (Pandoc meta bs) = do
7674
7775 let linkCites = maybe False truish $ lookupMeta "link-citations" meta
7876 let opts = defaultCiteprocOptions{ linkCitations = linkCites }
79− let result = Citeproc.citeproc opts style (localeLanguage locale)
80− refs citations
77+ let result = Citeproc.citeproc opts style mblang refs citations
8178 mapM_ (report . CiteprocWarning) (resultWarnings result)
8279 let sopts = styleOptions style
8380 let classes = "references" : -- TODO remove this or keep for compatibility?
@@ -91,24 +88,21 @@ processCitations (Pandoc meta bs) = do
9188 _ -> id) $ []
9289 let bibs = mconcat $ map (\(ident, out) ->
9390 B.divWith ("ref-" <> ident,["csl-entry"],[]) . B.para .
94− walk (convertQuotes locale) . insertSpace $ out)
91+ walk (convertQuotes locale) .
92+ insertSpace $ out)
9593 (resultBibliography result)
96− let moveNotes = maybe True truish $
97− lookupMeta "notes-after-punctuation" meta
98− let cits = map (walk fixLinks . walk (convertQuotes locale)) $
94+ let moveNotes = styleIsNoteStyle sopts &&
95+ maybe True truish (lookupMeta "notes-after-punctuation" meta)
96+ let cits = map (walk (convertQuotes locale)) $
9997 resultCitations result
10098
101− let fixQuotes = case localePunctuationInQuote locale of
102− Just True ->
103− B.toList . movePunctuationInsideQuotes . B.fromList
104− _ -> id
105−
10699 let metanocites = lookupMeta "nocite" meta
107100 let Pandoc meta'' bs' =
108101 maybe id (setMeta "nocite") metanocites .
109− walk (map capitalizeNoteCitation .
110− fixQuotes . mvPunct moveNotes locale) .
111− walk deNote .
102+ walk (mvPunct moveNotes locale) .
103+ (if styleIsNoteStyle sopts
104+ then walk addNote . walk deNote
105+ else id) .
112106 evalState (walkM insertResolvedCitations $ Pandoc meta' bs)
113107 $ cits
114108 return $ Pandoc meta''
@@ -197,7 +191,9 @@ getReferences mblocale (Pandoc meta bs) = do
197191 then const True
198192 else (`Set.member` citeIds)
199193 let inlineRefs = case lookupMeta "references" meta of
200− Just (MetaList rs) -> mapMaybe metaValueToReference rs
194+ Just (MetaList rs) ->
195+ filter (idpred . unItemId . referenceId)
196+ $ mapMaybe metaValueToReference rs
201197 _ -> []
202198 externalRefs <- case lookupMeta "bibliography" meta of
203199 Just (MetaList xs) ->
@@ -294,7 +290,7 @@ insertResolvedCitations (Cite cs ils) = do
294290 [] -> return (Cite cs ils)
295291 (x:xs) -> do
296292 put xs
297− return $ Cite cs (B.toList x)
293+ return $ Cite cs (walk fixLinks $ B.toList x)
298294insertResolvedCitations x = return x
299295
300296getCitations :: Locale
@@ -376,7 +372,6 @@ formatFromExtension fp = case dropWhile (== '.') $ takeExtension fp of
376372
377373
378374isNote :: Inline -> Bool
379−isNote (Note _) = True
380375isNote (Cite _ [Note _]) = True
381376 -- the following allows citation styles that are "in-text" but use superscript
382377 -- references to be treated as if they are "notes" for the purposes of moving
@@ -389,6 +384,12 @@ isSpacy Space = True
389384isSpacy SoftBreak = True
390385isSpacy _ = False
391386
387+movePunctInsideQuotes :: Locale -> [Inline] -> [Inline]
388+movePunctInsideQuotes locale
389+ | localePunctuationInQuote locale == Just True
390+ = B.toList . movePunctuationInsideQuotes . B.fromList
391+ | otherwise
392+ = id
392393
393394mvPunct :: Bool -> Locale -> [Inline] -> [Inline]
394395mvPunct moveNotes locale (x : xs)
@@ -401,7 +402,8 @@ mvPunct moveNotes locale (q : s : x : ys)
401402 in if moveNotes
402403 then if T.null spunct
403404 then q : x : mvPunct moveNotes locale ys
404− else q : Str spunct : x : mvPunct moveNotes locale
405+ else movePunctInsideQuotes locale
406+ [q , Str spunct , x] ++ mvPunct moveNotes locale
405407 (B.toList
406408 (dropTextWhile isPunctuation (B.fromList ys)))
407409 else q : x : mvPunct moveNotes locale ys
@@ -413,9 +415,10 @@ mvPunct moveNotes locale (Cite cs ils : ys)
413415 , moveNotes
414416 = let s = stringify ys
415417 spunct = T.takeWhile isPunctuation s
416− in Cite cs (init ils
417− ++ [Str spunct | not (endWithPunct False (init ils))]
418− ++ [last ils]) :
418+ in Cite cs (movePunctInsideQuotes locale $
419+ init ils
420+ ++ [Str spunct | not (endWithPunct False (init ils))]
421+ ++ [last ils]) :
419422 mvPunct moveNotes locale
420423 (B.toList (dropTextWhile isPunctuation (B.fromList ys)))
421424mvPunct moveNotes locale (s : x : ys) | isSpacy s, isNote x =
@@ -431,7 +434,7 @@ mvPunct _ _ [] = []
431434-- move https://doi.org etc. prefix inside link text (#6723):
432435fixLinks :: [Inline] -> [Inline]
433436fixLinks (Str t : Link attr [Str u1] (u2,tit) : xs)
434− | t <> u1 == u2
437+ | u2 == t <> u1
435438 = Link attr [Str (t <> u1)] (u2,tit) : fixLinks xs
436439fixLinks (x:xs) = x : fixLinks xs
437440fixLinks [] = []
@@ -501,7 +504,8 @@ insertRefs refkvs refclasses meta refs bs =
501504 put True
502505 -- refHeader isn't used if you have an explicit references div
503506 let cs' = ordNub $ cs ++ refclasses
504− return $ Div ("refs",cs',kvs) (xs ++ refs)
507+ let kvs' = ordNub $ kvs ++ refkvs
508+ return $ Div ("refs",cs',kvs') (xs ++ refs)
505509 go x = return x
506510
507511refTitle :: Meta -> Maybe [Inline]
@@ -560,42 +564,62 @@ extractText (FancyVal x) = toText x
560564extractText (NumVal n) = T.pack (show n)
561565extractText _ = mempty
562566
563−capitalizeNoteCitation :: Inline -> Inline
564−capitalizeNoteCitation (Cite cs [Note [Para ils]]) =
565− Cite cs
566− [Note [Para $ B.toList $ addTextCase Nothing CapitalizeFirst
567− $ B.fromList ils]]
568−capitalizeNoteCitation x = x
569−
570−deNote :: [Inline] -> [Inline]
571−deNote [] = []
572−deNote (Note bs:rest) =
573− Note (walk go bs) : deNote rest
567+-- Here we take the Spans with class csl-note that are left
568+-- after deNote has removed nested ones, and convert them
569+-- into real notes.
570+addNote :: Inline -> Inline
571+addNote (Span ("",["csl-note"],[]) ils) =
572+ Note [Para $
573+ B.toList . addTextCase Nothing CapitalizeFirst . B.fromList $ ils]
574+addNote x = x
575+
576+-- Here we handle citation notes that occur inside footnotes
577+-- or other citation notes, in a note style. We don't want
578+-- notes inside notes, so we convert these to parenthesized
579+-- or comma-separated citations.
580+deNote :: Inline -> Inline
581+deNote (Note bs) =
582+ case bs of
583+ [Para (cit@(Cite (c:_) _) : ils)]
584+ | citationMode c /= AuthorInText ->
585+ -- if citation is first in note, no need to parenthesize.
586+ Note [Para (walk removeNotes $ cit : walk addParens ils)]
587+ _ -> Note (walk removeNotes . walk addParens $ bs)
588+
574589 where
575− go [] = []
576− go (Cite (c:cs) ils : zs)
590+ addParens [] = []
591+ addParens (Cite (c:cs) ils : zs)
577592 | citationMode c == AuthorInText
578− = Cite (c:cs) (concatMap (noteAfterComma (needsPeriod zs)) ils) : go zs
593+ = Cite (c:cs) (concatMap (noteAfterComma (needsPeriod zs)) ils) :
594+ addParens zs
579595 | otherwise
580− = Cite (c:cs) (concatMap noteInParens ils) : go zs
581− go (x:xs) = x : go xs
596+ = Cite (c:cs) (concatMap noteInParens ils) : addParens zs
597+ addParens (x:xs) = x : addParens xs
598+
599+ removeNotes (Span ("",["csl-note"],[]) ils) = Span ("",[],[]) ils
600+ removeNotes x = x
601+
582602 needsPeriod [] = True
583603 needsPeriod (Str t:_) = case T.uncons t of
584604 Nothing -> False
585605 Just (c,_) -> isUpper c
586606 needsPeriod (Space:zs) = needsPeriod zs
587607 needsPeriod _ = False
588− noteInParens (Note bs')
608+
609+ noteInParens (Span ("",["csl-note"],[]) ils)
589610 = Space : Str "(" :
590− removeFinalPeriod (blocksToInlines bs') ++ [Str ")"]
611+ removeFinalPeriod ils ++ [Str ")"]
591612 noteInParens x = [x]
592− noteAfterComma needsPer (Note bs')
613+
614+ noteAfterComma needsPer (Span ("",["csl-note"],[]) ils)
615+ | not (null ils)
593616 = Str "," : Space :
594− (if needsPer
595− then id
596− else removeFinalPeriod) (blocksToInlines bs')
617+ if needsPer
618+ then ils
619+ else removeFinalPeriod ils
597620 noteAfterComma _ x = [x]
598−deNote (x:xs) = x : deNote xs
621+
622+deNote x = x
599623
600624-- Note: we can't use dropTextWhileEnd indiscriminately,
601625-- because this would remove the final period on abbreviations like Ibid.
@@ -630,13 +654,8 @@ removeFinalPeriod ils =
630654
631655bcp47LangToIETF :: PandocMonad m => Text -> m (Maybe Lang)
632656bcp47LangToIETF bcplang =
633− case BCP47.parseBCP47 bcplang of
657+ case parseLang bcplang of
634658 Left _ -> do
635659 report $ InvalidLang bcplang
636660 return Nothing
637− Right lang ->
638− return $ Just
639− $ Lang (BCP47.langLanguage lang)
640− (if T.null (BCP47.langRegion lang)
641− then Nothing
642− else Just (BCP47.langRegion lang))
661+ Right lang -> return $ Just lang
src/Text/Pandoc/Citeproc/BibTeX.hs+25−15
@@ -59,10 +59,11 @@ data Variant = Bibtex | Biblatex
5959 deriving (Show, Eq, Ord)
6060
6161-- | Parse BibTeX or BibLaTeX into a list of 'Reference's.
62−readBibtexString :: Variant -- ^ bibtex or biblatex
62+readBibtexString :: ToSources a
63+ => Variant -- ^ bibtex or biblatex
6364 -> Locale -- ^ Locale
6465 -> (Text -> Bool) -- ^ Filter on citation ids
65− -> Text -- ^ bibtex/biblatex text
66+ -> a -- ^ bibtex/biblatex text
6667 -> Either ParseError [Reference Inlines]
6768readBibtexString variant locale idpred contents = do
6869 case runParser (((resolveCrossRefs variant <$> bibEntries) <* eof) >>=
@@ -70,9 +71,11 @@ readBibtexString variant locale idpred contents = do
7071 filter (\item -> idpred (identifier item) &&
7172 entryType item /= "xdata"))
7273 (fromMaybe defaultLang $ localeLanguage locale, Map.empty)
73− "" contents of
74+ (initialSourceName sources) sources of
7475 Left err -> Left err
7576 Right xs -> return xs
77+ where
78+ sources = toSources contents
7679
7780-- | Write BibTeX or BibLaTeX given given a 'Reference'.
7881writeBibtexString :: WriterOptions -- ^ options (for writing LaTex)
@@ -155,6 +158,7 @@ writeBibtexString opts variant mblang ref =
155158 , "langid"
156159 , "abstract"
157160 , "keywords"
161+ , "annote"
158162 ]
159163 Bibtex ->
160164 [ "author"
@@ -174,6 +178,7 @@ writeBibtexString opts variant mblang ref =
174178 , "address"
175179 , "type"
176180 , "note"
181+ , "annote"
177182 ]
178183
179184 valToInlines (TextVal t) = B.text t
@@ -205,10 +210,13 @@ writeBibtexString opts variant mblang ref =
205210 [ (", " <>) <$> nameGiven name,
206211 nameDroppingParticle name ]
207212
208− mblang' = (parseLang <$> getVariableAsText "language") <|> mblang
213+ mblang' = case getVariableAsText "language" of
214+ Just l -> either (const Nothing) Just $ parseLang l
215+ Nothing -> mblang
209216
210217 titlecase = case mblang' of
211− Just (Lang "en" _) -> titlecase'
218+ Just lang | langLanguage lang == "en"
219+ -> titlecase'
212220 Nothing -> titlecase'
213221 _ ->
214222 case variant of
@@ -331,12 +339,12 @@ writeBibtexString opts variant mblang ref =
331339 renderFields = mconcat . intersperse ("," <> cr) . mapMaybe renderField
332340
333341defaultLang :: Lang
334−defaultLang = Lang "en" (Just "US")
342+defaultLang = Lang "en" Nothing (Just "US") [] [] []
335343
336344-- a map of bibtex "string" macros
337345type StringMap = Map.Map Text Text
338346
339−type BibParser = Parser Text (Lang, StringMap)
347+type BibParser = Parser Sources (Lang, StringMap)
340348
341349data Item = Item{ identifier :: Text
342350 , sourcePos :: SourcePos
@@ -351,9 +359,7 @@ itemToReference locale variant item = do
351359 bib item $ do
352360 let lang = fromMaybe defaultLang $ localeLanguage locale
353361 modify $ \st -> st{ localeLang = lang,
354− untitlecase = case lang of
355− (Lang "en" _) -> True
356− _ -> False }
362+ untitlecase = langLanguage lang == "en" }
357363
358364 id' <- asks identifier
359365 otherIds <- (Just <$> getRawField "ids")
@@ -711,7 +717,7 @@ itemToReference locale variant item = do
711717
712718
713719bib :: Item -> Bib a -> BibParser a
714−bib entry m = fst <$> evalRWST m entry (BibState True (Lang "en" (Just "US")))
720+bib entry m = fst <$> evalRWST m entry (BibState True defaultLang)
715721
716722resolveCrossRefs :: Variant -> [Item] -> [Item]
717723resolveCrossRefs variant entries =
@@ -803,7 +809,7 @@ bibEntries = do
803809 (bibComment <|> bibPreamble <|> bibString))
804810
805811bibSkip :: BibParser ()
806−bibSkip = () <$ take1WhileP (/='@')
812+bibSkip = skipMany1 (satisfy (/='@'))
807813
808814bibComment :: BibParser ()
809815bibComment = do
@@ -828,6 +834,9 @@ bibString = do
828834 updateState (\(l,m) -> (l, Map.insert k v m))
829835 return ()
830836
837+take1WhileP :: Monad m => (Char -> Bool) -> ParserT Sources u m Text
838+take1WhileP f = T.pack <$> many1 (satisfy f)
839+
831840inBraces :: BibParser Text
832841inBraces = do
833842 char '{'
@@ -859,7 +868,7 @@ fieldName = resolveAlias . T.toLower
859868
860869isBibtexKeyChar :: Char -> Bool
861870isBibtexKeyChar c =
862− isAlphaNum c || c `elem` (".:;?!`'()/*@_+=-[]*&" :: [Char])
871+ isAlphaNum c || c `elem` (".:;?!`'()$/*@_+=-[]*&" :: [Char])
863872
864873bibItem :: BibParser Item
865874bibItem = do
@@ -1456,8 +1465,9 @@ resolveKey lang ils = Walk.walk go ils
14561465 go x = x
14571466
14581467resolveKey' :: Lang -> Text -> Text
1459−resolveKey' lang@(Lang l _) k =
1460− case Map.lookup l biblatexStringMap >>= Map.lookup (T.toLower k) of
1468+resolveKey' lang k =
1469+ case Map.lookup (langLanguage lang) biblatexStringMap >>=
1470+ Map.lookup (T.toLower k) of
14611471 Nothing -> k
14621472 Just (x, _) -> either (const k) stringify $ parseLaTeX lang x
14631473
src/Text/Pandoc/Citeproc/Data.hs+7−6
@@ -10,7 +10,7 @@ import qualified Data.Text.Encoding as TE
1010import qualified Data.Text as T
1111import Data.Text (Text)
1212import Text.Pandoc.Citeproc.Util (toIETF)
13−import Citeproc (Lang(..), parseLang)
13+import Text.Collate.Lang (Lang(..), parseLang)
1414
1515biblatexLocalizations :: [(FilePath, ByteString)]
1616biblatexLocalizations = $(embedDir "citeproc/biblatex-localization")
@@ -21,11 +21,12 @@ biblatexStringMap :: M.Map Text (M.Map Text (Text, Text))
2121biblatexStringMap = foldr go mempty biblatexLocalizations
2222 where
2323 go (fp, bs) =
24− let Lang lang _ = parseLang (toIETF $ T.takeWhile (/= '.') $ T.pack fp)
25− ls = T.lines $ TE.decodeUtf8 bs
26− in if length ls > 4
27− then M.insert lang (toStringMap $ map (T.splitOn "|") ls)
28− else id
24+ let ls = T.lines $ TE.decodeUtf8 bs
25+ in case parseLang (toIETF $ T.takeWhile (/= '.') $ T.pack fp) of
26+ Right lang | length ls > 4
27+ -> M.insert (langLanguage lang)
28+ (toStringMap $ map (T.splitOn "|") ls)
29+ _ -> id
2930 toStringMap = foldr go' mempty
3031 go' [term, x, y] = M.insert term (x, y)
3132 go' _ = id
src/Text/Pandoc/Citeproc/Locator.hs+20−4
@@ -7,6 +7,7 @@ where
77import Citeproc.Types
88import Data.Text (Text)
99import qualified Data.Text as T
10+import Data.List (foldl')
1011import Text.Parsec
1112import Text.Pandoc.Definition
1213import Text.Pandoc.Parsing (romanNumeral)
@@ -19,7 +20,7 @@ parseLocator :: Locale -> [Inline] -> (Maybe (Text, Text), [Inline])
1920parseLocator locale inp =
2021 case parse (pLocatorWords (toLocatorMap locale)) "suffix" $ splitInp inp of
2122 Right r -> r
22− Left _ -> (Nothing, inp)
23+ Left _ -> (Nothing, maybeAddComma inp)
2324
2425splitInp :: [Inline] -> [Inline]
2526splitInp = splitStrWhen (\c -> isSpace c || (isPunctuation c && c /= ':'))
@@ -41,9 +42,17 @@ pLocatorWords locMap = do
4142 -- i.e. the first one will be " 9"
4243 return $
4344 if T.null la && T.null lo
44− then (Nothing, s)
45+ then (Nothing, maybeAddComma s)
4546 else (Just (la, T.strip lo), s)
4647
48+maybeAddComma :: [Inline] -> [Inline]
49+maybeAddComma [] = []
50+maybeAddComma ils@(Space : _) = ils
51+maybeAddComma ils@(Str t : _)
52+ | Just (c, _) <- T.uncons t
53+ , isPunctuation c = ils
54+maybeAddComma ils = Str "," : Space : ils
55+
4756pLocatorDelimited :: LocatorMap -> LocatorParser (Text, Text)
4857pLocatorDelimited locMap = try $ do
4958 _ <- pMatchChar "{" (== '{')
@@ -96,7 +105,7 @@ pLocatorLabel' locMap lim = go ""
96105 t <- anyToken
97106 ts <- manyTill anyToken (try $ lookAhead lim)
98107 let s = acc <> stringify (t:ts)
99− case M.lookup (T.strip s) locMap of
108+ case M.lookup (T.toCaseFold $ T.strip s) locMap of
100109 -- try to find a longer one, or return this one
101110 Just l -> go s <|> return (l, False)
102111 Nothing -> go s
@@ -139,7 +148,7 @@ pBalancedBraces braces p = try $ do
139148 where
140149 except = notFollowedBy pBraces >> p
141150 -- outer and inner
142− surround = foldl (\a (open, close) -> sur open close except <|> a)
151+ surround = foldl' (\a (open, close) -> sur open close except <|> a)
143152 except
144153 braces
145154
@@ -180,6 +189,7 @@ pPageUnit = roman <|> plainUnit
180189 plainUnit = do
181190 ts <- many1 (notFollowedBy pSpace >>
182191 notFollowedBy pLocatorPunct >>
192+ notFollowedBy pMath >>
183193 anyToken)
184194 let s = stringify ts
185195 -- otherwise look for actual digits or -s
@@ -210,6 +220,12 @@ pMatchChar msg f = satisfyTok f' <?> msg
210220pSpace :: LocatorParser Inline
211221pSpace = satisfyTok (\t -> isSpacey t || t == Str "\160") <?> "space"
212222
223+pMath :: LocatorParser Inline
224+pMath = satisfyTok isMath
225+ where
226+ isMath (Math{}) = True
227+ isMath _ = False
228+
213229satisfyTok :: (Inline -> Bool) -> LocatorParser Inline
214230satisfyTok f = tokenPrim show (\sp _ _ -> sp) (\tok -> if f tok
215231 then Just tok
src/Text/Pandoc/Class/CommonState.hs+1−1
@@ -19,7 +19,7 @@ where
1919
2020import Data.Default (Default (def))
2121import Data.Text (Text)
22−import Text.Pandoc.BCP47 (Lang)
22+import Text.Collate.Lang (Lang)
2323import Text.Pandoc.MediaBag (MediaBag)
2424import Text.Pandoc.Logging (LogMessage, Verbosity (WARNING))
2525import Text.Pandoc.Translations (Translations)
src/Text/Pandoc/Class/IO.hs+21−22
@@ -62,7 +62,7 @@ import Text.Pandoc.Definition (Pandoc, Inline (Image))
6262import Text.Pandoc.Error (PandocError (..))
6363import Text.Pandoc.Logging (LogMessage (..), messageVerbosity, showLogMessage)
6464import Text.Pandoc.MIME (MimeType)
65−import Text.Pandoc.MediaBag (MediaBag, lookupMedia, mediaDirectory)
65+import Text.Pandoc.MediaBag (MediaBag, MediaItem(..), lookupMedia, mediaItems)
6666import Text.Pandoc.Walk (walk)
6767import qualified Control.Exception as E
6868import qualified Data.ByteString as B
@@ -200,33 +200,32 @@ alertIndent (l:ls) = do
200200extractMedia :: (PandocMonad m, MonadIO m) => FilePath -> Pandoc -> m Pandoc
201201extractMedia dir d = do
202202 media <- getMediaBag
203− case [fp | (fp, _, _) <- mediaDirectory media] of
204− [] -> return d
205− fps -> do
206− mapM_ (writeMedia dir media) fps
207− return $ walk (adjustImagePath dir fps) d
203+ let items = mediaItems media
204+ if null items
205+ then return d
206+ else do
207+ mapM_ (writeMedia dir) items
208+ return $ walk (adjustImagePath dir media) d
208209
209210-- | Write the contents of a media bag to a path.
210211writeMedia :: (PandocMonad m, MonadIO m)
211− => FilePath -> MediaBag -> FilePath
212+ => FilePath
213+ -> (FilePath, MimeType, BL.ByteString)
212214 -> m ()
213−writeMedia dir mediabag subpath = do
214− -- we join and split to convert a/b/c to a\b\c on Windows;
215− -- in zip containers all paths use /
216− let fullpath = dir </> unEscapeString (normalise subpath)
217− let mbcontents = lookupMedia subpath mediabag
218− case mbcontents of
219− Nothing -> throwError $ PandocResourceNotFound $ pack subpath
220− Just (_, bs) -> do
221− report $ Extracting $ pack fullpath
222− liftIOError (createDirectoryIfMissing True) (takeDirectory fullpath)
223− logIOError $ BL.writeFile fullpath bs
215+writeMedia dir (fp, _mt, bs) = do
216+ -- we normalize to get proper path separators for the platform
217+ let fullpath = normalise $ dir </> fp
218+ liftIOError (createDirectoryIfMissing True) (takeDirectory fullpath)
219+ logIOError $ BL.writeFile fullpath bs
224220
225221-- | If the given Inline element is an image with a @src@ path equal to
226222-- one in the list of @paths@, then prepends @dir@ to the image source;
227223-- returns the element unchanged otherwise.
228−adjustImagePath :: FilePath -> [FilePath] -> Inline -> Inline
229−adjustImagePath dir paths (Image attr lab (src, tit))
230− | unpack src `elem` paths
231− = Image attr lab (pack (normalise $ dir </> unpack src), tit)
224+adjustImagePath :: FilePath -> MediaBag -> Inline -> Inline
225+adjustImagePath dir mediabag (Image attr lab (src, tit)) =
226+ case lookupMedia (T.unpack src) mediabag of
227+ Nothing -> Image attr lab (src, tit)
228+ Just item ->
229+ let fullpath = dir </> mediaPath item
230+ in Image attr lab (T.pack fullpath, tit)
232231adjustImagePath _ _ x = x
src/Text/Pandoc/Class/PandocMonad.hs+24−34
@@ -1,4 +1,5 @@
11{-# LANGUAGE CPP #-}
2+{-# LANGUAGE TupleSections #-}
23{-# LANGUAGE FlexibleContexts #-}
34{-# LANGUAGE FlexibleInstances #-}
45{-# LANGUAGE MultiParamTypeClasses #-}
@@ -37,7 +38,6 @@ module Text.Pandoc.Class.PandocMonad
3738 , setUserDataDir
3839 , getUserDataDir
3940 , fetchItem
40− , fetchMediaResource
4141 , getInputFiles
4242 , setInputFiles
4343 , getOutputFile
@@ -57,8 +57,7 @@ module Text.Pandoc.Class.PandocMonad
5757import Codec.Archive.Zip
5858import Control.Monad.Except (MonadError (catchError, throwError),
5959 MonadTrans, lift, when)
60−import Data.Digest.Pure.SHA (sha1, showDigest)
61−import Data.Maybe (fromMaybe)
60+import Data.List (foldl')
6261import Data.Time (UTCTime)
6362import Data.Time.Clock.POSIX (POSIXTime, utcTimeToPOSIXSeconds,
6463 posixSecondsToUTCTime)
@@ -66,16 +65,16 @@ import Data.Time.LocalTime (TimeZone, ZonedTime, utcToZonedTime)
6665import Network.URI ( escapeURIString, nonStrictRelativeTo,
6766 unEscapeString, parseURIReference, isAllowedInURI,
6867 parseURI, URI(..) )
69−import System.FilePath ((</>), (<.>), takeExtension, dropExtension,
70− isRelative, splitDirectories)
68+import System.FilePath ((</>), takeExtension, dropExtension,
69+ isRelative, splitDirectories, makeRelative)
7170import System.Random (StdGen)
72−import Text.Pandoc.BCP47 (Lang(..), parseBCP47, renderLang)
71+import Text.Collate.Lang (Lang(..), parseLang, renderLang)
7372import Text.Pandoc.Class.CommonState (CommonState (..))
7473import Text.Pandoc.Definition
7574import Text.Pandoc.Error
7675import Text.Pandoc.Logging
77−import Text.Pandoc.MIME (MimeType, getMimeType, extensionFromMimeType)
78−import Text.Pandoc.MediaBag (MediaBag, lookupMedia)
76+import Text.Pandoc.MIME (MimeType, getMimeType)
77+import Text.Pandoc.MediaBag (MediaBag, lookupMedia, MediaItem(..))
7978import Text.Pandoc.Shared (uriPathToPath, safeRead)
8079import Text.Pandoc.Translations (Term(..), Translations, lookupTerm,
8180 readTranslations)
@@ -284,7 +283,7 @@ readFileFromDirs (d:ds) f = catchError
284283toLang :: PandocMonad m => Maybe T.Text -> m (Maybe Lang)
285284toLang Nothing = return Nothing
286285toLang (Just s) =
287− case parseBCP47 s of
286+ case parseLang s of
288287 Left _ -> do
289288 report $ InvalidLang s
290289 return Nothing
@@ -375,7 +374,8 @@ fetchItem :: PandocMonad m
375374fetchItem s = do
376375 mediabag <- getMediaBag
377376 case lookupMedia (T.unpack s) mediabag of
378− Just (mime, bs) -> return (BL.toStrict bs, Just mime)
377+ Just item -> return (BL.toStrict (mediaContents item),
378+ Just (mediaMimeType item))
379379 Nothing -> downloadOrRead s
380380
381381-- | Returns the content and, if available, the MIME type of a resource.
@@ -410,9 +410,10 @@ downloadOrRead s = do
410410 _ -> readLocalFile fp -- get from local file system
411411 where readLocalFile f = do
412412 resourcePath <- getResourcePath
413− cont <- if isRelative f
414− then withPaths resourcePath readFileStrict f
415− else readFileStrict f
413+ (fp', cont) <- if isRelative f
414+ then withPaths resourcePath readFileStrict f
415+ else (f,) <$> readFileStrict f
416+ report $ LoadedResource f (makeRelative "." fp')
416417 return (cont, mime)
417418 httpcolon = URI{ uriScheme = "http:",
418419 uriAuthority = Nothing,
@@ -612,7 +613,7 @@ checkExistence fn = do
612613-- | Canonicalizes a file path by removing redundant @.@ and @..@.
613614makeCanonical :: FilePath -> FilePath
614615makeCanonical = Posix.joinPath . transformPathParts . splitDirectories
615− where transformPathParts = reverse . foldl go []
616+ where transformPathParts = reverse . foldl' go []
616617 go as "." = as
617618 go (_:as) ".." = as
618619 go as x = x : as
@@ -622,25 +623,13 @@ makeCanonical = Posix.joinPath . transformPathParts . splitDirectories
622623-- that filepath. Returns the result of the first successful execution
623624-- of the action, or throws a @PandocResourceNotFound@ exception if the
624625-- action errors for all filepaths.
625−withPaths :: PandocMonad m => [FilePath] -> (FilePath -> m a) -> FilePath -> m a
626+withPaths :: PandocMonad m
627+ => [FilePath] -> (FilePath -> m a) -> FilePath -> m (FilePath, a)
626628withPaths [] _ fp = throwError $ PandocResourceNotFound $ T.pack fp
627629withPaths (p:ps) action fp =
628− catchError (action (p </> fp))
630+ catchError ((p </> fp,) <$> action (p </> fp))
629631 (\_ -> withPaths ps action fp)
630632
631−-- | Fetch local or remote resource (like an image) and provide data suitable
632−-- for adding it to the MediaBag.
633−fetchMediaResource :: PandocMonad m
634− => T.Text -> m (FilePath, Maybe MimeType, BL.ByteString)
635−fetchMediaResource src = do
636− (bs, mt) <- downloadOrRead src
637− let ext = fromMaybe (T.pack $ takeExtension $ T.unpack src)
638− (mt >>= extensionFromMimeType)
639− let bs' = BL.fromChunks [bs]
640− let basename = showDigest $ sha1 bs'
641− let fname = basename <.> T.unpack ext
642− return (fname, mt, bs')
643−
644633-- | Traverse tree, filling media bag for any images that
645634-- aren't already in the media bag.
646635fillMediaBag :: PandocMonad m => Pandoc -> m Pandoc
@@ -648,12 +637,13 @@ fillMediaBag d = walkM handleImage d
648637 where handleImage :: PandocMonad m => Inline -> m Inline
649638 handleImage (Image attr lab (src, tit)) = catchError
650639 (do mediabag <- getMediaBag
651− case lookupMedia (T.unpack src) mediabag of
652− Just (_, _) -> return $ Image attr lab (src, tit)
640+ let fp = T.unpack src
641+ case lookupMedia fp mediabag of
642+ Just _ -> return ()
653643 Nothing -> do
654− (fname, mt, bs) <- fetchMediaResource src
655− insertMedia fname mt bs
656− return $ Image attr lab (T.pack fname, tit))
644+ (bs, mt) <- fetchItem src
645+ insertMedia fp mt (BL.fromStrict bs)
646+ return $ Image attr lab (src, tit))
657647 (\e ->
658648 case e of
659649 PandocResourceNotFound _ -> do
src/Text/Pandoc/Error.hs+23−16
@@ -23,26 +23,27 @@ import Control.Exception (Exception, displayException)
2323import Data.Typeable (Typeable)
2424import Data.Word (Word8)
2525import Data.Text (Text)
26+import Data.List (sortOn)
2627import qualified Data.Text as T
28+import Data.Ord (Down(..))
2729import GHC.Generics (Generic)
2830import Network.HTTP.Client (HttpException)
2931import System.Exit (ExitCode (..), exitWith)
3032import System.IO (stderr)
3133import qualified Text.Pandoc.UTF8 as UTF8
34+import Text.Pandoc.Sources (Sources(..))
3235import Text.Printf (printf)
3336import Text.Parsec.Error
3437import Text.Parsec.Pos hiding (Line)
3538import Text.Pandoc.Shared (tshow)
3639import Citeproc (CiteprocError, prettyCiteprocError)
3740
38−type Input = Text
39−
4041data PandocError = PandocIOError Text IOError
4142 | PandocHttpError Text HttpException
4243 | PandocShouldNeverHappenError Text
4344 | PandocSomeError Text
4445 | PandocParseError Text
45− | PandocParsecError Input ParseError
46+ | PandocParsecError Sources ParseError
4647 | PandocMakePDFError Text
4748 | PandocOptionError Text
4849 | PandocSyntaxMapError Text
@@ -81,22 +82,28 @@ renderError e =
8182 "Please report this to pandoc's developers: " <> s
8283 PandocSomeError s -> s
8384 PandocParseError s -> s
84− PandocParsecError input err' ->
85+ PandocParsecError (Sources inputs) err' ->
8586 let errPos = errorPos err'
8687 errLine = sourceLine errPos
8788 errColumn = sourceColumn errPos
88− ls = T.lines input <> [""]
89− errorInFile = if length ls > errLine - 1
90− then T.concat ["\n", ls !! (errLine - 1)
91− ,"\n", T.replicate (errColumn - 1) " "
92− ,"^"]
93− else ""
94− in "\nError at " <> tshow err' <>
95− -- if error comes from a chunk or included file,
96− -- then we won't get the right text this way:
97− if sourceName errPos == "source"
98− then errorInFile
99− else ""
89+ errFile = sourceName errPos
90+ errorInFile =
91+ case sortOn (Down . sourceLine . fst)
92+ [ (pos,t)
93+ | (pos,t) <- inputs
94+ , sourceName pos == errFile
95+ , sourceLine pos <= errLine
96+ ] of
97+ [] -> ""
98+ ((pos,txt):_) ->
99+ let ls = T.lines txt <> [""]
100+ ln = (errLine - sourceLine pos) + 1
101+ in if length ls > ln && ln >= 1
102+ then T.concat ["\n", ls !! (ln - 1)
103+ ,"\n", T.replicate (errColumn - 1) " "
104+ ,"^"]
105+ else ""
106+ in "Error at " <> tshow err' <> errorInFile
100107 PandocMakePDFError s -> s
101108 PandocOptionError s -> s
102109 PandocSyntaxMapError s -> s
src/Text/Pandoc/Extensions.hs+9−1
@@ -34,6 +34,7 @@ module Text.Pandoc.Extensions ( Extension(..)
3434where
3535import Data.Bits (clearBit, setBit, testBit, (.|.))
3636import Data.Data (Data)
37+import Data.List (foldl')
3738import qualified Data.Text as T
3839import Data.Typeable (Typeable)
3940import GHC.Generics (Generic)
@@ -135,6 +136,8 @@ data Extension =
135136 | Ext_raw_html -- ^ Allow raw HTML
136137 | Ext_raw_tex -- ^ Allow raw TeX (other than math)
137138 | Ext_raw_markdown -- ^ Parse markdown in ipynb as raw markdown
139+ | Ext_rebase_relative_paths -- ^ Rebase relative image and link paths,
140+ -- relative to directory of containing file
138141 | Ext_shortcut_reference_links -- ^ Shortcut reference links
139142 | Ext_simple_tables -- ^ Pandoc-style simple tables
140143 | Ext_smart -- ^ "Smart" quotes, apostrophes, ellipses, dashes
@@ -353,6 +356,7 @@ getDefaultExtensions "gfm" = extensionsFromList
353356 , Ext_strikeout
354357 , Ext_task_lists
355358 , Ext_emoji
359+ , Ext_yaml_metadata_block
356360 ]
357361getDefaultExtensions "commonmark" = extensionsFromList
358362 [Ext_raw_html]
@@ -378,6 +382,7 @@ getDefaultExtensions "commonmark_x" = extensionsFromList
378382 , Ext_raw_attribute
379383 , Ext_implicit_header_references
380384 , Ext_attributes
385+ , Ext_yaml_metadata_block
381386 ]
382387getDefaultExtensions "org" = extensionsFromList
383388 [Ext_citations,
@@ -459,6 +464,7 @@ getAllExtensions f = universalExtensions <> getAll f
459464 , Ext_gutenberg
460465 , Ext_smart
461466 , Ext_literate_haskell
467+ , Ext_rebase_relative_paths
462468 ]
463469 getAll "markdown_strict" = allMarkdownExtensions
464470 getAll "markdown_phpextra" = allMarkdownExtensions
@@ -510,6 +516,8 @@ getAllExtensions f = universalExtensions <> getAll f
510516 , Ext_implicit_header_references
511517 , Ext_attributes
512518 , Ext_sourcepos
519+ , Ext_yaml_metadata_block
520+ , Ext_rebase_relative_paths
513521 ]
514522 getAll "commonmark_x" = getAll "commonmark"
515523 getAll "org" = autoIdExtensions <>
@@ -593,7 +601,7 @@ parseFormatSpec :: T.Text
593601parseFormatSpec = parse formatSpec ""
594602 where formatSpec = do
595603 name <- formatName
596− (extsToEnable, extsToDisable) <- foldl (flip ($)) ([],[]) <$>
604+ (extsToEnable, extsToDisable) <- foldl' (flip ($)) ([],[]) <$>
597605 many extMod
598606 return (T.pack name, reverse extsToEnable, reverse extsToDisable)
599607 formatName = many1 $ noneOf "-+"
src/Text/Pandoc/Highlighting.hs+5−5
@@ -52,12 +52,12 @@ highlightingStyles =
5252 ("breezedark", breezeDark),
5353 ("haddock", haddock)]
5454
55−languages :: [T.Text]
56−languages = [T.toLower (sName s) | s <- M.elems defaultSyntaxMap]
55+languages :: SyntaxMap -> [T.Text]
56+languages syntaxmap = [T.toLower (sName s) | s <- M.elems syntaxmap]
5757
58−languagesByExtension :: T.Text -> [T.Text]
59−languagesByExtension ext =
60− [T.toLower (sName s) | s <- syntaxesByExtension defaultSyntaxMap (T.unpack ext)]
58+languagesByExtension :: SyntaxMap -> T.Text -> [T.Text]
59+languagesByExtension syntaxmap ext =
60+ [T.toLower (sName s) | s <- syntaxesByExtension syntaxmap (T.unpack ext)]
6161
6262highlight :: SyntaxMap
6363 -> (FormatOptions -> [SourceLine] -> a) -- ^ Formatter
src/Text/Pandoc/ImageSize.hs+5−1
@@ -57,7 +57,8 @@ import Codec.Picture (decodeImageWithMetadata)
5757-- quick and dirty functions to get image sizes
5858-- algorithms borrowed from wwwis.pl
5959
60−data ImageType = Png | Gif | Jpeg | Svg | Pdf | Eps | Emf deriving Show
60+data ImageType = Png | Gif | Jpeg | Svg | Pdf | Eps | Emf | Tiff
61+ deriving Show
6162data Direction = Width | Height
6263instance Show Direction where
6364 show Width = "width"
@@ -100,6 +101,8 @@ imageType :: ByteString -> Maybe ImageType
100101imageType img = case B.take 4 img of
101102 "\x89\x50\x4e\x47" -> return Png
102103 "\x47\x49\x46\x38" -> return Gif
104+ "\x49\x49\x2a\x00" -> return Tiff
105+ "\x4D\x4D\x00\x2a" -> return Tiff
103106 "\xff\xd8\xff\xe0" -> return Jpeg -- JFIF
104107 "\xff\xd8\xff\xe1" -> return Jpeg -- Exif
105108 "%PDF" -> return Pdf
@@ -124,6 +127,7 @@ imageSize opts img = checkDpi <$>
124127 Just Png -> getSize img
125128 Just Gif -> getSize img
126129 Just Jpeg -> getSize img
130+ Just Tiff -> getSize img
127131 Just Svg -> mbToEither "could not determine SVG size" $ svgSize opts img
128132 Just Eps -> mbToEither "could not determine EPS size" $ epsSize img
129133 Just Pdf -> mbToEither "could not determine PDF size" $ pdfSize img
src/Text/Pandoc/Logging.hs+32−9
@@ -36,6 +36,7 @@ import Data.Typeable (Typeable)
3636import GHC.Generics (Generic)
3737import Text.Pandoc.Definition
3838import Text.Parsec.Pos
39+import Text.Pandoc.Shared (tshow)
3940
4041-- | Verbosity level.
4142data Verbosity = ERROR | WARNING | INFO
@@ -84,6 +85,7 @@ data LogMessage =
8485 | CouldNotParseCSS Text
8586 | Fetching Text
8687 | Extracting Text
88+ | LoadedResource FilePath FilePath
8789 | NoTitleElement Text
8890 | NoLangSpecified
8991 | InvalidLang Text
@@ -100,6 +102,8 @@ data LogMessage =
100102 | FilterCompleted FilePath Integer
101103 | CiteprocWarning Text
102104 | ATXHeadingInLHS Int Text
105+ | EnvironmentVariableUndefined Text
106+ | DuplicateAttribute Text Text
103107 deriving (Show, Eq, Data, Ord, Typeable, Generic)
104108
105109instance ToJSON LogMessage where
@@ -192,6 +196,9 @@ instance ToJSON LogMessage where
192196 ["path" .= fp]
193197 Extracting fp ->
194198 ["path" .= fp]
199+ LoadedResource orig found ->
200+ ["for" .= orig
201+ ,"from" .= found]
195202 NoTitleElement fallback ->
196203 ["fallback" .= fallback]
197204 NoLangSpecified -> []
@@ -229,13 +236,20 @@ instance ToJSON LogMessage where
229236 ATXHeadingInLHS lvl contents ->
230237 ["level" .= lvl
231238 ,"contents" .= contents]
239+ EnvironmentVariableUndefined var ->
240+ ["variable" .= var ]
241+ DuplicateAttribute attr val ->
242+ ["attribute" .= attr
243+ ,"value" .= val]
232244
233245showPos :: SourcePos -> Text
234246showPos pos = Text.pack $ sn ++ "line " ++
235247 show (sourceLine pos) ++ " column " ++ show (sourceColumn pos)
236− where sn = if sourceName pos == "source" || sourceName pos == ""
237− then ""
238− else sourceName pos ++ " "
248+ where
249+ sn' = sourceName pos
250+ sn = if sn' == "source" || sn' == "" || sn' == "-"
251+ then ""
252+ else sn' ++ " "
239253
240254encodeLogMessages :: [LogMessage] -> BL.ByteString
241255encodeLogMessages ms =
@@ -268,7 +282,7 @@ showLogMessage msg =
268282 ParsingUnescaped s pos ->
269283 "Parsing unescaped '" <> s <> "' at " <> showPos pos
270284 CouldNotLoadIncludeFile fp pos ->
271− "Could not load include file '" <> fp <> "' at " <> showPos pos
285+ "Could not load include file " <> fp <> " at " <> showPos pos
272286 MacroAlreadyDefined name pos ->
273287 "Macro '" <> name <> "' already defined, ignoring at " <> showPos pos
274288 InlineNotRendered il ->
@@ -280,18 +294,18 @@ showLogMessage msg =
280294 IgnoredIOError s ->
281295 "IO Error (ignored): " <> s
282296 CouldNotFetchResource fp s ->
283− "Could not fetch resource '" <> fp <> "'" <>
297+ "Could not fetch resource " <> fp <>
284298 if Text.null s then "" else ": " <> s
285299 CouldNotDetermineImageSize fp s ->
286− "Could not determine image size for '" <> fp <> "'" <>
300+ "Could not determine image size for " <> fp <>
287301 if Text.null s then "" else ": " <> s
288302 CouldNotConvertImage fp s ->
289− "Could not convert image '" <> fp <> "'" <>
303+ "Could not convert image " <> fp <>
290304 if Text.null s then "" else ": " <> s
291305 CouldNotDetermineMimeType fp ->
292− "Could not determine mime type for '" <> fp <> "'"
306+ "Could not determine mime type for " <> fp
293307 CouldNotConvertTeXMath s m ->
294− "Could not convert TeX math '" <> s <> "', rendering as TeX" <>
308+ "Could not convert TeX math " <> s <> ", rendering as TeX" <>
295309 if Text.null m then "" else ":\n" <> m
296310 CouldNotParseCSS m ->
297311 "Could not parse CSS" <> if Text.null m then "" else ":\n" <> m
@@ -299,6 +313,8 @@ showLogMessage msg =
299313 "Fetching " <> fp <> "..."
300314 Extracting fp ->
301315 "Extracting " <> fp <> "..."
316+ LoadedResource orig found ->
317+ "Loaded " <> Text.pack orig <> " from " <> Text.pack found
302318 NoTitleElement fallback ->
303319 "This document format requires a nonempty <title> element.\n" <>
304320 "Defaulting to '" <> fallback <> "' as the title.\n" <>
@@ -345,6 +361,10 @@ showLogMessage msg =
345361 if lvl < 3
346362 then " Consider using --markdown-headings=setext."
347363 else ""
364+ EnvironmentVariableUndefined var ->
365+ "Undefined environment variable " <> var <> " in defaults file."
366+ DuplicateAttribute attr val ->
367+ "Ignoring duplicate attribute " <> attr <> "=" <> tshow val <> "."
348368
349369messageVerbosity :: LogMessage -> Verbosity
350370messageVerbosity msg =
@@ -375,6 +395,7 @@ messageVerbosity msg =
375395 CouldNotParseCSS{} -> WARNING
376396 Fetching{} -> INFO
377397 Extracting{} -> INFO
398+ LoadedResource{} -> INFO
378399 NoTitleElement{} -> WARNING
379400 NoLangSpecified -> INFO
380401 InvalidLang{} -> WARNING
@@ -391,3 +412,5 @@ messageVerbosity msg =
391412 FilterCompleted{} -> INFO
392413 CiteprocWarning{} -> WARNING
393414 ATXHeadingInLHS{} -> WARNING
415+ EnvironmentVariableUndefined{}-> WARNING
416+ DuplicateAttribute{} -> WARNING
src/Text/Pandoc/Lua/Filter.hs+4−1
@@ -13,7 +13,9 @@ module Text.Pandoc.Lua.Filter ( LuaFilterFunction
1313 , LuaFilter
1414 , runFilterFile
1515 , walkInlines
16+ , walkInlineLists
1617 , walkBlocks
18+ , walkBlockLists
1719 , module Text.Pandoc.Lua.Walk
1820 ) where
1921import Control.Applicative ((<|>))
@@ -22,6 +24,7 @@ import Control.Monad.Catch (finally, try)
2224import Data.Data (Data, DataType, dataTypeConstrs, dataTypeName, dataTypeOf,
2325 showConstr, toConstr, tyconUQname)
2426import Data.Foldable (foldrM)
27+import Data.List (foldl')
2528import Data.Map (Map)
2629import Data.Maybe (fromMaybe)
2730import Foreign.Lua (Lua, Peekable, Pushable, StackIndex)
@@ -204,7 +207,7 @@ walkMeta lf (Pandoc m bs) = do
204207
205208walkPandoc :: LuaFilter -> Pandoc -> Lua Pandoc
206209walkPandoc (LuaFilter fnMap) =
207− case foldl mplus Nothing (map (`Map.lookup` fnMap) pandocFilterNames) of
210+ case foldl' mplus Nothing (map (`Map.lookup` fnMap) pandocFilterNames) of
208211 Just fn -> \x -> runFilterFunction fn x *> singleElement x
209212 Nothing -> return
210213
src/Text/Pandoc/Lua/Marshaling/AST.hs+77−79
@@ -1,4 +1,5 @@
11{-# OPTIONS_GHC -fno-warn-orphans #-}
2+{-# LANGUAGE BangPatterns #-}
23{-# LANGUAGE LambdaCase #-}
34{- |
45 Module : Text.Pandoc.Lua.Marshaling.AST
@@ -17,6 +18,7 @@ module Text.Pandoc.Lua.Marshaling.AST
1718 ) where
1819
1920import Control.Applicative ((<|>))
21+import Control.Monad ((<$!>))
2022import Foreign.Lua (Lua, Peekable, Pushable, StackIndex)
2123import Text.Pandoc.Definition
2224import Text.Pandoc.Error (PandocError)
@@ -32,17 +34,16 @@ instance Pushable Pandoc where
3234 pushViaConstructor "Pandoc" blocks meta
3335
3436instance Peekable Pandoc where
35− peek idx = defineHowTo "get Pandoc value" $ do
36− blocks <- LuaUtil.rawField idx "blocks"
37− meta <- LuaUtil.rawField idx "meta"
38− return $ Pandoc meta blocks
37+ peek idx = defineHowTo "get Pandoc value" $! Pandoc
38+ <$!> LuaUtil.rawField idx "meta"
39+ <*> LuaUtil.rawField idx "blocks"
3940
4041instance Pushable Meta where
4142 push (Meta mmap) =
4243 pushViaConstructor "Meta" mmap
4344instance Peekable Meta where
44− peek idx = defineHowTo "get Meta value" $
45− Meta <$> Lua.peek idx
45+ peek idx = defineHowTo "get Meta value" $!
46+ Meta <$!> Lua.peek idx
4647
4748instance Pushable MetaValue where
4849 push = pushMetaValue
@@ -68,14 +69,13 @@ instance Pushable Citation where
6869 pushViaConstructor "Citation" cid mode prefix suffix noteNum hash
6970
7071instance Peekable Citation where
71− peek idx = do
72− id' <- LuaUtil.rawField idx "id"
73− prefix <- LuaUtil.rawField idx "prefix"
74− suffix <- LuaUtil.rawField idx "suffix"
75− mode <- LuaUtil.rawField idx "mode"
76− num <- LuaUtil.rawField idx "note_num"
77− hash <- LuaUtil.rawField idx "hash"
78− return $ Citation id' prefix suffix mode num hash
72+ peek idx = Citation
73+ <$!> LuaUtil.rawField idx "id"
74+ <*> LuaUtil.rawField idx "prefix"
75+ <*> LuaUtil.rawField idx "suffix"
76+ <*> LuaUtil.rawField idx "mode"
77+ <*> LuaUtil.rawField idx "note_num"
78+ <*> LuaUtil.rawField idx "hash"
7979
8080instance Pushable Alignment where
8181 push = Lua.push . show
@@ -90,7 +90,7 @@ instance Peekable CitationMode where
9090instance Pushable Format where
9191 push (Format f) = Lua.push f
9292instance Peekable Format where
93− peek idx = Format <$> Lua.peek idx
93+ peek idx = Format <$!> Lua.peek idx
9494
9595instance Pushable ListNumberDelim where
9696 push = Lua.push . show
@@ -130,26 +130,26 @@ peekMetaValue idx = defineHowTo "get MetaValue" $ do
130130 elementContent = Lua.peek idx
131131 luatype <- Lua.ltype idx
132132 case luatype of
133− Lua.TypeBoolean -> MetaBool <$> Lua.peek idx
134− Lua.TypeString -> MetaString <$> Lua.peek idx
133+ Lua.TypeBoolean -> MetaBool <$!> Lua.peek idx
134+ Lua.TypeString -> MetaString <$!> Lua.peek idx
135135 Lua.TypeTable -> do
136136 tag <- try $ LuaUtil.getTag idx
137137 case tag of
138− Right "MetaBlocks" -> MetaBlocks <$> elementContent
139− Right "MetaBool" -> MetaBool <$> elementContent
140− Right "MetaMap" -> MetaMap <$> elementContent
141− Right "MetaInlines" -> MetaInlines <$> elementContent
142− Right "MetaList" -> MetaList <$> elementContent
143− Right "MetaString" -> MetaString <$> elementContent
138+ Right "MetaBlocks" -> MetaBlocks <$!> elementContent
139+ Right "MetaBool" -> MetaBool <$!> elementContent
140+ Right "MetaMap" -> MetaMap <$!> elementContent
141+ Right "MetaInlines" -> MetaInlines <$!> elementContent
142+ Right "MetaList" -> MetaList <$!> elementContent
143+ Right "MetaString" -> MetaString <$!> elementContent
144144 Right t -> Lua.throwMessage ("Unknown meta tag: " <> t)
145145 Left _ -> do
146146 -- no meta value tag given, try to guess.
147147 len <- Lua.rawlen idx
148148 if len <= 0
149− then MetaMap <$> Lua.peek idx
150− else (MetaInlines <$> Lua.peek idx)
151− <|> (MetaBlocks <$> Lua.peek idx)
152− <|> (MetaList <$> Lua.peek idx)
149+ then MetaMap <$!> Lua.peek idx
150+ else (MetaInlines <$!> Lua.peek idx)
151+ <|> (MetaBlocks <$!> Lua.peek idx)
152+ <|> (MetaList <$!> Lua.peek idx)
153153 _ -> Lua.throwMessage "could not get meta value"
154154
155155-- | Push a block element to the top of the Lua stack.
@@ -174,25 +174,25 @@ pushBlock = \case
174174
175175-- | Return the value at the given index as block if possible.
176176peekBlock :: StackIndex -> Lua Block
177−peekBlock idx = defineHowTo "get Block value" $ do
177+peekBlock idx = defineHowTo "get Block value" $! do
178178 tag <- LuaUtil.getTag idx
179179 case tag of
180− "BlockQuote" -> BlockQuote <$> elementContent
181− "BulletList" -> BulletList <$> elementContent
182− "CodeBlock" -> withAttr CodeBlock <$> elementContent
183− "DefinitionList" -> DefinitionList <$> elementContent
184− "Div" -> withAttr Div <$> elementContent
180+ "BlockQuote" -> BlockQuote <$!> elementContent
181+ "BulletList" -> BulletList <$!> elementContent
182+ "CodeBlock" -> withAttr CodeBlock <$!> elementContent
183+ "DefinitionList" -> DefinitionList <$!> elementContent
184+ "Div" -> withAttr Div <$!> elementContent
185185 "Header" -> (\(lvl, LuaAttr attr, lst) -> Header lvl attr lst)
186− <$> elementContent
186+ <$!> elementContent
187187 "HorizontalRule" -> return HorizontalRule
188− "LineBlock" -> LineBlock <$> elementContent
188+ "LineBlock" -> LineBlock <$!> elementContent
189189 "OrderedList" -> (\(LuaListAttributes lstAttr, lst) ->
190190 OrderedList lstAttr lst)
191− <$> elementContent
191+ <$!> elementContent
192192 "Null" -> return Null
193− "Para" -> Para <$> elementContent
194− "Plain" -> Plain <$> elementContent
195− "RawBlock" -> uncurry RawBlock <$> elementContent
193+ "Para" -> Para <$!> elementContent
194+ "Plain" -> Plain <$!> elementContent
195+ "RawBlock" -> uncurry RawBlock <$!> elementContent
196196 "Table" -> (\(attr, capt, colSpecs, thead, tbodies, tfoot) ->
197197 Table (fromLuaAttr attr)
198198 capt
@@ -200,7 +200,7 @@ peekBlock idx = defineHowTo "get Block value" $ do
200200 thead
201201 tbodies
202202 tfoot)
203− <$> elementContent
203+ <$!> elementContent
204204 _ -> Lua.throwMessage ("Unknown block type: " <> tag)
205205 where
206206 -- Get the contents of an AST element.
@@ -222,15 +222,14 @@ pushCaption (Caption shortCaption longCaption) = do
222222
223223-- | Peek Caption element
224224peekCaption :: StackIndex -> Lua Caption
225−peekCaption idx = do
226− short <- Lua.fromOptional <$> LuaUtil.rawField idx "short"
227− long <- LuaUtil.rawField idx "long"
228− return $ Caption short long
225+peekCaption idx = Caption
226+ <$!> (Lua.fromOptional <$!> LuaUtil.rawField idx "short")
227+ <*> LuaUtil.rawField idx "long"
229228
230229instance Peekable ColWidth where
231230 peek idx = do
232− width <- Lua.fromOptional <$> Lua.peek idx
233− return $ maybe ColWidthDefault ColWidth width
231+ width <- Lua.fromOptional <$!> Lua.peek idx
232+ return $! maybe ColWidthDefault ColWidth width
234233
235234instance Pushable ColWidth where
236235 push = \case
@@ -252,12 +251,11 @@ instance Pushable TableBody where
252251 LuaUtil.addField "body" body
253252
254253instance Peekable TableBody where
255− peek idx = do
256− attr <- LuaUtil.rawField idx "attr"
257− rowHeadColumns <- LuaUtil.rawField idx "row_head_columns"
258− head' <- LuaUtil.rawField idx "head"
259− body <- LuaUtil.rawField idx "body"
260− return $ TableBody attr (RowHeadColumns rowHeadColumns) head' body
254+ peek idx = TableBody
255+ <$!> LuaUtil.rawField idx "attr"
256+ <*> (RowHeadColumns <$!> LuaUtil.rawField idx "row_head_columns")
257+ <*> LuaUtil.rawField idx "head"
258+ <*> LuaUtil.rawField idx "body"
261259
262260instance Pushable TableHead where
263261 push (TableHead attr rows) = Lua.push (attr, rows)
@@ -287,13 +285,12 @@ pushCell (Cell attr align (RowSpan rowSpan) (ColSpan colSpan) contents) = do
287285 LuaUtil.addField "contents" contents
288286
289287peekCell :: StackIndex -> Lua Cell
290−peekCell idx = do
291− attr <- fromLuaAttr <$> LuaUtil.rawField idx "attr"
292− align <- LuaUtil.rawField idx "alignment"
293− rowSpan <- LuaUtil.rawField idx "row_span"
294− colSpan <- LuaUtil.rawField idx "col_span"
295− contents <- LuaUtil.rawField idx "contents"
296− return $ Cell attr align (RowSpan rowSpan) (ColSpan colSpan) contents
288+peekCell idx = Cell
289+ <$!> (fromLuaAttr <$!> LuaUtil.rawField idx "attr")
290+ <*> LuaUtil.rawField idx "alignment"
291+ <*> (RowSpan <$!> LuaUtil.rawField idx "row_span")
292+ <*> (ColSpan <$!> LuaUtil.rawField idx "col_span")
293+ <*> LuaUtil.rawField idx "contents"
297294
298295-- | Push an inline element to the top of the lua stack.
299296pushInline :: Inline -> Lua ()
@@ -324,28 +321,29 @@ peekInline :: StackIndex -> Lua Inline
324321peekInline idx = defineHowTo "get Inline value" $ do
325322 tag <- LuaUtil.getTag idx
326323 case tag of
327− "Cite" -> uncurry Cite <$> elementContent
328− "Code" -> withAttr Code <$> elementContent
329− "Emph" -> Emph <$> elementContent
330− "Underline" -> Underline <$> elementContent
331− "Image" -> (\(LuaAttr attr, lst, tgt) -> Image attr lst tgt)
332− <$> elementContent
333− "Link" -> (\(LuaAttr attr, lst, tgt) -> Link attr lst tgt)
334− <$> elementContent
324+ "Cite" -> uncurry Cite <$!> elementContent
325+ "Code" -> withAttr Code <$!> elementContent
326+ "Emph" -> Emph <$!> elementContent
327+ "Underline" -> Underline <$!> elementContent
328+ "Image" -> (\(LuaAttr !attr, !lst, !tgt) -> Image attr lst tgt)
329+ <$!> elementContent
330+ "Link" -> (\(LuaAttr !attr, !lst, !tgt) -> Link attr lst tgt)
331+ <$!> elementContent
335332 "LineBreak" -> return LineBreak
336− "Note" -> Note <$> elementContent
337− "Math" -> uncurry Math <$> elementContent
338− "Quoted" -> uncurry Quoted <$> elementContent
339− "RawInline" -> uncurry RawInline <$> elementContent
340− "SmallCaps" -> SmallCaps <$> elementContent
333+ "Note" -> Note <$!> elementContent
334+ "Math" -> uncurry Math <$!> elementContent
335+ "Quoted" -> uncurry Quoted <$!> elementContent
336+ "RawInline" -> uncurry RawInline <$!> elementContent
337+ "SmallCaps" -> SmallCaps <$!> elementContent
341338 "SoftBreak" -> return SoftBreak
342339 "Space" -> return Space
343− "Span" -> withAttr Span <$> elementContent
344− "Str" -> Str <$> elementContent
345− "Strikeout" -> Strikeout <$> elementContent
346− "Strong" -> Strong <$> elementContent
347− "Subscript" -> Subscript <$> elementContent
348− "Superscript"-> Superscript <$> elementContent
340+ "Span" -> withAttr Span <$!> elementContent
341+ -- strict to Lua string is copied before gc
342+ "Str" -> Str <$!> elementContent
343+ "Strikeout" -> Strikeout <$!> elementContent
344+ "Strong" -> Strong <$!> elementContent
345+ "Subscript" -> Subscript <$!> elementContent
346+ "Superscript"-> Superscript <$!> elementContent
349347 _ -> Lua.throwMessage ("Unknown inline type: " <> tag)
350348 where
351349 -- Get the contents of an AST element.
@@ -366,7 +364,7 @@ instance Pushable LuaAttr where
366364 pushViaConstructor "Attr" id' classes kv
367365
368366instance Peekable LuaAttr where
369− peek idx = defineHowTo "get Attr value" (LuaAttr <$> Lua.peek idx)
367+ peek idx = defineHowTo "get Attr value" $! (LuaAttr <$!> Lua.peek idx)
370368
371369-- | Wrapper for ListAttributes
372370newtype LuaListAttributes = LuaListAttributes ListAttributes
src/Text/Pandoc/Lua/Module/MediaBag.hs+3−3
@@ -73,9 +73,9 @@ lookup fp = do
7373 res <- MB.lookupMedia fp <$> getMediaBag
7474 liftPandocLua $ case res of
7575 Nothing -> 1 <$ Lua.pushnil
76− Just (mimeType, contents) -> do
77− Lua.push mimeType
78− Lua.push contents
76+ Just item -> do
77+ Lua.push $ MB.mediaMimeType item
78+ Lua.push $ MB.mediaContents item
7979 return 2
8080
8181list :: PandocLua NumResults
src/Text/Pandoc/Lua/Module/Pandoc.hs+8−3
@@ -23,8 +23,10 @@ import Foreign.Lua (Lua, NumResults, Optional, Peekable, Pushable)
2323import System.Exit (ExitCode (..))
2424import Text.Pandoc.Class.PandocIO (runIO)
2525import Text.Pandoc.Definition (Block, Inline)
26−import Text.Pandoc.Lua.Filter (walkInlines, walkBlocks, LuaFilter, SingletonsList (..))
26+import Text.Pandoc.Lua.Filter (LuaFilter, SingletonsList (..), walkInlines,
27+ walkInlineLists, walkBlocks, walkBlockLists)
2728import Text.Pandoc.Lua.Marshaling ()
29+import Text.Pandoc.Lua.Marshaling.List (List (..))
2830import Text.Pandoc.Lua.PandocLua (PandocLua, addFunction, liftPandocLua,
2931 loadDefaultModule)
3032import Text.Pandoc.Walk (Walkable)
@@ -51,9 +53,12 @@ pushModule = do
5153 return 1
5254
5355walkElement :: (Walkable (SingletonsList Inline) a,
54− Walkable (SingletonsList Block) a)
56+ Walkable (SingletonsList Block) a,
57+ Walkable (List Inline) a,
58+ Walkable (List Block) a)
5559 => a -> LuaFilter -> PandocLua a
56−walkElement x f = liftPandocLua $ walkInlines f x >>= walkBlocks f
60+walkElement x f = liftPandocLua $
61+ walkInlines f x >>= walkInlineLists f >>= walkBlocks f >>= walkBlockLists f
5762
5863walk_inline :: Inline -> LuaFilter -> PandocLua Inline
5964walk_inline = walkElement
src/Text/Pandoc/Lua/Module/Utils.hs+1−1
@@ -146,7 +146,7 @@ from_simple_table (SimpleTable capt aligns widths head' body) = do
146146 nullAttr
147147 (Caption Nothing [Plain capt])
148148 (zipWith (\a w -> (a, toColWidth w)) aligns widths)
149− (TableHead nullAttr [blockListToRow head'])
149+ (TableHead nullAttr [blockListToRow head' | not (null head') ])
150150 [TableBody nullAttr 0 [] $ map blockListToRow body]
151151 (TableFoot nullAttr [])
152152 return (NumResults 1)
src/Text/Pandoc/MIME.hs+10
@@ -43,6 +43,16 @@ getMimeTypeDef :: FilePath -> MimeType
4343getMimeTypeDef = fromMaybe "application/octet-stream" . getMimeType
4444
4545extensionFromMimeType :: MimeType -> Maybe T.Text
46+-- few special cases, where there are multiple options:
47+extensionFromMimeType "text/plain" = Just "txt"
48+extensionFromMimeType "video/quicktime" = Just "mov"
49+extensionFromMimeType "video/mpeg" = Just "mpeg"
50+extensionFromMimeType "video/dv" = Just "dv"
51+extensionFromMimeType "image/vnd.djvu" = Just "djvu"
52+extensionFromMimeType "image/tiff" = Just "tiff"
53+extensionFromMimeType "image/jpeg" = Just "jpg"
54+extensionFromMimeType "application/xml" = Just "xml"
55+extensionFromMimeType "application/ogg" = Just "ogg"
4656extensionFromMimeType mimetype =
4757 M.lookup (T.takeWhile (/=';') mimetype) reverseMimeTypes
4858 -- note: we just look up the basic mime type, dropping the content-encoding etc.
src/Text/Pandoc/MediaBag.hs+45−14
@@ -1,4 +1,5 @@
11{-# LANGUAGE CPP #-}
2+{-# LANGUAGE OverloadedStrings #-}
23{-# LANGUAGE DeriveDataTypeable #-}
34{-# LANGUAGE GeneralizedNewtypeDeriving #-}
45{- |
@@ -14,6 +15,7 @@ Definition of a MediaBag object to hold binary resources, and an
1415interface for interacting with it.
1516-}
1617module Text.Pandoc.MediaBag (
18+ MediaItem(..),
1719 MediaBag,
1820 deleteMedia,
1921 lookupMedia,
@@ -24,29 +26,43 @@ module Text.Pandoc.MediaBag (
2426import qualified Data.ByteString.Lazy as BL
2527import Data.Data (Data)
2628import qualified Data.Map as M
27−import Data.Maybe (fromMaybe)
29+import Data.Maybe (fromMaybe, isNothing)
2830import Data.Typeable (Typeable)
2931import System.FilePath
30−import qualified System.FilePath.Posix as Posix
31−import Text.Pandoc.MIME (MimeType, getMimeTypeDef)
32+import Text.Pandoc.MIME (MimeType, getMimeTypeDef, extensionFromMimeType)
33+import Data.Text (Text)
34+import qualified Data.Text as T
35+import Data.Digest.Pure.SHA (sha1, showDigest)
36+import Network.URI (URI (..), parseURI)
37+
38+data MediaItem =
39+ MediaItem
40+ { mediaMimeType :: MimeType
41+ , mediaPath :: FilePath
42+ , mediaContents :: BL.ByteString
43+ } deriving (Eq, Ord, Show, Data, Typeable)
3244
3345-- | A container for a collection of binary resources, with names and
3446-- mime types. Note that a 'MediaBag' is a Monoid, so 'mempty'
3547-- can be used for an empty 'MediaBag', and '<>' can be used to append
3648-- two 'MediaBag's.
37−newtype MediaBag = MediaBag (M.Map [FilePath] (MimeType, BL.ByteString))
49+newtype MediaBag = MediaBag (M.Map Text MediaItem)
3850 deriving (Semigroup, Monoid, Data, Typeable)
3951
4052instance Show MediaBag where
4153 show bag = "MediaBag " ++ show (mediaDirectory bag)
4254
55+-- | We represent paths with /, in normalized form.
56+canonicalize :: FilePath -> Text
57+canonicalize = T.replace "\\" "/" . T.pack . normalise
58+
4359-- | Delete a media item from a 'MediaBag', or do nothing if no item corresponds
4460-- to the given path.
4561deleteMedia :: FilePath -- ^ relative path and canonical name of resource
4662 -> MediaBag
4763 -> MediaBag
4864deleteMedia fp (MediaBag mediamap) =
49− MediaBag $ M.delete (splitDirectories fp) mediamap
65+ MediaBag $ M.delete (canonicalize fp) mediamap
5066
5167-- | Insert a media item into a 'MediaBag', replacing any existing
5268-- value with the same name.
@@ -56,26 +72,41 @@ insertMedia :: FilePath -- ^ relative path and canonical name of resource
5672 -> MediaBag
5773 -> MediaBag
5874insertMedia fp mbMime contents (MediaBag mediamap) =
59− MediaBag (M.insert (splitDirectories fp) (mime, contents) mediamap)
60− where mime = fromMaybe fallback mbMime
75+ MediaBag (M.insert fp' mediaItem mediamap)
76+ where mediaItem = MediaItem{ mediaPath = newpath
77+ , mediaContents = contents
78+ , mediaMimeType = mt }
79+ fp' = canonicalize fp
80+ uri = parseURI fp
81+ newpath = if isRelative fp
82+ && isNothing uri
83+ && ".." `notElem` splitPath fp
84+ then T.unpack fp'
85+ else showDigest (sha1 contents) <> "." <> ext
6186 fallback = case takeExtension fp of
6287 ".gz" -> getMimeTypeDef $ dropExtension fp
6388 _ -> getMimeTypeDef fp
89+ mt = fromMaybe fallback mbMime
90+ path = maybe fp uriPath uri
91+ ext = case takeExtension path of
92+ '.':e -> e
93+ _ -> maybe "" T.unpack $ extensionFromMimeType mt
94+
6495
6596-- | Lookup a media item in a 'MediaBag', returning mime type and contents.
6697lookupMedia :: FilePath
6798 -> MediaBag
68− -> Maybe (MimeType, BL.ByteString)
69−lookupMedia fp (MediaBag mediamap) = M.lookup (splitDirectories fp) mediamap
99+ -> Maybe MediaItem
100+lookupMedia fp (MediaBag mediamap) = M.lookup (canonicalize fp) mediamap
70101
71102-- | Get a list of the file paths stored in a 'MediaBag', with
72103-- their corresponding mime types and the lengths in bytes of the contents.
73104mediaDirectory :: MediaBag -> [(FilePath, MimeType, Int)]
74−mediaDirectory (MediaBag mediamap) =
75− M.foldrWithKey (\fp (mime,contents) ->
76− ((Posix.joinPath fp, mime, fromIntegral $ BL.length contents):)) [] mediamap
105+mediaDirectory mediabag =
106+ map (\(fp, mt, bs) -> (fp, mt, fromIntegral (BL.length bs)))
107+ (mediaItems mediabag)
77108
78109mediaItems :: MediaBag -> [(FilePath, MimeType, BL.ByteString)]
79110mediaItems (MediaBag mediamap) =
80− M.foldrWithKey (\fp (mime,contents) ->
81− ((Posix.joinPath fp, mime, contents):)) [] mediamap
111+ map (\item -> (mediaPath item, mediaMimeType item, mediaContents item))
112+ (M.elems mediamap)
src/Text/Pandoc/Options.hs+17−17
@@ -315,6 +315,23 @@ defaultMathJaxURL = "https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml-full.j
315315defaultKaTeXURL :: Text
316316defaultKaTeXURL = "https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.11.1/"
317317
318+-- Update documentation in doc/filters.md if this is changed.
319+$(deriveJSON defaultOptions{ constructorTagModifier =
320+ camelCaseStrToHyphenated
321+ } ''TrackChanges)
322+
323+$(deriveJSON defaultOptions{ constructorTagModifier =
324+ camelCaseStrToHyphenated
325+ } ''WrapOption)
326+
327+$(deriveJSON defaultOptions{ constructorTagModifier =
328+ camelCaseStrToHyphenated . drop 8
329+ } ''TopLevelDivision)
330+
331+$(deriveJSON defaultOptions{ constructorTagModifier =
332+ camelCaseStrToHyphenated
333+ } ''ReferenceLocation)
334+
318335-- Update documentation in doc/filters.md if this is changed.
319336$(deriveJSON defaultOptions ''ReaderOptions)
320337
@@ -338,20 +355,3 @@ $(deriveJSON defaultOptions{ constructorTagModifier =
338355 } ''ObfuscationMethod)
339356
340357$(deriveJSON defaultOptions ''HTMLSlideVariant)
341−
342−-- Update documentation in doc/filters.md if this is changed.
343−$(deriveJSON defaultOptions{ constructorTagModifier =
344− camelCaseStrToHyphenated
345− } ''TrackChanges)
346−
347−$(deriveJSON defaultOptions{ constructorTagModifier =
348− camelCaseStrToHyphenated
349− } ''WrapOption)
350−
351−$(deriveJSON defaultOptions{ constructorTagModifier =
352− camelCaseStrToHyphenated . drop 8
353− } ''TopLevelDivision)
354−
355−$(deriveJSON defaultOptions{ constructorTagModifier =
356− camelCaseStrToHyphenated
357− } ''ReferenceLocation)
src/Text/Pandoc/PDF.hs+16−3
@@ -202,7 +202,7 @@ convertImage opts tmpdir fname = do
202202 Just "image/svg+xml" -> E.catch (do
203203 (exit, _) <- pipeProcess Nothing "rsvg-convert"
204204 ["-f","pdf","-a","--dpi-x",dpi,"--dpi-y",dpi,
205− "-o",pdfOut,fname] BL.empty
205+ "-o",pdfOut,svgIn] BL.empty
206206 if exit == ExitSuccess
207207 then return $ Right pdfOut
208208 else return $ Left "conversion from SVG failed")
@@ -217,6 +217,7 @@ convertImage opts tmpdir fname = do
217217 where
218218 pngOut = replaceDirectory (replaceExtension fname ".png") tmpdir
219219 pdfOut = replaceDirectory (replaceExtension fname ".pdf") tmpdir
220+ svgIn = tmpdir </> fname
220221 mime = getMimeType fname
221222 doNothing = return (Right fname)
222223
@@ -506,8 +507,20 @@ showVerboseInfo mbTmpDir program programArgs env source = do
506507 UTF8.hPutStrLn stderr $
507508 T.pack program <> " " <> T.pack (unwords (map show programArgs))
508509 UTF8.hPutStr stderr "\n"
509− UTF8.hPutStrLn stderr "[makePDF] Environment:"
510− mapM_ (UTF8.hPutStrLn stderr . tshow) env
510+ UTF8.hPutStrLn stderr "[makePDF] Relevant environment variables:"
511+ -- we filter out irrelevant stuff to avoid leaking passwords and keys!
512+ let isRelevant ("PATH",_) = True
513+ isRelevant ("TMPDIR",_) = True
514+ isRelevant ("PWD",_) = True
515+ isRelevant ("LANG",_) = True
516+ isRelevant ("HOME",_) = True
517+ isRelevant ("LUA_PATH",_) = True
518+ isRelevant ("LUA_CPATH",_) = True
519+ isRelevant ("SHELL",_) = True
520+ isRelevant ("TEXINPUTS",_) = True
521+ isRelevant ("TEXMFOUTPUT",_) = True
522+ isRelevant _ = False
523+ mapM_ (UTF8.hPutStrLn stderr . tshow) (filter isRelevant env)
511524 UTF8.hPutStr stderr "\n"
512525 UTF8.hPutStrLn stderr "[makePDF] Source:"
513526 UTF8.hPutStrLn stderr source
src/Text/Pandoc/Parsing.hs+360−242
@@ -5,7 +5,6 @@
55{-# LANGUAGE GeneralizedNewtypeDeriving #-}
66{-# LANGUAGE IncoherentInstances #-}
77{-# LANGUAGE MultiParamTypeClasses #-}
8−{-# LANGUAGE ViewPatterns #-}
98{-# LANGUAGE OverloadedStrings #-}
109{- |
1110 Module : Text.Pandoc.Parsing
@@ -19,8 +18,7 @@
1918A utility library with parsers used in pandoc readers.
2019-}
2120
22−module Text.Pandoc.Parsing ( take1WhileP,
23− takeP,
21+module Text.Pandoc.Parsing ( module Text.Pandoc.Sources,
2422 countChar,
2523 textStr,
2624 anyLine,
@@ -105,14 +103,14 @@ module Text.Pandoc.Parsing ( take1WhileP,
105103 singleQuoteEnd,
106104 doubleQuoteStart,
107105 doubleQuoteEnd,
108− ellipses,
109106 apostrophe,
107+ doubleCloseQuote,
108+ ellipses,
110109 dash,
111110 nested,
112111 citeKey,
113112 Parser,
114113 ParserT,
115− F,
116114 Future(..),
117115 runF,
118116 askF,
@@ -123,7 +121,6 @@ module Text.Pandoc.Parsing ( take1WhileP,
123121 (<+?>),
124122 extractIdClass,
125123 insertIncludedFile,
126− insertIncludedFileF,
127124 -- * Re-exports from Text.Parsec
128125 Stream,
129126 runParser,
@@ -134,22 +131,10 @@ module Text.Pandoc.Parsing ( take1WhileP,
134131 getInput,
135132 setInput,
136133 unexpected,
137− char,
138− letter,
139− digit,
140− alphaNum,
141134 skipMany,
142135 skipMany1,
143− spaces,
144− space,
145− anyChar,
146− satisfy,
147− newline,
148− string,
149136 count,
150137 eof,
151− noneOf,
152− oneOf,
153138 lookAhead,
154139 notFollowedBy,
155140 many,
@@ -174,6 +159,8 @@ module Text.Pandoc.Parsing ( take1WhileP,
174159 SourcePos,
175160 getPosition,
176161 setPosition,
162+ sourceName,
163+ setSourceName,
177164 sourceColumn,
178165 sourceLine,
179166 setSourceColumn,
@@ -189,48 +176,141 @@ module Text.Pandoc.Parsing ( take1WhileP,
189176where
190177
191178import Control.Monad.Identity
179+ ( guard,
180+ join,
181+ unless,
182+ when,
183+ void,
184+ liftM2,
185+ liftM,
186+ Identity(..),
187+ MonadPlus(mzero) )
192188import Control.Monad.Reader
189+ ( asks, runReader, MonadReader(ask), Reader, ReaderT(ReaderT) )
193190import Data.Char (chr, isAlphaNum, isAscii, isAsciiUpper, isAsciiLower,
194− isPunctuation, isSpace, ord, toLower, toUpper)
195−import Data.Default
191+ isSpace, ord, toLower, toUpper)
192+import Data.Default ( Default(..) )
196193import Data.Functor (($>))
197194import Data.List (intercalate, transpose)
198195import qualified Data.Map as M
199−import Data.Maybe (mapMaybe, fromMaybe)
196+import Data.Maybe (fromMaybe)
200197import qualified Data.Set as Set
201−import Data.String
202198import Data.Text (Text)
203199import qualified Data.Text as T
204200import Text.HTML.TagSoup.Entity (lookupEntity)
205−import Text.Pandoc.Asciify (toAsciiChar)
201+import Text.Pandoc.Asciify (toAsciiText)
206202import Text.Pandoc.Builder (Blocks, HasMeta (..), Inlines, trimInlines)
207203import qualified Text.Pandoc.Builder as B
208204import Text.Pandoc.Class.PandocMonad (PandocMonad, readFileFromDirs, report)
209205import Text.Pandoc.Definition
206+ ( Target,
207+ nullMeta,
208+ nullAttr,
209+ Meta,
210+ ColWidth(ColWidthDefault, ColWidth),
211+ TableFoot(TableFoot),
212+ TableBody(TableBody),
213+ Attr,
214+ TableHead(TableHead),
215+ Row(..),
216+ Alignment(..),
217+ Inline(Str),
218+ ListNumberDelim(..),
219+ ListAttributes,
220+ ListNumberStyle(..) )
210221import Text.Pandoc.Logging
222+ ( LogMessage(CouldNotLoadIncludeFile, DuplicateIdentifier) )
211223import Text.Pandoc.Options
224+ ( extensionEnabled,
225+ Extension(Ext_old_dashes, Ext_tex_math_dollars,
226+ Ext_tex_math_single_backslash, Ext_tex_math_double_backslash,
227+ Ext_auto_identifiers, Ext_ascii_identifiers, Ext_smart),
228+ ReaderOptions(readerTabStop, readerColumns, readerExtensions) )
212229import Text.Pandoc.Readers.LaTeX.Types (Macro)
213230import Text.Pandoc.Shared
231+ ( uniqueIdent,
232+ tshow,
233+ mapLeft,
234+ compactify,
235+ trim,
236+ trimr,
237+ splitTextByIndices,
238+ safeRead,
239+ trimMath,
240+ schemes,
241+ escapeURI )
242+import Text.Pandoc.Sources
214243import qualified Text.Pandoc.UTF8 as UTF8 (putStrLn)
215244import Text.Pandoc.XML (fromEntities)
216−import Text.Parsec hiding (token)
217−import Text.Parsec.Pos (initialPos, newPos, updatePosString)
218−
219−import Control.Monad.Except
245+import Text.Parsec
246+ ( between,
247+ setSourceName,
248+ Parsec,
249+ Column,
250+ Line,
251+ incSourceLine,
252+ incSourceColumn,
253+ setSourceLine,
254+ setSourceColumn,
255+ sourceLine,
256+ sourceColumn,
257+ sourceName,
258+ setSourceName,
259+ setPosition,
260+ getPosition,
261+ updateState,
262+ setState,
263+ getState,
264+ optionMaybe,
265+ optional,
266+ option,
267+ endBy1,
268+ endBy,
269+ sepEndBy1,
270+ sepEndBy,
271+ sepBy1,
272+ sepBy,
273+ try,
274+ choice,
275+ (<?>),
276+ (<|>),
277+ manyTill,
278+ many1,
279+ many,
280+ notFollowedBy,
281+ lookAhead,
282+ eof,
283+ count,
284+ skipMany1,
285+ skipMany,
286+ unexpected,
287+ setInput,
288+ getInput,
289+ anyToken,
290+ tokenPrim,
291+ parse,
292+ runParserT,
293+ runParser,
294+ ParseError,
295+ ParsecT,
296+ SourcePos,
297+ Stream(..) )
298+import Text.Parsec.Pos (initialPos, newPos)
299+import Control.Monad.Except ( MonadError(throwError) )
220300import Text.Pandoc.Error
301+ ( PandocError(PandocParseError, PandocParsecError) )
221302
222303type Parser t s = Parsec t s
223304
224305type ParserT = ParsecT
225306
307+
226308-- | Reader monad wrapping the parser state. This is used to possibly delay
227309-- evaluation until all relevant information has been parsed and made available
228310-- in the parser state.
229311newtype Future s a = Future { runDelayed :: Reader s a }
230312 deriving (Monad, Applicative, Functor)
231313
232−type F = Future ParserState
233−
234314runF :: Future s a -> s -> a
235315runF = runReader . runDelayed
236316
@@ -253,70 +333,48 @@ instance (Semigroup a, Monoid a) => Monoid (Future s a) where
253333 mappend = (<>)
254334
255335-- | Like @count@, but packs its result
256−countChar :: (Stream s m Char, Monad m)
336+countChar :: (Stream s m Char, UpdateSourcePos s Char, Monad m)
257337 => Int
258338 -> ParsecT s st m Char
259339 -> ParsecT s st m Text
260340countChar n = fmap T.pack . count n
261341
262342-- | Like @string@, but uses @Text@.
263−textStr :: Stream s m Char => Text -> ParsecT s u m Text
343+textStr :: (Stream s m Char, UpdateSourcePos s Char)
344+ => Text -> ParsecT s u m Text
264345textStr t = string (T.unpack t) $> t
265346
266−-- | Parse characters while a predicate is true.
267−take1WhileP :: Monad m
268− => (Char -> Bool)
269− -> ParserT Text st m Text
270−take1WhileP f = do
271− -- needed to persuade parsec that this won't match an empty string:
272− c <- satisfy f
273− inp <- getInput
274− pos <- getPosition
275− let (t, rest) = T.span f inp
276− setInput rest
277− setPosition $
278− if f '\t' || f '\n'
279− then updatePosString pos $ T.unpack t
280− else incSourceColumn pos (T.length t)
281− return $ T.singleton c <> t
282−
283−-- Parse n characters of input (or the rest of the input if
284−-- there aren't n characters).
285−takeP :: Monad m => Int -> ParserT Text st m Text
286−takeP n = do
287− guard (n > 0)
288− -- faster than 'count n anyChar'
289− inp <- getInput
290− pos <- getPosition
291− let (xs, rest) = T.splitAt n inp
292− -- needed to persuade parsec that this won't match an empty string:
293− anyChar
294− setInput rest
295− setPosition $ updatePosString pos $ T.unpack xs
296− return xs
297−
298−-- | Parse any line of text
299−anyLine :: Monad m => ParserT Text st m Text
347+
348+-- | Parse any line of text, returning the contents without the
349+-- final newline.
350+anyLine :: Monad m => ParserT Sources st m Text
300351anyLine = do
301352 -- This is much faster than:
302353 -- manyTill anyChar newline
303354 inp <- getInput
304− pos <- getPosition
305− case T.break (=='\n') inp of
306− (this, T.uncons -> Just ('\n', rest)) -> do
307− -- needed to persuade parsec that this won't match an empty string:
308− anyChar
309− setInput rest
310− setPosition $ incSourceLine (setSourceColumn pos 1) 1
311− return this
312− _ -> mzero
355+ case inp of
356+ Sources [] -> mzero
357+ Sources ((fp,t):inps) ->
358+ -- we assume that lines don't span different input files
359+ case T.break (=='\n') t of
360+ (this, rest)
361+ | T.null rest
362+ , not (null inps) ->
363+ -- line may span different input files, so do it
364+ -- character by character
365+ T.pack <$> manyTill anyChar newline
366+ | otherwise -> do -- either end of inputs or newline in rest
367+ setInput $ Sources ((fp, rest):inps)
368+ char '\n' -- needed so parsec knows we won't match empty string
369+ -- and so source pos is updated
370+ return this
313371
314372-- | Parse any line, include the final newline in the output
315−anyLineNewline :: Monad m => ParserT Text st m Text
373+anyLineNewline :: Monad m => ParserT Sources st m Text
316374anyLineNewline = (<> "\n") <$> anyLine
317375
318376-- | Parse indent by specified number of spaces (or equiv. tabs)
319−indentWith :: Stream s m Char
377+indentWith :: (Stream s m Char, UpdateSourcePos s Char)
320378 => HasReaderOptions st
321379 => Int -> ParserT s st m Text
322380indentWith num = do
@@ -401,11 +459,13 @@ notFollowedBy' p = try $ join $ do a <- try p
401459 return (return ())
402460-- (This version due to Andrew Pimlott on the Haskell mailing list.)
403461
404−oneOfStrings' :: Stream s m Char => (Char -> Char -> Bool) -> [Text] -> ParserT s st m Text
462+oneOfStrings' :: (Stream s m Char, UpdateSourcePos s Char)
463+ => (Char -> Char -> Bool) -> [Text] -> ParserT s st m Text
405464oneOfStrings' f = fmap T.pack . oneOfStrings'' f . fmap T.unpack
406465
407466-- TODO: This should be re-implemented in a Text-aware way
408−oneOfStrings'' :: Stream s m Char => (Char -> Char -> Bool) -> [String] -> ParserT s st m String
467+oneOfStrings'' :: (Stream s m Char, UpdateSourcePos s Char)
468+ => (Char -> Char -> Bool) -> [String] -> ParserT s st m String
409469oneOfStrings'' _ [] = Prelude.fail "no strings"
410470oneOfStrings'' matches strs = try $ do
411471 c <- anyChar
@@ -420,14 +480,16 @@ oneOfStrings'' matches strs = try $ do
420480-- | Parses one of a list of strings. If the list contains
421481-- two strings one of which is a prefix of the other, the longer
422482-- string will be matched if possible.
423−oneOfStrings :: Stream s m Char => [Text] -> ParserT s st m Text
483+oneOfStrings :: (Stream s m Char, UpdateSourcePos s Char)
484+ => [Text] -> ParserT s st m Text
424485oneOfStrings = oneOfStrings' (==)
425486
426487-- | Parses one of a list of strings (tried in order), case insensitive.
427488
428489-- TODO: This will not be accurate with general Unicode (neither
429490-- Text.toLower nor Text.toCaseFold can be implemented with a map)
430−oneOfStringsCI :: Stream s m Char => [Text] -> ParserT s st m Text
491+oneOfStringsCI :: (Stream s m Char, UpdateSourcePos s Char)
492+ => [Text] -> ParserT s st m Text
431493oneOfStringsCI = oneOfStrings' ciMatch
432494 where ciMatch x y = toLower' x == toLower' y
433495 -- this optimizes toLower by checking common ASCII case
@@ -438,11 +500,13 @@ oneOfStringsCI = oneOfStrings' ciMatch
438500 | otherwise = toLower c
439501
440502-- | Parses a space or tab.
441−spaceChar :: Stream s m Char => ParserT s st m Char
503+spaceChar :: (Stream s m Char, UpdateSourcePos s Char)
504+ => ParserT s st m Char
442505spaceChar = satisfy $ \c -> c == ' ' || c == '\t'
443506
444507-- | Parses a nonspace, nonnewline character.
445−nonspaceChar :: Stream s m Char => ParserT s st m Char
508+nonspaceChar :: (Stream s m Char, UpdateSourcePos s Char)
509+ => ParserT s st m Char
446510nonspaceChar = satisfy (not . isSpaceChar)
447511
448512isSpaceChar :: Char -> Bool
@@ -453,21 +517,24 @@ isSpaceChar '\r' = True
453517isSpaceChar _ = False
454518
455519-- | Skips zero or more spaces or tabs.
456−skipSpaces :: Stream s m Char => ParserT s st m ()
520+skipSpaces :: (Stream s m Char, UpdateSourcePos s Char)
521+ => ParserT s st m ()
457522skipSpaces = skipMany spaceChar
458523
459524-- | Skips zero or more spaces or tabs, then reads a newline.
460−blankline :: Stream s m Char => ParserT s st m Char
525+blankline :: (Stream s m Char, UpdateSourcePos s Char)
526+ => ParserT s st m Char
461527blankline = try $ skipSpaces >> newline
462528
463529-- | Parses one or more blank lines and returns a string of newlines.
464−blanklines :: Stream s m Char => ParserT s st m Text
530+blanklines :: (Stream s m Char, UpdateSourcePos s Char)
531+ => ParserT s st m Text
465532blanklines = T.pack <$> many1 blankline
466533
467534-- | Gobble n spaces; if tabs are encountered, expand them
468535-- and gobble some or all of their spaces, leaving the rest.
469536gobbleSpaces :: (HasReaderOptions st, Monad m)
470− => Int -> ParserT Text st m ()
537+ => Int -> ParserT Sources st m ()
471538gobbleSpaces 0 = return ()
472539gobbleSpaces n
473540 | n < 0 = error "gobbleSpaces called with negative number"
@@ -475,18 +542,26 @@ gobbleSpaces n
475542 char ' ' <|> eatOneSpaceOfTab
476543 gobbleSpaces (n - 1)
477544
478−eatOneSpaceOfTab :: (HasReaderOptions st, Monad m) => ParserT Text st m Char
545+eatOneSpaceOfTab :: (HasReaderOptions st, Monad m) => ParserT Sources st m Char
479546eatOneSpaceOfTab = do
480− char '\t'
547+ lookAhead (char '\t')
548+ pos <- getPosition
481549 tabstop <- getOption readerTabStop
550+ -- replace the tab on the input stream with spaces
551+ let numSpaces = tabstop - ((sourceColumn pos - 1) `mod` tabstop)
482552 inp <- getInput
483− setInput $ T.replicate (tabstop - 1) " " <> inp
484− return ' '
553+ setInput $
554+ case inp of
555+ Sources [] -> error "eatOneSpaceOfTab - empty Sources list"
556+ Sources ((fp,t):rest) ->
557+ -- drop the tab and add spaces
558+ Sources ((fp, T.replicate numSpaces " " <> T.drop 1 t):rest)
559+ char ' '
485560
486561-- | Gobble up to n spaces; if tabs are encountered, expand them
487562-- and gobble some or all of their spaces, leaving the rest.
488563gobbleAtMostSpaces :: (HasReaderOptions st, Monad m)
489− => Int -> ParserT Text st m Int
564+ => Int -> ParserT Sources st m Int
490565gobbleAtMostSpaces 0 = return 0
491566gobbleAtMostSpaces n
492567 | n < 0 = error "gobbleAtMostSpaces called with negative number"
@@ -495,7 +570,8 @@ gobbleAtMostSpaces n
495570 (+ 1) <$> gobbleAtMostSpaces (n - 1)
496571
497572-- | Parses material enclosed between start and end parsers.
498−enclosed :: (Show end, Stream s m Char) => ParserT s st m t -- ^ start parser
573+enclosed :: (Show end, Stream s m Char, UpdateSourcePos s Char)
574+ => ParserT s st m t -- ^ start parser
499575 -> ParserT s st m end -- ^ end parser
500576 -> ParserT s st m a -- ^ content parser (to be used repeatedly)
501577 -> ParserT s st m [a]
@@ -503,39 +579,41 @@ enclosed start end parser = try $
503579 start >> notFollowedBy space >> many1Till parser end
504580
505581-- | Parse string, case insensitive.
506−stringAnyCase :: Stream s m Char => Text -> ParserT s st m Text
582+stringAnyCase :: (Stream s m Char, UpdateSourcePos s Char)
583+ => Text -> ParserT s st m Text
507584stringAnyCase = fmap T.pack . stringAnyCase' . T.unpack
508585
509−stringAnyCase' :: Stream s m Char => String -> ParserT s st m String
586+stringAnyCase' :: (Stream s m Char, UpdateSourcePos s Char)
587+ => String -> ParserT s st m String
510588stringAnyCase' [] = string ""
511589stringAnyCase' (x:xs) = do
512590 firstChar <- char (toUpper x) <|> char (toLower x)
513591 rest <- stringAnyCase' xs
514592 return (firstChar:rest)
515593
594+-- TODO rewrite by just adding to Sources stream?
516595-- | Parse contents of 'str' using 'parser' and return result.
517−parseFromString :: (Stream s m Char, IsString s)
518− => ParserT s st m r
596+parseFromString :: Monad m
597+ => ParserT Sources st m r
519598 -> Text
520− -> ParserT s st m r
599+ -> ParserT Sources st m r
521600parseFromString parser str = do
522601 oldPos <- getPosition
523602 setPosition $ initialPos "chunk"
524603 oldInput <- getInput
525− setInput $ fromString $ T.unpack str
604+ setInput $ toSources str
526605 result <- parser
527606 spaces
528− eof
529607 setInput oldInput
530608 setPosition oldPos
531609 return result
532610
533611-- | Like 'parseFromString' but specialized for 'ParserState'.
534612-- This resets 'stateLastStrPos', which is almost always what we want.
535−parseFromString' :: (Stream s m Char, IsString s, HasLastStrPosition u)
536− => ParserT s u m a
613+parseFromString' :: (Monad m, HasLastStrPosition u)
614+ => ParserT Sources u m a
537615 -> Text
538− -> ParserT s u m a
616+ -> ParserT Sources u m a
539617parseFromString' parser str = do
540618 oldLastStrPos <- getLastStrPos <$> getState
541619 updateState $ setLastStrPos Nothing
@@ -544,7 +622,7 @@ parseFromString' parser str = do
544622 return res
545623
546624-- | Parse raw line block up to and including blank lines.
547−lineClump :: Monad m => ParserT Text st m Text
625+lineClump :: Monad m => ParserT Sources st m Text
548626lineClump = blanklines
549627 <|> (T.unlines <$> many1 (notFollowedBy blankline >> anyLine))
550628
@@ -553,7 +631,7 @@ lineClump = blanklines
553631-- pairs of open and close, which must be different. For example,
554632-- @charsInBalanced '(' ')' anyChar@ will parse "(hello (there))"
555633-- and return "hello (there)".
556−charsInBalanced :: Stream s m Char => Char -> Char -> ParserT s st m Char
634+charsInBalanced :: (Stream s m Char, UpdateSourcePos s Char) => Char -> Char -> ParserT s st m Char
557635 -> ParserT s st m Text
558636charsInBalanced open close parser = try $ do
559637 char open
@@ -572,7 +650,7 @@ charsInBalanced open close parser = try $ do
572650-- Auxiliary functions for romanNumeral:
573651
574652-- | Parses a roman numeral (uppercase or lowercase), returns number.
575−romanNumeral :: Stream s m Char => Bool -- ^ Uppercase if true
653+romanNumeral :: (Stream s m Char, UpdateSourcePos s Char) => Bool -- ^ Uppercase if true
576654 -> ParserT s st m Int
577655romanNumeral upperCase = do
578656 let rchar uc = char $ if upperCase then uc else toLower uc
@@ -608,20 +686,19 @@ romanNumeral upperCase = do
608686
609687-- | Parses an email address; returns original and corresponding
610688-- escaped mailto: URI.
611−emailAddress :: Stream s m Char => ParserT s st m (Text, Text)
689+emailAddress :: (Stream s m Char, UpdateSourcePos s Char) => ParserT s st m (Text, Text)
612690emailAddress = try $ toResult <$> mailbox <*> (char '@' *> domain)
613691 where toResult mbox dom = let full = fromEntities $ T.pack $ mbox ++ '@':dom
614692 in (full, escapeURI $ "mailto:" <> full)
615693 mailbox = intercalate "." <$> (emailWord `sepBy1'` dot)
616694 domain = intercalate "." <$> (subdomain `sepBy1'` dot)
617695 dot = char '.'
618− subdomain = many1 $ alphaNum <|> innerPunct
696+ subdomain = many1 $ alphaNum <|> innerPunct (=='-')
619697 -- this excludes some valid email addresses, since an
620698 -- email could contain e.g. '__', but gives better results
621699 -- for our purposes, when combined with markdown parsing:
622− innerPunct = try (satisfy (\c -> isEmailPunct c || c == '@')
623− <* notFollowedBy space
624− <* notFollowedBy (satisfy isPunctuation))
700+ innerPunct f = try (satisfy f
701+ <* notFollowedBy (satisfy (not . isAlphaNum)))
625702 -- technically an email address could begin with a symbol,
626703 -- but allowing this creates too many problems.
627704 -- See e.g. https://github.com/jgm/pandoc/issues/2940
@@ -632,11 +709,11 @@ emailAddress = try $ toResult <$> mailbox <*> (char '@' *> domain)
632709 isEmailPunct c = T.any (== c) "!\"#$%&'*+-/=?^_{|}~;"
633710
634711
635−uriScheme :: Stream s m Char => ParserT s st m Text
712+uriScheme :: (Stream s m Char, UpdateSourcePos s Char) => ParserT s st m Text
636713uriScheme = oneOfStringsCI (Set.toList schemes)
637714
638715-- | Parses a URI. Returns pair of original and URI-escaped version.
639−uri :: Stream s m Char => ParserT s st m (Text, Text)
716+uri :: (Stream s m Char, UpdateSourcePos s Char) => ParserT s st m (Text, Text)
640717uri = try $ do
641718 scheme <- uriScheme
642719 char ':'
@@ -679,7 +756,7 @@ uri = try $ do
679756 uriChunkBetween l r = try $ do chunk <- between (char l) (char r) uriChunk
680757 return (T.pack $ [l] ++ chunk ++ [r])
681758
682−mathInlineWith :: Stream s m Char => Text -> Text -> ParserT s st m Text
759+mathInlineWith :: (Stream s m Char, UpdateSourcePos s Char) => Text -> Text -> ParserT s st m Text
683760mathInlineWith op cl = try $ do
684761 textStr op
685762 when (op == "$") $ notFollowedBy space
@@ -700,10 +777,10 @@ mathInlineWith op cl = try $ do
700777 notFollowedBy digit -- to prevent capture of $5
701778 return $ trimMath $ T.concat words'
702779 where
703− inBalancedBraces :: Stream s m Char => Int -> Text -> ParserT s st m Text
780+ inBalancedBraces :: (Stream s m Char, UpdateSourcePos s Char) => Int -> Text -> ParserT s st m Text
704781 inBalancedBraces n = fmap T.pack . inBalancedBraces' n . T.unpack
705782
706− inBalancedBraces' :: Stream s m Char => Int -> String -> ParserT s st m String
783+ inBalancedBraces' :: (Stream s m Char, UpdateSourcePos s Char) => Int -> String -> ParserT s st m String
707784 inBalancedBraces' 0 "" = do
708785 c <- anyChar
709786 if c == '{'
@@ -720,13 +797,13 @@ mathInlineWith op cl = try $ do
720797 '{' -> inBalancedBraces' (numOpen + 1) (c:xs)
721798 _ -> inBalancedBraces' numOpen (c:xs)
722799
723−mathDisplayWith :: Stream s m Char => Text -> Text -> ParserT s st m Text
800+mathDisplayWith :: (Stream s m Char, UpdateSourcePos s Char) => Text -> Text -> ParserT s st m Text
724801mathDisplayWith op cl = try $ fmap T.pack $ do
725802 textStr op
726803 many1Till (satisfy (/= '\n') <|> (newline <* notFollowedBy' blankline))
727804 (try $ textStr cl)
728805
729−mathDisplay :: (HasReaderOptions st, Stream s m Char)
806+mathDisplay :: (HasReaderOptions st, Stream s m Char, UpdateSourcePos s Char)
730807 => ParserT s st m Text
731808mathDisplay =
732809 (guardEnabled Ext_tex_math_dollars >> mathDisplayWith "$$" "$$")
@@ -735,7 +812,7 @@ mathDisplay =
735812 <|> (guardEnabled Ext_tex_math_double_backslash >>
736813 mathDisplayWith "\\\\[" "\\\\]")
737814
738−mathInline :: (HasReaderOptions st , Stream s m Char)
815+mathInline :: (HasReaderOptions st, Stream s m Char, UpdateSourcePos s Char)
739816 => ParserT s st m Text
740817mathInline =
741818 (guardEnabled Ext_tex_math_dollars >> mathInlineWith "$" "$")
@@ -748,7 +825,7 @@ mathInline =
748825-- displacement (the difference between the source column at the end
749826-- and the source column at the beginning). Vertical displacement
750827-- (source row) is ignored.
751−withHorizDisplacement :: Stream s m Char
828+withHorizDisplacement :: (Stream s m Char, UpdateSourcePos s Char)
752829 => ParserT s st m a -- ^ Parser to apply
753830 -> ParserT s st m (a, Int) -- ^ (result, displacement)
754831withHorizDisplacement parser = do
@@ -760,30 +837,37 @@ withHorizDisplacement parser = do
760837-- | Applies a parser and returns the raw string that was parsed,
761838-- along with the value produced by the parser.
762839withRaw :: Monad m
763− => ParsecT Text st m a
764− -> ParsecT Text st m (a, Text)
840+ => ParsecT Sources st m a
841+ -> ParsecT Sources st m (a, Text)
765842withRaw parser = do
766− pos1 <- getPosition
767− inp <- getInput
843+ inps1 <- getInput
768844 result <- parser
769− pos2 <- getPosition
770− let (l1,c1) = (sourceLine pos1, sourceColumn pos1)
771− let (l2,c2) = (sourceLine pos2, sourceColumn pos2)
772− let inplines = take ((l2 - l1) + 1) $ T.lines inp
773− let raw = case inplines of
774− [] -> ""
775− [l] -> T.take (c2 - c1) l
776− ls -> T.unlines (init ls) <> T.take (c2 - 1) (last ls)
777− return (result, raw)
845+ inps2 <- getInput
846+ -- 'raw' is the difference between inps1 and inps2
847+ return (result, sourcesDifference inps1 inps2)
848+
849+sourcesDifference :: Sources -> Sources -> Text
850+sourcesDifference (Sources is1) (Sources is2) = go is1 is2
851+ where
852+ go inps1 inps2 =
853+ case (inps1, inps2) of
854+ ([], _) -> mempty
855+ (_, []) -> mconcat $ map snd inps1
856+ ((p1,t1):rest1, (p2, t2):rest2)
857+ | p1 == p2
858+ , t1 == t2 -> go rest1 rest2
859+ | p1 == p2
860+ , t1 /= t2 -> fromMaybe mempty $ T.stripSuffix t2 t1
861+ | otherwise -> t1 <> go rest1 inps2
778862
779863-- | Parses backslash, then applies character parser.
780−escaped :: Stream s m Char
864+escaped :: (Stream s m Char, UpdateSourcePos s Char)
781865 => ParserT s st m Char -- ^ Parser for character to escape
782866 -> ParserT s st m Char
783867escaped parser = try $ char '\\' >> parser
784868
785869-- | Parse character entity.
786−characterReference :: Stream s m Char => ParserT s st m Char
870+characterReference :: (Stream s m Char, UpdateSourcePos s Char) => ParserT s st m Char
787871characterReference = try $ do
788872 char '&'
789873 ent <- many1Till nonspaceChar (char ';')
@@ -796,19 +880,19 @@ characterReference = try $ do
796880 _ -> Prelude.fail "entity not found"
797881
798882-- | Parses an uppercase roman numeral and returns (UpperRoman, number).
799−upperRoman :: Stream s m Char => ParserT s st m (ListNumberStyle, Int)
883+upperRoman :: (Stream s m Char, UpdateSourcePos s Char) => ParserT s st m (ListNumberStyle, Int)
800884upperRoman = do
801885 num <- romanNumeral True
802886 return (UpperRoman, num)
803887
804888-- | Parses a lowercase roman numeral and returns (LowerRoman, number).
805−lowerRoman :: Stream s m Char => ParserT s st m (ListNumberStyle, Int)
889+lowerRoman :: (Stream s m Char, UpdateSourcePos s Char) => ParserT s st m (ListNumberStyle, Int)
806890lowerRoman = do
807891 num <- romanNumeral False
808892 return (LowerRoman, num)
809893
810894-- | Parses a decimal numeral and returns (Decimal, number).
811−decimal :: Stream s m Char => ParserT s st m (ListNumberStyle, Int)
895+decimal :: (Stream s m Char, UpdateSourcePos s Char) => ParserT s st m (ListNumberStyle, Int)
812896decimal = do
813897 num <- many1 digit
814898 return (Decimal, fromMaybe 1 $ safeRead $ T.pack num)
@@ -817,7 +901,7 @@ decimal = do
817901-- returns (DefaultStyle, [next example number]). The next
818902-- example number is incremented in parser state, and the label
819903-- (if present) is added to the label table.
820−exampleNum :: Stream s m Char
904+exampleNum :: (Stream s m Char, UpdateSourcePos s Char)
821905 => ParserT s ParserState m (ListNumberStyle, Int)
822906exampleNum = do
823907 char '@'
@@ -836,37 +920,37 @@ exampleNum = do
836920 return (Example, num)
837921
838922-- | Parses a '#' returns (DefaultStyle, 1).
839−defaultNum :: Stream s m Char => ParserT s st m (ListNumberStyle, Int)
923+defaultNum :: (Stream s m Char, UpdateSourcePos s Char) => ParserT s st m (ListNumberStyle, Int)
840924defaultNum = do
841925 char '#'
842926 return (DefaultStyle, 1)
843927
844928-- | Parses a lowercase letter and returns (LowerAlpha, number).
845−lowerAlpha :: Stream s m Char => ParserT s st m (ListNumberStyle, Int)
929+lowerAlpha :: (Stream s m Char, UpdateSourcePos s Char) => ParserT s st m (ListNumberStyle, Int)
846930lowerAlpha = do
847931 ch <- satisfy isAsciiLower
848932 return (LowerAlpha, ord ch - ord 'a' + 1)
849933
850934-- | Parses an uppercase letter and returns (UpperAlpha, number).
851−upperAlpha :: Stream s m Char => ParserT s st m (ListNumberStyle, Int)
935+upperAlpha :: (Stream s m Char, UpdateSourcePos s Char) => ParserT s st m (ListNumberStyle, Int)
852936upperAlpha = do
853937 ch <- satisfy isAsciiUpper
854938 return (UpperAlpha, ord ch - ord 'A' + 1)
855939
856940-- | Parses a roman numeral i or I
857−romanOne :: Stream s m Char => ParserT s st m (ListNumberStyle, Int)
941+romanOne :: (Stream s m Char, UpdateSourcePos s Char) => ParserT s st m (ListNumberStyle, Int)
858942romanOne = (char 'i' >> return (LowerRoman, 1)) <|>
859943 (char 'I' >> return (UpperRoman, 1))
860944
861945-- | Parses an ordered list marker and returns list attributes.
862−anyOrderedListMarker :: Stream s m Char => ParserT s ParserState m ListAttributes
946+anyOrderedListMarker :: (Stream s m Char, UpdateSourcePos s Char) => ParserT s ParserState m ListAttributes
863947anyOrderedListMarker = choice
864948 [delimParser numParser | delimParser <- [inPeriod, inOneParen, inTwoParens],
865949 numParser <- [decimal, exampleNum, defaultNum, romanOne,
866950 lowerAlpha, lowerRoman, upperAlpha, upperRoman]]
867951
868952-- | Parses a list number (num) followed by a period, returns list attributes.
869−inPeriod :: Stream s m Char
953+inPeriod :: (Stream s m Char, UpdateSourcePos s Char)
870954 => ParserT s st m (ListNumberStyle, Int)
871955 -> ParserT s st m ListAttributes
872956inPeriod num = try $ do
@@ -878,7 +962,7 @@ inPeriod num = try $ do
878962 return (start, style, delim)
879963
880964-- | Parses a list number (num) followed by a paren, returns list attributes.
881−inOneParen :: Stream s m Char
965+inOneParen :: (Stream s m Char, UpdateSourcePos s Char)
882966 => ParserT s st m (ListNumberStyle, Int)
883967 -> ParserT s st m ListAttributes
884968inOneParen num = try $ do
@@ -887,7 +971,7 @@ inOneParen num = try $ do
887971 return (start, style, OneParen)
888972
889973-- | Parses a list number (num) enclosed in parens, returns list attributes.
890−inTwoParens :: Stream s m Char
974+inTwoParens :: (Stream s m Char, UpdateSourcePos s Char)
891975 => ParserT s st m (ListNumberStyle, Int)
892976 -> ParserT s st m ListAttributes
893977inTwoParens num = try $ do
@@ -898,7 +982,7 @@ inTwoParens num = try $ do
898982
899983-- | Parses an ordered list marker with a given style and delimiter,
900984-- returns number.
901−orderedListMarker :: Stream s m Char
985+orderedListMarker :: (Stream s m Char, UpdateSourcePos s Char)
902986 => ListNumberStyle
903987 -> ListNumberDelim
904988 -> ParserT s ParserState m Int
@@ -921,10 +1005,10 @@ orderedListMarker style delim = do
9211005 return start
9221006
9231007-- | Parses a character reference and returns a Str element.
924−charRef :: Stream s m Char => ParserT s st m Inline
1008+charRef :: (Stream s m Char, UpdateSourcePos s Char) => ParserT s st m Inline
9251009charRef = Str . T.singleton <$> characterReference
9261010
927−lineBlockLine :: Monad m => ParserT Text st m Text
1011+lineBlockLine :: Monad m => ParserT Sources st m Text
9281012lineBlockLine = try $ do
9291013 char '|'
9301014 char ' '
@@ -934,11 +1018,11 @@ lineBlockLine = try $ do
9341018 continuations <- many (try $ char ' ' >> anyLine)
9351019 return $ white <> T.unwords (line : continuations)
9361020
937−blankLineBlockLine :: Stream s m Char => ParserT s st m Char
1021+blankLineBlockLine :: (Stream s m Char, UpdateSourcePos s Char) => ParserT s st m Char
9381022blankLineBlockLine = try (char '|' >> blankline)
9391023
9401024-- | Parses an RST-style line block and returns a list of strings.
941−lineBlockLines :: Monad m => ParserT Text st m [Text]
1025+lineBlockLines :: Monad m => ParserT Sources st m [Text]
9421026lineBlockLines = try $ do
9431027 lines' <- many1 (lineBlockLine <|> (T.singleton <$> blankLineBlockLine))
9441028 skipMany blankline
@@ -946,7 +1030,8 @@ lineBlockLines = try $ do
9461030
9471031-- | Parse a table using 'headerParser', 'rowParser',
9481032-- 'lineParser', and 'footerParser'.
949−tableWith :: (Stream s m Char, HasReaderOptions st, Monad mf)
1033+tableWith :: (Stream s m Char, UpdateSourcePos s Char,
1034+ HasReaderOptions st, Monad mf)
9501035 => ParserT s st m (mf [Blocks], [Alignment], [Int])
9511036 -> ([Int] -> ParserT s st m (mf [Blocks]))
9521037 -> ParserT s st m sep
@@ -966,7 +1051,8 @@ tableWith headerParser rowParser lineParser footerParser = try $ do
9661051
9671052type TableComponents mf = ([Alignment], [Double], mf [Row], mf [Row])
9681053
969−tableWith' :: (Stream s m Char, HasReaderOptions st, Monad mf)
1054+tableWith' :: (Stream s m Char, UpdateSourcePos s Char,
1055+ HasReaderOptions st, Monad mf)
9701056 => ParserT s st m (mf [Blocks], [Alignment], [Int])
9711057 -> ([Int] -> ParserT s st m (mf [Blocks]))
9721058 -> ParserT s st m sep
@@ -1015,20 +1101,19 @@ widthsFromIndices numColumns' indices =
10151101-- (which may be grid), then the rows,
10161102-- which may be grid, separated by blank lines, and
10171103-- ending with a footer (dashed line followed by blank line).
1018−gridTableWith :: (Stream s m Char, HasReaderOptions st, HasLastStrPosition st,
1019− Monad mf, IsString s)
1020− => ParserT s st m (mf Blocks) -- ^ Block list parser
1104+gridTableWith :: (Monad m, HasReaderOptions st, HasLastStrPosition st, Monad mf)
1105+ => ParserT Sources st m (mf Blocks) -- ^ Block list parser
10211106 -> Bool -- ^ Headerless table
1022− -> ParserT s st m (mf Blocks)
1107+ -> ParserT Sources st m (mf Blocks)
10231108gridTableWith blocks headless =
10241109 tableWith (gridTableHeader headless blocks) (gridTableRow blocks)
10251110 (gridTableSep '-') gridTableFooter
10261111
1027−gridTableWith' :: (Stream s m Char, HasReaderOptions st, HasLastStrPosition st,
1028− Monad mf, IsString s)
1029− => ParserT s st m (mf Blocks) -- ^ Block list parser
1112+gridTableWith' :: (Monad m, HasReaderOptions st, HasLastStrPosition st,
1113+ Monad mf)
1114+ => ParserT Sources st m (mf Blocks) -- ^ Block list parser
10301115 -> Bool -- ^ Headerless table
1031− -> ParserT s st m (TableComponents mf)
1116+ -> ParserT Sources st m (TableComponents mf)
10321117gridTableWith' blocks headless =
10331118 tableWith' (gridTableHeader headless blocks) (gridTableRow blocks)
10341119 (gridTableSep '-') gridTableFooter
@@ -1037,7 +1122,7 @@ gridTableSplitLine :: [Int] -> Text -> [Text]
10371122gridTableSplitLine indices line = map removeFinalBar $ tail $
10381123 splitTextByIndices (init indices) $ trimr line
10391124
1040−gridPart :: Stream s m Char => Char -> ParserT s st m ((Int, Int), Alignment)
1125+gridPart :: Monad m => Char -> ParserT Sources st m ((Int, Int), Alignment)
10411126gridPart ch = do
10421127 leftColon <- option False (True <$ char ':')
10431128 dashes <- many1 (char ch)
@@ -1052,7 +1137,7 @@ gridPart ch = do
10521137 (False, False) -> AlignDefault
10531138 return ((lengthDashes, lengthDashes + 1), alignment)
10541139
1055−gridDashedLines :: Stream s m Char => Char -> ParserT s st m [((Int, Int), Alignment)]
1140+gridDashedLines :: Monad m => Char -> ParserT Sources st m [((Int, Int), Alignment)]
10561141gridDashedLines ch = try $ char '+' >> many1 (gridPart ch) <* blankline
10571142
10581143removeFinalBar :: Text -> Text
@@ -1061,14 +1146,14 @@ removeFinalBar = T.dropWhileEnd go . T.dropWhileEnd (=='|')
10611146 go c = T.any (== c) " \t"
10621147
10631148-- | Separator between rows of grid table.
1064−gridTableSep :: Stream s m Char => Char -> ParserT s st m Char
1149+gridTableSep :: Monad m => Char -> ParserT Sources st m Char
10651150gridTableSep ch = try $ gridDashedLines ch >> return '\n'
10661151
10671152-- | Parse header for a grid table.
1068−gridTableHeader :: (Stream s m Char, Monad mf, IsString s, HasLastStrPosition st)
1153+gridTableHeader :: (Monad m, Monad mf, HasLastStrPosition st)
10691154 => Bool -- ^ Headerless table
1070− -> ParserT s st m (mf Blocks)
1071− -> ParserT s st m (mf [Blocks], [Alignment], [Int])
1155+ -> ParserT Sources st m (mf Blocks)
1156+ -> ParserT Sources st m (mf [Blocks], [Alignment], [Int])
10721157gridTableHeader True _ = do
10731158 optional blanklines
10741159 dashes <- gridDashedLines '-'
@@ -1091,17 +1176,17 @@ gridTableHeader False blocks = try $ do
10911176 heads <- sequence <$> mapM (parseFromString' blocks . trim) rawHeads
10921177 return (heads, aligns, indices)
10931178
1094−gridTableRawLine :: Stream s m Char => [Int] -> ParserT s st m [Text]
1179+gridTableRawLine :: (Stream s m Char, UpdateSourcePos s Char) => [Int] -> ParserT s st m [Text]
10951180gridTableRawLine indices = do
10961181 char '|'
10971182 line <- many1Till anyChar newline
10981183 return (gridTableSplitLine indices $ T.pack line)
10991184
11001185-- | Parse row of grid table.
1101−gridTableRow :: (Stream s m Char, Monad mf, IsString s, HasLastStrPosition st)
1102− => ParserT s st m (mf Blocks)
1186+gridTableRow :: (Monad m, Monad mf, HasLastStrPosition st)
1187+ => ParserT Sources st m (mf Blocks)
11031188 -> [Int]
1104− -> ParserT s st m (mf [Blocks])
1189+ -> ParserT Sources st m (mf [Blocks])
11051190gridTableRow blocks indices = do
11061191 colLines <- many1 (gridTableRawLine indices)
11071192 let cols = map ((<> "\n") . T.unlines . removeOneLeadingSpace) $
@@ -1122,34 +1207,38 @@ removeOneLeadingSpace xs =
11221207 Just (c, _) -> c == ' '
11231208
11241209-- | Parse footer for a grid table.
1125−gridTableFooter :: Stream s m Char => ParserT s st m ()
1210+gridTableFooter :: (Stream s m Char, UpdateSourcePos s Char) => ParserT s st m ()
11261211gridTableFooter = optional blanklines
11271212
11281213---
11291214
11301215-- | Removes the ParsecT layer from the monad transformer stack
1131−readWithM :: (Stream s m Char, ToText s)
1132− => ParserT s st m a -- ^ parser
1133− -> st -- ^ initial state
1134− -> s -- ^ input
1216+readWithM :: (Monad m, ToSources t)
1217+ => ParserT Sources st m a -- ^ parser
1218+ -> st -- ^ initial state
1219+ -> t -- ^ input
11351220 -> m (Either PandocError a)
11361221readWithM parser state input =
1137− mapLeft (PandocParsecError $ toText input) `liftM` runParserT parser state "source" input
1222+ mapLeft (PandocParsecError sources)
1223+ <$> runParserT parser state (initialSourceName sources) sources
1224+ where
1225+ sources = toSources input
11381226
11391227-- | Parse a string with a given parser and state
1140−readWith :: Parser Text st a
1228+readWith :: ToSources t
1229+ => Parser Sources st a
11411230 -> st
1142− -> Text
1231+ -> t
11431232 -> Either PandocError a
11441233readWith p t inp = runIdentity $ readWithM p t inp
11451234
11461235-- | Parse a string with @parser@ (for testing).
11471236testStringWith :: Show a
1148− => ParserT Text ParserState Identity a
1237+ => ParserT Sources ParserState Identity a
11491238 -> Text
11501239 -> IO ()
11511240testStringWith parser str = UTF8.putStrLn $ tshow $
1152− readWith parser defaultParserState str
1241+ readWith parser defaultParserState (toSources str)
11531242
11541243-- | Parsing options.
11551244data ParserState = ParserState
@@ -1169,7 +1258,7 @@ data ParserState = ParserState
11691258 stateInNote :: Bool, -- ^ True if parsing note contents
11701259 stateNoteNumber :: Int, -- ^ Last note number for citations
11711260 stateMeta :: Meta, -- ^ Document metadata
1172− stateMeta' :: F Meta, -- ^ Document metadata
1261+ stateMeta' :: Future ParserState Meta, -- ^ Document metadata
11731262 stateCitations :: M.Map Text Text, -- ^ RST-style citations
11741263 stateHeaderTable :: [HeaderType], -- ^ Ordered list of header types used
11751264 stateIdentifiers :: Set.Set Text, -- ^ Header identifiers used
@@ -1348,7 +1437,7 @@ data QuoteContext
13481437
13491438type NoteTable = [(Text, Text)]
13501439
1351−type NoteTable' = M.Map Text (SourcePos, F Blocks)
1440+type NoteTable' = M.Map Text (SourcePos, Future ParserState Blocks)
13521441-- used in markdown reader
13531442
13541443newtype Key = Key Text deriving (Show, Read, Eq, Ord)
@@ -1383,7 +1472,7 @@ registerHeader (ident,classes,kvs) header' = do
13831472 then do
13841473 let id' = uniqueIdent exts (B.toList header') ids
13851474 let id'' = if Ext_ascii_identifiers `extensionEnabled` exts
1386− then T.pack $ mapMaybe toAsciiChar $ T.unpack id'
1475+ then toAsciiText id'
13871476 else id'
13881477 updateState $ updateIdentifierList $ Set.insert id'
13891478 updateState $ updateIdentifierList $ Set.insert id''
@@ -1396,34 +1485,42 @@ registerHeader (ident,classes,kvs) header' = do
13961485 updateState $ updateIdentifierList $ Set.insert ident
13971486 return (ident,classes,kvs)
13981487
1399−smartPunctuation :: (HasReaderOptions st, HasLastStrPosition st, HasQuoteContext st m, Stream s m Char)
1488+smartPunctuation :: (HasReaderOptions st, HasLastStrPosition st,
1489+ HasQuoteContext st m,
1490+ Stream s m Char, UpdateSourcePos s Char)
14001491 => ParserT s st m Inlines
14011492 -> ParserT s st m Inlines
14021493smartPunctuation inlineParser = do
14031494 guardEnabled Ext_smart
1404− choice [ quoted inlineParser, apostrophe, dash, ellipses ]
1495+ choice [ quoted inlineParser, apostrophe, doubleCloseQuote, dash, ellipses ]
14051496
1406−apostrophe :: Stream s m Char => ParserT s st m Inlines
1407−apostrophe = (char '\'' <|> char '\8217') >> return (B.str "\x2019")
1408−
1409−quoted :: (HasLastStrPosition st, HasQuoteContext st m, Stream s m Char)
1497+quoted :: (HasLastStrPosition st, HasQuoteContext st m,
1498+ Stream s m Char, UpdateSourcePos s Char)
14101499 => ParserT s st m Inlines
14111500 -> ParserT s st m Inlines
14121501quoted inlineParser = doubleQuoted inlineParser <|> singleQuoted inlineParser
14131502
1414−singleQuoted :: (HasLastStrPosition st, HasQuoteContext st m, Stream s m Char)
1503+singleQuoted :: (HasLastStrPosition st, HasQuoteContext st m,
1504+ Stream s m Char, UpdateSourcePos s Char)
14151505 => ParserT s st m Inlines
14161506 -> ParserT s st m Inlines
1417−singleQuoted inlineParser = try $ B.singleQuoted . mconcat
1418− <$ singleQuoteStart
1419− <*> withQuoteContext InSingleQuote (many1Till inlineParser singleQuoteEnd)
1420−
1421−doubleQuoted :: (HasQuoteContext st m, Stream s m Char)
1507+singleQuoted inlineParser = do
1508+ singleQuoteStart
1509+ (B.singleQuoted . mconcat <$>
1510+ try
1511+ (withQuoteContext InSingleQuote (many1Till inlineParser singleQuoteEnd)))
1512+ <|> pure "\8217"
1513+
1514+doubleQuoted :: (HasQuoteContext st m, HasLastStrPosition st,
1515+ Stream s m Char, UpdateSourcePos s Char)
14221516 => ParserT s st m Inlines
14231517 -> ParserT s st m Inlines
1424−doubleQuoted inlineParser = try $ B.doubleQuoted . mconcat
1425− <$ doubleQuoteStart
1426− <*> withQuoteContext InDoubleQuote (manyTill inlineParser doubleQuoteEnd)
1518+doubleQuoted inlineParser = do
1519+ doubleQuoteStart
1520+ (B.doubleQuoted . mconcat <$>
1521+ try
1522+ (withQuoteContext InDoubleQuote (manyTill inlineParser doubleQuoteEnd)))
1523+ <|> pure (B.str "\8220")
14271524
14281525failIfInQuoteContext :: (HasQuoteContext st m, Stream s m t)
14291526 => QuoteContext
@@ -1432,13 +1529,14 @@ failIfInQuoteContext context = do
14321529 context' <- getQuoteContext
14331530 when (context' == context) $ Prelude.fail "already inside quotes"
14341531
1435−charOrRef :: Stream s m Char => [Char] -> ParserT s st m Char
1532+charOrRef :: (Stream s m Char, UpdateSourcePos s Char) => [Char] -> ParserT s st m Char
14361533charOrRef cs =
14371534 oneOf cs <|> try (do c <- characterReference
14381535 guard (c `elem` cs)
14391536 return c)
14401537
1441−singleQuoteStart :: (HasLastStrPosition st, HasQuoteContext st m, Stream s m Char)
1538+singleQuoteStart :: (HasLastStrPosition st, HasQuoteContext st m,
1539+ Stream s m Char, UpdateSourcePos s Char)
14421540 => ParserT s st m ()
14431541singleQuoteStart = do
14441542 failIfInQuoteContext InSingleQuote
@@ -1446,30 +1544,39 @@ singleQuoteStart = do
14461544 guard =<< notAfterString
14471545 try $ do
14481546 charOrRef "'\8216\145"
1449− notFollowedBy (oneOf [' ', '\t', '\n'])
1547+ void $ lookAhead (satisfy (not . isSpaceChar))
14501548
1451−singleQuoteEnd :: Stream s m Char
1549+singleQuoteEnd :: (Stream s m Char, UpdateSourcePos s Char)
14521550 => ParserT s st m ()
14531551singleQuoteEnd = try $ do
14541552 charOrRef "'\8217\146"
14551553 notFollowedBy alphaNum
14561554
1457−doubleQuoteStart :: (HasQuoteContext st m, Stream s m Char)
1555+doubleQuoteStart :: (HasLastStrPosition st,
1556+ HasQuoteContext st m,
1557+ Stream s m Char, UpdateSourcePos s Char)
14581558 => ParserT s st m ()
14591559doubleQuoteStart = do
14601560 failIfInQuoteContext InDoubleQuote
1561+ guard =<< notAfterString
14611562 try $ do charOrRef "\"\8220\147"
1462− notFollowedBy (oneOf [' ', '\t', '\n'])
1563+ void $ lookAhead (satisfy (not . isSpaceChar))
14631564
1464−doubleQuoteEnd :: Stream s m Char
1565+doubleQuoteEnd :: (Stream s m Char, UpdateSourcePos s Char)
14651566 => ParserT s st m ()
14661567doubleQuoteEnd = void (charOrRef "\"\8221\148")
14671568
1468−ellipses :: Stream s m Char
1569+apostrophe :: (Stream s m Char, UpdateSourcePos s Char) => ParserT s st m Inlines
1570+apostrophe = (char '\'' <|> char '\8217') >> return (B.str "\8217")
1571+
1572+doubleCloseQuote :: (Stream s m Char, UpdateSourcePos s Char) => ParserT s st m Inlines
1573+doubleCloseQuote = B.str "\8221" <$ char '"'
1574+
1575+ellipses :: (Stream s m Char, UpdateSourcePos s Char)
14691576 => ParserT s st m Inlines
14701577ellipses = try (string "..." >> return (B.str "\8230"))
14711578
1472−dash :: (HasReaderOptions st, Stream s m Char)
1579+dash :: (HasReaderOptions st, Stream s m Char, UpdateSourcePos s Char)
14731580 => ParserT s st m Inlines
14741581dash = try $ do
14751582 oldDashes <- extensionEnabled Ext_old_dashes <$> getOption readerExtensions
@@ -1496,20 +1603,28 @@ nested p = do
14961603 updateState $ \st -> st{ stateMaxNestingLevel = nestlevel }
14971604 return res
14981605
1499−citeKey :: (Stream s m Char, HasLastStrPosition st)
1500− => ParserT s st m (Bool, Text)
1501−citeKey = try $ do
1606+citeKey :: (Stream s m Char, UpdateSourcePos s Char, HasLastStrPosition st)
1607+ => Bool -- ^ If True, allow expanded @{..} syntax.
1608+ -> ParserT s st m (Bool, Text)
1609+citeKey allowBraced = try $ do
15021610 guard =<< notAfterString
15031611 suppress_author <- option False (True <$ char '-')
15041612 char '@'
1613+ key <- simpleCiteIdentifier
1614+ <|> if allowBraced
1615+ then charsInBalanced '{' '}' (satisfy (not . isSpace))
1616+ else mzero
1617+ return (suppress_author, key)
1618+
1619+simpleCiteIdentifier :: (Stream s m Char, UpdateSourcePos s Char)
1620+ => ParserT s st m Text
1621+simpleCiteIdentifier = do
15051622 firstChar <- alphaNum <|> char '_' <|> char '*' -- @* for wildcard in nocite
15061623 let regchar = satisfy (\c -> isAlphaNum c || c == '_')
15071624 let internal p = try $ p <* lookAhead regchar
15081625 rest <- many $ regchar <|> internal (oneOf ":.#$%&-+?<>~/") <|>
15091626 try (oneOf ":/" <* lookAhead (char '/'))
1510− let key = firstChar:rest
1511− return (suppress_author, T.pack key)
1512−
1627+ return $ T.pack $ firstChar:rest
15131628
15141629token :: (Stream s m t)
15151630 => (t -> Text)
@@ -1529,12 +1644,15 @@ extractIdClass (ident, cls, kvs) = (ident', cls', kvs')
15291644 cls' = maybe cls T.words $ lookup "class" kvs
15301645 kvs' = filter (\(k,_) -> k /= "id" || k /= "class") kvs
15311646
1532−insertIncludedFile' :: (PandocMonad m, HasIncludeFiles st)
1533− => ParserT a st m (mf Blocks)
1534− -> (Text -> a)
1535− -> [FilePath] -> FilePath
1536− -> ParserT a st m (mf Blocks)
1537−insertIncludedFile' blocks totoks dirs f = do
1647+insertIncludedFile :: (PandocMonad m, HasIncludeFiles st)
1648+ => ParserT a st m b -- ^ parser to apply
1649+ -> (Text -> a) -- ^ convert Text to stream type
1650+ -> [FilePath] -- ^ search path (directories)
1651+ -> FilePath -- ^ path of file to include
1652+ -> Maybe Int -- ^ start line (negative counts from end)
1653+ -> Maybe Int -- ^ end line (negative counts from end)
1654+ -> ParserT a st m b
1655+insertIncludedFile parser toStream dirs f mbstartline mbendline = do
15381656 oldPos <- getPosition
15391657 oldInput <- getInput
15401658 containers <- getIncludeFiles <$> getState
@@ -1543,32 +1661,32 @@ insertIncludedFile' blocks totoks dirs f = do
15431661 updateState $ addIncludeFile $ T.pack f
15441662 mbcontents <- readFileFromDirs dirs f
15451663 contents <- case mbcontents of
1546− Just s -> return s
1664+ Just s -> return $ exciseLines mbstartline mbendline s
15471665 Nothing -> do
15481666 report $ CouldNotLoadIncludeFile (T.pack f) oldPos
15491667 return ""
1550− setPosition $ newPos f 1 1
1551− setInput $ totoks contents
1552− bs <- blocks
1668+ setInput $ toStream contents
1669+ setPosition $ newPos f (fromMaybe 1 mbstartline) 1
1670+ result <- parser
15531671 setInput oldInput
15541672 setPosition oldPos
15551673 updateState dropLatestIncludeFile
1556− return bs
1674+ return result
1675+
1676+exciseLines :: Maybe Int -> Maybe Int -> Text -> Text
1677+exciseLines Nothing Nothing t = t
1678+exciseLines mbstartline mbendline t =
1679+ T.unlines $ take (endline' - (startline' - 1))
1680+ $ drop (startline' - 1) contentLines
1681+ where
1682+ contentLines = T.lines t
1683+ numLines = length contentLines
1684+ startline' = case mbstartline of
1685+ Nothing -> 1
1686+ Just x | x >= 0 -> x
1687+ | otherwise -> numLines + x -- negative from end
1688+ endline' = case mbendline of
1689+ Nothing -> numLines
1690+ Just x | x >= 0 -> x
1691+ | otherwise -> numLines + x -- negative from end
15571692
1558−-- | Parse content of include file as blocks. Circular includes result in an
1559−-- @PandocParseError@.
1560−insertIncludedFile :: (PandocMonad m, HasIncludeFiles st)
1561− => ParserT [a] st m Blocks
1562− -> (Text -> [a])
1563− -> [FilePath] -> FilePath
1564− -> ParserT [a] st m Blocks
1565−insertIncludedFile blocks totoks dirs f =
1566− runIdentity <$> insertIncludedFile' (Identity <$> blocks) totoks dirs f
1567−
1568−-- | Parse content of include file as future blocks. Circular includes result in
1569−-- an @PandocParseError@.
1570−insertIncludedFileF :: (PandocMonad m, HasIncludeFiles st)
1571− => ParserT Text st m (Future st Blocks)
1572− -> [FilePath] -> FilePath
1573− -> ParserT Text st m (Future st Blocks)
1574−insertIncludedFileF p = insertIncludedFile' p id
src/Text/Pandoc/Readers.hs+55−48
@@ -1,4 +1,5 @@
11{-# LANGUAGE MonoLocalBinds #-}
2+{-# LANGUAGE RankNTypes #-}
23{-# LANGUAGE ScopedTypeVariables #-}
34{-# LANGUAGE OverloadedStrings #-}
45{- |
@@ -65,12 +66,14 @@ import Data.Aeson
6566import qualified Data.ByteString.Lazy as BL
6667import Data.Text (Text)
6768import qualified Data.Text as T
69+import Text.Pandoc.Shared (tshow)
6870import Text.Pandoc.Class
6971import Text.Pandoc.Definition
7072import Text.Pandoc.Error
7173import Text.Pandoc.Extensions
7274import Text.Pandoc.Options
7375import Text.Pandoc.Readers.CommonMark
76+import Text.Pandoc.Readers.Markdown
7477import Text.Pandoc.Readers.Creole
7578import Text.Pandoc.Readers.DocBook
7679import Text.Pandoc.Readers.Docx
@@ -83,7 +86,6 @@ import Text.Pandoc.Readers.HTML (readHtml)
8386import Text.Pandoc.Readers.JATS (readJATS)
8487import Text.Pandoc.Readers.Jira (readJira)
8588import Text.Pandoc.Readers.LaTeX
86−import Text.Pandoc.Readers.Markdown
8789import Text.Pandoc.Readers.MediaWiki
8890import Text.Pandoc.Readers.Muse
8991import Text.Pandoc.Readers.Native
@@ -101,59 +103,60 @@ import Text.Pandoc.Readers.CSV
101103import Text.Pandoc.Readers.CslJson
102104import Text.Pandoc.Readers.BibTeX
103105import qualified Text.Pandoc.UTF8 as UTF8
104−import Text.Parsec.Error
106+import Text.Pandoc.Sources (ToSources(..), sourcesToText)
105107
106−data Reader m = TextReader (ReaderOptions -> Text -> m Pandoc)
108+data Reader m = TextReader (forall a . ToSources a =>
109+ ReaderOptions -> a -> m Pandoc)
107110 | ByteStringReader (ReaderOptions -> BL.ByteString -> m Pandoc)
108111
109112-- | Association list of formats and readers.
110113readers :: PandocMonad m => [(Text, Reader m)]
111−readers = [ ("native" , TextReader readNative)
112− ,("json" , TextReader readJSON)
113− ,("markdown" , TextReader readMarkdown)
114− ,("markdown_strict" , TextReader readMarkdown)
115− ,("markdown_phpextra" , TextReader readMarkdown)
116− ,("markdown_github" , TextReader readMarkdown)
117− ,("markdown_mmd", TextReader readMarkdown)
118− ,("commonmark" , TextReader readCommonMark)
119− ,("commonmark_x" , TextReader readCommonMark)
120− ,("creole" , TextReader readCreole)
121− ,("dokuwiki" , TextReader readDokuWiki)
122− ,("gfm" , TextReader readCommonMark)
123− ,("rst" , TextReader readRST)
124− ,("mediawiki" , TextReader readMediaWiki)
125− ,("vimwiki" , TextReader readVimwiki)
126− ,("docbook" , TextReader readDocBook)
127− ,("opml" , TextReader readOPML)
128− ,("org" , TextReader readOrg)
129− ,("textile" , TextReader readTextile) -- TODO : textile+lhs
130− ,("html" , TextReader readHtml)
131− ,("jats" , TextReader readJATS)
132− ,("jira" , TextReader readJira)
133− ,("latex" , TextReader readLaTeX)
134− ,("haddock" , TextReader readHaddock)
135− ,("twiki" , TextReader readTWiki)
136− ,("tikiwiki" , TextReader readTikiWiki)
137− ,("docx" , ByteStringReader readDocx)
138− ,("odt" , ByteStringReader readOdt)
139− ,("t2t" , TextReader readTxt2Tags)
140− ,("epub" , ByteStringReader readEPUB)
141− ,("muse" , TextReader readMuse)
142− ,("man" , TextReader readMan)
143− ,("fb2" , TextReader readFB2)
144− ,("ipynb" , TextReader readIpynb)
145− ,("csv" , TextReader readCSV)
146− ,("csljson" , TextReader readCslJson)
147− ,("bibtex" , TextReader readBibTeX)
148− ,("biblatex" , TextReader readBibLaTeX)
114+readers = [("native" , TextReader readNative)
115+ ,("json" , TextReader readJSON)
116+ ,("markdown" , TextReader readMarkdown)
117+ ,("markdown_strict" , TextReader readMarkdown)
118+ ,("markdown_phpextra" , TextReader readMarkdown)
119+ ,("markdown_github" , TextReader readMarkdown)
120+ ,("markdown_mmd", TextReader readMarkdown)
121+ ,("commonmark" , TextReader readCommonMark)
122+ ,("commonmark_x" , TextReader readCommonMark)
123+ ,("creole" , TextReader readCreole)
124+ ,("dokuwiki" , TextReader readDokuWiki)
125+ ,("gfm" , TextReader readCommonMark)
126+ ,("rst" , TextReader readRST)
127+ ,("mediawiki" , TextReader readMediaWiki)
128+ ,("vimwiki" , TextReader readVimwiki)
129+ ,("docbook" , TextReader readDocBook)
130+ ,("opml" , TextReader readOPML)
131+ ,("org" , TextReader readOrg)
132+ ,("textile" , TextReader readTextile) -- TODO : textile+lhs
133+ ,("html" , TextReader readHtml)
134+ ,("jats" , TextReader readJATS)
135+ ,("jira" , TextReader readJira)
136+ ,("latex" , TextReader readLaTeX)
137+ ,("haddock" , TextReader readHaddock)
138+ ,("twiki" , TextReader readTWiki)
139+ ,("tikiwiki" , TextReader readTikiWiki)
140+ ,("docx" , ByteStringReader readDocx)
141+ ,("odt" , ByteStringReader readOdt)
142+ ,("t2t" , TextReader readTxt2Tags)
143+ ,("epub" , ByteStringReader readEPUB)
144+ ,("muse" , TextReader readMuse)
145+ ,("man" , TextReader readMan)
146+ ,("fb2" , TextReader readFB2)
147+ ,("ipynb" , TextReader readIpynb)
148+ ,("csv" , TextReader readCSV)
149+ ,("csljson" , TextReader readCslJson)
150+ ,("bibtex" , TextReader readBibTeX)
151+ ,("biblatex" , TextReader readBibLaTeX)
149152 ]
150153
151154-- | Retrieve reader, extensions based on formatSpec (format+extensions).
152155getReader :: PandocMonad m => Text -> m (Reader m, Extensions)
153156getReader s =
154157 case parseFormatSpec s of
155− Left e -> throwError $ PandocAppError
156− $ T.intercalate "\n" [T.pack m | Message m <- errorMessages e]
158+ Left e -> throwError $ PandocAppError $
159+ "Error parsing reader format " <> tshow s <> ": " <> tshow e
157160 Right (readerName, extsToEnable, extsToDisable) ->
158161 case lookup readerName readers of
159162 Nothing -> throwError $ PandocUnknownReaderError
@@ -173,9 +176,13 @@ getReader s =
173176 return (r, exts)
174177
175178-- | Read pandoc document from JSON format.
176−readJSON :: PandocMonad m
177− => ReaderOptions -> Text -> m Pandoc
178−readJSON _ t =
179− case eitherDecode' . BL.fromStrict . UTF8.fromText $ t of
179+readJSON :: (PandocMonad m, ToSources a)
180+ => ReaderOptions
181+ -> a
182+ -> m Pandoc
183+readJSON _ s =
184+ case eitherDecode' . BL.fromStrict . UTF8.fromText
185+ . sourcesToText . toSources $ s of
180186 Right doc -> return doc
181− Left e -> throwError $ PandocParseError ("JSON parse error: " <> T.pack e)
187+ Left e -> throwError $ PandocParseError ("JSON parse error: "
188+ <> T.pack e)
src/Text/Pandoc/Readers/BibTeX.hs+14−8
@@ -23,41 +23,47 @@ where
2323import Text.Pandoc.Options
2424import Text.Pandoc.Definition
2525import Text.Pandoc.Builder (setMeta, cite, str)
26−import Data.Text (Text)
2726import Citeproc (Lang(..), parseLang)
2827import Citeproc.Locale (getLocale)
2928import Text.Pandoc.Error (PandocError(..))
3029import Text.Pandoc.Class (PandocMonad, lookupEnv)
3130import Text.Pandoc.Citeproc.BibTeX as BibTeX
3231import Text.Pandoc.Citeproc.MetaValue (referenceToMetaValue)
32+import Text.Pandoc.Sources (ToSources(..))
3333import Control.Monad.Except (throwError)
3434
3535-- | Read BibTeX from an input string and return a Pandoc document.
3636-- The document will have only metadata, with an empty body.
3737-- The metadata will contain a `references` field with the
3838-- bibliography entries, and a `nocite` field with the wildcard `[@*]`.
39−readBibTeX :: PandocMonad m => ReaderOptions -> Text -> m Pandoc
39+readBibTeX :: (PandocMonad m, ToSources a)
40+ => ReaderOptions -> a -> m Pandoc
4041readBibTeX = readBibTeX' BibTeX.Bibtex
4142
4243-- | Read BibLaTeX from an input string and return a Pandoc document.
4344-- The document will have only metadata, with an empty body.
4445-- The metadata will contain a `references` field with the
4546-- bibliography entries, and a `nocite` field with the wildcard `[@*]`.
46−readBibLaTeX :: PandocMonad m => ReaderOptions -> Text -> m Pandoc
47+readBibLaTeX :: (PandocMonad m, ToSources a)
48+ => ReaderOptions -> a -> m Pandoc
4749readBibLaTeX = readBibTeX' BibTeX.Biblatex
4850
49−readBibTeX' :: PandocMonad m => Variant -> ReaderOptions -> Text -> m Pandoc
51+readBibTeX' :: (PandocMonad m, ToSources a)
52+ => Variant -> ReaderOptions -> a -> m Pandoc
5053readBibTeX' variant _opts t = do
51− lang <- maybe (Lang "en" (Just "US")) parseLang
52− <$> lookupEnv "LANG"
54+ mblangEnv <- lookupEnv "LANG"
55+ let defaultLang = Lang "en" Nothing (Just "US") [] [] []
56+ let lang = case mblangEnv of
57+ Nothing -> defaultLang
58+ Just l -> either (const defaultLang) id $ parseLang l
5359 locale <- case getLocale lang of
5460 Left e ->
55− case getLocale (Lang "en" (Just "US")) of
61+ case getLocale (Lang "en" Nothing (Just "US") [] [] []) of
5662 Right l -> return l
5763 Left _ -> throwError $ PandocCiteprocError e
5864 Right l -> return l
5965 case BibTeX.readBibtexString variant locale (const True) t of
60− Left e -> throwError $ PandocParsecError t e
66+ Left e -> throwError $ PandocParsecError (toSources t) e
6167 Right refs -> return $ setMeta "references"
6268 (map referenceToMetaValue refs)
6369 . setMeta "nocite"
src/Text/Pandoc/Readers/CSV.hs+7−7
@@ -13,23 +13,23 @@
1313Conversion from CSV to a 'Pandoc' table.
1414-}
1515module Text.Pandoc.Readers.CSV ( readCSV ) where
16−import Data.Text (Text)
1716import qualified Data.Text as T
1817import Text.Pandoc.CSV (parseCSV, defaultCSVOptions)
1918import Text.Pandoc.Definition
2019import qualified Text.Pandoc.Builder as B
2120import Text.Pandoc.Class (PandocMonad)
22−import Text.Pandoc.Shared (crFilter)
2321import Text.Pandoc.Error
22+import Text.Pandoc.Sources (ToSources(..), sourcesToText)
2423import Text.Pandoc.Options (ReaderOptions)
2524import Control.Monad.Except (throwError)
2625
27−readCSV :: PandocMonad m
26+readCSV :: (PandocMonad m, ToSources a)
2827 => ReaderOptions -- ^ Reader options
29− -> Text -- ^ Text to parse (assuming @'\n'@ line endings)
28+ -> a
3029 -> m Pandoc
31−readCSV _opts s =
32− case parseCSV defaultCSVOptions (crFilter s) of
30+readCSV _opts s = do
31+ let txt = sourcesToText $ toSources s
32+ case parseCSV defaultCSVOptions txt of
3333 Right (r:rs) -> return $ B.doc $ B.table capt
3434 (zip aligns widths)
3535 (TableHead nullAttr hdrs)
@@ -45,4 +45,4 @@ readCSV _opts s =
4545 aligns = replicate numcols AlignDefault
4646 widths = replicate numcols ColWidthDefault
4747 Right [] -> return $ B.doc mempty
48− Left e -> throwError $ PandocParsecError s e
48+ Left e -> throwError $ PandocParsecError (toSources [("",txt)]) e
src/Text/Pandoc/Readers/CommonMark.hs+46−4
@@ -26,19 +26,59 @@ import Text.Pandoc.Definition
2626import Text.Pandoc.Builder as B
2727import Text.Pandoc.Options
2828import Text.Pandoc.Error
29+import Text.Pandoc.Readers.Metadata (yamlMetaBlock)
2930import Control.Monad.Except
3031import Data.Functor.Identity (runIdentity)
3132import Data.Typeable
33+import Text.Pandoc.Parsing (runParserT, getInput,
34+ runF, defaultParserState, option, many1, anyChar,
35+ Sources(..), ToSources(..), ParserT, Future,
36+ sourceName)
37+import qualified Data.Text as T
3238
3339-- | Parse a CommonMark formatted string into a 'Pandoc' structure.
34−readCommonMark :: PandocMonad m => ReaderOptions -> Text -> m Pandoc
40+readCommonMark :: (PandocMonad m, ToSources a)
41+ => ReaderOptions -> a -> m Pandoc
3542readCommonMark opts s
43+ | isEnabled Ext_yaml_metadata_block opts = do
44+ let sources = toSources s
45+ let toks = concatMap sourceToToks (unSources sources)
46+ res <- runParserT (do meta <- yamlMetaBlock (metaValueParser opts)
47+ rest <- getInput
48+ return (meta, rest))
49+ defaultParserState "YAML metadata" (toSources s)
50+ case res of
51+ Left _ -> readCommonMarkBody opts sources toks
52+ Right (meta, rest) -> do
53+ -- strip off metadata section and parse body
54+ let body = concatMap sourceToToks (unSources rest)
55+ Pandoc _ bs <- readCommonMarkBody opts sources body
56+ return $ Pandoc (runF meta defaultParserState) bs
57+ | otherwise = do
58+ let sources = toSources s
59+ let toks = concatMap sourceToToks (unSources sources)
60+ readCommonMarkBody opts sources toks
61+
62+sourceToToks :: (SourcePos, Text) -> [Tok]
63+sourceToToks (pos, s) = tokenize (sourceName pos) s
64+
65+metaValueParser :: Monad m
66+ => ReaderOptions -> ParserT Sources st m (Future st MetaValue)
67+metaValueParser opts = do
68+ inp <- option "" $ T.pack <$> many1 anyChar
69+ let toks = concatMap sourceToToks (unSources (toSources inp))
70+ case runIdentity (parseCommonmarkWith (specFor opts) toks) of
71+ Left _ -> mzero
72+ Right (Cm bls :: Cm () Blocks) -> return $ return $ B.toMetaValue bls
73+
74+readCommonMarkBody :: PandocMonad m => ReaderOptions -> Sources -> [Tok] -> m Pandoc
75+readCommonMarkBody opts s toks
3676 | isEnabled Ext_sourcepos opts =
37− case runIdentity (commonmarkWith (specFor opts) "" s) of
77+ case runIdentity (parseCommonmarkWith (specFor opts) toks) of
3878 Left err -> throwError $ PandocParsecError s err
3979 Right (Cm bls :: Cm SourceRange Blocks) -> return $ B.doc bls
4080 | otherwise =
41− case runIdentity (commonmarkWith (specFor opts) "" s) of
81+ case runIdentity (parseCommonmarkWith (specFor opts) toks) of
4282 Left err -> throwError $ PandocParsecError s err
4383 Right (Cm bls :: Cm () Blocks) -> return $ B.doc bls
4484
@@ -72,5 +112,7 @@ specFor opts = foldr ($) defaultSyntaxSpec exts
72112 | isEnabled Ext_implicit_header_references opts ] ++
73113 [ (footnoteSpec <>) | isEnabled Ext_footnotes opts ] ++
74114 [ (definitionListSpec <>) | isEnabled Ext_definition_lists opts ] ++
75− [ (taskListSpec <>) | isEnabled Ext_task_lists opts ]
115+ [ (taskListSpec <>) | isEnabled Ext_task_lists opts ] ++
116+ [ (rebaseRelativePathsSpec <>)
117+ | isEnabled Ext_rebase_relative_paths opts ]
76118
src/Text/Pandoc/Readers/Creole.hs+5−6
@@ -23,21 +23,20 @@ import Text.Pandoc.Class.PandocMonad (PandocMonad (..))
2323import Text.Pandoc.Definition
2424import Text.Pandoc.Options
2525import Text.Pandoc.Parsing hiding (enclosed)
26−import Text.Pandoc.Shared (crFilter)
27−
2826
2927-- | Read creole from an input string and return a Pandoc document.
30−readCreole :: PandocMonad m
28+readCreole :: (PandocMonad m, ToSources a)
3129 => ReaderOptions
32− -> Text
30+ -> a
3331 -> m Pandoc
3432readCreole opts s = do
35− res <- readWithM parseCreole def{ stateOptions = opts } $ crFilter s <> "\n\n"
33+ let sources = ensureFinalNewlines 2 (toSources s)
34+ res <- readWithM parseCreole def{ stateOptions = opts } sources
3635 case res of
3736 Left e -> throwError e
3837 Right d -> return d
3938
40−type CRLParser = ParserT Text ParserState
39+type CRLParser = ParserT Sources ParserState
4140
4241--
4342-- Utility functions
src/Text/Pandoc/Readers/CslJson.hs+5−4
@@ -24,21 +24,22 @@ import Text.Pandoc.Options
2424import Text.Pandoc.Definition
2525import Text.Pandoc.Builder (setMeta, cite, str)
2626import qualified Text.Pandoc.UTF8 as UTF8
27−import Data.Text (Text)
2827import qualified Data.Text as T
2928import Text.Pandoc.Error (PandocError(..))
3029import Text.Pandoc.Class (PandocMonad)
3130import Text.Pandoc.Citeproc.CslJson (cslJsonToReferences)
3231import Text.Pandoc.Citeproc.MetaValue (referenceToMetaValue)
3332import Control.Monad.Except (throwError)
33+import Text.Pandoc.Sources (ToSources(..), sourcesToText)
3434
3535-- | Read CSL JSON from an input string and return a Pandoc document.
3636-- The document will have only metadata, with an empty body.
3737-- The metadata will contain a `references` field with the
3838-- bibliography entries, and a `nocite` field with the wildcard `[@*]`.
39−readCslJson :: PandocMonad m => ReaderOptions -> Text -> m Pandoc
40−readCslJson _opts t =
41− case cslJsonToReferences (UTF8.fromText t) of
39+readCslJson :: (PandocMonad m, ToSources a)
40+ => ReaderOptions -> a -> m Pandoc
41+readCslJson _opts x =
42+ case cslJsonToReferences (UTF8.fromText $ sourcesToText $ toSources x) of
4243 Left e -> throwError $ PandocParseError $ T.pack e
4344 Right refs -> return $ setMeta "references"
4445 (map referenceToMetaValue refs)
src/Text/Pandoc/Readers/DocBook.hs+30−15
@@ -18,6 +18,7 @@ import Data.Either (rights)
1818import Data.Foldable (asum)
1919import Data.Generics
2020import Data.List (intersperse,elemIndex)
21+import Data.List.NonEmpty (nonEmpty)
2122import Data.Maybe (fromMaybe,mapMaybe)
2223import Data.Text (Text)
2324import qualified Data.Text as T
@@ -29,7 +30,8 @@ import Text.Pandoc.Builder
2930import Text.Pandoc.Class.PandocMonad (PandocMonad, report)
3031import Text.Pandoc.Options
3132import Text.Pandoc.Logging (LogMessage(..))
32−import Text.Pandoc.Shared (crFilter, safeRead, extractSpaces)
33+import Text.Pandoc.Shared (safeRead, extractSpaces)
34+import Text.Pandoc.Sources (ToSources(..), sourcesToText)
3335import Text.TeXMath (readMathML, writeTeX)
3436import Text.Pandoc.XML.Light
3537
@@ -132,6 +134,7 @@ List of all DocBook tags, with [x] indicating implemented,
132134[ ] corpcredit - A corporation or organization credited in a document
133135[ ] corpname - The name of a corporation
134136[ ] country - The name of a country
137+[x] danger - An admonition set off from the text indicating hazardous situation
135138[ ] database - The name of a database, or part of a database
136139[x] date - The date of publication or revision of a document
137140[ ] dedication - A wrapper for the dedication section of a book
@@ -538,11 +541,15 @@ instance Default DBState where
538541 , dbContent = [] }
539542
540543
541−readDocBook :: PandocMonad m => ReaderOptions -> Text -> m Pandoc
544+readDocBook :: (PandocMonad m, ToSources a)
545+ => ReaderOptions
546+ -> a
547+ -> m Pandoc
542548readDocBook _ inp = do
549+ let sources = toSources inp
543550 tree <- either (throwError . PandocXMLError "") return $
544551 parseXMLContents
545− (TL.fromStrict . handleInstructions $ crFilter inp)
552+ (TL.fromStrict . handleInstructions . sourcesToText $ sources)
546553 (bs, st') <- flip runStateT (def{ dbContent = tree }) $ mapM parseBlock tree
547554 return $ Pandoc (dbMeta st') (toList . mconcat $ bs)
548555
@@ -594,16 +601,24 @@ addMetadataFromElement e = do
594601 Nothing -> return ()
595602 Just z -> addMetaField "author" z
596603 addMetaField "subtitle" e
597− addMetaField "author" e
604+ addAuthor e
598605 addMetaField "date" e
599606 addMetaField "release" e
600607 addMetaField "releaseinfo" e
601608 return mempty
602− where addMetaField fieldname elt =
603− case filterChildren (named fieldname) elt of
604− [] -> return ()
605− [z] -> getInlines z >>= addMeta fieldname
606− zs -> mapM getInlines zs >>= addMeta fieldname
609+ where
610+ addAuthor elt =
611+ case filterChildren (named "author") elt of
612+ [] -> return ()
613+ [z] -> fromAuthor z >>= addMeta "author"
614+ zs -> mapM fromAuthor zs >>= addMeta "author"
615+ fromAuthor elt =
616+ mconcat . intersperse space <$> mapM getInlines (elChildren elt)
617+ addMetaField fieldname elt =
618+ case filterChildren (named fieldname) elt of
619+ [] -> return ()
620+ [z] -> getInlines z >>= addMeta fieldname
621+ zs -> mapM getInlines zs >>= addMeta fieldname
607622
608623addMeta :: PandocMonad m => ToMetaValue a => Text -> a -> DB m ()
609624addMeta field val = modify (setMeta field val)
@@ -704,7 +719,7 @@ blockTags =
704719 ] ++ admonitionTags
705720
706721admonitionTags :: [Text]
707−admonitionTags = ["important","caution","note","tip","warning"]
722+admonitionTags = ["caution","danger","important","note","tip","warning"]
708723
709724-- Trim leading and trailing newline characters
710725trimNl :: Text -> Text
@@ -949,9 +964,8 @@ parseBlock (Elem e) =
949964 (x >= '0' && x <= '9')
950965 || x == '.') w
951966 if n > 0 then Just n else Nothing
952− let numrows = case bodyrows of
953− [] -> 0
954− xs -> maximum $ map length xs
967+ let numrows = maybe 0 maximum $ nonEmpty
968+ $ map length bodyrows
955969 let aligns = case colspecs of
956970 [] -> replicate numrows AlignDefault
957971 cs -> map toAlignment cs
@@ -1075,7 +1089,7 @@ parseInline (Elem e) =
10751089 return $ spanWith (attrValue "id" e, [], []) mempty
10761090 "phrase" -> do
10771091 let ident = attrValue "id" e
1078− let classes = T.words $ attrValue "class" e
1092+ let classes = T.words $ attrValue "role" e
10791093 if ident /= "" || classes /= []
10801094 then innerInlines (spanWith (ident,classes,[]))
10811095 else innerInlines id
@@ -1239,7 +1253,8 @@ equation e constructor =
12391253 where
12401254 mathMLEquations :: [Text]
12411255 mathMLEquations = map writeTeX $ rights $ readMath
1242− (\x -> qName (elName x) == "math" && qPrefix (elName x) == Just "mml")
1256+ (\x -> qName (elName x) == "math" &&
1257+ qURI (elName x) == Just "http://www.w3.org/1998/Math/MathML")
12431258 (readMathML . showElement)
12441259
12451260 latexEquations :: [Text]
src/Text/Pandoc/Readers/Docx.hs+59−42
@@ -61,13 +61,14 @@ module Text.Pandoc.Readers.Docx
6161import Codec.Archive.Zip
6262import Control.Monad.Reader
6363import Control.Monad.State.Strict
64+import Data.Bifunctor (bimap, first)
6465import qualified Data.ByteString.Lazy as B
6566import Data.Default (Default)
66−import Data.List (delete, intersect)
67+import Data.List (delete, intersect, foldl')
6768import Data.Char (isSpace)
6869import qualified Data.Map as M
6970import qualified Data.Text as T
70−import Data.Maybe (isJust, fromMaybe)
71+import Data.Maybe (catMaybes, isJust, fromMaybe)
7172import Data.Sequence (ViewL (..), viewl)
7273import qualified Data.Sequence as Seq
7374import qualified Data.Set as Set
@@ -85,6 +86,7 @@ import Text.Pandoc.Class.PandocMonad (PandocMonad)
8586import qualified Text.Pandoc.Class.PandocMonad as P
8687import Text.Pandoc.Error
8788import Text.Pandoc.Logging
89+import Data.List.NonEmpty (nonEmpty)
8890
8991readDocx :: PandocMonad m
9092 => ReaderOptions
@@ -112,6 +114,7 @@ data DState = DState { docxAnchorMap :: M.Map T.Text T.Text
112114 -- restarting
113115 , docxListState :: M.Map (T.Text, T.Text) Integer
114116 , docxPrevPara :: Inlines
117+ , docxTableCaptions :: [Blocks]
115118 }
116119
117120instance Default DState where
@@ -122,6 +125,7 @@ instance Default DState where
122125 , docxDropCap = mempty
123126 , docxListState = M.empty
124127 , docxPrevPara = mempty
128+ , docxTableCaptions = []
125129 }
126130
127131data DEnv = DEnv { docxOptions :: ReaderOptions
@@ -490,15 +494,32 @@ singleParaToPlain blks
490494 singleton $ Plain ils
491495singleParaToPlain blks = blks
492496
493−cellToBlocks :: PandocMonad m => Docx.Cell -> DocxContext m Blocks
494−cellToBlocks (Docx.Cell bps) = do
497+cellToCell :: PandocMonad m => RowSpan -> Docx.Cell -> DocxContext m Pandoc.Cell
498+cellToCell rowSpan (Docx.Cell gridSpan _ bps) = do
495499 blks <- smushBlocks <$> mapM bodyPartToBlocks bps
496− return $ fromList $ blocksToDefinitions $ blocksToBullets $ toList blks
500+ let blks' = singleParaToPlain $ fromList $ blocksToDefinitions $ blocksToBullets $ toList blks
501+ return (cell AlignDefault rowSpan (ColSpan (fromIntegral gridSpan)) blks')
502+
503+rowsToRows :: PandocMonad m => [Docx.Row] -> DocxContext m [Pandoc.Row]
504+rowsToRows rows = do
505+ let rowspans = (fmap . fmap) (first RowSpan) (Docx.rowsToRowspans rows)
506+ cells <- traverse (traverse (uncurry cellToCell)) rowspans
507+ return (fmap (Pandoc.Row nullAttr) cells)
508+
509+splitHeaderRows :: Bool -> [Docx.Row] -> ([Docx.Row], [Docx.Row])
510+splitHeaderRows hasFirstRowFormatting rs = bimap reverse reverse $ fst
511+ $ if hasFirstRowFormatting
512+ then foldl' f ((take 1 rs, []), True) (drop 1 rs)
513+ else foldl' f (([], []), False) rs
514+ where
515+ f ((headerRows, bodyRows), previousRowWasHeader) r@(Docx.Row h cs)
516+ | h == HasTblHeader || (previousRowWasHeader && any isContinuationCell cs)
517+ = ((r : headerRows, bodyRows), True)
518+ | otherwise
519+ = ((headerRows, r : bodyRows), False)
520+
521+ isContinuationCell (Docx.Cell _ vm _) = vm == Docx.Continue
497522
498−rowToBlocksList :: PandocMonad m => Docx.Row -> DocxContext m [Blocks]
499−rowToBlocksList (Docx.Row cells) = do
500− blksList <- mapM cellToBlocks cells
501− return $ map singleParaToPlain blksList
502523
503524-- like trimInlines, but also take out linebreaks
504525trimSps :: Inlines -> Inlines
@@ -545,6 +566,11 @@ normalizeToClassName = T.map go . fromStyleName
545566 where go c | isSpace c = '-'
546567 | otherwise = c
547568
569+bodyPartToTableCaption :: PandocMonad m => BodyPart -> DocxContext m (Maybe Blocks)
570+bodyPartToTableCaption (TblCaption pPr parparts) =
571+ Just <$> bodyPartToBlocks (Paragraph pPr parparts)
572+bodyPartToTableCaption _ = pure Nothing
573+
548574bodyPartToBlocks :: PandocMonad m => BodyPart -> DocxContext m Blocks
549575bodyPartToBlocks (Paragraph pPr parparts)
550576 | Just True <- pBidi pPr = do
@@ -636,54 +662,43 @@ bodyPartToBlocks (ListItem pPr _ _ _ parparts) =
636662 let pPr' = pPr {pStyle = constructBogusParStyleData "list-paragraph": pStyle pPr}
637663 in
638664 bodyPartToBlocks $ Paragraph pPr' parparts
665+bodyPartToBlocks (TblCaption _ _) =
666+ return $ para mempty -- collected separately
639667bodyPartToBlocks (Tbl _ _ _ []) =
640668 return $ para mempty
641−bodyPartToBlocks (Tbl cap _ look parts@(r:rs)) = do
642− let cap' = simpleCaption $ plain $ text cap
643− (hdr, rows) = case firstRowFormatting look of
644− True | null rs -> (Nothing, [r])
645− | otherwise -> (Just r, rs)
646− False -> (Nothing, r:rs)
647−
648− cells <- mapM rowToBlocksList rows
669+bodyPartToBlocks (Tbl cap grid look parts) = do
670+ captions <- gets docxTableCaptions
671+ fullCaption <- case captions of
672+ c : cs -> do
673+ modify (\s -> s { docxTableCaptions = cs })
674+ return c
675+ [] -> return $ if T.null cap then mempty else plain (text cap)
676+ let shortCaption = if T.null cap then Nothing else Just (toList (text cap))
677+ cap' = caption shortCaption fullCaption
678+ (hdr, rows) = splitHeaderRows (firstRowFormatting look) parts
649679
650680 let width = maybe 0 maximum $ nonEmpty $ map rowLength parts
651− -- Data.List.NonEmpty is not available with ghc 7.10 so we roll out
652− -- our own, see
653− -- https://github.com/jgm/pandoc/pull/4361#issuecomment-365416155
654− nonEmpty [] = Nothing
655− nonEmpty l = Just l
656681 rowLength :: Docx.Row -> Int
657− rowLength (Docx.Row c) = length c
682+ rowLength (Docx.Row _ c) = sum (fmap (\(Docx.Cell gridSpan _ _) -> fromIntegral gridSpan) c)
658683
659− let toRow = Pandoc.Row nullAttr . map simpleCell
660− toHeaderRow l = [toRow l | not (null l)]
684+ headerCells <- rowsToRows hdr
685+ bodyCells <- rowsToRows rows
661686
662− -- pad cells. New Text.Pandoc.Builder will do that for us,
663− -- so this is for compatibility while we switch over.
664− let cells' = map (\row -> toRow $ take width (row ++ repeat mempty)) cells
665−
666− hdrCells <- case hdr of
667− Just r' -> toHeaderRow <$> rowToBlocksList r'
668− Nothing -> return []
669−
670− -- The two following variables (horizontal column alignment and
671− -- relative column widths) go to the default at the
672− -- moment. Width information is in the TblGrid field of the Tbl,
673− -- so should be possible. Alignment might be more difficult,
674− -- since there doesn't seem to be a column entity in docx.
687+ -- Horizontal column alignment goes to the default at the moment. Getting
688+ -- it might be difficult, since there doesn't seem to be a column entity
689+ -- in docx.
675690 let alignments = replicate width AlignDefault
676− widths = replicate width ColWidthDefault
691+ totalWidth = sum grid
692+ widths = (\w -> ColWidth (fromInteger w / fromInteger totalWidth)) <$> grid
677693
678694 return $ table cap'
679695 (zip alignments widths)
680− (TableHead nullAttr hdrCells)
681− [TableBody nullAttr 0 [] cells']
696+ (TableHead nullAttr headerCells)
697+ [TableBody nullAttr 0 [] bodyCells]
682698 (TableFoot nullAttr [])
683699bodyPartToBlocks (OMathPara e) =
684700 return $ para $ displayMath (writeTeX e)
685701
686−
687702-- replace targets with generated anchors.
688703rewriteLink' :: PandocMonad m => Inline -> DocxContext m Inline
689704rewriteLink' l@(Link attr ils (T.uncons -> Just ('#',target), title)) = do
@@ -719,6 +734,8 @@ bodyToOutput :: PandocMonad m => Body -> DocxContext m (Meta, [Block])
719734bodyToOutput (Body bps) = do
720735 let (metabps, blkbps) = sepBodyParts bps
721736 meta <- bodyPartsToMeta metabps
737+ captions <- catMaybes <$> mapM bodyPartToTableCaption blkbps
738+ modify (\s -> s { docxTableCaptions = captions })
722739 blks <- smushBlocks <$> mapM bodyPartToBlocks blkbps
723740 blks' <- rewriteLinks $ blocksToDefinitions $ blocksToBullets $ toList blks
724741 blks'' <- removeOrphanAnchors blks'
src/Text/Pandoc/Readers/Docx/Combine.hs+5−5
@@ -61,7 +61,7 @@ import Data.List
6161import Data.Bifunctor
6262import Data.Sequence ( ViewL (..), ViewR (..), viewl, viewr, spanr, spanl
6363 , (><), (|>) )
64−import Text.Pandoc.Builder
64+import Text.Pandoc.Builder as B
6565
6666data Modifier a = Modifier (a -> a)
6767 | AttrModifier (Attr -> a -> a) Attr
@@ -116,12 +116,12 @@ ilModifierAndInnards ils = case viewl $ unMany ils of
116116
117117inlinesL :: Inlines -> (Inlines, Inlines)
118118inlinesL ils = case viewl $ unMany ils of
119− (s :< sq) -> (singleton s, Many sq)
119+ (s :< sq) -> (B.singleton s, Many sq)
120120 _ -> (mempty, ils)
121121
122122inlinesR :: Inlines -> (Inlines, Inlines)
123123inlinesR ils = case viewr $ unMany ils of
124− (sq :> s) -> (Many sq, singleton s)
124+ (sq :> s) -> (Many sq, B.singleton s)
125125 _ -> (ils, mempty)
126126
127127combineInlines :: Inlines -> Inlines -> Inlines
@@ -182,7 +182,7 @@ isAttrModifier _ = False
182182
183183smushInlines :: [Inlines] -> Inlines
184184smushInlines xs = combineInlines xs' mempty
185− where xs' = foldl combineInlines mempty xs
185+ where xs' = foldl' combineInlines mempty xs
186186
187187smushBlocks :: [Blocks] -> Blocks
188−smushBlocks xs = foldl combineBlocks mempty xs
188+smushBlocks xs = foldl' combineBlocks mempty xs
src/Text/Pandoc/Readers/Docx/Parse.hs+121−21
@@ -33,7 +33,9 @@ module Text.Pandoc.Readers.Docx.Parse ( Docx(..)
3333 , ParStyle
3434 , CharStyle(cStyleData)
3535 , Row(..)
36+ , TblHeader(..)
3637 , Cell(..)
38+ , VMerge(..)
3739 , TrackedChange(..)
3840 , ChangeType(..)
3941 , ChangeInfo(..)
@@ -50,6 +52,7 @@ module Text.Pandoc.Readers.Docx.Parse ( Docx(..)
5052 , pHeading
5153 , constructBogusParStyleData
5254 , leftBiasedMergeRunStyle
55+ , rowsToRowspans
5356 ) where
5457import Text.Pandoc.Readers.Docx.Parse.Styles
5558import Codec.Archive.Zip
@@ -225,6 +228,7 @@ defaultParagraphStyle = ParagraphStyle { pStyle = []
225228data BodyPart = Paragraph ParagraphStyle [ParPart]
226229 | ListItem ParagraphStyle T.Text T.Text (Maybe Level) [ParPart]
227230 | Tbl T.Text TblGrid TblLook [Row]
231+ | TblCaption ParagraphStyle [ParPart]
228232 | OMathPara [Exp]
229233 deriving Show
230234
@@ -236,12 +240,61 @@ newtype TblLook = TblLook {firstRowFormatting::Bool}
236240defaultTblLook :: TblLook
237241defaultTblLook = TblLook{firstRowFormatting = False}
238242
239−newtype Row = Row [Cell]
240− deriving Show
243+data Row = Row TblHeader [Cell] deriving Show
244+
245+data TblHeader = HasTblHeader | NoTblHeader deriving (Show, Eq)
241246
242−newtype Cell = Cell [BodyPart]
247+data Cell = Cell GridSpan VMerge [BodyPart]
243248 deriving Show
244249
250+type GridSpan = Integer
251+
252+data VMerge = Continue
253+ -- ^ This cell should be merged with the one above it
254+ | Restart
255+ -- ^ This cell should not be merged with the one above it
256+ deriving (Show, Eq)
257+
258+rowsToRowspans :: [Row] -> [[(Int, Cell)]]
259+rowsToRowspans rows = let
260+ removeMergedCells = fmap (filter (\(_, Cell _ vmerge _) -> vmerge == Restart))
261+ in removeMergedCells (foldr f [] rows)
262+ where
263+ f :: Row -> [[(Int, Cell)]] -> [[(Int, Cell)]]
264+ f (Row _ cells) acc = let
265+ spans = g cells Nothing (listToMaybe acc)
266+ in spans : acc
267+
268+ g ::
269+ -- | The current row
270+ [Cell] ->
271+ -- | Number of columns left below
272+ Maybe Integer ->
273+ -- | (rowspan so far, cell) for the row below this one
274+ Maybe [(Int, Cell)] ->
275+ -- | (rowspan so far, cell) for this row
276+ [(Int, Cell)]
277+ g cells _ Nothing = zip (repeat 1) cells
278+ g cells columnsLeftBelow (Just rowBelow) =
279+ case cells of
280+ [] -> []
281+ thisCell@(Cell thisGridSpan _ _) : restOfRow -> case rowBelow of
282+ [] -> zip (repeat 1) cells
283+ (spanSoFarBelow, Cell gridSpanBelow vmerge _) : _ ->
284+ let spanSoFar = case vmerge of
285+ Restart -> 1
286+ Continue -> 1 + spanSoFarBelow
287+ columnsToDrop = thisGridSpan + (gridSpanBelow - fromMaybe gridSpanBelow columnsLeftBelow)
288+ (newColumnsLeftBelow, restOfRowBelow) = dropColumns columnsToDrop rowBelow
289+ in (spanSoFar, thisCell) : g restOfRow (Just newColumnsLeftBelow) (Just restOfRowBelow)
290+
291+ dropColumns :: Integer -> [(a, Cell)] -> (Integer, [(a, Cell)])
292+ dropColumns n [] = (n, [])
293+ dropColumns n cells@((_, Cell gridSpan _ _) : otherCells) =
294+ if n < gridSpan
295+ then (gridSpan - n, cells)
296+ else dropColumns (n - gridSpan) otherCells
297+
245298leftBiasedMergeRunStyle :: RunStyle -> RunStyle -> RunStyle
246299leftBiasedMergeRunStyle a b = RunStyle
247300 { isBold = isBold a <|> isBold b
@@ -426,20 +479,26 @@ filePathToRelType path docXmlPath =
426479 then Just InDocument
427480 else Nothing
428481
429−relElemToRelationship :: DocumentLocation -> Element -> Maybe Relationship
430−relElemToRelationship relType element | qName (elName element) == "Relationship" =
482+relElemToRelationship :: FilePath -> DocumentLocation -> Element
483+ -> Maybe Relationship
484+relElemToRelationship fp relType element | qName (elName element) == "Relationship" =
431485 do
432486 relId <- findAttr (QName "Id" Nothing Nothing) element
433487 target <- findAttr (QName "Target" Nothing Nothing) element
434− return $ Relationship relType relId target
435−relElemToRelationship _ _ = Nothing
488+ -- target may be relative (media/image1.jpeg) or absolute
489+ -- (/word/media/image1.jpeg); we need to relativize it (see #7374)
490+ let frontOfFp = T.pack $ takeWhile (/= '_') fp
491+ let target' = fromMaybe target $
492+ T.stripPrefix frontOfFp $ T.dropWhile (== '/') target
493+ return $ Relationship relType relId target'
494+relElemToRelationship _ _ _ = Nothing
436495
437496filePathToRelationships :: Archive -> FilePath -> FilePath -> [Relationship]
438497filePathToRelationships ar docXmlPath fp
439498 | Just relType <- filePathToRelType fp docXmlPath
440499 , Just entry <- findEntryByPath fp ar
441500 , Just relElems <- parseXMLFromEntry entry =
442− mapMaybe (relElemToRelationship relType) $ elChildren relElems
501+ mapMaybe (relElemToRelationship fp relType) $ elChildren relElems
443502filePathToRelationships _ _ _ = []
444503
445504archiveToRelationships :: Archive -> FilePath -> [Relationship]
@@ -563,7 +622,7 @@ elemToTblGrid :: NameSpaces -> Element -> D TblGrid
563622elemToTblGrid ns element | isElem ns "w" "tblGrid" element =
564623 let cols = findChildrenByName ns "w" "gridCol" element
565624 in
566− mapD (\e -> maybeToD (findAttrByName ns "w" "val" e >>= stringToInteger))
625+ mapD (\e -> maybeToD (findAttrByName ns "w" "w" e >>= stringToInteger))
567626 cols
568627elemToTblGrid _ _ = throwError WrongElem
569628
@@ -587,14 +646,31 @@ elemToRow ns element | isElem ns "w" "tr" element =
587646 do
588647 let cellElems = findChildrenByName ns "w" "tc" element
589648 cells <- mapD (elemToCell ns) cellElems
590− return $ Row cells
649+ let hasTblHeader = maybe NoTblHeader (const HasTblHeader)
650+ (findChildByName ns "w" "trPr" element
651+ >>= findChildByName ns "w" "tblHeader")
652+ return $ Row hasTblHeader cells
591653elemToRow _ _ = throwError WrongElem
592654
593655elemToCell :: NameSpaces -> Element -> D Cell
594656elemToCell ns element | isElem ns "w" "tc" element =
595657 do
658+ let properties = findChildByName ns "w" "tcPr" element
659+ let gridSpan = properties
660+ >>= findChildByName ns "w" "gridSpan"
661+ >>= findAttrByName ns "w" "val"
662+ >>= stringToInteger
663+ let vMerge = case properties >>= findChildByName ns "w" "vMerge" of
664+ Nothing -> Restart
665+ Just e ->
666+ fromMaybe Continue $ do
667+ s <- findAttrByName ns "w" "val" e
668+ case s of
669+ "continue" -> Just Continue
670+ "restart" -> Just Restart
671+ _ -> Nothing
596672 cellContents <- mapD (elemToBodyPart ns) (elChildren element)
597− return $ Cell cellContents
673+ return $ Cell (fromMaybe 1 gridSpan) vMerge cellContents
598674elemToCell _ _ = throwError WrongElem
599675
600676elemToParIndentation :: NameSpaces -> Element -> Maybe ParIndentation
@@ -626,10 +702,9 @@ pNumInfo = getParStyleField numInfo . pStyle
626702elemToBodyPart :: NameSpaces -> Element -> D BodyPart
627703elemToBodyPart ns element
628704 | isElem ns "w" "p" element
629− , (c:_) <- findChildrenByName ns "m" "oMathPara" element =
630− do
631− expsLst <- eitherToD $ readOMML $ showElement c
632− return $ OMathPara expsLst
705+ , (c:_) <- findChildrenByName ns "m" "oMathPara" element = do
706+ expsLst <- eitherToD $ readOMML $ showElement c
707+ return $ OMathPara expsLst
633708elemToBodyPart ns element
634709 | isElem ns "w" "p" element
635710 , Just (numId, lvl) <- getNumInfo ns element = do
@@ -647,13 +722,31 @@ elemToBodyPart ns element
647722 Nothing | Just (numId, lvl) <- pNumInfo parstyle -> do
648723 levelInfo <- lookupLevel numId lvl <$> asks envNumbering
649724 return $ ListItem parstyle numId lvl levelInfo parparts
650− _ -> return $ Paragraph parstyle parparts
725+ _ -> let
726+ hasCaptionStyle = elem "Caption" (pStyleId <$> pStyle parstyle)
727+
728+ hasSimpleTableField = fromMaybe False $ do
729+ fldSimple <- findChildByName ns "w" "fldSimple" element
730+ instr <- findAttrByName ns "w" "instr" fldSimple
731+ pure ("Table" `elem` T.words instr)
732+
733+ hasComplexTableField = fromMaybe False $ do
734+ instrText <- findElementByName ns "w" "instrText" element
735+ pure ("Table" `elem` T.words (strContent instrText))
736+
737+ in if hasCaptionStyle && (hasSimpleTableField || hasComplexTableField)
738+ then return $ TblCaption parstyle parparts
739+ else return $ Paragraph parstyle parparts
740+
651741elemToBodyPart ns element
652742 | isElem ns "w" "tbl" element = do
653− let caption' = findChildByName ns "w" "tblPr" element
743+ let tblProperties = findChildByName ns "w" "tblPr" element
744+ caption = fromMaybe "" $ tblProperties
654745 >>= findChildByName ns "w" "tblCaption"
655746 >>= findAttrByName ns "w" "val"
656− caption = fromMaybe "" caption'
747+ description = fromMaybe "" $ tblProperties
748+ >>= findChildByName ns "w" "tblDescription"
749+ >>= findAttrByName ns "w" "val"
657750 grid' = case findChildByName ns "w" "tblGrid" element of
658751 Just g -> elemToTblGrid ns g
659752 Nothing -> return []
@@ -666,7 +759,7 @@ elemToBodyPart ns element
666759 grid <- grid'
667760 tblLook <- tblLook'
668761 rows <- mapD (elemToRow ns) (elChildren element)
669− return $ Tbl caption grid tblLook rows
762+ return $ Tbl (caption <> description) grid tblLook rows
670763elemToBodyPart _ _ = throwError WrongElem
671764
672765lookupRelationship :: DocumentLocation -> RelId -> [Relationship] -> Maybe Target
@@ -709,7 +802,8 @@ elemToParPart ns element
709802 case drawing of
710803 Just s -> expandDrawingId s >>= (\(fp, bs) -> return $ Drawing fp title alt bs $ elemToExtent drawingElem)
711804 Nothing -> throwError WrongElem
712−-- The below is an attempt to deal with images in deprecated vml format.
805+-- The two cases below are an attempt to deal with images in deprecated vml format.
806+-- Todo: check out title and attr for deprecated format.
713807elemToParPart ns element
714808 | isElem ns "w" "r" element
715809 , Just _ <- findChildByName ns "w" "pict" element =
@@ -717,9 +811,15 @@ elemToParPart ns element
717811 >>= findAttrByName ns "r" "id"
718812 in
719813 case drawing of
720− -- Todo: check out title and attr for deprecated format.
721814 Just s -> expandDrawingId s >>= (\(fp, bs) -> return $ Drawing fp "" "" bs Nothing)
722815 Nothing -> throwError WrongElem
816+elemToParPart ns element
817+ | isElem ns "w" "r" element
818+ , Just objectElem <- findChildByName ns "w" "object" element
819+ , Just shapeElem <- findChildByName ns "v" "shape" objectElem
820+ , Just imagedataElem <- findChildByName ns "v" "imagedata" shapeElem
821+ , Just drawingId <- findAttrByName ns "r" "id" imagedataElem
822+ = expandDrawingId drawingId >>= (\(fp, bs) -> return $ Drawing fp "" "" bs Nothing)
723823-- Chart
724824elemToParPart ns element
725825 | isElem ns "w" "r" element
src/Text/Pandoc/Readers/Docx/Util.hs+7
@@ -19,6 +19,7 @@ module Text.Pandoc.Readers.Docx.Util (
1919 , elemToNameSpaces
2020 , findChildByName
2121 , findChildrenByName
22+ , findElementByName
2223 , findAttrByName
2324 ) where
2425
@@ -56,6 +57,12 @@ findChildrenByName ns pref name el =
5657 let ns' = ns <> elemToNameSpaces el
5758 in findChildren (elemName ns' pref name) el
5859
60+-- | Like 'findChildrenByName', but searches descendants.
61+findElementByName :: NameSpaces -> Text -> Text -> Element -> Maybe Element
62+findElementByName ns pref name el =
63+ let ns' = ns <> elemToNameSpaces el
64+ in findElement (elemName ns' pref name) el
65+
5966findAttrByName :: NameSpaces -> Text -> Text -> Element -> Maybe Text
6067findAttrByName ns pref name el =
6168 let ns' = ns <> elemToNameSpaces el
src/Text/Pandoc/Readers/DokuWiki.hs+9−8
@@ -29,26 +29,27 @@ import Text.Pandoc.Definition
2929import Text.Pandoc.Error (PandocError (PandocParsecError))
3030import Text.Pandoc.Options
3131import Text.Pandoc.Parsing hiding (enclosed, nested)
32−import Text.Pandoc.Shared (crFilter, trim, stringify, tshow)
32+import Text.Pandoc.Shared (trim, stringify, tshow)
3333
3434-- | Read DokuWiki from an input string and return a Pandoc document.
35−readDokuWiki :: PandocMonad m
35+readDokuWiki :: (PandocMonad m, ToSources a)
3636 => ReaderOptions
37− -> Text
37+ -> a
3838 -> m Pandoc
3939readDokuWiki opts s = do
40− let input = crFilter s
41− res <- runParserT parseDokuWiki def {stateOptions = opts } "source" input
40+ let sources = toSources s
41+ res <- runParserT parseDokuWiki def {stateOptions = opts }
42+ (initialSourceName sources) sources
4243 case res of
43− Left e -> throwError $ PandocParsecError input e
44+ Left e -> throwError $ PandocParsecError sources e
4445 Right d -> return d
4546
46−type DWParser = ParserT Text ParserState
47+type DWParser = ParserT Sources ParserState
4748
4849-- * Utility functions
4950
5051-- | Parse end-of-line, which can be either a newline or end-of-file.
51−eol :: Stream s m Char => ParserT s st m ()
52+eol :: (Stream s m Char, UpdateSourcePos s Char) => ParserT s st m ()
5253eol = void newline <|> eof
5354
5455nested :: PandocMonad m => DWParser m a -> DWParser m a
src/Text/Pandoc/Readers/FB2.hs+6−3
@@ -40,9 +40,9 @@ import Text.Pandoc.Class.PandocMonad (PandocMonad, insertMedia, report)
4040import Text.Pandoc.Error
4141import Text.Pandoc.Logging
4242import Text.Pandoc.Options
43−import Text.Pandoc.Shared (crFilter)
4443import Text.Pandoc.XML.Light
4544import qualified Text.Pandoc.UTF8 as UTF8
45+import Text.Pandoc.Sources (ToSources(..), sourcesToText)
4646
4747type FB2 m = StateT FB2State m
4848
@@ -63,9 +63,12 @@ instance HasMeta FB2State where
6363 setMeta field v s = s {fb2Meta = setMeta field v (fb2Meta s)}
6464 deleteMeta field s = s {fb2Meta = deleteMeta field (fb2Meta s)}
6565
66−readFB2 :: PandocMonad m => ReaderOptions -> Text -> m Pandoc
66+readFB2 :: (PandocMonad m, ToSources a)
67+ => ReaderOptions
68+ -> a
69+ -> m Pandoc
6770readFB2 _ inp =
68− case parseXMLElement $ TL.fromStrict $ crFilter inp of
71+ case parseXMLElement $ TL.fromStrict $ sourcesToText $ toSources inp of
6972 Left msg -> throwError $ PandocXMLError "" msg
7073 Right el -> do
7174 (bs, st) <- runStateT (parseRootElement el) def
src/Text/Pandoc/Readers/HTML.hs+48−28
@@ -32,6 +32,7 @@ import Data.Char (isAlphaNum, isLetter)
3232import Data.Default (Default (..), def)
3333import Data.Foldable (for_)
3434import Data.List.Split (splitWhen)
35+import Data.List (foldl')
3536import qualified Data.Map as M
3637import Data.Maybe (fromMaybe, isJust, isNothing)
3738import Data.Monoid (First (..))
@@ -61,21 +62,21 @@ import Text.Pandoc.Options (
6162 extensionEnabled)
6263import Text.Pandoc.Parsing hiding ((<|>))
6364import Text.Pandoc.Shared (
64− addMetaField, blocksToInlines', crFilter, escapeURI, extractSpaces,
65+ addMetaField, blocksToInlines', escapeURI, extractSpaces,
6566 htmlSpanLikeElements, renderTags', safeRead, tshow)
6667import Text.Pandoc.Walk
6768import Text.Parsec.Error
6869import Text.TeXMath (readMathML, writeTeX)
6970
7071-- | Convert HTML-formatted string to 'Pandoc' document.
71−readHtml :: PandocMonad m
72+readHtml :: (PandocMonad m, ToSources a)
7273 => ReaderOptions -- ^ Reader options
73− -> Text -- ^ String to parse (assumes @'\n'@ line endings)
74+ -> a -- ^ Input to parse
7475 -> m Pandoc
7576readHtml opts inp = do
7677 let tags = stripPrefixes $ canonicalizeTags $
7778 parseTagsOptions parseOptions{ optTagPosition = True }
78− (crFilter inp)
79+ (sourcesToText $ toSources inp)
7980 parseDoc = do
8081 blocks <- fixPlains False . mconcat <$> manyTill block eof
8182 meta <- stateMeta . parserState <$> getState
@@ -204,6 +205,7 @@ block = ((do
204205 | otherwise
205206 -> pDiv
206207 "section" -> pDiv
208+ "header" -> pDiv
207209 "main" -> pDiv
208210 "figure" -> pFigure
209211 "iframe" -> pIframe
@@ -360,7 +362,10 @@ pDefListItem = try $ do
360362 terms <- many1 (try $ skipMany nonItem >> pInTags "dt" inline)
361363 defs <- many1 (try $ skipMany nonItem >> pInTags "dd" block)
362364 skipMany nonItem
363− let term = foldl1 (\x y -> x <> B.linebreak <> y) $ map trimInlines terms
365+ let term = foldl' (\x y -> if null x
366+ then trimInlines y
367+ else x <> B.linebreak <> trimInlines y)
368+ mempty terms
364369 return (term, map (fixPlains True) defs)
365370
366371fixPlains :: Bool -> Blocks -> Blocks
@@ -400,6 +405,7 @@ pLineBlock = try $ do
400405isDivLike :: Text -> Bool
401406isDivLike "div" = True
402407isDivLike "section" = True
408+isDivLike "header" = True
403409isDivLike "main" = True
404410isDivLike _ = False
405411
@@ -495,17 +501,13 @@ pHeader = try $ do
495501 tagOpen (`elem` ["h1","h2","h3","h4","h5","h6"])
496502 (const True)
497503 let attr = toStringAttr attr'
498− let bodyTitle = TagOpen tagtype attr' ~== TagOpen ("h1" :: Text)
499− [("class","title")]
500504 level <- headerLevel tagtype
501505 contents <- trimInlines . mconcat <$> manyTill inline (pCloses tagtype <|> eof)
502506 let ident = fromMaybe "" $ lookup "id" attr
503507 let classes = maybe [] T.words $ lookup "class" attr
504508 let keyvals = [(k,v) | (k,v) <- attr, k /= "class", k /= "id"]
505509 attr'' <- registerHeader (ident, classes, keyvals) contents
506− return $ if bodyTitle
507− then mempty -- skip a representation of the title in the body
508− else B.headerWith attr'' level contents
510+ return $ B.headerWith attr'' level contents
509511
510512pHrule :: PandocMonad m => TagParser m Blocks
511513pHrule = do
@@ -555,7 +557,18 @@ pFigure = try $ do
555557pCodeBlock :: PandocMonad m => TagParser m Blocks
556558pCodeBlock = try $ do
557559 TagOpen _ attr' <- pSatisfy (matchTagOpen "pre" [])
558− let attr = toAttr attr'
560+ -- if the `pre` has no attributes, try if it is followed by a `code`
561+ -- element and use those attributes if possible.
562+ attr <- case attr' of
563+ _:_ -> pure (toAttr attr')
564+ [] -> option nullAttr $ do
565+ TagOpen _ codeAttr <- pSatisfy (matchTagOpen "code" [])
566+ pure $ toAttr
567+ [ (k, v') | (k, v) <- codeAttr
568+ -- strip language from class
569+ , let v' = if k == "class"
570+ then fromMaybe v (T.stripPrefix "language-" v)
571+ else v ]
559572 contents <- manyTill pAny (pCloses "pre" <|> eof)
560573 let rawText = T.concat $ map tagToText contents
561574 -- drop leading newline if any
@@ -826,17 +839,19 @@ pInlinesInTags tagtype f = extractSpaces f <$> pInTags tagtype inline
826839
827840pTagText :: PandocMonad m => TagParser m Inlines
828841pTagText = try $ do
842+ pos <- getPosition
829843 (TagText str) <- pSatisfy isTagText
830844 st <- getState
831845 qu <- ask
832846 parsed <- lift $ lift $
833− flip runReaderT qu $ runParserT (many pTagContents) st "text" str
847+ flip runReaderT qu $ runParserT (many pTagContents) st "text"
848+ (Sources [(pos, str)])
834849 case parsed of
835850 Left _ -> throwError $ PandocParseError $
836851 "Could not parse `" <> str <> "'"
837852 Right result -> return $ mconcat result
838853
839−type InlinesParser m = HTMLParser m Text
854+type InlinesParser m = HTMLParser m Sources
840855
841856pTagContents :: PandocMonad m => InlinesParser m Inlines
842857pTagContents =
@@ -936,13 +951,15 @@ getTagName (TagClose t) = Just t
936951getTagName _ = Nothing
937952
938953isInlineTag :: Tag Text -> Bool
939−isInlineTag t =
940− isCommentTag t ||
941− case getTagName t of
942− Nothing -> False
943− Just "script" -> "math/tex" `T.isPrefixOf` fromAttrib "type" t
944− Just x -> x `Set.notMember` blockTags ||
945− T.take 1 x == "?" -- processing instr.
954+isInlineTag t = isCommentTag t || case t of
955+ TagOpen "script" _ -> "math/tex" `T.isPrefixOf` fromAttrib "type" t
956+ TagClose "script" -> True
957+ TagOpen name _ -> isInlineTagName name
958+ TagClose name -> isInlineTagName name
959+ _ -> False
960+ where isInlineTagName x =
961+ x `Set.notMember` blockTags ||
962+ T.take 1 x == "?" -- processing instr.
946963
947964isBlockTag :: Tag Text -> Bool
948965isBlockTag t = isBlockTagName || isTagComment t
@@ -966,13 +983,14 @@ isCommentTag = tagComment (const True)
966983-- | Matches a stretch of HTML in balanced tags.
967984htmlInBalanced :: Monad m
968985 => (Tag Text -> Bool)
969− -> ParserT Text st m Text
986+ -> ParserT Sources st m Text
970987htmlInBalanced f = try $ do
971988 lookAhead (char '<')
972− inp <- getInput
973− let ts = canonicalizeTags $
974− parseTagsOptions parseOptions{ optTagWarning = True,
975− optTagPosition = True } inp
989+ sources <- getInput
990+ let ts = canonicalizeTags
991+ $ parseTagsOptions parseOptions{ optTagWarning = True,
992+ optTagPosition = True }
993+ $ sourcesToText sources
976994 case ts of
977995 (TagPosition sr sc : t@(TagOpen tn _) : rest) -> do
978996 guard $ f t
@@ -1014,15 +1032,17 @@ hasTagWarning _ = False
10141032-- | Matches a tag meeting a certain condition.
10151033htmlTag :: (HasReaderOptions st, Monad m)
10161034 => (Tag Text -> Bool)
1017− -> ParserT Text st m (Tag Text, Text)
1035+ -> ParserT Sources st m (Tag Text, Text)
10181036htmlTag f = try $ do
10191037 lookAhead (char '<')
10201038 startpos <- getPosition
1021− inp <- getInput
1039+ sources <- getInput
1040+ let inp = sourcesToText sources
10221041 let ts = canonicalizeTags $ parseTagsOptions
10231042 parseOptions{ optTagWarning = False
10241043 , optTagPosition = True }
1025− (inp <> " ") -- add space to ensure that
1044+ (inp <> " ")
1045+ -- add space to ensure that
10261046 -- we get a TagPosition after the tag
10271047 (next, ln, col) <- case ts of
10281048 (TagPosition{} : next : TagPosition ln col : _)
src/Text/Pandoc/Readers/HTML/Table.hs+35−15
@@ -17,6 +17,8 @@ module Text.Pandoc.Readers.HTML.Table (pTable) where
1717
1818import Control.Applicative ((<|>))
1919import Data.Maybe (fromMaybe)
20+import Data.Either (lefts, rights)
21+import Data.List.NonEmpty (nonEmpty)
2022import Data.Text (Text)
2123import Text.HTML.TagSoup
2224import Text.Pandoc.Builder (Blocks)
@@ -32,34 +34,51 @@ import Text.Pandoc.Shared (onlySimpleTableCells, safeRead)
3234import qualified Data.Text as T
3335import qualified Text.Pandoc.Builder as B
3436
35−-- | Parses a @<col>@ element, returning the column's width. Defaults to
36−-- @'ColWidthDefault'@ if the width is not set or cannot be determined.
37−pCol :: PandocMonad m => TagParser m ColWidth
37+-- | Parses a @<col>@ element, returning the column's width.
38+-- An Either value is used: Left i means a "relative length" with
39+-- integral value i (see https://www.w3.org/TR/html4/types.html#h-6.6);
40+-- Right w means a regular width. Defaults to @'Right ColWidthDefault'@
41+-- if the width is not set or cannot be determined.
42+pCol :: PandocMonad m => TagParser m (Either Int ColWidth)
3843pCol = try $ do
3944 TagOpen _ attribs' <- pSatisfy (matchTagOpen "col" [])
4045 let attribs = toStringAttr attribs'
4146 skipMany pBlank
4247 optional $ pSatisfy (matchTagClose "col")
4348 skipMany pBlank
44− let width = case lookup "width" attribs of
49+ return $ case lookup "width" attribs of
4550 Nothing -> case lookup "style" attribs of
4651 Just (T.stripPrefix "width:" -> Just xs) | T.any (== '%') xs ->
47− fromMaybe 0.0 $ safeRead (T.filter
48− (`notElem` (" \t\r\n%'\";" :: [Char])) xs)
49− _ -> 0.0
52+ maybe (Right ColWidthDefault) (Right . ColWidth . (/ 100.0))
53+ $ safeRead (T.filter
54+ (`notElem` (" \t\r\n%'\";" :: [Char])) xs)
55+ _ -> Right ColWidthDefault
56+ Just (T.unsnoc -> Just (xs, '*')) ->
57+ maybe (Left 1) Left $ safeRead xs
5058 Just (T.unsnoc -> Just (xs, '%')) ->
51− fromMaybe 0.0 $ safeRead xs
52− _ -> 0.0
53− if width > 0.0
54− then return $ ColWidth $ width / 100.0
55− else return ColWidthDefault
59+ maybe (Right ColWidthDefault)
60+ (Right . ColWidth . (/ 100.0)) $ safeRead xs
61+ _ -> Right ColWidthDefault
5662
57−pColgroup :: PandocMonad m => TagParser m [ColWidth]
63+pColgroup :: PandocMonad m => TagParser m [Either Int ColWidth]
5864pColgroup = try $ do
5965 pSatisfy (matchTagOpen "colgroup" [])
6066 skipMany pBlank
6167 manyTill pCol (pCloses "colgroup" <|> eof) <* skipMany pBlank
6268
69+resolveRelativeLengths :: [Either Int ColWidth] -> [ColWidth]
70+resolveRelativeLengths ws =
71+ let remaining = 1 - sum (map getColWidth $ rights ws)
72+ relatives = sum $ lefts ws
73+ relUnit = remaining / fromIntegral relatives
74+ toColWidth (Right x) = x
75+ toColWidth (Left i) = ColWidth (fromIntegral i * relUnit)
76+ in map toColWidth ws
77+
78+getColWidth :: ColWidth -> Double
79+getColWidth ColWidthDefault = 0
80+getColWidth (ColWidth w) = w
81+
6382data CellType
6483 = HeaderCell
6584 | BodyCell
@@ -181,7 +200,8 @@ pTable :: PandocMonad m
181200pTable block = try $ do
182201 TagOpen _ attribs <- pSatisfy (matchTagOpen "table" []) <* skipMany pBlank
183202 caption <- option mempty $ pInTags "caption" block <* skipMany pBlank
184− widths <- ((mconcat <$> many1 pColgroup) <|> many pCol) <* skipMany pBlank
203+ widths <- resolveRelativeLengths <$>
204+ ((mconcat <$> many1 pColgroup) <|> many pCol) <* skipMany pBlank
185205 thead <- pTableHead block <* skipMany pBlank
186206 topfoot <- optionMaybe (pTableFoot block) <* skipMany pBlank
187207 tbodies <- many (pTableBody block) <* skipMany pBlank
@@ -216,7 +236,7 @@ normalize widths head' bodies foot = do
216236 let rows = headRows head' <> concatMap bodyRows bodies <> footRows foot
217237 let cellWidth (Cell _ _ _ (ColSpan cs) _) = cs
218238 let rowLength = foldr (\cell acc -> cellWidth cell + acc) 0 . rowCells
219− let ncols = maximum (map rowLength rows)
239+ let ncols = maybe 0 maximum $ nonEmpty $ map rowLength rows
220240 let tblType = tableType (map rowCells rows)
221241 -- fail on empty table
222242 if null rows
src/Text/Pandoc/Readers/Haddock.hs+11−7
@@ -17,8 +17,9 @@ module Text.Pandoc.Readers.Haddock
1717
1818import Control.Monad.Except (throwError)
1919import Data.List (intersperse)
20+import Data.List.NonEmpty (nonEmpty)
2021import Data.Maybe (fromMaybe)
21−import Data.Text (Text, unpack)
22+import Data.Text (unpack)
2223import qualified Data.Text as T
2324import Documentation.Haddock.Parser
2425import Documentation.Haddock.Types as H
@@ -28,15 +29,17 @@ import Text.Pandoc.Class.PandocMonad (PandocMonad)
2829import Text.Pandoc.Definition
2930import Text.Pandoc.Error
3031import Text.Pandoc.Options
31−import Text.Pandoc.Shared (crFilter, splitTextBy, trim)
32+import Text.Pandoc.Sources (ToSources(..), sourcesToText)
33+import Text.Pandoc.Shared (splitTextBy, trim)
3234
3335
3436-- | Parse Haddock markup and return a 'Pandoc' document.
35−readHaddock :: PandocMonad m
37+readHaddock :: (PandocMonad m, ToSources a)
3638 => ReaderOptions
37− -> Text
39+ -> a
3840 -> m Pandoc
39−readHaddock opts s = case readHaddockEither opts (unpack (crFilter s)) of
41+readHaddock opts s = case readHaddockEither opts
42+ (unpack . sourcesToText . toSources $ s) of
4043 Right result -> return result
4144 Left e -> throwError e
4245
@@ -92,7 +95,7 @@ docHToBlocks d' =
9295 then ([], map toCells bodyRows)
9396 else (toCells (head headerRows),
9497 map toCells (tail headerRows ++ bodyRows))
95− colspecs = replicate (maximum (map length body))
98+ colspecs = replicate (maybe 0 maximum (nonEmpty (map length body)))
9699 (AlignDefault, ColWidthDefault)
97100 in B.table B.emptyCaption
98101 colspecs
@@ -128,7 +131,8 @@ docHToInlines isCode d' =
128131 DocIdentifier s -> B.codeWith ("",["haskell","identifier"],[]) $ T.pack s
129132 _ -> mempty
130133 DocIdentifierUnchecked s -> B.codeWith ("",["haskell","identifier"],[]) $ T.pack s
131− DocModule s -> B.codeWith ("",["haskell","module"],[]) $ T.pack s
134+ DocModule s -> B.codeWith ("",["haskell","module"],[]) $
135+ T.pack (modLinkName s)
132136 DocWarning _ -> mempty -- TODO
133137 DocEmphasis d -> B.emph (docHToInlines isCode d)
134138 DocMonospaced (DocString s) -> B.code $ T.pack s
src/Text/Pandoc/Readers/Ipynb.hs+5−3
@@ -39,10 +39,12 @@ import Data.Aeson as Aeson
3939import Control.Monad.Except (throwError)
4040import Text.Pandoc.Readers.Markdown (readMarkdown)
4141import qualified Text.Pandoc.UTF8 as UTF8
42+import Text.Pandoc.Sources (ToSources(..), sourcesToText)
4243
43−readIpynb :: PandocMonad m => ReaderOptions -> Text -> m Pandoc
44−readIpynb opts t = do
45− let src = BL.fromStrict (TE.encodeUtf8 t)
44+readIpynb :: (PandocMonad m, ToSources a)
45+ => ReaderOptions -> a -> m Pandoc
46+readIpynb opts x = do
47+ let src = BL.fromStrict . TE.encodeUtf8 . sourcesToText $ toSources x
4648 case eitherDecode src of
4749 Right (notebook4 :: Notebook NbV4) -> notebookToPandoc opts notebook4
4850 Left _ ->
src/Text/Pandoc/Readers/JATS.hs+13−6
@@ -29,11 +29,12 @@ import Text.HTML.TagSoup.Entity (lookupEntity)
2929import Text.Pandoc.Builder
3030import Text.Pandoc.Class.PandocMonad (PandocMonad)
3131import Text.Pandoc.Options
32−import Text.Pandoc.Shared (crFilter, safeRead, extractSpaces)
32+import Text.Pandoc.Shared (safeRead, extractSpaces)
3333import Text.TeXMath (readMathML, writeTeX)
3434import Text.Pandoc.XML.Light
3535import qualified Data.Set as S (fromList, member)
3636import Data.Set ((\\))
37+import Text.Pandoc.Sources (ToSources(..), sourcesToText)
3738
3839type JATS m = StateT JATSState m
3940
@@ -52,10 +53,14 @@ instance Default JATSState where
5253 , jatsContent = [] }
5354
5455
55−readJATS :: PandocMonad m => ReaderOptions -> Text -> m Pandoc
56+readJATS :: (PandocMonad m, ToSources a)
57+ => ReaderOptions
58+ -> a
59+ -> m Pandoc
5660readJATS _ inp = do
61+ let sources = toSources inp
5762 tree <- either (throwError . PandocXMLError "") return $
58− parseXMLContents (TL.fromStrict $ crFilter inp)
63+ parseXMLContents (TL.fromStrict . sourcesToText $ sources)
5964 (bs, st') <- flip runStateT (def{ jatsContent = tree }) $ mapM parseBlock tree
6065 return $ Pandoc (jatsMeta st') (toList . mconcat $ bs)
6166
@@ -491,7 +496,8 @@ parseInline (Elem e) =
491496
492497 "disp-formula" -> formula displayMath
493498 "inline-formula" -> formula math
494− "math" | qPrefix (elName e) == Just "mml" -> return . math $ mathML e
499+ "math" | qURI (elName e) == Just "http://www.w3.org/1998/Math/MathML"
500+ -> return . math $ mathML e
495501 "tex-math" -> return . math $ textContent e
496502
497503 "email" -> return $ link ("mailto:" <> textContent e) ""
@@ -514,8 +520,9 @@ parseInline (Elem e) =
514520 filterChildren isMathML whereToLook
515521 return . mconcat . take 1 . map constructor $ texMaths ++ mathMLs
516522
517− isMathML x = qName (elName x) == "math" &&
518− qPrefix (elName x) == Just "mml"
523+ isMathML x = qName (elName x) == "math" &&
524+ qURI (elName x) ==
525+ Just "http://www.w3.org/1998/Math/MathML"
519526 removePrefix elname = elname { qPrefix = Nothing }
520527 codeWithLang = do
521528 let classes' = case attrValue "language" e of
src/Text/Pandoc/Readers/Jira.hs+13−9
@@ -20,18 +20,20 @@ import Text.Pandoc.Builder hiding (cell)
2020import Text.Pandoc.Error (PandocError (PandocParseError))
2121import Text.Pandoc.Options (ReaderOptions)
2222import Text.Pandoc.Shared (stringify)
23−
23+import Text.Pandoc.Sources (ToSources(..), sourcesToText)
2424import qualified Text.Jira.Markup as Jira
2525
2626-- | Read Jira wiki markup.
27−readJira :: PandocMonad m
27+readJira :: (PandocMonad m, ToSources a)
2828 => ReaderOptions
29− -> Text
29+ -> a
3030 -> m Pandoc
31−readJira _opts s = case parse s of
32− Right d -> return $ jiraToPandoc d
33− Left e -> throwError . PandocParseError $
34− "Jira parse error" `append` pack (show e)
31+readJira _opts inp = do
32+ let sources = toSources inp
33+ case parse (sourcesToText sources) of
34+ Right d -> return $ jiraToPandoc d
35+ Left e -> throwError . PandocParseError $
36+ "Jira parse error" `append` pack (show e)
3537
3638jiraToPandoc :: Jira.Doc -> Pandoc
3739jiraToPandoc (Jira.Doc blks) = doc $ foldMap jiraToPandocBlocks blks
@@ -71,10 +73,10 @@ toPandocCodeBlocks langMay params txt =
7173 Nothing -> []
7274 in codeBlockWith ("", classes, map paramToPair params) txt
7375
74−-- | Create a pandoc @'Div'@
76+-- | Create a pandoc @'Div'@ from a panel.
7577toPandocDiv :: [Jira.Parameter] -> [Jira.Block] -> Blocks
7678toPandocDiv params =
77− divWith ("", [], map paramToPair params) . foldMap jiraToPandocBlocks
79+ divWith ("", ["panel"], map paramToPair params) . foldMap jiraToPandocBlocks
7880
7981paramToPair :: Jira.Parameter -> (Text, Text)
8082paramToPair (Jira.Parameter key value) = (key, value)
@@ -170,6 +172,8 @@ jiraLinkToPandoc linkType alias url =
170172 Jira.Email -> link ("mailto:" <> url') "" alias'
171173 Jira.Attachment -> linkWith ("", ["attachment"], []) url' "" alias'
172174 Jira.User -> linkWith ("", ["user-account"], []) url' "" alias'
175+ Jira.SmartCard -> linkWith ("", ["smart-card"], []) url' "" alias'
176+ Jira.SmartLink -> linkWith ("", ["smart-link"], []) url' "" alias'
173177
174178-- | Get unicode representation of a Jira icon.
175179iconUnicode :: Jira.Icon -> Text
src/Text/Pandoc/Readers/LaTeX.hs+223−1424
@@ -1,7 +1,3 @@
1−{-# LANGUAGE BangPatterns #-}
2−{-# LANGUAGE CPP #-}
3−{-# LANGUAGE FlexibleInstances #-}
4−{-# LANGUAGE MultiParamTypeClasses #-}
51{-# LANGUAGE OverloadedStrings #-}
62{-# LANGUAGE PatternGuards #-}
73{-# LANGUAGE ScopedTypeVariables #-}
@@ -22,50 +18,58 @@ module Text.Pandoc.Readers.LaTeX ( readLaTeX,
2218 applyMacros,
2319 rawLaTeXInline,
2420 rawLaTeXBlock,
25− inlineCommand,
26− tokenize,
27− untokenize
21+ inlineCommand
2822 ) where
2923
3024import Control.Applicative (many, optional, (<|>))
3125import Control.Monad
3226import Control.Monad.Except (throwError)
33−import Data.Char (isDigit, isLetter, toUpper, chr)
27+import Data.Char (isDigit, isLetter, isAlphaNum, toUpper, chr)
3428import Data.Default
35−import Data.Functor (($>))
3629import Data.List (intercalate)
3730import qualified Data.Map as M
3831import Data.Maybe (fromMaybe, maybeToList)
3932import qualified Data.Set as Set
40−import qualified Data.Sequence as Seq
4133import Data.Text (Text)
4234import qualified Data.Text as T
35+import Skylighting (defaultSyntaxMap)
4336import System.FilePath (addExtension, replaceExtension, takeExtension)
44−import Text.Pandoc.BCP47 (Lang (..), renderLang)
45−import Text.Pandoc.Builder
37+import Text.Collate.Lang (renderLang)
38+import Text.Pandoc.Builder as B
4639import Text.Pandoc.Class.PandocPure (PandocPure)
4740import Text.Pandoc.Class.PandocMonad (PandocMonad (..), getResourcePath,
48− readFileFromDirs, report, setResourcePath,
49− setTranslations, translateTerm)
41+ readFileFromDirs, report,
42+ setResourcePath)
5043import Text.Pandoc.Error (PandocError (PandocParseError, PandocParsecError))
51−import Text.Pandoc.Highlighting (fromListingsLanguage, languagesByExtension)
44+import Text.Pandoc.Highlighting (languagesByExtension)
5245import Text.Pandoc.ImageSize (numUnit, showFl)
5346import Text.Pandoc.Logging
5447import Text.Pandoc.Options
5548import Text.Pandoc.Parsing hiding (blankline, many, mathDisplay, mathInline,
5649 optional, space, spaces, withRaw, (<|>))
57−import Text.Pandoc.Readers.LaTeX.Types (ExpansionPoint (..), Macro (..),
58− ArgSpec (..), Tok (..), TokType (..))
50+import Text.Pandoc.Readers.LaTeX.Types (Tok (..), TokType (..))
5951import Text.Pandoc.Readers.LaTeX.Parsing
60−import Text.Pandoc.Readers.LaTeX.Lang (polyglossiaLangToBCP47,
61− babelLangToBCP47)
62−import Text.Pandoc.Readers.LaTeX.SIunitx
52+import Text.Pandoc.Readers.LaTeX.Citation (citationCommands, cites)
53+import Text.Pandoc.Readers.LaTeX.Math (dollarsMath, inlineEnvironments,
54+ inlineEnvironment,
55+ mathDisplay, mathInline,
56+ newtheorem, theoremstyle, proof,
57+ theoremEnvironment)
58+import Text.Pandoc.Readers.LaTeX.Table (tableEnvironments)
59+import Text.Pandoc.Readers.LaTeX.Macro (macroDef)
60+import Text.Pandoc.Readers.LaTeX.Lang (inlineLanguageCommands,
61+ enquoteCommands,
62+ babelLangToBCP47, setDefaultLanguage)
63+import Text.Pandoc.Readers.LaTeX.SIunitx (siunitxCommands)
64+import Text.Pandoc.Readers.LaTeX.Inline (acronymCommands, refCommands,
65+ nameCommands, charCommands,
66+ accentCommands,
67+ biblatexInlineCommands,
68+ verbCommands, rawInlineOr,
69+ listingsLanguage)
6370import Text.Pandoc.Shared
64−import qualified Text.Pandoc.Translations as Translations
6571import Text.Pandoc.Walk
66−import qualified Text.Pandoc.Builder as B
67−import qualified Data.Text.Normalize as Normalize
68−import Safe
72+import Data.List.NonEmpty (nonEmpty)
6973
7074-- for debugging:
7175-- import Text.Pandoc.Extensions (getDefaultExtensions)
@@ -73,16 +77,17 @@ import Safe
7377-- import Debug.Trace (traceShowId)
7478
7579-- | Parse LaTeX from string and return 'Pandoc' document.
76−readLaTeX :: PandocMonad m
80+readLaTeX :: (PandocMonad m, ToSources a)
7781 => ReaderOptions -- ^ Reader options
78− -> Text -- ^ String to parse (assumes @'\n'@ line endings)
82+ -> a -- ^ Input to parse
7983 -> m Pandoc
8084readLaTeX opts ltx = do
85+ let sources = toSources ltx
8186 parsed <- runParserT parseLaTeX def{ sOptions = opts } "source"
82− (tokenize "source" (crFilter ltx))
87+ (tokenizeSources sources)
8388 case parsed of
8489 Right result -> return result
85− Left e -> throwError $ PandocParsecError ltx e
90+ Left e -> throwError $ PandocParsecError sources e
8691
8792parseLaTeX :: PandocMonad m => LP m Pandoc
8893parseLaTeX = do
@@ -93,11 +98,7 @@ parseLaTeX = do
9398 let doc' = doc bs
9499 let headerLevel (Header n _ _) = [n]
95100 headerLevel _ = []
96−#if MIN_VERSION_safe(0,3,18)
97− let bottomLevel = minimumBound 1 $ query headerLevel doc'
98−#else
99− let bottomLevel = minimumDef 1 $ query headerLevel doc'
100−#endif
101+ let bottomLevel = maybe 1 minimum $ nonEmpty $ query headerLevel doc'
101102 let adjustHeaders m (Header n attr ils) = Header (n+m) attr ils
102103 adjustHeaders _ x = x
103104 let (Pandoc _ bs') =
@@ -132,11 +133,11 @@ resolveRefs _ x = x
132133
133134
134135rawLaTeXBlock :: (PandocMonad m, HasMacros s, HasReaderOptions s)
135− => ParserT Text s m Text
136+ => ParserT Sources s m Text
136137rawLaTeXBlock = do
137138 lookAhead (try (char '\\' >> letter))
138139 inp <- getInput
139− let toks = tokenize "source" inp
140+ let toks = tokenizeSources inp
140141 snd <$> (rawLaTeXParser toks False (macroDef (const mempty)) blocks
141142 <|> rawLaTeXParser toks True
142143 (do choice (map controlSeq
@@ -163,14 +164,14 @@ beginOrEndCommand = try $ do
163164 (txt <> untokenize rawargs)
164165
165166rawLaTeXInline :: (PandocMonad m, HasMacros s, HasReaderOptions s)
166− => ParserT Text s m Text
167+ => ParserT Sources s m Text
167168rawLaTeXInline = do
168169 lookAhead (try (char '\\' >> letter))
169170 inp <- getInput
170− let toks = tokenize "source" inp
171+ let toks = tokenizeSources inp
171172 raw <- snd <$>
172173 ( rawLaTeXParser toks True
173− (mempty <$ (controlSeq "input" >> skipMany opt >> braced))
174+ (mempty <$ (controlSeq "input" >> skipMany rawopt >> braced))
174175 inlines
175176 <|> rawLaTeXParser toks True (inlineEnvironment <|> inlineCommand')
176177 inlines
@@ -178,11 +179,11 @@ rawLaTeXInline = do
178179 finalbraces <- mconcat <$> many (try (string "{}")) -- see #5439
179180 return $ raw <> T.pack finalbraces
180181
181−inlineCommand :: PandocMonad m => ParserT Text ParserState m Inlines
182+inlineCommand :: PandocMonad m => ParserT Sources ParserState m Inlines
182183inlineCommand = do
183184 lookAhead (try (char '\\' >> letter))
184185 inp <- getInput
185− let toks = tokenize "source" inp
186+ let toks = tokenizeSources inp
186187 fst <$> rawLaTeXParser toks True (inlineEnvironment <|> inlineCommand')
187188 inlines
188189
@@ -191,12 +192,6 @@ inlineCommand = do
191192word :: PandocMonad m => LP m Inlines
192193word = str . untoken <$> satisfyTok isWordTok
193194
194−regularSymbol :: PandocMonad m => LP m Inlines
195−regularSymbol = str . untoken <$> satisfyTok isRegularSymbol
196− where isRegularSymbol (Tok _ Symbol t) = not $ T.any isSpecial t
197− isRegularSymbol _ = False
198− isSpecial c = c `Set.member` specialChars
199−
200195inlineGroup :: PandocMonad m => LP m Inlines
201196inlineGroup = do
202197 ils <- grouped inline
@@ -237,19 +232,6 @@ mkImage options (T.unpack -> src) = do
237232 _ -> return src
238233 return $ imageWith attr (T.pack src') "" alt
239234
240−doxspace :: PandocMonad m => LP m Inlines
241−doxspace =
242− (space <$ lookAhead (satisfyTok startsWithLetter)) <|> return mempty
243− where startsWithLetter (Tok _ Word t) =
244− case T.uncons t of
245− Just (c, _) | isLetter c -> True
246− _ -> False
247− startsWithLetter _ = False
248−
249−
250−lit :: Text -> LP m Inlines
251−lit = pure . str
252−
253235removeDoubleQuotes :: Text -> Text
254236removeDoubleQuotes t =
255237 Data.Maybe.fromMaybe t $ T.stripPrefix "\"" t >>= T.stripSuffix "\""
@@ -296,23 +278,14 @@ quoted' f starter ender = do
296278 cs -> cs)
297279 else lit startchs
298280
299−enquote :: PandocMonad m => Bool -> Maybe Text -> LP m Inlines
300−enquote starred mblang = do
301− skipopts
302− let lang = mblang >>= babelLangToBCP47
303− let langspan = case lang of
304− Nothing -> id
305− Just l -> spanWith ("",[],[("lang", renderLang l)])
306− quoteContext <- sQuoteContext <$> getState
307− if starred || quoteContext == InDoubleQuote
308− then singleQuoted . langspan <$> withQuoteContext InSingleQuote tok
309− else doubleQuoted . langspan <$> withQuoteContext InDoubleQuote tok
281+lit :: Text -> LP m Inlines
282+lit = pure . str
310283
311284blockquote :: PandocMonad m => Bool -> Maybe Text -> LP m Blocks
312285blockquote cvariant mblang = do
313286 citepar <- if cvariant
314287 then (\xs -> para (cite xs mempty))
315− <$> cites NormalCitation False
288+ <$> cites inline NormalCitation False
316289 else option mempty $ para <$> bracketed inline
317290 let lang = mblang >>= babelLangToBCP47
318291 let langdiv = case lang of
@@ -323,224 +296,13 @@ blockquote cvariant mblang = do
323296 optional $ symbolIn (".:;?!" :: [Char]) -- currently ignored
324297 return $ blockQuote . langdiv $ (bs <> citepar)
325298
326−doAcronym :: PandocMonad m => Text -> LP m Inlines
327−doAcronym form = do
328− acro <- braced
329− return . mconcat $ [spanWith ("",[],[("acronym-label", untokenize acro),
330− ("acronym-form", "singular+" <> form)])
331− $ str $ untokenize acro]
332−
333−doAcronymPlural :: PandocMonad m => Text -> LP m Inlines
334−doAcronymPlural form = do
335− acro <- braced
336− plural <- lit "s"
337− return . mconcat $ [spanWith ("",[],[("acronym-label", untokenize acro),
338− ("acronym-form", "plural+" <> form)]) $
339− mconcat [str $ untokenize acro, plural]]
340−
341−doverb :: PandocMonad m => LP m Inlines
342−doverb = do
343− Tok _ Symbol t <- anySymbol
344− marker <- case T.uncons t of
345− Just (c, ts) | T.null ts -> return c
346− _ -> mzero
347− withVerbatimMode $
348− code . untokenize <$>
349− manyTill (notFollowedBy newlineTok >> verbTok marker) (symbol marker)
350−
351−verbTok :: PandocMonad m => Char -> LP m Tok
352−verbTok stopchar = do
353− t@(Tok pos toktype txt) <- anyTok
354− case T.findIndex (== stopchar) txt of
355− Nothing -> return t
356− Just i -> do
357− let (t1, t2) = T.splitAt i txt
358− inp <- getInput
359− setInput $ Tok (incSourceColumn pos i) Symbol (T.singleton stopchar)
360− : totoks (incSourceColumn pos (i + 1)) (T.drop 1 t2) ++ inp
361− return $ Tok pos toktype t1
362−
363−listingsLanguage :: [(Text, Text)] -> Maybe Text
364−listingsLanguage opts =
365− case lookup "language" opts of
366− Nothing -> Nothing
367− Just l -> fromListingsLanguage l `mplus` Just l
368−
369−dolstinline :: PandocMonad m => LP m Inlines
370−dolstinline = do
371− options <- option [] keyvals
372− let classes = maybeToList $ listingsLanguage options
373− doinlinecode classes
374−
375−domintinline :: PandocMonad m => LP m Inlines
376−domintinline = do
377− skipopts
378− cls <- untokenize <$> braced
379− doinlinecode [cls]
380−
381−doinlinecode :: PandocMonad m => [Text] -> LP m Inlines
382−doinlinecode classes = do
383− Tok _ Symbol t <- anySymbol
384− marker <- case T.uncons t of
385− Just (c, ts) | T.null ts -> return c
386− _ -> mzero
387− let stopchar = if marker == '{' then '}' else marker
388− withVerbatimMode $
389− codeWith ("",classes,[]) . T.map nlToSpace . untokenize <$>
390− manyTill (verbTok stopchar) (symbol stopchar)
391−
392−nlToSpace :: Char -> Char
393−nlToSpace '\n' = ' '
394−nlToSpace x = x
395−
396−mathDisplay :: Text -> Inlines
397−mathDisplay = displayMath . trimMath
398−
399−mathInline :: Text -> Inlines
400−mathInline = math . trimMath
401−
402−dollarsMath :: PandocMonad m => LP m Inlines
403−dollarsMath = do
404− symbol '$'
405− display <- option False (True <$ symbol '$')
406− (do contents <- try $ untokenize <$> pDollarsMath 0
407− if display
408− then mathDisplay contents <$ symbol '$'
409− else return $ mathInline contents)
410− <|> (guard display >> return (mathInline ""))
411−
412−-- Int is number of embedded groupings
413−pDollarsMath :: PandocMonad m => Int -> LP m [Tok]
414−pDollarsMath n = do
415− tk@(Tok _ toktype t) <- anyTok
416− case toktype of
417− Symbol | t == "$"
418− , n == 0 -> return []
419− | t == "\\" -> do
420− tk' <- anyTok
421− (tk :) . (tk' :) <$> pDollarsMath n
422− | t == "{" -> (tk :) <$> pDollarsMath (n+1)
423− | t == "}" ->
424− if n > 0
425− then (tk :) <$> pDollarsMath (n-1)
426− else mzero
427− _ -> (tk :) <$> pDollarsMath n
428−
429−-- citations
430−
431−addPrefix :: [Inline] -> [Citation] -> [Citation]
432−addPrefix p (k:ks) = k {citationPrefix = p ++ citationPrefix k} : ks
433−addPrefix _ _ = []
434−
435−addSuffix :: [Inline] -> [Citation] -> [Citation]
436−addSuffix s ks@(_:_) =
437− let k = last ks
438− in init ks ++ [k {citationSuffix = citationSuffix k ++ s}]
439−addSuffix _ _ = []
440−
441−simpleCiteArgs :: PandocMonad m => LP m [Citation]
442−simpleCiteArgs = try $ do
443− first <- optionMaybe $ toList <$> opt
444− second <- optionMaybe $ toList <$> opt
445− keys <- try $ bgroup *> manyTill citationLabel egroup
446− let (pre, suf) = case (first , second ) of
447− (Just s , Nothing) -> (mempty, s )
448− (Just s , Just t ) -> (s , t )
449− _ -> (mempty, mempty)
450− conv k = Citation { citationId = k
451− , citationPrefix = []
452− , citationSuffix = []
453− , citationMode = NormalCitation
454− , citationHash = 0
455− , citationNoteNum = 0
456− }
457− return $ addPrefix pre $ addSuffix suf $ map conv keys
458−
459−citationLabel :: PandocMonad m => LP m Text
460−citationLabel = do
461− sp
462− untokenize <$>
463− (many1 (satisfyTok isWordTok <|> symbolIn bibtexKeyChar)
464− <* sp
465− <* optional (symbol ',')
466− <* sp)
467− where bibtexKeyChar = ".:;?!`'()/*@_+=-&[]" :: [Char]
468−
469−cites :: PandocMonad m => CitationMode -> Bool -> LP m [Citation]
470−cites mode multi = try $ do
471− cits <- if multi
472− then do
473− multiprenote <- optionMaybe $ toList <$> paropt
474− multipostnote <- optionMaybe $ toList <$> paropt
475− let (pre, suf) = case (multiprenote, multipostnote) of
476− (Just s , Nothing) -> (mempty, s)
477− (Nothing , Just t) -> (mempty, t)
478− (Just s , Just t ) -> (s, t)
479− _ -> (mempty, mempty)
480− tempCits <- many1 simpleCiteArgs
481− case tempCits of
482− (k:ks) -> case ks of
483− (_:_) -> return $ (addMprenote pre k : init ks) ++
484− [addMpostnote suf (last ks)]
485− _ -> return [addMprenote pre (addMpostnote suf k)]
486− _ -> return [[]]
487− else count 1 simpleCiteArgs
488− let cs = concat cits
489− return $ case mode of
490− AuthorInText -> case cs of
491− (c:rest) -> c {citationMode = mode} : rest
492− [] -> []
493− _ -> map (\a -> a {citationMode = mode}) cs
494− where mprenote (k:ks) = (k:ks) ++ [Space]
495− mprenote _ = mempty
496− mpostnote (k:ks) = [Str ",", Space] ++ (k:ks)
497− mpostnote _ = mempty
498− addMprenote mpn (k:ks) =
499− let mpnfinal = case citationPrefix k of
500− (_:_) -> mprenote mpn
501− _ -> mpn
502− in addPrefix mpnfinal (k:ks)
503− addMprenote _ _ = []
504− addMpostnote = addSuffix . mpostnote
505−
506−citation :: PandocMonad m => Text -> CitationMode -> Bool -> LP m Inlines
507−citation name mode multi = do
508− (c,raw) <- withRaw $ cites mode multi
509− return $ cite c (rawInline "latex" $ "\\" <> name <> untokenize raw)
510−
511−handleCitationPart :: Inlines -> [Citation]
512−handleCitationPart ils =
513− let isCite Cite{} = True
514− isCite _ = False
515− (pref, rest) = break isCite (toList ils)
516− in case rest of
517− (Cite cs _:suff) -> addPrefix pref $ addSuffix suff cs
518− _ -> []
519−
520−complexNatbibCitation :: PandocMonad m => CitationMode -> LP m Inlines
521−complexNatbibCitation mode = try $ do
522− (cs, raw) <-
523− withRaw $ concat <$> do
524− bgroup
525− items <- mconcat <$>
526− many1 (notFollowedBy (symbol ';') >> inline)
527− `sepBy1` symbol ';'
528− egroup
529− return $ map handleCitationPart items
530− case cs of
531− [] -> mzero
532− (c:cits) -> return $ cite (c{ citationMode = mode }:cits)
533− (rawInline "latex" $ "\\citetext" <> untokenize raw)
534−
535−inNote :: Inlines -> Inlines
536−inNote ils =
537− note $ para $ ils <> str "."
538−
539299inlineCommand' :: PandocMonad m => LP m Inlines
540300inlineCommand' = try $ do
541301 Tok _ (CtrlSeq name) cmd <- anyControlSeq
542302 guard $ name /= "begin" && name /= "end" && name /= "and"
543− star <- option "" ("*" <$ symbol '*' <* sp)
303+ star <- if T.all isAlphaNum name
304+ then option "" ("*" <$ symbol '*' <* sp)
305+ else pure ""
544306 overlay <- option "" overlaySpecification
545307 let name' = name <> star <> overlay
546308 let names = ordNub [name', name] -- check non-starred as fallback
@@ -551,28 +313,8 @@ inlineCommand' = try $ do
551313 <|> ignore rawcommand
552314 lookupListDefault raw names inlineCommands
553315
554−
555316tok :: PandocMonad m => LP m Inlines
556−tok = try $ spaces >> grouped inline <|> inlineCommand' <|> singleChar'
557− where singleChar' = do
558− Tok _ _ t <- singleChar
559− return $ str t
560−
561−opt :: PandocMonad m => LP m Inlines
562−opt = do
563− toks <- try (sp *> bracketedToks <* sp)
564− -- now parse the toks as inlines
565− st <- getState
566− parsed <- runParserT (mconcat <$> many inline) st "bracketed option" toks
567− case parsed of
568− Right result -> return result
569− Left e -> throwError $ PandocParsecError (untokenize toks) e
570−
571−paropt :: PandocMonad m => LP m Inlines
572−paropt = parenWrapped inline
573−
574−inBrackets :: Inlines -> Inlines
575−inBrackets x = str "[" <> x <> str "]"
317+tok = tokWith inline
576318
577319unescapeURL :: Text -> Text
578320unescapeURL = T.concat . go . T.splitOn "\\"
@@ -585,397 +327,107 @@ unescapeURL = T.concat . go . T.splitOn "\\"
585327 , isEscapable c = t
586328 | otherwise = "\\" <> t
587329
588−mathEnvWith :: PandocMonad m
589− => (Inlines -> a) -> Maybe Text -> Text -> LP m a
590−mathEnvWith f innerEnv name = f . mathDisplay . inner <$> mathEnv name
591− where inner x = case innerEnv of
592− Nothing -> x
593− Just y -> "\\begin{" <> y <> "}\n" <> x <>
594− "\\end{" <> y <> "}"
595−
596−mathEnv :: PandocMonad m => Text -> LP m Text
597−mathEnv name = do
598− skipopts
599− optional blankline
600− res <- manyTill anyTok (end_ name)
601− return $ stripTrailingNewlines $ untokenize res
602−
603−inlineEnvironment :: PandocMonad m => LP m Inlines
604−inlineEnvironment = try $ do
605− controlSeq "begin"
606− name <- untokenize <$> braced
607− M.findWithDefault mzero name inlineEnvironments
608−
609−inlineEnvironments :: PandocMonad m => M.Map Text (LP m Inlines)
610−inlineEnvironments = M.fromList [
611− ("displaymath", mathEnvWith id Nothing "displaymath")
612− , ("math", math <$> mathEnv "math")
613− , ("equation", mathEnvWith id Nothing "equation")
614− , ("equation*", mathEnvWith id Nothing "equation*")
615− , ("gather", mathEnvWith id (Just "gathered") "gather")
616− , ("gather*", mathEnvWith id (Just "gathered") "gather*")
617− , ("multline", mathEnvWith id (Just "gathered") "multline")
618− , ("multline*", mathEnvWith id (Just "gathered") "multline*")
619− , ("eqnarray", mathEnvWith id (Just "aligned") "eqnarray")
620− , ("eqnarray*", mathEnvWith id (Just "aligned") "eqnarray*")
621− , ("align", mathEnvWith id (Just "aligned") "align")
622− , ("align*", mathEnvWith id (Just "aligned") "align*")
623− , ("alignat", mathEnvWith id (Just "aligned") "alignat")
624− , ("alignat*", mathEnvWith id (Just "aligned") "alignat*")
625− , ("dmath", mathEnvWith id Nothing "dmath")
626− , ("dmath*", mathEnvWith id Nothing "dmath*")
627− , ("dgroup", mathEnvWith id (Just "aligned") "dgroup")
628− , ("dgroup*", mathEnvWith id (Just "aligned") "dgroup*")
629− , ("darray", mathEnvWith id (Just "aligned") "darray")
630− , ("darray*", mathEnvWith id (Just "aligned") "darray*")
631− ]
632−
633330inlineCommands :: PandocMonad m => M.Map Text (LP m Inlines)
634−inlineCommands = M.union inlineLanguageCommands $ M.fromList
635− [ ("emph", extractSpaces emph <$> tok)
636− , ("textit", extractSpaces emph <$> tok)
637− , ("textsl", extractSpaces emph <$> tok)
638− , ("textsc", extractSpaces smallcaps <$> tok)
639− , ("textsf", extractSpaces (spanWith ("",["sans-serif"],[])) <$> tok)
640− , ("textmd", extractSpaces (spanWith ("",["medium"],[])) <$> tok)
641− , ("textrm", extractSpaces (spanWith ("",["roman"],[])) <$> tok)
642− , ("textup", extractSpaces (spanWith ("",["upright"],[])) <$> tok)
643− , ("texttt", ttfamily)
644− , ("sout", extractSpaces strikeout <$> tok)
645− , ("alert", skipopts >> spanWith ("",["alert"],[]) <$> tok) -- beamer
646− , ("lq", return (str "‘"))
647− , ("rq", return (str "’"))
648− , ("textquoteleft", return (str "‘"))
649− , ("textquoteright", return (str "’"))
650− , ("textquotedblleft", return (str "“"))
651− , ("textquotedblright", return (str "”"))
652− , ("textsuperscript", extractSpaces superscript <$> tok)
653− , ("textsubscript", extractSpaces subscript <$> tok)
654− , ("textbackslash", lit "\\")
655− , ("backslash", lit "\\")
656− , ("slash", lit "/")
657− , ("textbf", extractSpaces strong <$> tok)
658− , ("textnormal", extractSpaces (spanWith ("",["nodecor"],[])) <$> tok)
659− , ("underline", underline <$> tok)
660− , ("ldots", lit "…")
661− , ("vdots", lit "\8942")
662− , ("dots", lit "…")
663− , ("mdots", lit "…")
664− , ("sim", lit "~")
665− , ("sep", lit ",")
666− , ("label", rawInlineOr "label" dolabel)
667− , ("ref", rawInlineOr "ref" $ doref "ref")
668− , ("cref", rawInlineOr "cref" $ doref "ref") -- from cleveref.sty
669− , ("vref", rawInlineOr "vref" $ doref "ref+page") -- from varioref.sty
670− , ("eqref", rawInlineOr "eqref" $ doref "eqref") -- from amsmath.sty
671− , ("mbox", rawInlineOr "mbox" $ processHBox <$> tok)
672− , ("hbox", rawInlineOr "hbox" $ processHBox <$> tok)
673− , ("lettrine", rawInlineOr "lettrine" lettrine)
674− , ("(", mathInline . untokenize <$> manyTill anyTok (controlSeq ")"))
675− , ("[", mathDisplay . untokenize <$> manyTill anyTok (controlSeq "]"))
676− , ("ensuremath", mathInline . untokenize <$> braced)
677− , ("texorpdfstring", const <$> tok <*> tok)
678− , ("P", lit "¶")
679− , ("S", lit "§")
680− , ("$", lit "$")
681− , ("%", lit "%")
682− , ("&", lit "&")
683− , ("#", lit "#")
684− , ("_", lit "_")
685− , ("{", lit "{")
686− , ("}", lit "}")
687− , ("qed", lit "\a0\x25FB")
688− -- old TeX commands
689− , ("em", extractSpaces emph <$> inlines)
690− , ("it", extractSpaces emph <$> inlines)
691− , ("sl", extractSpaces emph <$> inlines)
692− , ("bf", extractSpaces strong <$> inlines)
693− , ("tt", code . stringify . toList <$> inlines)
694− , ("rm", inlines)
695− , ("itshape", extractSpaces emph <$> inlines)
696− , ("slshape", extractSpaces emph <$> inlines)
697− , ("scshape", extractSpaces smallcaps <$> inlines)
698− , ("bfseries", extractSpaces strong <$> inlines)
699− , ("MakeUppercase", makeUppercase <$> tok)
700− , ("MakeTextUppercase", makeUppercase <$> tok) -- textcase
701− , ("uppercase", makeUppercase <$> tok)
702− , ("MakeLowercase", makeLowercase <$> tok)
703− , ("MakeTextLowercase", makeLowercase <$> tok)
704− , ("lowercase", makeLowercase <$> tok)
705− , ("/", pure mempty) -- italic correction
706− , ("aa", lit "å")
707− , ("AA", lit "Å")
708− , ("ss", lit "ß")
709− , ("o", lit "ø")
710− , ("O", lit "Ø")
711− , ("L", lit "Ł")
712− , ("l", lit "ł")
713− , ("ae", lit "æ")
714− , ("AE", lit "Æ")
715− , ("oe", lit "œ")
716− , ("OE", lit "Œ")
717− , ("pounds", lit "£")
718− , ("euro", lit "€")
719− , ("copyright", lit "©")
720− , ("textasciicircum", lit "^")
721− , ("textasciitilde", lit "~")
722− , ("H", accent '\779' Nothing) -- hungarumlaut
723− , ("`", accent '\768' (Just '`')) -- grave
724− , ("'", accent '\769' (Just '\'')) -- acute
725− , ("^", accent '\770' (Just '^')) -- circ
726− , ("~", accent '\771' (Just '~')) -- tilde
727− , ("\"", accent '\776' Nothing) -- umlaut
728− , (".", accent '\775' Nothing) -- dot
729− , ("=", accent '\772' Nothing) -- macron
730− , ("|", accent '\781' Nothing) -- vertical line above
731− , ("b", accent '\817' Nothing) -- macron below
732− , ("c", accent '\807' Nothing) -- cedilla
733− , ("G", accent '\783' Nothing) -- doublegrave
734− , ("h", accent '\777' Nothing) -- hookabove
735− , ("d", accent '\803' Nothing) -- dotbelow
736− , ("f", accent '\785' Nothing) -- inverted breve
737− , ("r", accent '\778' Nothing) -- ringabove
738− , ("t", accent '\865' Nothing) -- double inverted breve
739− , ("U", accent '\782' Nothing) -- double vertical line above
740− , ("v", accent '\780' Nothing) -- hacek
741− , ("u", accent '\774' Nothing) -- breve
742− , ("k", accent '\808' Nothing) -- ogonek
743− , ("textogonekcentered", accent '\808' Nothing) -- ogonek
744− , ("i", lit "ı") -- dotless i
745− , ("j", lit "ȷ") -- dotless j
746− , ("newtie", accent '\785' Nothing) -- inverted breve
747− , ("textcircled", accent '\8413' Nothing) -- combining circle
748− , ("\\", linebreak <$ (do inTableCell <- sInTableCell <$> getState
749− guard $ not inTableCell
750− optional opt
751− spaces))
752− , (",", lit "\8198")
753− , ("@", pure mempty)
754− , (" ", lit "\160")
755− , ("ps", pure $ str "PS." <> space)
756− , ("TeX", lit "TeX")
757− , ("LaTeX", lit "LaTeX")
758− , ("bar", lit "|")
759− , ("textless", lit "<")
760− , ("textgreater", lit ">")
761− , ("thanks", skipopts >> note <$> grouped block)
762− , ("footnote", skipopts >> note <$> grouped block)
763− , ("passthrough", tok) -- \passthrough macro used by latex writer
764− -- for listings
765− , ("verb", doverb)
766− , ("lstinline", dolstinline)
767− , ("mintinline", domintinline)
768− , ("Verb", doverb)
769− , ("url", (\url -> link url "" (str url)) . unescapeURL . untokenize <$>
770− bracedUrl)
771− , ("nolinkurl", code . unescapeURL . untokenize <$> bracedUrl)
772− , ("href", do url <- bracedUrl
773− sp
774− link (unescapeURL $ untokenize url) "" <$> tok)
775− , ("includegraphics", do options <- option [] keyvals
776− src <- braced
777− mkImage options . unescapeURL . removeDoubleQuotes $
778− untokenize src)
779− , ("enquote*", enquote True Nothing)
780− , ("enquote", enquote False Nothing)
781− -- foreignquote is supposed to use native quote marks
782− , ("foreignquote*", braced >>= enquote True . Just . untokenize)
783− , ("foreignquote", braced >>= enquote False . Just . untokenize)
784− -- hypehnquote uses regular quotes
785− , ("hyphenquote*", braced >>= enquote True . Just . untokenize)
786− , ("hyphenquote", braced >>= enquote False . Just . untokenize)
787− , ("figurename", doTerm Translations.Figure)
788− , ("prefacename", doTerm Translations.Preface)
789− , ("refname", doTerm Translations.References)
790− , ("bibname", doTerm Translations.Bibliography)
791− , ("chaptername", doTerm Translations.Chapter)
792− , ("partname", doTerm Translations.Part)
793− , ("contentsname", doTerm Translations.Contents)
794− , ("listfigurename", doTerm Translations.ListOfFigures)
795− , ("listtablename", doTerm Translations.ListOfTables)
796− , ("indexname", doTerm Translations.Index)
797− , ("abstractname", doTerm Translations.Abstract)
798− , ("tablename", doTerm Translations.Table)
799− , ("enclname", doTerm Translations.Encl)
800− , ("ccname", doTerm Translations.Cc)
801− , ("headtoname", doTerm Translations.To)
802− , ("pagename", doTerm Translations.Page)
803− , ("seename", doTerm Translations.See)
804− , ("seealsoname", doTerm Translations.SeeAlso)
805− , ("proofname", doTerm Translations.Proof)
806− , ("glossaryname", doTerm Translations.Glossary)
807− , ("lstlistingname", doTerm Translations.Listing)
808− , ("cite", citation "cite" NormalCitation False)
809− , ("Cite", citation "Cite" NormalCitation False)
810− , ("citep", citation "citep" NormalCitation False)
811− , ("citep*", citation "citep*" NormalCitation False)
812− , ("citeal", citation "citeal" NormalCitation False)
813− , ("citealp", citation "citealp" NormalCitation False)
814− , ("citealp*", citation "citealp*" NormalCitation False)
815− , ("autocite", citation "autocite" NormalCitation False)
816− , ("smartcite", citation "smartcite" NormalCitation False)
817− , ("footcite", inNote <$> citation "footcite" NormalCitation False)
818− , ("parencite", citation "parencite" NormalCitation False)
819− , ("supercite", citation "supercite" NormalCitation False)
820− , ("footcitetext", inNote <$> citation "footcitetext" NormalCitation False)
821− , ("citeyearpar", citation "citeyearpar" SuppressAuthor False)
822− , ("citeyear", citation "citeyear" SuppressAuthor False)
823− , ("autocite*", citation "autocite*" SuppressAuthor False)
824− , ("cite*", citation "cite*" SuppressAuthor False)
825− , ("parencite*", citation "parencite*" SuppressAuthor False)
826− , ("textcite", citation "textcite" AuthorInText False)
827− , ("citet", citation "citet" AuthorInText False)
828− , ("citet*", citation "citet*" AuthorInText False)
829− , ("citealt", citation "citealt" AuthorInText False)
830− , ("citealt*", citation "citealt*" AuthorInText False)
831− , ("textcites", citation "textcites" AuthorInText True)
832− , ("cites", citation "cites" NormalCitation True)
833− , ("autocites", citation "autocites" NormalCitation True)
834− , ("footcites", inNote <$> citation "footcites" NormalCitation True)
835− , ("parencites", citation "parencites" NormalCitation True)
836− , ("supercites", citation "supercites" NormalCitation True)
837− , ("footcitetexts", inNote <$> citation "footcitetexts" NormalCitation True)
838− , ("Autocite", citation "Autocite" NormalCitation False)
839− , ("Smartcite", citation "Smartcite" NormalCitation False)
840− , ("Footcite", inNote <$> citation "Footcite" NormalCitation False)
841− , ("Parencite", citation "Parencite" NormalCitation False)
842− , ("Supercite", citation "Supercite" NormalCitation False)
843− , ("Footcitetext", inNote <$> citation "Footcitetext" NormalCitation False)
844− , ("Citeyearpar", citation "Citeyearpar" SuppressAuthor False)
845− , ("Citeyear", citation "Citeyear" SuppressAuthor False)
846− , ("Autocite*", citation "Autocite*" SuppressAuthor False)
847− , ("Cite*", citation "Cite*" SuppressAuthor False)
848− , ("Parencite*", citation "Parencite*" SuppressAuthor False)
849− , ("Textcite", citation "Textcite" AuthorInText False)
850− , ("Textcites", citation "Textcites" AuthorInText True)
851− , ("Cites", citation "Cites" NormalCitation True)
852− , ("Autocites", citation "Autocites" NormalCitation True)
853− , ("Footcites", inNote <$> citation "Footcites" NormalCitation True)
854− , ("Parencites", citation "Parencites" NormalCitation True)
855− , ("Supercites", citation "Supercites" NormalCitation True)
856− , ("Footcitetexts", inNote <$> citation "Footcitetexts" NormalCitation True)
857− , ("citetext", complexNatbibCitation NormalCitation)
858− , ("citeauthor", (try (tok *> sp *> controlSeq "citetext") *>
859− complexNatbibCitation AuthorInText)
860− <|> citation "citeauthor" AuthorInText False)
861− , ("nocite", mempty <$ (citation "nocite" NormalCitation False >>=
862− addMeta "nocite"))
863− , ("hyperlink", hyperlink)
864− , ("hypertarget", hypertargetInline)
865− -- glossaries package
866− , ("gls", doAcronym "short")
867− , ("Gls", doAcronym "short")
868− , ("glsdesc", doAcronym "long")
869− , ("Glsdesc", doAcronym "long")
870− , ("GLSdesc", doAcronym "long")
871− , ("acrlong", doAcronym "long")
872− , ("Acrlong", doAcronym "long")
873− , ("acrfull", doAcronym "full")
874− , ("Acrfull", doAcronym "full")
875− , ("acrshort", doAcronym "abbrv")
876− , ("Acrshort", doAcronym "abbrv")
877− , ("glspl", doAcronymPlural "short")
878− , ("Glspl", doAcronymPlural "short")
879− , ("glsdescplural", doAcronymPlural "long")
880− , ("Glsdescplural", doAcronymPlural "long")
881− , ("GLSdescplural", doAcronymPlural "long")
882− -- acronyms package
883− , ("ac", doAcronym "short")
884− , ("acf", doAcronym "full")
885− , ("acs", doAcronym "abbrv")
886− , ("acl", doAcronym "long")
887− , ("acp", doAcronymPlural "short")
888− , ("acfp", doAcronymPlural "full")
889− , ("acsp", doAcronymPlural "abbrv")
890− , ("aclp", doAcronymPlural "long")
891− , ("Ac", doAcronym "short")
892− , ("Acf", doAcronym "full")
893− , ("Acs", doAcronym "abbrv")
894− , ("Acl", doAcronym "long")
895− , ("Acp", doAcronymPlural "short")
896− , ("Acfp", doAcronymPlural "full")
897− , ("Acsp", doAcronymPlural "abbrv")
898− , ("Aclp", doAcronymPlural "long")
899− -- siuntix
900− , ("si", skipopts *> dosi tok)
901− , ("SI", doSI tok)
902− , ("SIrange", doSIrange True tok)
903− , ("numrange", doSIrange False tok)
904− , ("numlist", doSInumlist)
905− , ("num", doSInum)
906− , ("ang", doSIang)
907− -- hyphenat
908− , ("bshyp", lit "\\\173")
909− , ("fshyp", lit "/\173")
910− , ("dothyp", lit ".\173")
911− , ("colonhyp", lit ":\173")
912− , ("hyp", lit "-")
913− , ("nohyphens", tok)
914− , ("textnhtt", ttfamily)
915− , ("nhttfamily", ttfamily)
916− -- LaTeX colors
917− , ("textcolor", coloredInline "color")
918− , ("colorbox", coloredInline "background-color")
919− -- fontawesome
920− , ("faCheck", lit "\10003")
921− , ("faClose", lit "\10007")
922− -- xspace
923− , ("xspace", doxspace)
924− -- etoolbox
925− , ("ifstrequal", ifstrequal)
926− , ("newtoggle", braced >>= newToggle)
927− , ("toggletrue", braced >>= setToggle True)
928− , ("togglefalse", braced >>= setToggle False)
929− , ("iftoggle", try $ ifToggle >> inline)
930− -- biblatex misc
931− , ("RN", romanNumeralUpper)
932− , ("Rn", romanNumeralLower)
933− -- babel
934− , ("foreignlanguage", foreignlanguage)
935− -- include
936− , ("input", rawInlineOr "input" $ include "input")
937− -- soul package
938− , ("ul", underline <$> tok)
939− -- ulem package
940− , ("uline", underline <$> tok)
941− -- plain tex stuff that should just be passed through as raw tex
942− , ("ifdim", ifdim)
943− -- bibtex
944− , ("mkbibquote", spanWith nullAttr . doubleQuoted <$> tok)
945− , ("mkbibemph", spanWith nullAttr . emph <$> tok)
946− , ("mkbibitalic", spanWith nullAttr . emph <$> tok)
947− , ("mkbibbold", spanWith nullAttr . strong <$> tok)
948− , ("mkbibparens",
949− spanWith nullAttr . (\x -> str "(" <> x <> str ")") <$> tok)
950− , ("mkbibbrackets",
951− spanWith nullAttr . (\x -> str "[" <> x <> str "]") <$> tok)
952− , ("autocap", spanWith nullAttr <$> tok)
953− , ("textnormal", spanWith ("",["nodecor"],[]) <$> tok)
954− , ("bibstring",
955− (\x -> spanWith ("",[],[("bibstring",x)]) (str x)) . untokenize
956− <$> braced)
957− , ("adddot", pure (str "."))
958− , ("adddotspace", pure (spanWith nullAttr (str "." <> space)))
959− , ("addabbrvspace", pure space)
960− , ("hyphen", pure (str "-"))
961− ]
962−
963−accent :: PandocMonad m => Char -> Maybe Char -> LP m Inlines
964−accent combiningAccent fallBack = try $ do
965− ils <- tok
966− case toList ils of
967− (Str (T.uncons -> Just (x, xs)) : ys) -> return $ fromList $
968− -- try to normalize to the combined character:
969− Str (Normalize.normalize Normalize.NFC
970− (T.pack [x, combiningAccent]) <> xs) : ys
971− [Space] -> return $ str $ T.singleton $ fromMaybe combiningAccent fallBack
972− [] -> return $ str $ T.singleton $ fromMaybe combiningAccent fallBack
973− _ -> return ils
974−
331+inlineCommands = M.unions
332+ [ accentCommands tok
333+ , citationCommands inline
334+ , siunitxCommands tok
335+ , acronymCommands
336+ , refCommands
337+ , nameCommands
338+ , verbCommands
339+ , charCommands
340+ , enquoteCommands tok
341+ , inlineLanguageCommands tok
342+ , biblatexInlineCommands tok
343+ , rest ]
344+ where
345+ rest = M.fromList
346+ [ ("emph", extractSpaces emph <$> tok)
347+ , ("textit", extractSpaces emph <$> tok)
348+ , ("textsl", extractSpaces emph <$> tok)
349+ , ("textsc", extractSpaces smallcaps <$> tok)
350+ , ("textsf", extractSpaces (spanWith ("",["sans-serif"],[])) <$> tok)
351+ , ("textmd", extractSpaces (spanWith ("",["medium"],[])) <$> tok)
352+ , ("textrm", extractSpaces (spanWith ("",["roman"],[])) <$> tok)
353+ , ("textup", extractSpaces (spanWith ("",["upright"],[])) <$> tok)
354+ , ("texttt", ttfamily)
355+ , ("sout", extractSpaces strikeout <$> tok)
356+ , ("alert", skipopts >> spanWith ("",["alert"],[]) <$> tok) -- beamer
357+ , ("textsuperscript", extractSpaces superscript <$> tok)
358+ , ("textsubscript", extractSpaces subscript <$> tok)
359+ , ("textbf", extractSpaces strong <$> tok)
360+ , ("textnormal", extractSpaces (spanWith ("",["nodecor"],[])) <$> tok)
361+ , ("underline", underline <$> tok)
362+ , ("mbox", rawInlineOr "mbox" $ processHBox <$> tok)
363+ , ("hbox", rawInlineOr "hbox" $ processHBox <$> tok)
364+ , ("lettrine", rawInlineOr "lettrine" lettrine)
365+ , ("(", mathInline . untokenize <$> manyTill anyTok (controlSeq ")"))
366+ , ("[", mathDisplay . untokenize <$> manyTill anyTok (controlSeq "]"))
367+ , ("ensuremath", mathInline . untokenize <$> braced)
368+ , ("texorpdfstring", const <$> tok <*> tok)
369+ -- old TeX commands
370+ , ("em", extractSpaces emph <$> inlines)
371+ , ("it", extractSpaces emph <$> inlines)
372+ , ("sl", extractSpaces emph <$> inlines)
373+ , ("bf", extractSpaces strong <$> inlines)
374+ , ("tt", code . stringify . toList <$> inlines)
375+ , ("rm", inlines)
376+ , ("itshape", extractSpaces emph <$> inlines)
377+ , ("slshape", extractSpaces emph <$> inlines)
378+ , ("scshape", extractSpaces smallcaps <$> inlines)
379+ , ("bfseries", extractSpaces strong <$> inlines)
380+ , ("MakeUppercase", makeUppercase <$> tok)
381+ , ("MakeTextUppercase", makeUppercase <$> tok) -- textcase
382+ , ("uppercase", makeUppercase <$> tok)
383+ , ("MakeLowercase", makeLowercase <$> tok)
384+ , ("MakeTextLowercase", makeLowercase <$> tok)
385+ , ("lowercase", makeLowercase <$> tok)
386+ , ("thanks", skipopts >> note <$> grouped block)
387+ , ("footnote", skipopts >> note <$> grouped block)
388+ , ("passthrough", tok) -- \passthrough macro used by latex writer
389+ -- for listings
390+ , ("includegraphics", do options <- option [] keyvals
391+ src <- braced
392+ mkImage options .
393+ unescapeURL .
394+ removeDoubleQuotes $ untokenize src)
395+ -- hyperref
396+ , ("url", (\url -> link url "" (str url)) . unescapeURL . untokenize <$>
397+ bracedUrl)
398+ , ("nolinkurl", code . unescapeURL . untokenize <$> bracedUrl)
399+ , ("href", do url <- bracedUrl
400+ sp
401+ link (unescapeURL $ untokenize url) "" <$> tok)
402+ , ("hyperlink", hyperlink)
403+ , ("hyperref", hyperref)
404+ , ("hypertarget", hypertargetInline)
405+ -- hyphenat
406+ , ("nohyphens", tok)
407+ , ("textnhtt", ttfamily)
408+ , ("nhttfamily", ttfamily)
409+ -- LaTeX colors
410+ , ("textcolor", coloredInline "color")
411+ , ("colorbox", coloredInline "background-color")
412+ -- etoolbox
413+ , ("ifstrequal", ifstrequal)
414+ , ("newtoggle", braced >>= newToggle)
415+ , ("toggletrue", braced >>= setToggle True)
416+ , ("togglefalse", braced >>= setToggle False)
417+ , ("iftoggle", try $ ifToggle >> inline)
418+ -- include
419+ , ("input", rawInlineOr "input" $ include "input")
420+ -- soul package
421+ , ("ul", underline <$> tok)
422+ -- ulem package
423+ , ("uline", underline <$> tok)
424+ -- plain tex stuff that should just be passed through as raw tex
425+ , ("ifdim", ifdim)
426+ ]
975427
976428lettrine :: PandocMonad m => LP m Inlines
977429lettrine = do
978− optional opt
430+ optional rawopt
979431 x <- tok
980432 y <- tok
981433 return $ extractSpaces (spanWith ("",["lettrine"],[])) x <> smallcaps y
@@ -995,32 +447,18 @@ alterStr :: (Text -> Text) -> Inline -> Inline
995447alterStr f (Str xs) = Str (f xs)
996448alterStr _ x = x
997449
998−foreignlanguage :: PandocMonad m => LP m Inlines
999−foreignlanguage = do
1000− babelLang <- untokenize <$> braced
1001− case babelLangToBCP47 babelLang of
1002− Just lang -> spanWith ("", [], [("lang", renderLang lang)]) <$> tok
1003− _ -> tok
1004−
1005−inlineLanguageCommands :: PandocMonad m => M.Map Text (LP m Inlines)
1006−inlineLanguageCommands = M.fromList $ mk <$> M.toList polyglossiaLangToBCP47
1007− where
1008− mk (polyglossia, bcp47Func) =
1009− ("text" <> polyglossia, inlineLanguage bcp47Func)
1010−
1011−inlineLanguage :: PandocMonad m => (Text -> Lang) -> LP m Inlines
1012−inlineLanguage bcp47Func = do
1013− o <- option "" $ T.filter (\c -> c /= '[' && c /= ']')
1014− <$> rawopt
1015− let lang = renderLang $ bcp47Func o
1016− extractSpaces (spanWith ("", [], [("lang", lang)])) <$> tok
1017−
1018450hyperlink :: PandocMonad m => LP m Inlines
1019451hyperlink = try $ do
1020452 src <- untokenize <$> braced
1021453 lab <- tok
1022454 return $ link ("#" <> src) "" lab
1023455
456+hyperref :: PandocMonad m => LP m Inlines
457+hyperref = try $ do
458+ url <- (("#" <>) . untokenize <$> try (sp *> bracketedToks <* sp))
459+ <|> untokenize <$> (bracedUrl <* bracedUrl <* bracedUrl)
460+ link url "" <$> tok
461+
1024462hypertargetBlock :: PandocMonad m => LP m Blocks
1025463hypertargetBlock = try $ do
1026464 ref <- untokenize <$> braced
@@ -1035,31 +473,6 @@ hypertargetInline = try $ do
1035473 ils <- grouped inline
1036474 return $ spanWith (ref, [], []) ils
1037475
1038−romanNumeralUpper :: (PandocMonad m) => LP m Inlines
1039−romanNumeralUpper =
1040− str . toRomanNumeral <$> romanNumeralArg
1041−
1042−romanNumeralLower :: (PandocMonad m) => LP m Inlines
1043−romanNumeralLower =
1044− str . T.toLower . toRomanNumeral <$> romanNumeralArg
1045−
1046−romanNumeralArg :: (PandocMonad m) => LP m Int
1047−romanNumeralArg = spaces *> (parser <|> inBraces)
1048− where
1049− inBraces = do
1050− symbol '{'
1051− spaces
1052− res <- parser
1053− spaces
1054− symbol '}'
1055− return res
1056− parser = do
1057− s <- untokenize <$> many1 (satisfyTok isWordTok)
1058− let (digits, rest) = T.span isDigit s
1059− unless (T.null rest) $
1060− Prelude.fail "Non-digits in argument to \\Rn or \\RN"
1061− safeRead digits
1062−
1063476newToggle :: (Monoid a, PandocMonad m) => [Tok] -> LP m a
1064477newToggle name = do
1065478 updateState $ \st ->
@@ -1090,9 +503,6 @@ ifToggle = do
1090503 report $ UndefinedToggle name' pos
1091504 return ()
1092505
1093−doTerm :: PandocMonad m => Translations.Term -> LP m Inlines
1094−doTerm term = str <$> translateTerm term
1095−
1096506ifstrequal :: (PandocMonad m, Monoid a) => LP m a
1097507ifstrequal = do
1098508 str1 <- tok
@@ -1113,13 +523,6 @@ coloredInline stylename = do
1113523ttfamily :: PandocMonad m => LP m Inlines
1114524ttfamily = code . stringify . toList <$> tok
1115525
1116−rawInlineOr :: PandocMonad m => Text -> LP m Inlines -> LP m Inlines
1117−rawInlineOr name' fallback = do
1118− parseRaw <- extensionEnabled Ext_raw_tex <$> getOption readerExtensions
1119− if parseRaw
1120− then rawInline "latex" <$> getRawCommand name' ("\\" <> name')
1121− else fallback
1122−
1123526processHBox :: Inlines -> Inlines
1124527processHBox = walk convert
1125528 where
@@ -1170,67 +573,67 @@ treatAsInline = Set.fromList
1170573 , "pagebreak"
1171574 ]
1172575
1173−label :: PandocMonad m => LP m ()
1174−label = do
1175− controlSeq "label"
1176− t <- braced
1177− updateState $ \st -> st{ sLastLabel = Just $ untokenize t }
1178−
1179−dolabel :: PandocMonad m => LP m Inlines
1180−dolabel = do
1181− v <- braced
1182− let refstr = untokenize v
1183− updateState $ \st ->
1184− st{ sLastLabel = Just refstr }
1185− return $ spanWith (refstr,[],[("label", refstr)])
1186− $ inBrackets $ str $ untokenize v
1187−
1188−doref :: PandocMonad m => Text -> LP m Inlines
1189−doref cls = do
1190− v <- braced
1191− let refstr = untokenize v
1192− return $ linkWith ("",[],[ ("reference-type", cls)
1193− , ("reference", refstr)])
1194− ("#" <> refstr)
1195− ""
1196− (inBrackets $ str refstr)
1197−
1198576lookupListDefault :: (Ord k) => v -> [k] -> M.Map k v -> v
1199577lookupListDefault d = (fromMaybe d .) . lookupList
1200578 where lookupList l m = msum $ map (`M.lookup` m) l
1201579
1202580inline :: PandocMonad m => LP m Inlines
1203−inline = (mempty <$ comment)
1204− <|> (space <$ whitespace)
1205− <|> (softbreak <$ endline)
1206− <|> word
1207− <|> macroDef (rawInline "latex")
1208− <|> inlineCommand'
1209− <|> inlineEnvironment
1210− <|> inlineGroup
1211− <|> (symbol '-' *>
1212− option (str "-") (symbol '-' *>
1213− option (str "–") (str "—" <$ symbol '-')))
1214− <|> doubleQuote
1215− <|> singleQuote
1216− <|> (str "”" <$ try (symbol '\'' >> symbol '\''))
1217− <|> (str "”" <$ symbol '”')
1218− <|> (str "’" <$ symbol '\'')
1219− <|> (str "’" <$ symbol '’')
1220− <|> (str "\160" <$ symbol '~')
1221− <|> dollarsMath
1222− <|> (guardEnabled Ext_literate_haskell *> symbol '|' *> doLHSverb)
1223− <|> (str . T.singleton <$> primEscape)
1224− <|> regularSymbol
1225− <|> (do res <- symbolIn "#^'`\"[]&"
1226− pos <- getPosition
1227− let s = untoken res
1228− report $ ParsingUnescaped s pos
1229− return $ str s)
581+inline = do
582+ Tok pos toktype t <- lookAhead anyTok
583+ let symbolAsString = str . untoken <$> anySymbol
584+ let unescapedSymbolAsString =
585+ do s <- untoken <$> anySymbol
586+ report $ ParsingUnescaped s pos
587+ return $ str s
588+ case toktype of
589+ Comment -> mempty <$ comment
590+ Spaces -> space <$ whitespace
591+ Newline -> softbreak <$ endline
592+ Word -> word
593+ Esc1 -> str . T.singleton <$> primEscape
594+ Esc2 -> str . T.singleton <$> primEscape
595+ Symbol ->
596+ case t of
597+ "-" -> symbol '-' *>
598+ option (str "-") (symbol '-' *>
599+ option (str "–") (str "—" <$ symbol '-'))
600+ "'" -> symbol '\'' *>
601+ option (str "’") (str "”" <$ symbol '\'')
602+ "~" -> str "\160" <$ symbol '~'
603+ "`" -> doubleQuote <|> singleQuote <|> symbolAsString
604+ "\"" -> doubleQuote <|> singleQuote <|> symbolAsString
605+ "“" -> doubleQuote <|> symbolAsString
606+ "‘" -> singleQuote <|> symbolAsString
607+ "$" -> dollarsMath <|> unescapedSymbolAsString
608+ "|" -> (guardEnabled Ext_literate_haskell *>
609+ symbol '|' *> doLHSverb) <|> symbolAsString
610+ "{" -> inlineGroup
611+ "#" -> unescapedSymbolAsString
612+ "&" -> unescapedSymbolAsString
613+ "_" -> unescapedSymbolAsString
614+ "^" -> unescapedSymbolAsString
615+ "\\" -> mzero
616+ "}" -> mzero
617+ _ -> symbolAsString
618+ CtrlSeq _ -> macroDef (rawInline "latex")
619+ <|> inlineCommand'
620+ <|> inlineEnvironment
621+ <|> inlineGroup
622+ _ -> mzero
1230623
1231624inlines :: PandocMonad m => LP m Inlines
1232625inlines = mconcat <$> many inline
1233626
627+opt :: PandocMonad m => LP m Inlines
628+opt = do
629+ toks <- try (sp *> bracketedToks <* sp)
630+ -- now parse the toks as inlines
631+ st <- getState
632+ parsed <- runParserT (mconcat <$> many inline) st "bracketed option" toks
633+ case parsed of
634+ Right result -> return result
635+ Left e -> throwError $ PandocParsecError (toSources toks) e
636+
1234637-- block elements:
1235638
1236639preamble :: PandocMonad m => LP m Blocks
@@ -1324,10 +727,6 @@ insertIncluded defaultExtension f' = do
1324727 getInput >>= setInput . (tokenize f contents ++)
1325728 updateState dropLatestIncludeFile
1326729
1327−addMeta :: PandocMonad m => ToMetaValue a => Text -> a -> LP m ()
1328−addMeta field val = updateState $ \st ->
1329− st{ sMeta = addMetaField field val $ sMeta st }
1330−
1331730authors :: PandocMonad m => LP m ()
1332731authors = try $ do
1333732 bgroup
@@ -1336,150 +735,6 @@ authors = try $ do
1336735 egroup
1337736 addMeta "author" (map trimInlines auths)
1338737
1339−macroDef :: (PandocMonad m, Monoid a) => (Text -> a) -> LP m a
1340−macroDef constructor = do
1341− (_, s) <- withRaw (commandDef <|> environmentDef)
1342− (constructor (untokenize s) <$
1343− guardDisabled Ext_latex_macros)
1344− <|> return mempty
1345− where commandDef = do
1346− (name, macro') <- newcommand <|> letmacro <|> defmacro
1347− guardDisabled Ext_latex_macros <|>
1348− updateState (\s -> s{ sMacros = M.insert name macro' (sMacros s) })
1349− environmentDef = do
1350− mbenv <- newenvironment
1351− case mbenv of
1352− Nothing -> return ()
1353− Just (name, macro1, macro2) ->
1354− guardDisabled Ext_latex_macros <|>
1355− do updateState $ \s -> s{ sMacros =
1356− M.insert name macro1 (sMacros s) }
1357− updateState $ \s -> s{ sMacros =
1358− M.insert ("end" <> name) macro2 (sMacros s) }
1359− -- @\newenvironment{envname}[n-args][default]{begin}{end}@
1360− -- is equivalent to
1361− -- @\newcommand{\envname}[n-args][default]{begin}@
1362− -- @\newcommand{\endenvname}@
1363−
1364−letmacro :: PandocMonad m => LP m (Text, Macro)
1365−letmacro = do
1366− controlSeq "let"
1367− (name, contents) <- withVerbatimMode $ do
1368− Tok _ (CtrlSeq name) _ <- anyControlSeq
1369− optional $ symbol '='
1370− spaces
1371− -- we first parse in verbatim mode, and then expand macros,
1372− -- because we don't want \let\foo\bar to turn into
1373− -- \let\foo hello if we have previously \def\bar{hello}
1374− contents <- bracedOrToken
1375− return (name, contents)
1376− contents' <- doMacros' 0 contents
1377− return (name, Macro ExpandWhenDefined [] Nothing contents')
1378−
1379−defmacro :: PandocMonad m => LP m (Text, Macro)
1380−defmacro = try $
1381− -- we use withVerbatimMode, because macros are to be expanded
1382− -- at point of use, not point of definition
1383− withVerbatimMode $ do
1384− controlSeq "def"
1385− Tok _ (CtrlSeq name) _ <- anyControlSeq
1386− argspecs <- many (argspecArg <|> argspecPattern)
1387− contents <- bracedOrToken
1388− return (name, Macro ExpandWhenUsed argspecs Nothing contents)
1389−
1390−argspecArg :: PandocMonad m => LP m ArgSpec
1391−argspecArg = do
1392− Tok _ (Arg i) _ <- satisfyTok isArgTok
1393− return $ ArgNum i
1394−
1395−argspecPattern :: PandocMonad m => LP m ArgSpec
1396−argspecPattern =
1397− Pattern <$> many1 (satisfyTok (\(Tok _ toktype' txt) ->
1398− (toktype' == Symbol || toktype' == Word) &&
1399− (txt /= "{" && txt /= "\\" && txt /= "}")))
1400−
1401−newcommand :: PandocMonad m => LP m (Text, Macro)
1402−newcommand = do
1403− pos <- getPosition
1404− Tok _ (CtrlSeq mtype) _ <- controlSeq "newcommand" <|>
1405− controlSeq "renewcommand" <|>
1406− controlSeq "providecommand" <|>
1407− controlSeq "DeclareMathOperator" <|>
1408− controlSeq "DeclareRobustCommand"
1409− withVerbatimMode $ do
1410− Tok _ (CtrlSeq name) txt <- do
1411− optional (symbol '*')
1412− anyControlSeq <|>
1413− (symbol '{' *> spaces *> anyControlSeq <* spaces <* symbol '}')
1414− spaces
1415− numargs <- option 0 $ try bracketedNum
1416− let argspecs = map ArgNum [1..numargs]
1417− spaces
1418− optarg <- option Nothing $ Just <$> try bracketedToks
1419− spaces
1420− contents' <- bracedOrToken
1421− let contents =
1422− case mtype of
1423− "DeclareMathOperator" ->
1424− Tok pos (CtrlSeq "mathop") "\\mathop"
1425− : Tok pos Symbol "{"
1426− : Tok pos (CtrlSeq "mathrm") "\\mathrm"
1427− : Tok pos Symbol "{"
1428− : (contents' ++
1429− [ Tok pos Symbol "}", Tok pos Symbol "}" ])
1430− _ -> contents'
1431− macros <- sMacros <$> getState
1432− case M.lookup name macros of
1433− Just macro
1434− | mtype == "newcommand" -> do
1435− report $ MacroAlreadyDefined txt pos
1436− return (name, macro)
1437− | mtype == "providecommand" -> return (name, macro)
1438− _ -> return (name, Macro ExpandWhenUsed argspecs optarg contents)
1439−
1440−newenvironment :: PandocMonad m => LP m (Maybe (Text, Macro, Macro))
1441−newenvironment = do
1442− pos <- getPosition
1443− Tok _ (CtrlSeq mtype) _ <- controlSeq "newenvironment" <|>
1444− controlSeq "renewenvironment" <|>
1445− controlSeq "provideenvironment"
1446− withVerbatimMode $ do
1447− optional $ symbol '*'
1448− spaces
1449− name <- untokenize <$> braced
1450− spaces
1451− numargs <- option 0 $ try bracketedNum
1452− spaces
1453− optarg <- option Nothing $ Just <$> try bracketedToks
1454− let argspecs = map (\i -> ArgNum i) [1..numargs]
1455− startcontents <- spaces >> bracedOrToken
1456− endcontents <- spaces >> bracedOrToken
1457− macros <- sMacros <$> getState
1458− case M.lookup name macros of
1459− Just _
1460− | mtype == "newenvironment" -> do
1461− report $ MacroAlreadyDefined name pos
1462− return Nothing
1463− | mtype == "provideenvironment" ->
1464− return Nothing
1465− _ -> return $ Just (name,
1466− Macro ExpandWhenUsed argspecs optarg startcontents,
1467− Macro ExpandWhenUsed [] Nothing endcontents)
1468−
1469−bracketedNum :: PandocMonad m => LP m Int
1470−bracketedNum = do
1471− ds <- untokenize <$> bracketedToks
1472− case safeRead ds of
1473− Just i -> return i
1474− _ -> return 0
1475−
1476−setCaption :: PandocMonad m => LP m ()
1477−setCaption = try $ do
1478− skipopts
1479− ils <- tok
1480− optional $ try $ spaces *> label
1481− updateState $ \st -> st{ sCaption = Just ils }
1482−
1483738looseItem :: PandocMonad m => LP m Blocks
1484739looseItem = do
1485740 inListItem <- sInListItem <$> getState
@@ -1493,10 +748,6 @@ epigraph = do
1493748 p2 <- grouped block
1494749 return $ divWith ("", ["epigraph"], []) (p1 <> p2)
1495750
1496−resetCaption :: PandocMonad m => LP m ()
1497−resetCaption = updateState $ \st -> st{ sCaption = Nothing
1498− , sLastLabel = Nothing }
1499−
1500751section :: PandocMonad m => Attr -> Int -> LP m Blocks
1501752section (ident, classes, kvs) lvl = do
1502753 skipopts
@@ -1589,7 +840,7 @@ blockCommands = M.fromList
1589840 , ("address", mempty <$ (skipopts *> tok >>= addMeta "address"))
1590841 , ("signature", mempty <$ (skipopts *> authors))
1591842 , ("date", mempty <$ (skipopts *> tok >>= addMeta "date"))
1592− , ("newtheorem", newtheorem)
843+ , ("newtheorem", newtheorem inline)
1593844 , ("theoremstyle", theoremstyle)
1594845 -- KOMA-Script metadata commands
1595846 , ("extratitle", mempty <$ (skipopts *> tok >>= addMeta "extratitle"))
@@ -1637,7 +888,7 @@ blockCommands = M.fromList
1637888 , ("item", looseItem)
1638889 , ("documentclass", skipopts *> braced *> preamble)
1639890 , ("centerline", para . trimInlines <$> (skipopts *> tok))
1640− , ("caption", mempty <$ setCaption)
891+ , ("caption", mempty <$ setCaption inline)
1641892 , ("bibliography", mempty <$ (skipopts *> braced >>=
1642893 addMeta "bibliography" . splitBibs . untokenize))
1643894 , ("addbibresource", mempty <$ (skipopts *> braced >>=
@@ -1675,7 +926,8 @@ blockCommands = M.fromList
1675926
1676927
1677928environments :: PandocMonad m => M.Map Text (LP m Blocks)
1678−environments = M.fromList
929+environments = M.union (tableEnvironments blocks inline) $
930+ M.fromList
1679931 [ ("document", env "document" blocks <* skipMany anyTok)
1680932 , ("abstract", mempty <$ (env "abstract" blocks >>= addMeta "abstract"))
1681933 , ("sloppypar", env "sloppypar" blocks)
@@ -1685,13 +937,6 @@ environments = M.fromList
1685937 , ("figure", env "figure" $ skipopts *> figure)
1686938 , ("subfigure", env "subfigure" $ skipopts *> tok *> figure)
1687939 , ("center", divWith ("", ["center"], []) <$> env "center" blocks)
1688− , ("longtable", env "longtable" $
1689− resetCaption *> simpTable "longtable" False >>= addTableCaption)
1690− , ("table", env "table" $
1691− skipopts *> resetCaption *> blocks >>= addTableCaption)
1692− , ("tabular*", env "tabular*" $ simpTable "tabular*" True)
1693− , ("tabularx", env "tabularx" $ simpTable "tabularx" True)
1694− , ("tabular", env "tabular" $ simpTable "tabular" False)
1695940 , ("quote", blockQuote <$> env "quote" blocks)
1696941 , ("quotation", blockQuote <$> env "quotation" blocks)
1697942 , ("verse", blockQuote <$> env "verse" blocks)
@@ -1714,7 +959,7 @@ environments = M.fromList
1714959 , ("lilypond", rawVerbEnv "lilypond")
1715960 , ("ly", rawVerbEnv "ly")
1716961 -- amsthm
1717− , ("proof", proof)
962+ , ("proof", proof blocks opt)
1718963 -- etoolbox
1719964 , ("ifstrequal", ifstrequal)
1720965 , ("newtoggle", braced >>= newToggle)
@@ -1735,131 +980,17 @@ filecontents = try $ do
1735980 st{ sFileContents = M.insert fp txt (sFileContents st) }
1736981 return mempty
1737982
1738−theoremstyle :: PandocMonad m => LP m Blocks
1739−theoremstyle = do
1740− stylename <- untokenize <$> braced
1741− let mbstyle = case stylename of
1742− "plain" -> Just PlainStyle
1743− "definition" -> Just DefinitionStyle
1744− "remark" -> Just RemarkStyle
1745− _ -> Nothing
1746− case mbstyle of
1747− Nothing -> return ()
1748− Just sty -> updateState $ \s -> s{ sLastTheoremStyle = sty }
1749− return mempty
1750−
1751−newtheorem :: PandocMonad m => LP m Blocks
1752−newtheorem = do
1753− number <- option True (False <$ symbol '*' <* sp)
1754− name <- untokenize <$> braced
1755− sp
1756− series <- option Nothing $ Just . untokenize <$> bracketedToks
1757− sp
1758− showName <- tok
1759− sp
1760− syncTo <- option Nothing $ Just . untokenize <$> bracketedToks
1761− sty <- sLastTheoremStyle <$> getState
1762− let spec = TheoremSpec { theoremName = showName
1763− , theoremStyle = sty
1764− , theoremSeries = series
1765− , theoremSyncTo = syncTo
1766− , theoremNumber = number
1767− , theoremLastNum = DottedNum [0] }
1768− tmap <- sTheoremMap <$> getState
1769− updateState $ \s -> s{ sTheoremMap =
1770− M.insert name spec tmap }
1771− return mempty
1772−
1773−proof :: PandocMonad m => LP m Blocks
1774−proof = do
1775− title <- option (B.text "Proof") opt
1776− bs <- env "proof" blocks
1777− return $
1778− B.divWith ("", ["proof"], []) $
1779− addQed $ addTitle (B.emph (title <> ".")) bs
1780−
1781−addTitle :: Inlines -> Blocks -> Blocks
1782−addTitle ils bs =
1783− case B.toList bs of
1784− (Para xs : rest)
1785− -> B.fromList (Para (B.toList ils ++ (Space : xs)) : rest)
1786− _ -> B.para ils <> bs
1787−
1788−addQed :: Blocks -> Blocks
1789−addQed bs =
1790− case Seq.viewr (B.unMany bs) of
1791− s Seq.:> Para ils
1792− -> B.Many (s Seq.|> Para (ils ++ B.toList qedSign))
1793− _ -> bs <> B.para qedSign
1794− where
1795− qedSign = B.str "\xa0\x25FB"
1796−
1797983environment :: PandocMonad m => LP m Blocks
1798984environment = try $ do
1799985 controlSeq "begin"
1800986 name <- untokenize <$> braced
1801987 M.findWithDefault mzero name environments <|>
1802− theoremEnvironment name <|>
988+ theoremEnvironment blocks opt name <|>
1803989 if M.member name (inlineEnvironments
1804990 :: M.Map Text (LP PandocPure Inlines))
1805991 then mzero
1806992 else try (rawEnv name) <|> rawVerbEnv name
1807993
1808−theoremEnvironment :: PandocMonad m => Text -> LP m Blocks
1809−theoremEnvironment name = do
1810− tmap <- sTheoremMap <$> getState
1811− case M.lookup name tmap of
1812− Nothing -> mzero
1813− Just tspec -> do
1814− optTitle <- option mempty $ (\x -> space <> "(" <> x <> ")") <$> opt
1815− mblabel <- option Nothing $ Just . untokenize <$>
1816− try (spaces >> controlSeq "label" >> spaces >> braced)
1817− bs <- env name blocks
1818− number <-
1819− if theoremNumber tspec
1820− then do
1821− let name' = fromMaybe name $ theoremSeries tspec
1822− num <- getNextNumber
1823− (maybe (DottedNum [0]) theoremLastNum .
1824− M.lookup name' . sTheoremMap)
1825− updateState $ \s ->
1826− s{ sTheoremMap =
1827− M.adjust
1828− (\spec -> spec{ theoremLastNum = num })
1829− name'
1830− (sTheoremMap s)
1831− }
1832−
1833− case mblabel of
1834− Just ident ->
1835− updateState $ \s ->
1836− s{ sLabels = M.insert ident
1837− (B.toList $
1838− theoremName tspec <> "\160" <>
1839− str (renderDottedNum num)) (sLabels s) }
1840− Nothing -> return ()
1841− return $ space <> B.text (renderDottedNum num)
1842− else return mempty
1843− let titleEmph = case theoremStyle tspec of
1844− PlainStyle -> B.strong
1845− DefinitionStyle -> B.strong
1846− RemarkStyle -> B.emph
1847− let title = titleEmph (theoremName tspec <> number)
1848− <> optTitle <> "." <> space
1849− return $ divWith (fromMaybe "" mblabel, [name], []) $ addTitle title
1850− $ case theoremStyle tspec of
1851− PlainStyle -> walk italicize bs
1852− _ -> bs
1853−
1854−italicize :: Block -> Block
1855−italicize x@(Para [Image{}]) = x -- see #6925
1856−italicize (Para ils) = Para [Emph ils]
1857−italicize (Plain ils) = Plain [Emph ils]
1858−italicize x = x
1859−
1860−env :: PandocMonad m => Text -> LP m a -> LP m a
1861−env name p = p <* end_ name
1862−
1863994rawEnv :: PandocMonad m => Text -> LP m Blocks
1864995rawEnv name = do
1865996 exts <- getOption readerExtensions
@@ -2031,7 +1162,8 @@ inputListing = do
20311162 let (ident,classes,kvs) = parseListingsOptions options
20321163 let classes' =
20331164 (case listingsLanguage options of
2034− Nothing -> (take 1 (languagesByExtension (T.pack $ takeExtension $ T.unpack f)) <>)
1165+ Nothing -> (take 1 (languagesByExtension defaultSyntaxMap
1166+ (T.pack $ takeExtension $ T.unpack f)) <>)
20351167 Just _ -> id) classes
20361168 let firstline = fromMaybe 1 $ lookup "firstline" options >>= safeRead
20371169 let lastline = fromMaybe (length codeLines) $
@@ -2097,356 +1229,23 @@ orderedList' = try $ do
20971229 bs <- listenv "enumerate" (many item)
20981230 return $ orderedListWith (start, style, delim) bs
20991231
2100−-- tables
2101−
2102−hline :: PandocMonad m => LP m ()
2103−hline = try $ do
2104− spaces
2105− controlSeq "hline" <|>
2106− -- booktabs rules:
2107− controlSeq "toprule" <|>
2108− controlSeq "bottomrule" <|>
2109− controlSeq "midrule" <|>
2110− controlSeq "endhead" <|>
2111− controlSeq "endfirsthead"
2112− spaces
2113− optional opt
2114− return ()
2115−
2116−lbreak :: PandocMonad m => LP m Tok
2117−lbreak = (controlSeq "\\" <|> controlSeq "tabularnewline")
2118− <* skipopts <* spaces
2119−
2120−amp :: PandocMonad m => LP m Tok
2121−amp = symbol '&'
2122−
2123−-- Split a Word into individual Symbols (for parseAligns)
2124−splitWordTok :: PandocMonad m => LP m ()
2125−splitWordTok = do
2126− inp <- getInput
2127− case inp of
2128− (Tok spos Word t : rest) ->
2129− setInput $ map (Tok spos Symbol . T.singleton) (T.unpack t) <> rest
2130− _ -> return ()
2131−
2132−parseAligns :: PandocMonad m => LP m [(Alignment, ColWidth, ([Tok], [Tok]))]
2133−parseAligns = try $ do
2134− let maybeBar = skipMany
2135− (try $ sp *> (() <$ symbol '|' <|> () <$ (symbol '@' >> braced)))
2136− let cAlign = AlignCenter <$ symbol 'c'
2137− let lAlign = AlignLeft <$ symbol 'l'
2138− let rAlign = AlignRight <$ symbol 'r'
2139− let parAlign = AlignLeft <$ symbol 'p'
2140− -- aligns from tabularx
2141− let xAlign = AlignLeft <$ symbol 'X'
2142− let mAlign = AlignLeft <$ symbol 'm'
2143− let bAlign = AlignLeft <$ symbol 'b'
2144− let alignChar = splitWordTok *> ( cAlign <|> lAlign <|> rAlign <|> parAlign
2145− <|> xAlign <|> mAlign <|> bAlign )
2146− let alignPrefix = symbol '>' >> braced
2147− let alignSuffix = symbol '<' >> braced
2148− let colWidth = try $ do
2149− symbol '{'
2150− ds <- trim . untokenize <$> manyTill anyTok (controlSeq "linewidth")
2151− spaces
2152− symbol '}'
2153− return $ safeRead ds
2154− let alignSpec = do
2155− pref <- option [] alignPrefix
2156− spaces
2157− al <- alignChar
2158− width <- colWidth <|> option Nothing (do s <- untokenize <$> braced
2159− pos <- getPosition
2160− report $ SkippedContent s pos
2161− return Nothing)
2162− spaces
2163− suff <- option [] alignSuffix
2164− return (al, width, (pref, suff))
2165− let starAlign = do -- '*{2}{r}' == 'rr', we just expand like a macro
2166− symbol '*'
2167− spaces
2168− ds <- trim . untokenize <$> braced
2169− spaces
2170− spec <- braced
2171− case safeRead ds of
2172− Just n ->
2173− getInput >>= setInput . (mconcat (replicate n spec) ++)
2174− Nothing -> Prelude.fail $ "Could not parse " <> T.unpack ds <> " as number"
2175− bgroup
2176− spaces
2177− maybeBar
2178− aligns' <- many $ try $ spaces >> optional starAlign >>
2179− (alignSpec <* maybeBar)
2180− spaces
2181− egroup
2182− spaces
2183− return $ map toSpec aligns'
2184− where
2185− toColWidth (Just w) | w > 0 = ColWidth w
2186− toColWidth _ = ColWidthDefault
2187− toSpec (x, y, z) = (x, toColWidth y, z)
2188−
2189−-- N.B. this parser returns a Row that may have erroneous empty cells
2190−-- in it. See the note above fixTableHead for details.
2191−parseTableRow :: PandocMonad m
2192− => Text -- ^ table environment name
2193− -> [([Tok], [Tok])] -- ^ pref/suffixes
2194− -> LP m Row
2195−parseTableRow envname prefsufs = do
2196− notFollowedBy (spaces *> end_ envname)
2197− -- add prefixes and suffixes in token stream:
2198− let celltoks (pref, suff) = do
2199− prefpos <- getPosition
2200− contents <- mconcat <$>
2201− many ( snd <$> withRaw (controlSeq "parbox" >> parbox) -- #5711
2202− <|>
2203− snd <$> withRaw (inlineEnvironment <|> dollarsMath)
2204− <|>
2205− (do notFollowedBy
2206− (() <$ amp <|> () <$ lbreak <|> end_ envname)
2207− count 1 anyTok) )
2208−
2209− suffpos <- getPosition
2210− option [] (count 1 amp)
2211− return $ map (setpos prefpos) pref ++ contents ++ map (setpos suffpos) suff
2212− rawcells <- mapM celltoks prefsufs
2213− cells <- mapM (parseFromToks parseTableCell) rawcells
2214− spaces
2215− return $ Row nullAttr cells
2216−
2217−parseTableCell :: PandocMonad m => LP m Cell
2218−parseTableCell = do
2219− spaces
2220− updateState $ \st -> st{ sInTableCell = True }
2221− cell' <- multicolumnCell
2222− <|> multirowCell
2223− <|> parseSimpleCell
2224− <|> parseEmptyCell
2225− updateState $ \st -> st{ sInTableCell = False }
2226− spaces
2227− return cell'
2228− where
2229− -- The parsing of empty cells is important in LaTeX, especially when dealing
2230− -- with multirow/multicolumn. See #6603.
2231− parseEmptyCell = spaces $> emptyCell
2232−
2233−cellAlignment :: PandocMonad m => LP m Alignment
2234−cellAlignment = skipMany (symbol '|') *> alignment <* skipMany (symbol '|')
2235− where
2236− alignment = do
2237− c <- untoken <$> singleChar
2238− return $ case c of
2239− "l" -> AlignLeft
2240− "r" -> AlignRight
2241− "c" -> AlignCenter
2242− "*" -> AlignDefault
2243− _ -> AlignDefault
2244−
2245−plainify :: Blocks -> Blocks
2246−plainify bs = case toList bs of
2247− [Para ils] -> plain (fromList ils)
2248− _ -> bs
2249−
2250−multirowCell :: PandocMonad m => LP m Cell
2251−multirowCell = controlSeq "multirow" >> do
2252− -- Full prototype for \multirow macro is:
2253− -- \multirow[vpos]{nrows}[bigstruts]{width}[vmove]{text}
2254− -- However, everything except `nrows` and `text` make
2255− -- sense in the context of the Pandoc AST
2256− _ <- optional $ symbol '[' *> cellAlignment <* symbol ']' -- vertical position
2257− nrows <- fmap (fromMaybe 1 . safeRead . untokenize) braced
2258− _ <- optional $ symbol '[' *> manyTill anyTok (symbol ']') -- bigstrut-related
2259− _ <- symbol '{' *> manyTill anyTok (symbol '}') -- Cell width
2260− _ <- optional $ symbol '[' *> manyTill anyTok (symbol ']') -- Length used for fine-tuning
2261− content <- symbol '{' *> (plainify <$> blocks) <* symbol '}'
2262− return $ cell AlignDefault (RowSpan nrows) (ColSpan 1) content
2263−
2264−multicolumnCell :: PandocMonad m => LP m Cell
2265−multicolumnCell = controlSeq "multicolumn" >> do
2266− span' <- fmap (fromMaybe 1 . safeRead . untokenize) braced
2267− alignment <- symbol '{' *> cellAlignment <* symbol '}'
2268−
2269− let singleCell = do
2270− content <- plainify <$> blocks
2271− return $ cell alignment (RowSpan 1) (ColSpan span') content
2272−
2273− -- Two possible contents: either a \multirow cell, or content.
2274− -- E.g. \multicol{1}{c}{\multirow{2}{1em}{content}}
2275− -- Note that a \multirow cell can be nested in a \multicolumn,
2276− -- but not the other way around. See #6603
2277− let nestedCell = do
2278− (Cell _ _ (RowSpan rs) _ bs) <- multirowCell
2279− return $ cell
2280− alignment
2281− (RowSpan rs)
2282− (ColSpan span')
2283− (fromList bs)
2284−
2285− symbol '{' *> (nestedCell <|> singleCell) <* symbol '}'
2286−
2287−-- Parse a simple cell, i.e. not multirow/multicol
2288−parseSimpleCell :: PandocMonad m => LP m Cell
2289−parseSimpleCell = simpleCell <$> (plainify <$> blocks)
2290−
2291−-- LaTeX tables are stored with empty cells underneath multirow cells
2292−-- denoting the grid spaces taken up by them. More specifically, if a
2293−-- cell spans m rows, then it will overwrite all the cells in the
2294−-- columns it spans for (m-1) rows underneath it, requiring padding
2295−-- cells in these places. These padding cells need to be removed for
2296−-- proper table reading. See #6603.
2297−--
2298−-- These fixTable functions do not otherwise fix up malformed
2299−-- input tables: that is left to the table builder.
2300−fixTableHead :: TableHead -> TableHead
2301−fixTableHead (TableHead attr rows) = TableHead attr rows'
2302− where
2303− rows' = fixTableRows rows
2304−
2305−fixTableBody :: TableBody -> TableBody
2306−fixTableBody (TableBody attr rhc th tb)
2307− = TableBody attr rhc th' tb'
2308− where
2309− th' = fixTableRows th
2310− tb' = fixTableRows tb
2311−
2312−fixTableRows :: [Row] -> [Row]
2313−fixTableRows = fixTableRows' $ repeat Nothing
2314− where
2315− fixTableRows' oldHang (Row attr cells : rs)
2316− = let (newHang, cells') = fixTableRow oldHang cells
2317− rs' = fixTableRows' newHang rs
2318− in Row attr cells' : rs'
2319− fixTableRows' _ [] = []
2320−
2321−-- The overhang is represented as Just (relative cell dimensions) or
2322−-- Nothing for an empty grid space.
2323−fixTableRow :: [Maybe (ColSpan, RowSpan)] -> [Cell] -> ([Maybe (ColSpan, RowSpan)], [Cell])
2324−fixTableRow oldHang cells
2325− -- If there's overhang, drop cells until their total width meets the
2326− -- width of the occupied grid spaces (or we run out)
2327− | (n, prefHang, restHang) <- splitHang oldHang
2328− , n > 0
2329− = let cells' = dropToWidth getCellW n cells
2330− (restHang', cells'') = fixTableRow restHang cells'
2331− in (prefHang restHang', cells'')
2332− -- Otherwise record the overhang of a pending cell and fix the rest
2333− -- of the row
2334− | c@(Cell _ _ h w _):cells' <- cells
2335− = let h' = max 1 h
2336− w' = max 1 w
2337− oldHang' = dropToWidth getHangW w' oldHang
2338− (newHang, cells'') = fixTableRow oldHang' cells'
2339− in (toHang w' h' <> newHang, c : cells'')
2340− | otherwise
2341− = (oldHang, [])
2342− where
2343− getCellW (Cell _ _ _ w _) = w
2344− getHangW = maybe 1 fst
2345− getCS (ColSpan n) = n
2346−
2347− toHang c r
2348− | r > 1 = [Just (c, r)]
2349− | otherwise = replicate (getCS c) Nothing
2350−
2351− -- Take the prefix of the overhang list representing filled grid
2352− -- spaces. Also return the remainder and the length of this prefix.
2353− splitHang = splitHang' 0 id
2354−
2355− splitHang' !n l (Just (c, r):xs)
2356− = splitHang' (n + c) (l . (toHang c (r-1) ++)) xs
2357− splitHang' n l xs = (n, l, xs)
2358−
2359− -- Drop list items until the total width of the dropped items
2360− -- exceeds the passed width.
2361− dropToWidth _ n l | n < 1 = l
2362− dropToWidth wproj n (c:cs) = dropToWidth wproj (n - wproj c) cs
2363− dropToWidth _ _ [] = []
2364−
2365−simpTable :: PandocMonad m => Text -> Bool -> LP m Blocks
2366−simpTable envname hasWidthParameter = try $ do
2367− when hasWidthParameter $ () <$ (spaces >> tok)
2368− skipopts
2369− colspecs <- parseAligns
2370− let (aligns, widths, prefsufs) = unzip3 colspecs
2371− optional $ controlSeq "caption" *> setCaption
2372− spaces
2373− optional label
2374− spaces
2375− optional lbreak
2376− spaces
2377− skipMany hline
2378− spaces
2379− header' <- option [] . try . fmap (:[]) $
2380− parseTableRow envname prefsufs <* lbreak <* many1 hline
2381− spaces
2382− rows <- sepEndBy (parseTableRow envname prefsufs)
2383− (lbreak <* optional (skipMany hline))
2384− spaces
2385− optional $ controlSeq "caption" *> setCaption
2386− spaces
2387− optional label
2388− spaces
2389− optional lbreak
2390− spaces
2391− lookAhead $ controlSeq "end" -- make sure we're at end
2392− let th = fixTableHead $ TableHead nullAttr header'
2393− let tbs = [fixTableBody $ TableBody nullAttr 0 [] rows]
2394− let tf = TableFoot nullAttr []
2395− return $ table emptyCaption (zip aligns widths) th tbs tf
2396−
2397−addTableCaption :: PandocMonad m => Blocks -> LP m Blocks
2398−addTableCaption = walkM go
2399− where go (Table attr c spec th tb tf) = do
2400− st <- getState
2401− let mblabel = sLastLabel st
2402− capt <- case (sCaption st, mblabel) of
2403− (Just ils, Nothing) -> return $ caption Nothing (plain ils)
2404− (Just ils, Just lab) -> do
2405− num <- getNextNumber sLastTableNum
2406− setState
2407− st{ sLastTableNum = num
2408− , sLabels = M.insert lab
2409− [Str (renderDottedNum num)]
2410− (sLabels st) }
2411− return $ caption Nothing (plain ils) -- add number??
2412− (Nothing, _) -> return c
2413− let attr' = case (attr, mblabel) of
2414− ((_,classes,kvs), Just ident) ->
2415− (ident,classes,kvs)
2416− _ -> attr
2417− return $ addAttrDiv attr' $ Table nullAttr capt spec th tb tf
2418− go x = return x
2419−
2420−-- TODO: For now we add a Div to contain table attributes, since
2421−-- most writers don't do anything yet with attributes on Table.
2422−-- This can be removed when that changes.
2423−addAttrDiv :: Attr -> Block -> Block
2424−addAttrDiv ("",[],[]) b = b
2425−addAttrDiv attr b = Div attr [b]
2426−
24271232block :: PandocMonad m => LP m Blocks
24281233block = do
2429− res <- (mempty <$ spaces1)
2430− <|> environment
2431− <|> macroDef (rawBlock "latex")
2432− <|> blockCommand
2433− <|> paragraph
2434− <|> grouped block
1234+ Tok _ toktype _ <- lookAhead anyTok
1235+ res <- (case toktype of
1236+ Newline -> mempty <$ spaces1
1237+ Spaces -> mempty <$ spaces1
1238+ Comment -> mempty <$ spaces1
1239+ Word -> paragraph
1240+ CtrlSeq "begin" -> environment
1241+ CtrlSeq _ -> macroDef (rawBlock "latex")
1242+ <|> blockCommand
1243+ _ -> mzero)
1244+ <|> paragraph
1245+ <|> grouped block
24351246 trace (T.take 60 $ tshow $ B.toList res)
24361247 return res
24371248
24381249blocks :: PandocMonad m => LP m Blocks
24391250blocks = mconcat <$> many block
24401251
2441−setDefaultLanguage :: PandocMonad m => LP m Blocks
2442−setDefaultLanguage = do
2443− o <- option "" $ T.filter (\c -> c /= '[' && c /= ']')
2444− <$> rawopt
2445− polylang <- untokenize <$> braced
2446− case M.lookup polylang polyglossiaLangToBCP47 of
2447− Nothing -> return mempty -- TODO mzero? warning?
2448− Just langFunc -> do
2449− let l = langFunc o
2450− setTranslations l
2451− updateState $ setMeta "lang" $ str (renderLang l)
2452− return mempty
src/Text/Pandoc/Readers/LaTeX/Citation.hsnew file+210
@@ -0,0 +1,210 @@
1+{-# LANGUAGE ScopedTypeVariables #-}
2+{-# LANGUAGE OverloadedStrings #-}
3+module Text.Pandoc.Readers.LaTeX.Citation
4+ ( citationCommands
5+ , cites
6+ )
7+where
8+
9+import Text.Pandoc.Class
10+import Text.Pandoc.Readers.LaTeX.Parsing
11+import Text.Pandoc.Builder as B
12+import qualified Data.Map as M
13+import Data.Text (Text)
14+import Control.Applicative ((<|>), optional, many)
15+import Control.Monad (mzero)
16+import Control.Monad.Trans (lift)
17+import Control.Monad.Except (throwError)
18+import Text.Pandoc.Error (PandocError(PandocParsecError))
19+import Text.Pandoc.Parsing hiding (blankline, many, mathDisplay, mathInline,
20+ optional, space, spaces, withRaw, (<|>))
21+
22+citationCommands :: PandocMonad m => LP m Inlines -> M.Map Text (LP m Inlines)
23+citationCommands inline =
24+ let citation = citationWith inline
25+ tok = spaces *> grouped inline
26+ in M.fromList
27+ [ ("cite", citation "cite" NormalCitation False)
28+ , ("Cite", citation "Cite" NormalCitation False)
29+ , ("citep", citation "citep" NormalCitation False)
30+ , ("citep*", citation "citep*" NormalCitation False)
31+ , ("citeal", citation "citeal" NormalCitation False)
32+ , ("citealp", citation "citealp" NormalCitation False)
33+ , ("citealp*", citation "citealp*" NormalCitation False)
34+ , ("autocite", citation "autocite" NormalCitation False)
35+ , ("smartcite", citation "smartcite" NormalCitation False)
36+ , ("footcite", inNote <$> citation "footcite" NormalCitation False)
37+ , ("parencite", citation "parencite" NormalCitation False)
38+ , ("supercite", citation "supercite" NormalCitation False)
39+ , ("footcitetext", inNote <$> citation "footcitetext" NormalCitation False)
40+ , ("citeyearpar", citation "citeyearpar" SuppressAuthor False)
41+ , ("citeyear", citation "citeyear" SuppressAuthor False)
42+ , ("autocite*", citation "autocite*" SuppressAuthor False)
43+ , ("cite*", citation "cite*" SuppressAuthor False)
44+ , ("parencite*", citation "parencite*" SuppressAuthor False)
45+ , ("textcite", citation "textcite" AuthorInText False)
46+ , ("citet", citation "citet" AuthorInText False)
47+ , ("citet*", citation "citet*" AuthorInText False)
48+ , ("citealt", citation "citealt" AuthorInText False)
49+ , ("citealt*", citation "citealt*" AuthorInText False)
50+ , ("textcites", citation "textcites" AuthorInText True)
51+ , ("cites", citation "cites" NormalCitation True)
52+ , ("autocites", citation "autocites" NormalCitation True)
53+ , ("footcites", inNote <$> citation "footcites" NormalCitation True)
54+ , ("parencites", citation "parencites" NormalCitation True)
55+ , ("supercites", citation "supercites" NormalCitation True)
56+ , ("footcitetexts", inNote <$> citation "footcitetexts" NormalCitation True)
57+ , ("Autocite", citation "Autocite" NormalCitation False)
58+ , ("Smartcite", citation "Smartcite" NormalCitation False)
59+ , ("Footcite", inNote <$> citation "Footcite" NormalCitation False)
60+ , ("Parencite", citation "Parencite" NormalCitation False)
61+ , ("Supercite", citation "Supercite" NormalCitation False)
62+ , ("Footcitetext", inNote <$> citation "Footcitetext" NormalCitation False)
63+ , ("Citeyearpar", citation "Citeyearpar" SuppressAuthor False)
64+ , ("Citeyear", citation "Citeyear" SuppressAuthor False)
65+ , ("Autocite*", citation "Autocite*" SuppressAuthor False)
66+ , ("Cite*", citation "Cite*" SuppressAuthor False)
67+ , ("Parencite*", citation "Parencite*" SuppressAuthor False)
68+ , ("Textcite", citation "Textcite" AuthorInText False)
69+ , ("Textcites", citation "Textcites" AuthorInText True)
70+ , ("Cites", citation "Cites" NormalCitation True)
71+ , ("Autocites", citation "Autocites" NormalCitation True)
72+ , ("Footcites", inNote <$> citation "Footcites" NormalCitation True)
73+ , ("Parencites", citation "Parencites" NormalCitation True)
74+ , ("Supercites", citation "Supercites" NormalCitation True)
75+ , ("Footcitetexts", inNote <$> citation "Footcitetexts" NormalCitation True)
76+ , ("citetext", complexNatbibCitation inline NormalCitation)
77+ , ("citeauthor", (try (tok *> sp *> controlSeq "citetext") *>
78+ complexNatbibCitation inline AuthorInText)
79+ <|> citation "citeauthor" AuthorInText False)
80+ , ("nocite", mempty <$ (citation "nocite" NormalCitation False >>=
81+ addMeta "nocite"))
82+ ]
83+
84+-- citations
85+
86+addPrefix :: [Inline] -> [Citation] -> [Citation]
87+addPrefix p (k:ks) = k {citationPrefix = p ++ citationPrefix k} : ks
88+addPrefix _ _ = []
89+
90+addSuffix :: [Inline] -> [Citation] -> [Citation]
91+addSuffix s ks@(_:_) =
92+ let k = last ks
93+ in init ks ++ [k {citationSuffix = citationSuffix k ++ s}]
94+addSuffix _ _ = []
95+
96+simpleCiteArgs :: forall m . PandocMonad m => LP m Inlines -> LP m [Citation]
97+simpleCiteArgs inline = try $ do
98+ first <- optionMaybe $ toList <$> opt
99+ second <- optionMaybe $ toList <$> opt
100+ keys <- try $ bgroup *> manyTill citationLabel egroup
101+ let (pre, suf) = case (first , second ) of
102+ (Just s , Nothing) -> (mempty, s )
103+ (Just s , Just t ) -> (s , t )
104+ _ -> (mempty, mempty)
105+ conv k = Citation { citationId = k
106+ , citationPrefix = []
107+ , citationSuffix = []
108+ , citationMode = NormalCitation
109+ , citationHash = 0
110+ , citationNoteNum = 0
111+ }
112+ return $ addPrefix pre $ addSuffix suf $ map conv keys
113+ where
114+ opt :: PandocMonad m => LP m Inlines
115+ opt = do
116+ toks <- try (sp *> bracketedToks <* sp)
117+ -- now parse the toks as inlines
118+ st <- getState
119+ parsed <- lift $
120+ runParserT (mconcat <$> many inline) st "bracketed option" toks
121+ case parsed of
122+ Right result -> return result
123+ Left e -> throwError $ PandocParsecError (toSources toks) e
124+
125+
126+
127+citationLabel :: PandocMonad m => LP m Text
128+citationLabel = do
129+ sp
130+ untokenize <$>
131+ (many1 (satisfyTok isWordTok <|> symbolIn bibtexKeyChar)
132+ <* sp
133+ <* optional (symbol ',')
134+ <* sp)
135+ where bibtexKeyChar = ".:;?!`'()/*@_+=-&[]" :: [Char]
136+
137+cites :: PandocMonad m
138+ => LP m Inlines -> CitationMode -> Bool -> LP m [Citation]
139+cites inline mode multi = try $ do
140+ let paropt = parenWrapped inline
141+ cits <- if multi
142+ then do
143+ multiprenote <- optionMaybe $ toList <$> paropt
144+ multipostnote <- optionMaybe $ toList <$> paropt
145+ let (pre, suf) = case (multiprenote, multipostnote) of
146+ (Just s , Nothing) -> (mempty, s)
147+ (Nothing , Just t) -> (mempty, t)
148+ (Just s , Just t ) -> (s, t)
149+ _ -> (mempty, mempty)
150+ tempCits <- many1 $ simpleCiteArgs inline
151+ case tempCits of
152+ (k:ks) -> case ks of
153+ (_:_) -> return $ (addMprenote pre k : init ks) ++
154+ [addMpostnote suf (last ks)]
155+ _ -> return [addMprenote pre (addMpostnote suf k)]
156+ _ -> return [[]]
157+ else count 1 $ simpleCiteArgs inline
158+ let cs = concat cits
159+ return $ case mode of
160+ AuthorInText -> case cs of
161+ (c:rest) -> c {citationMode = mode} : rest
162+ [] -> []
163+ _ -> map (\a -> a {citationMode = mode}) cs
164+ where mprenote (k:ks) = (k:ks) ++ [Space]
165+ mprenote _ = mempty
166+ mpostnote (k:ks) = [Str ",", Space] ++ (k:ks)
167+ mpostnote _ = mempty
168+ addMprenote mpn (k:ks) =
169+ let mpnfinal = case citationPrefix k of
170+ (_:_) -> mprenote mpn
171+ _ -> mpn
172+ in addPrefix mpnfinal (k:ks)
173+ addMprenote _ _ = []
174+ addMpostnote = addSuffix . mpostnote
175+
176+citationWith :: PandocMonad m
177+ => LP m Inlines -> Text -> CitationMode -> Bool -> LP m Inlines
178+citationWith inline name mode multi = do
179+ (c,raw) <- withRaw $ cites inline mode multi
180+ return $ cite c (rawInline "latex" $ "\\" <> name <> untokenize raw)
181+
182+handleCitationPart :: Inlines -> [Citation]
183+handleCitationPart ils =
184+ let isCite Cite{} = True
185+ isCite _ = False
186+ (pref, rest) = break isCite (toList ils)
187+ in case rest of
188+ (Cite cs _:suff) -> addPrefix pref $ addSuffix suff cs
189+ _ -> []
190+
191+complexNatbibCitation :: PandocMonad m
192+ => LP m Inlines -> CitationMode -> LP m Inlines
193+complexNatbibCitation inline mode = try $ do
194+ (cs, raw) <-
195+ withRaw $ concat <$> do
196+ bgroup
197+ items <- mconcat <$>
198+ many1 (notFollowedBy (symbol ';') >> inline)
199+ `sepBy1` symbol ';'
200+ egroup
201+ return $ map handleCitationPart items
202+ case cs of
203+ [] -> mzero
204+ (c:cits) -> return $ cite (c{ citationMode = mode }:cits)
205+ (rawInline "latex" $ "\\citetext" <> untokenize raw)
206+
207+inNote :: Inlines -> Inlines
208+inNote ils =
209+ note $ para $ ils <> str "."
210+
src/Text/Pandoc/Readers/LaTeX/Inline.hsnew file+397
@@ -0,0 +1,397 @@
1+{-# LANGUAGE OverloadedStrings #-}
2+{-# LANGUAGE ViewPatterns #-}
3+{- |
4+ Module : Text.Pandoc.Readers.LaTeX.Inline
5+ Copyright : Copyright (C) 2006-2021 John MacFarlane
6+ License : GNU GPL, version 2 or above
7+
8+ Maintainer : John MacFarlane <jgm@berkeley.edu>
9+ Stability : alpha
10+ Portability : portable
11+-}
12+module Text.Pandoc.Readers.LaTeX.Inline
13+ ( acronymCommands
14+ , verbCommands
15+ , charCommands
16+ , accentCommands
17+ , nameCommands
18+ , biblatexInlineCommands
19+ , refCommands
20+ , rawInlineOr
21+ , listingsLanguage
22+ )
23+where
24+
25+import qualified Data.Map as M
26+import Data.Text (Text)
27+import qualified Data.Text as T
28+import Text.Pandoc.Builder
29+import Text.Pandoc.Shared (toRomanNumeral, safeRead)
30+import Text.Pandoc.Readers.LaTeX.Types (Tok (..), TokType (..))
31+import Control.Applicative (optional, (<|>))
32+import Control.Monad (guard, mzero, mplus, unless)
33+import Text.Pandoc.Class.PandocMonad (PandocMonad (..), translateTerm)
34+import Text.Pandoc.Readers.LaTeX.Parsing
35+import Text.Pandoc.Extensions (extensionEnabled, Extension(..))
36+import Text.Pandoc.Parsing (getOption, updateState, getState, notFollowedBy,
37+ manyTill, getInput, setInput, incSourceColumn,
38+ option, many1, try)
39+import Data.Char (isDigit)
40+import Text.Pandoc.Highlighting (fromListingsLanguage,)
41+import Data.Maybe (maybeToList, fromMaybe)
42+import Text.Pandoc.Options (ReaderOptions(..))
43+import qualified Data.Text.Normalize as Normalize
44+import qualified Text.Pandoc.Translations as Translations
45+
46+rawInlineOr :: PandocMonad m => Text -> LP m Inlines -> LP m Inlines
47+rawInlineOr name' fallback = do
48+ parseRaw <- extensionEnabled Ext_raw_tex <$> getOption readerExtensions
49+ if parseRaw
50+ then rawInline "latex" <$> getRawCommand name' ("\\" <> name')
51+ else fallback
52+
53+dolabel :: PandocMonad m => LP m Inlines
54+dolabel = do
55+ v <- braced
56+ let refstr = untokenize v
57+ updateState $ \st ->
58+ st{ sLastLabel = Just refstr }
59+ return $ spanWith (refstr,[],[("label", refstr)])
60+ $ inBrackets $ str $ untokenize v
61+
62+doref :: PandocMonad m => Text -> LP m Inlines
63+doref cls = do
64+ v <- braced
65+ let refstr = untokenize v
66+ return $ linkWith ("",[],[ ("reference-type", cls)
67+ , ("reference", refstr)])
68+ ("#" <> refstr)
69+ ""
70+ (inBrackets $ str refstr)
71+
72+inBrackets :: Inlines -> Inlines
73+inBrackets x = str "[" <> x <> str "]"
74+
75+doTerm :: PandocMonad m => Translations.Term -> LP m Inlines
76+doTerm term = str <$> translateTerm term
77+
78+lit :: Text -> LP m Inlines
79+lit = pure . str
80+
81+doverb :: PandocMonad m => LP m Inlines
82+doverb = do
83+ Tok _ Symbol t <- anySymbol
84+ marker <- case T.uncons t of
85+ Just (c, ts) | T.null ts -> return c
86+ _ -> mzero
87+ withVerbatimMode $
88+ code . untokenize <$>
89+ manyTill (notFollowedBy newlineTok >> verbTok marker) (symbol marker)
90+
91+verbTok :: PandocMonad m => Char -> LP m Tok
92+verbTok stopchar = do
93+ t@(Tok pos toktype txt) <- anyTok
94+ case T.findIndex (== stopchar) txt of
95+ Nothing -> return t
96+ Just i -> do
97+ let (t1, t2) = T.splitAt i txt
98+ inp <- getInput
99+ setInput $ Tok (incSourceColumn pos i) Symbol (T.singleton stopchar)
100+ : totoks (incSourceColumn pos (i + 1)) (T.drop 1 t2) ++ inp
101+ return $ Tok pos toktype t1
102+
103+listingsLanguage :: [(Text, Text)] -> Maybe Text
104+listingsLanguage opts =
105+ case lookup "language" opts of
106+ Nothing -> Nothing
107+ Just l -> fromListingsLanguage l `mplus` Just l
108+
109+dolstinline :: PandocMonad m => LP m Inlines
110+dolstinline = do
111+ options <- option [] keyvals
112+ let classes = maybeToList $ listingsLanguage options
113+ doinlinecode classes
114+
115+domintinline :: PandocMonad m => LP m Inlines
116+domintinline = do
117+ skipopts
118+ cls <- untokenize <$> braced
119+ doinlinecode [cls]
120+
121+doinlinecode :: PandocMonad m => [Text] -> LP m Inlines
122+doinlinecode classes = do
123+ Tok _ Symbol t <- anySymbol
124+ marker <- case T.uncons t of
125+ Just (c, ts) | T.null ts -> return c
126+ _ -> mzero
127+ let stopchar = if marker == '{' then '}' else marker
128+ withVerbatimMode $
129+ codeWith ("",classes,[]) . T.map nlToSpace . untokenize <$>
130+ manyTill (verbTok stopchar) (symbol stopchar)
131+
132+nlToSpace :: Char -> Char
133+nlToSpace '\n' = ' '
134+nlToSpace x = x
135+
136+romanNumeralUpper :: (PandocMonad m) => LP m Inlines
137+romanNumeralUpper =
138+ str . toRomanNumeral <$> romanNumeralArg
139+
140+romanNumeralLower :: (PandocMonad m) => LP m Inlines
141+romanNumeralLower =
142+ str . T.toLower . toRomanNumeral <$> romanNumeralArg
143+
144+romanNumeralArg :: (PandocMonad m) => LP m Int
145+romanNumeralArg = spaces *> (parser <|> inBraces)
146+ where
147+ inBraces = do
148+ symbol '{'
149+ spaces
150+ res <- parser
151+ spaces
152+ symbol '}'
153+ return res
154+ parser = do
155+ s <- untokenize <$> many1 (satisfyTok isWordTok)
156+ let (digits, rest) = T.span isDigit s
157+ unless (T.null rest) $
158+ Prelude.fail "Non-digits in argument to \\Rn or \\RN"
159+ safeRead digits
160+
161+accentWith :: PandocMonad m
162+ => LP m Inlines -> Char -> Maybe Char -> LP m Inlines
163+accentWith tok combiningAccent fallBack = try $ do
164+ ils <- tok
165+ case toList ils of
166+ (Str (T.uncons -> Just (x, xs)) : ys) -> return $ fromList $
167+ -- try to normalize to the combined character:
168+ Str (Normalize.normalize Normalize.NFC
169+ (T.pack [x, combiningAccent]) <> xs) : ys
170+ [Space] -> return $ str $ T.singleton
171+ $ fromMaybe combiningAccent fallBack
172+ [] -> return $ str $ T.singleton
173+ $ fromMaybe combiningAccent fallBack
174+ _ -> return ils
175+
176+
177+verbCommands :: PandocMonad m => M.Map Text (LP m Inlines)
178+verbCommands = M.fromList
179+ [ ("verb", doverb)
180+ , ("lstinline", dolstinline)
181+ , ("mintinline", domintinline)
182+ , ("Verb", doverb)
183+ ]
184+
185+accentCommands :: PandocMonad m => LP m Inlines -> M.Map Text (LP m Inlines)
186+accentCommands tok =
187+ let accent = accentWith tok
188+ in M.fromList
189+ [ ("aa", lit "å")
190+ , ("AA", lit "Å")
191+ , ("ss", lit "ß")
192+ , ("o", lit "ø")
193+ , ("O", lit "Ø")
194+ , ("L", lit "Ł")
195+ , ("l", lit "ł")
196+ , ("ae", lit "æ")
197+ , ("AE", lit "Æ")
198+ , ("oe", lit "œ")
199+ , ("OE", lit "Œ")
200+ , ("pounds", lit "£")
201+ , ("euro", lit "€")
202+ , ("copyright", lit "©")
203+ , ("textasciicircum", lit "^")
204+ , ("textasciitilde", lit "~")
205+ , ("H", accent '\779' Nothing) -- hungarumlaut
206+ , ("`", accent '\768' (Just '`')) -- grave
207+ , ("'", accent '\769' (Just '\'')) -- acute
208+ , ("^", accent '\770' (Just '^')) -- circ
209+ , ("~", accent '\771' (Just '~')) -- tilde
210+ , ("\"", accent '\776' Nothing) -- umlaut
211+ , (".", accent '\775' Nothing) -- dot
212+ , ("=", accent '\772' Nothing) -- macron
213+ , ("|", accent '\781' Nothing) -- vertical line above
214+ , ("b", accent '\817' Nothing) -- macron below
215+ , ("c", accent '\807' Nothing) -- cedilla
216+ , ("G", accent '\783' Nothing) -- doublegrave
217+ , ("h", accent '\777' Nothing) -- hookabove
218+ , ("d", accent '\803' Nothing) -- dotbelow
219+ , ("f", accent '\785' Nothing) -- inverted breve
220+ , ("r", accent '\778' Nothing) -- ringabove
221+ , ("t", accent '\865' Nothing) -- double inverted breve
222+ , ("U", accent '\782' Nothing) -- double vertical line above
223+ , ("v", accent '\780' Nothing) -- hacek
224+ , ("u", accent '\774' Nothing) -- breve
225+ , ("k", accent '\808' Nothing) -- ogonek
226+ , ("textogonekcentered", accent '\808' Nothing) -- ogonek
227+ , ("i", lit "ı") -- dotless i
228+ , ("j", lit "ȷ") -- dotless j
229+ , ("newtie", accent '\785' Nothing) -- inverted breve
230+ , ("textcircled", accent '\8413' Nothing) -- combining circle
231+ ]
232+
233+charCommands :: PandocMonad m => M.Map Text (LP m Inlines)
234+charCommands = M.fromList
235+ [ ("ldots", lit "…")
236+ , ("vdots", lit "\8942")
237+ , ("dots", lit "…")
238+ , ("mdots", lit "…")
239+ , ("sim", lit "~")
240+ , ("sep", lit ",")
241+ , ("P", lit "¶")
242+ , ("S", lit "§")
243+ , ("$", lit "$")
244+ , ("%", lit "%")
245+ , ("&", lit "&")
246+ , ("#", lit "#")
247+ , ("_", lit "_")
248+ , ("{", lit "{")
249+ , ("}", lit "}")
250+ , ("qed", lit "\a0\x25FB")
251+ , ("lq", return (str "‘"))
252+ , ("rq", return (str "’"))
253+ , ("textquoteleft", return (str "‘"))
254+ , ("textquoteright", return (str "’"))
255+ , ("textquotedblleft", return (str "“"))
256+ , ("textquotedblright", return (str "”"))
257+ , ("/", pure mempty) -- italic correction
258+ , ("\\", linebreak <$ (do inTableCell <- sInTableCell <$> getState
259+ guard $ not inTableCell
260+ optional rawopt
261+ spaces))
262+ , (",", lit "\8198")
263+ , ("@", pure mempty)
264+ , (" ", lit "\160")
265+ , ("ps", pure $ str "PS." <> space)
266+ , ("TeX", lit "TeX")
267+ , ("LaTeX", lit "LaTeX")
268+ , ("bar", lit "|")
269+ , ("textless", lit "<")
270+ , ("textgreater", lit ">")
271+ , ("textbackslash", lit "\\")
272+ , ("backslash", lit "\\")
273+ , ("slash", lit "/")
274+ -- fontawesome
275+ , ("faCheck", lit "\10003")
276+ , ("faClose", lit "\10007")
277+ -- hyphenat
278+ , ("bshyp", lit "\\\173")
279+ , ("fshyp", lit "/\173")
280+ , ("dothyp", lit ".\173")
281+ , ("colonhyp", lit ":\173")
282+ , ("hyp", lit "-")
283+ ]
284+
285+biblatexInlineCommands :: PandocMonad m
286+ => LP m Inlines -> M.Map Text (LP m Inlines)
287+biblatexInlineCommands tok = M.fromList
288+ -- biblatex misc
289+ [ ("RN", romanNumeralUpper)
290+ , ("Rn", romanNumeralLower)
291+ , ("mkbibquote", spanWith nullAttr . doubleQuoted <$> tok)
292+ , ("mkbibemph", spanWith nullAttr . emph <$> tok)
293+ , ("mkbibitalic", spanWith nullAttr . emph <$> tok)
294+ , ("mkbibbold", spanWith nullAttr . strong <$> tok)
295+ , ("mkbibparens",
296+ spanWith nullAttr . (\x -> str "(" <> x <> str ")") <$> tok)
297+ , ("mkbibbrackets",
298+ spanWith nullAttr . (\x -> str "[" <> x <> str "]") <$> tok)
299+ , ("autocap", spanWith nullAttr <$> tok)
300+ , ("textnormal", spanWith ("",["nodecor"],[]) <$> tok)
301+ , ("bibstring",
302+ (\x -> spanWith ("",[],[("bibstring",x)]) (str x)) . untokenize
303+ <$> braced)
304+ , ("adddot", pure (str "."))
305+ , ("adddotspace", pure (spanWith nullAttr (str "." <> space)))
306+ , ("addabbrvspace", pure space)
307+ , ("hyphen", pure (str "-"))
308+ ]
309+
310+nameCommands :: PandocMonad m => M.Map Text (LP m Inlines)
311+nameCommands = M.fromList
312+ [ ("figurename", doTerm Translations.Figure)
313+ , ("prefacename", doTerm Translations.Preface)
314+ , ("refname", doTerm Translations.References)
315+ , ("bibname", doTerm Translations.Bibliography)
316+ , ("chaptername", doTerm Translations.Chapter)
317+ , ("partname", doTerm Translations.Part)
318+ , ("contentsname", doTerm Translations.Contents)
319+ , ("listfigurename", doTerm Translations.ListOfFigures)
320+ , ("listtablename", doTerm Translations.ListOfTables)
321+ , ("indexname", doTerm Translations.Index)
322+ , ("abstractname", doTerm Translations.Abstract)
323+ , ("tablename", doTerm Translations.Table)
324+ , ("enclname", doTerm Translations.Encl)
325+ , ("ccname", doTerm Translations.Cc)
326+ , ("headtoname", doTerm Translations.To)
327+ , ("pagename", doTerm Translations.Page)
328+ , ("seename", doTerm Translations.See)
329+ , ("seealsoname", doTerm Translations.SeeAlso)
330+ , ("proofname", doTerm Translations.Proof)
331+ , ("glossaryname", doTerm Translations.Glossary)
332+ , ("lstlistingname", doTerm Translations.Listing)
333+ ]
334+
335+refCommands :: PandocMonad m => M.Map Text (LP m Inlines)
336+refCommands = M.fromList
337+ [ ("label", rawInlineOr "label" dolabel)
338+ , ("ref", rawInlineOr "ref" $ doref "ref")
339+ , ("cref", rawInlineOr "cref" $ doref "ref") -- from cleveref.sty
340+ , ("vref", rawInlineOr "vref" $ doref "ref+page") -- from varioref.sty
341+ , ("eqref", rawInlineOr "eqref" $ doref "eqref") -- from amsmath.sty
342+ ]
343+
344+acronymCommands :: PandocMonad m => M.Map Text (LP m Inlines)
345+acronymCommands = M.fromList
346+ -- glossaries package
347+ [ ("gls", doAcronym "short")
348+ , ("Gls", doAcronym "short")
349+ , ("glsdesc", doAcronym "long")
350+ , ("Glsdesc", doAcronym "long")
351+ , ("GLSdesc", doAcronym "long")
352+ , ("acrlong", doAcronym "long")
353+ , ("Acrlong", doAcronym "long")
354+ , ("acrfull", doAcronym "full")
355+ , ("Acrfull", doAcronym "full")
356+ , ("acrshort", doAcronym "abbrv")
357+ , ("Acrshort", doAcronym "abbrv")
358+ , ("glspl", doAcronymPlural "short")
359+ , ("Glspl", doAcronymPlural "short")
360+ , ("glsdescplural", doAcronymPlural "long")
361+ , ("Glsdescplural", doAcronymPlural "long")
362+ , ("GLSdescplural", doAcronymPlural "long")
363+ -- acronyms package
364+ , ("ac", doAcronym "short")
365+ , ("acf", doAcronym "full")
366+ , ("acs", doAcronym "abbrv")
367+ , ("acl", doAcronym "long")
368+ , ("acp", doAcronymPlural "short")
369+ , ("acfp", doAcronymPlural "full")
370+ , ("acsp", doAcronymPlural "abbrv")
371+ , ("aclp", doAcronymPlural "long")
372+ , ("Ac", doAcronym "short")
373+ , ("Acf", doAcronym "full")
374+ , ("Acs", doAcronym "abbrv")
375+ , ("Acl", doAcronym "long")
376+ , ("Acp", doAcronymPlural "short")
377+ , ("Acfp", doAcronymPlural "full")
378+ , ("Acsp", doAcronymPlural "abbrv")
379+ , ("Aclp", doAcronymPlural "long")
380+ ]
381+
382+doAcronym :: PandocMonad m => Text -> LP m Inlines
383+doAcronym form = do
384+ acro <- braced
385+ return . mconcat $ [spanWith ("",[],[("acronym-label", untokenize acro),
386+ ("acronym-form", "singular+" <> form)])
387+ $ str $ untokenize acro]
388+
389+doAcronymPlural :: PandocMonad m => Text -> LP m Inlines
390+doAcronymPlural form = do
391+ acro <- braced
392+ let plural = str "s"
393+ return . mconcat $ [spanWith ("",[],[("acronym-label", untokenize acro),
394+ ("acronym-form", "plural+" <> form)]) $
395+ mconcat [str $ untokenize acro, plural]]
396+
397+
src/Text/Pandoc/Readers/LaTeX/Lang.hs+199−120
@@ -12,144 +12,223 @@ Functions for parsing polyglossia and babel language specifiers to
1212BCP47 'Lang'.
1313-}
1414module Text.Pandoc.Readers.LaTeX.Lang
15− ( polyglossiaLangToBCP47
15+ ( setDefaultLanguage
16+ , polyglossiaLangToBCP47
1617 , babelLangToBCP47
18+ , enquoteCommands
19+ , inlineLanguageCommands
1720 )
1821where
1922import qualified Data.Map as M
23+import Data.Text (Text)
2024import qualified Data.Text as T
21−import Text.Pandoc.BCP47 (Lang(..))
25+import Text.Pandoc.Shared (extractSpaces)
26+import Text.Collate.Lang (Lang(..), renderLang)
27+import Text.Pandoc.Class (PandocMonad(..), setTranslations)
28+import Text.Pandoc.Readers.LaTeX.Parsing
29+import Text.Pandoc.Parsing (updateState, option, getState, QuoteContext(..),
30+ withQuoteContext)
31+import Text.Pandoc.Builder (Blocks, Inlines, setMeta, str, spanWith,
32+ singleQuoted, doubleQuoted)
33+
34+enquote :: PandocMonad m
35+ => LP m Inlines
36+ -> Bool -> Maybe Text -> LP m Inlines
37+enquote tok starred mblang = do
38+ skipopts
39+ let lang = mblang >>= babelLangToBCP47
40+ let langspan = case lang of
41+ Nothing -> id
42+ Just l -> spanWith ("",[],[("lang", renderLang l)])
43+ quoteContext <- sQuoteContext <$> getState
44+ if starred || quoteContext == InDoubleQuote
45+ then singleQuoted . langspan <$> withQuoteContext InSingleQuote tok
46+ else doubleQuoted . langspan <$> withQuoteContext InDoubleQuote tok
47+
48+enquoteCommands :: PandocMonad m
49+ => LP m Inlines -> M.Map Text (LP m Inlines)
50+enquoteCommands tok = M.fromList
51+ [ ("enquote*", enquote tok True Nothing)
52+ , ("enquote", enquote tok False Nothing)
53+ -- foreignquote is supposed to use native quote marks
54+ , ("foreignquote*", braced >>= enquote tok True . Just . untokenize)
55+ , ("foreignquote", braced >>= enquote tok False . Just . untokenize)
56+ -- hypehnquote uses regular quotes
57+ , ("hyphenquote*", braced >>= enquote tok True . Just . untokenize)
58+ , ("hyphenquote", braced >>= enquote tok False . Just . untokenize)
59+ ]
60+
61+foreignlanguage :: PandocMonad m => LP m Inlines -> LP m Inlines
62+foreignlanguage tok = do
63+ babelLang <- untokenize <$> braced
64+ case babelLangToBCP47 babelLang of
65+ Just lang -> spanWith ("", [], [("lang", renderLang lang)]) <$> tok
66+ _ -> tok
67+
68+inlineLanguageCommands :: PandocMonad m
69+ => LP m Inlines -> M.Map Text (LP m Inlines)
70+inlineLanguageCommands tok =
71+ M.fromList $
72+ ("foreignlanguage", foreignlanguage tok) :
73+ (mk <$> M.toList polyglossiaLangToBCP47)
74+ where
75+ mk (polyglossia, bcp47Func) =
76+ ("text" <> polyglossia, inlineLanguage tok bcp47Func)
77+
78+inlineLanguage :: PandocMonad m
79+ => LP m Inlines -> (Text -> Lang) -> LP m Inlines
80+inlineLanguage tok bcp47Func = do
81+ o <- option "" $ T.filter (\c -> c /= '[' && c /= ']')
82+ <$> rawopt
83+ let lang = renderLang $ bcp47Func o
84+ extractSpaces (spanWith ("", [], [("lang", lang)])) <$> tok
85+
86+setDefaultLanguage :: PandocMonad m => LP m Blocks
87+setDefaultLanguage = do
88+ o <- option "" $ T.filter (\c -> c /= '[' && c /= ']')
89+ <$> rawopt
90+ polylang <- untokenize <$> braced
91+ case M.lookup polylang polyglossiaLangToBCP47 of
92+ Nothing -> return mempty -- TODO mzero? warning?
93+ Just langFunc -> do
94+ let l = langFunc o
95+ setTranslations l
96+ updateState $ setMeta "lang" $ str (renderLang l)
97+ return mempty
2298
2399polyglossiaLangToBCP47 :: M.Map T.Text (T.Text -> Lang)
24100polyglossiaLangToBCP47 = M.fromList
25101 [ ("arabic", \o -> case T.filter (/=' ') o of
26− "locale=algeria" -> Lang "ar" "" "DZ" []
27− "locale=mashriq" -> Lang "ar" "" "SY" []
28− "locale=libya" -> Lang "ar" "" "LY" []
29− "locale=morocco" -> Lang "ar" "" "MA" []
30− "locale=mauritania" -> Lang "ar" "" "MR" []
31− "locale=tunisia" -> Lang "ar" "" "TN" []
32− _ -> Lang "ar" "" "" [])
102+ "locale=algeria" -> Lang "ar" Nothing (Just "DZ") [] [] []
103+ "locale=mashriq" -> Lang "ar" Nothing (Just "SY") [] [] []
104+ "locale=libya" -> Lang "ar" Nothing (Just "LY") [] [] []
105+ "locale=morocco" -> Lang "ar" Nothing (Just "MA") [] [] []
106+ "locale=mauritania" -> Lang "ar" Nothing (Just "MR") [] [] []
107+ "locale=tunisia" -> Lang "ar" Nothing (Just "TN") [] [] []
108+ _ -> Lang "ar" Nothing (Just "") [] [] [])
33109 , ("german", \o -> case T.filter (/=' ') o of
34− "spelling=old" -> Lang "de" "" "DE" ["1901"]
110+ "spelling=old" -> Lang "de" Nothing (Just "DE") ["1901"] [] []
35111 "variant=austrian,spelling=old"
36− -> Lang "de" "" "AT" ["1901"]
37− "variant=austrian" -> Lang "de" "" "AT" []
112+ -> Lang "de" Nothing (Just "AT") ["1901"] [] []
113+ "variant=austrian" -> Lang "de" Nothing (Just "AT") [] [] []
38114 "variant=swiss,spelling=old"
39− -> Lang "de" "" "CH" ["1901"]
40− "variant=swiss" -> Lang "de" "" "CH" []
41− _ -> Lang "de" "" "" [])
42− , ("lsorbian", \_ -> Lang "dsb" "" "" [])
115+ -> Lang "de" Nothing (Just "CH") ["1901"] [] []
116+ "variant=swiss" -> Lang "de" Nothing (Just "CH") [] [] []
117+ _ -> Lang "de" Nothing Nothing [] [] [])
118+ , ("lsorbian", \_ -> Lang "dsb" Nothing Nothing [] [] [])
43119 , ("greek", \o -> case T.filter (/=' ') o of
44− "variant=poly" -> Lang "el" "" "polyton" []
45− "variant=ancient" -> Lang "grc" "" "" []
46− _ -> Lang "el" "" "" [])
120+ "variant=poly" -> Lang "el" Nothing (Just "polyton") [] [] []
121+ "variant=ancient" -> Lang "grc" Nothing Nothing [] [] []
122+ _ -> Lang "el" Nothing Nothing [] [] [])
47123 , ("english", \o -> case T.filter (/=' ') o of
48− "variant=australian" -> Lang "en" "" "AU" []
49− "variant=canadian" -> Lang "en" "" "CA" []
50− "variant=british" -> Lang "en" "" "GB" []
51− "variant=newzealand" -> Lang "en" "" "NZ" []
52− "variant=american" -> Lang "en" "" "US" []
53− _ -> Lang "en" "" "" [])
54− , ("usorbian", \_ -> Lang "hsb" "" "" [])
124+ "variant=australian" -> Lang "en" Nothing (Just "AU") [] [] []
125+ "variant=canadian" -> Lang "en" Nothing (Just "CA") [] [] []
126+ "variant=british" -> Lang "en" Nothing (Just "GB") [] [] []
127+ "variant=newzealand" -> Lang "en" Nothing (Just "NZ") [] [] []
128+ "variant=american" -> Lang "en" Nothing (Just "US") [] [] []
129+ _ -> Lang "en" Nothing (Just "") [] [] [])
130+ , ("usorbian", \_ -> Lang "hsb" Nothing Nothing [] [] [])
55131 , ("latin", \o -> case T.filter (/=' ') o of
56− "variant=classic" -> Lang "la" "" "" ["x-classic"]
57− _ -> Lang "la" "" "" [])
58− , ("slovenian", \_ -> Lang "sl" "" "" [])
59− , ("serbianc", \_ -> Lang "sr" "cyrl" "" [])
60− , ("pinyin", \_ -> Lang "zh" "Latn" "" ["pinyin"])
61− , ("afrikaans", \_ -> Lang "af" "" "" [])
62− , ("amharic", \_ -> Lang "am" "" "" [])
63− , ("assamese", \_ -> Lang "as" "" "" [])
64− , ("asturian", \_ -> Lang "ast" "" "" [])
65− , ("bulgarian", \_ -> Lang "bg" "" "" [])
66− , ("bengali", \_ -> Lang "bn" "" "" [])
67− , ("tibetan", \_ -> Lang "bo" "" "" [])
68− , ("breton", \_ -> Lang "br" "" "" [])
69− , ("catalan", \_ -> Lang "ca" "" "" [])
70− , ("welsh", \_ -> Lang "cy" "" "" [])
71− , ("czech", \_ -> Lang "cs" "" "" [])
72− , ("coptic", \_ -> Lang "cop" "" "" [])
73− , ("danish", \_ -> Lang "da" "" "" [])
74− , ("divehi", \_ -> Lang "dv" "" "" [])
75− , ("esperanto", \_ -> Lang "eo" "" "" [])
76− , ("spanish", \_ -> Lang "es" "" "" [])
77− , ("estonian", \_ -> Lang "et" "" "" [])
78− , ("basque", \_ -> Lang "eu" "" "" [])
79− , ("farsi", \_ -> Lang "fa" "" "" [])
80− , ("finnish", \_ -> Lang "fi" "" "" [])
81− , ("french", \_ -> Lang "fr" "" "" [])
82− , ("friulan", \_ -> Lang "fur" "" "" [])
83− , ("irish", \_ -> Lang "ga" "" "" [])
84− , ("scottish", \_ -> Lang "gd" "" "" [])
85− , ("ethiopic", \_ -> Lang "gez" "" "" [])
86− , ("galician", \_ -> Lang "gl" "" "" [])
87− , ("hebrew", \_ -> Lang "he" "" "" [])
88− , ("hindi", \_ -> Lang "hi" "" "" [])
89− , ("croatian", \_ -> Lang "hr" "" "" [])
90− , ("magyar", \_ -> Lang "hu" "" "" [])
91− , ("armenian", \_ -> Lang "hy" "" "" [])
92− , ("interlingua", \_ -> Lang "ia" "" "" [])
93− , ("indonesian", \_ -> Lang "id" "" "" [])
94− , ("icelandic", \_ -> Lang "is" "" "" [])
95− , ("italian", \_ -> Lang "it" "" "" [])
96− , ("japanese", \_ -> Lang "jp" "" "" [])
97− , ("khmer", \_ -> Lang "km" "" "" [])
98− , ("kurmanji", \_ -> Lang "kmr" "" "" [])
99− , ("kannada", \_ -> Lang "kn" "" "" [])
100− , ("korean", \_ -> Lang "ko" "" "" [])
101− , ("lao", \_ -> Lang "lo" "" "" [])
102− , ("lithuanian", \_ -> Lang "lt" "" "" [])
103− , ("latvian", \_ -> Lang "lv" "" "" [])
104− , ("malayalam", \_ -> Lang "ml" "" "" [])
105− , ("mongolian", \_ -> Lang "mn" "" "" [])
106− , ("marathi", \_ -> Lang "mr" "" "" [])
107− , ("dutch", \_ -> Lang "nl" "" "" [])
108− , ("nynorsk", \_ -> Lang "nn" "" "" [])
109− , ("norsk", \_ -> Lang "no" "" "" [])
110− , ("nko", \_ -> Lang "nqo" "" "" [])
111− , ("occitan", \_ -> Lang "oc" "" "" [])
112− , ("panjabi", \_ -> Lang "pa" "" "" [])
113− , ("polish", \_ -> Lang "pl" "" "" [])
114− , ("piedmontese", \_ -> Lang "pms" "" "" [])
115− , ("portuguese", \_ -> Lang "pt" "" "" [])
116− , ("romansh", \_ -> Lang "rm" "" "" [])
117− , ("romanian", \_ -> Lang "ro" "" "" [])
118− , ("russian", \_ -> Lang "ru" "" "" [])
119− , ("sanskrit", \_ -> Lang "sa" "" "" [])
120− , ("samin", \_ -> Lang "se" "" "" [])
121− , ("slovak", \_ -> Lang "sk" "" "" [])
122− , ("albanian", \_ -> Lang "sq" "" "" [])
123− , ("serbian", \_ -> Lang "sr" "" "" [])
124− , ("swedish", \_ -> Lang "sv" "" "" [])
125− , ("syriac", \_ -> Lang "syr" "" "" [])
126− , ("tamil", \_ -> Lang "ta" "" "" [])
127− , ("telugu", \_ -> Lang "te" "" "" [])
128− , ("thai", \_ -> Lang "th" "" "" [])
129− , ("turkmen", \_ -> Lang "tk" "" "" [])
130− , ("turkish", \_ -> Lang "tr" "" "" [])
131− , ("ukrainian", \_ -> Lang "uk" "" "" [])
132− , ("urdu", \_ -> Lang "ur" "" "" [])
133− , ("vietnamese", \_ -> Lang "vi" "" "" [])
132+ "variant=classic" -> Lang "la" Nothing Nothing ["x-classic"] [] []
133+ _ -> Lang "la" Nothing Nothing [] [] [])
134+ , ("slovenian", \_ -> Lang "sl" Nothing Nothing [] [] [])
135+ , ("serbianc", \_ -> Lang "sr" (Just "Cyrl") Nothing [] [] [])
136+ , ("pinyin", \_ -> Lang "zh" (Just "Latn") Nothing ["pinyin"] [] [])
137+ , ("afrikaans", \_ -> simpleLang "af")
138+ , ("amharic", \_ -> simpleLang "am")
139+ , ("assamese", \_ -> simpleLang "as")
140+ , ("asturian", \_ -> simpleLang "ast")
141+ , ("bulgarian", \_ -> simpleLang "bg")
142+ , ("bengali", \_ -> simpleLang "bn")
143+ , ("tibetan", \_ -> simpleLang "bo")
144+ , ("breton", \_ -> simpleLang "br")
145+ , ("catalan", \_ -> simpleLang "ca")
146+ , ("welsh", \_ -> simpleLang "cy")
147+ , ("czech", \_ -> simpleLang "cs")
148+ , ("coptic", \_ -> simpleLang "cop")
149+ , ("danish", \_ -> simpleLang "da")
150+ , ("divehi", \_ -> simpleLang "dv")
151+ , ("esperanto", \_ -> simpleLang "eo")
152+ , ("spanish", \_ -> simpleLang "es")
153+ , ("estonian", \_ -> simpleLang "et")
154+ , ("basque", \_ -> simpleLang "eu")
155+ , ("farsi", \_ -> simpleLang "fa")
156+ , ("finnish", \_ -> simpleLang "fi")
157+ , ("french", \_ -> simpleLang "fr")
158+ , ("friulan", \_ -> simpleLang "fur")
159+ , ("irish", \_ -> simpleLang "ga")
160+ , ("scottish", \_ -> simpleLang "gd")
161+ , ("ethiopic", \_ -> simpleLang "gez")
162+ , ("galician", \_ -> simpleLang "gl")
163+ , ("hebrew", \_ -> simpleLang "he")
164+ , ("hindi", \_ -> simpleLang "hi")
165+ , ("croatian", \_ -> simpleLang "hr")
166+ , ("magyar", \_ -> simpleLang "hu")
167+ , ("armenian", \_ -> simpleLang "hy")
168+ , ("interlingua", \_ -> simpleLang "ia")
169+ , ("indonesian", \_ -> simpleLang "id")
170+ , ("icelandic", \_ -> simpleLang "is")
171+ , ("italian", \_ -> simpleLang "it")
172+ , ("japanese", \_ -> simpleLang "jp")
173+ , ("khmer", \_ -> simpleLang "km")
174+ , ("kurmanji", \_ -> simpleLang "kmr")
175+ , ("kannada", \_ -> simpleLang "kn")
176+ , ("korean", \_ -> simpleLang "ko")
177+ , ("lao", \_ -> simpleLang "lo")
178+ , ("lithuanian", \_ -> simpleLang "lt")
179+ , ("latvian", \_ -> simpleLang "lv")
180+ , ("malayalam", \_ -> simpleLang "ml")
181+ , ("mongolian", \_ -> simpleLang "mn")
182+ , ("marathi", \_ -> simpleLang "mr")
183+ , ("dutch", \_ -> simpleLang "nl")
184+ , ("nynorsk", \_ -> simpleLang "nn")
185+ , ("norsk", \_ -> simpleLang "no")
186+ , ("nko", \_ -> simpleLang "nqo")
187+ , ("occitan", \_ -> simpleLang "oc")
188+ , ("panjabi", \_ -> simpleLang "pa")
189+ , ("polish", \_ -> simpleLang "pl")
190+ , ("piedmontese", \_ -> simpleLang "pms")
191+ , ("portuguese", \_ -> simpleLang "pt")
192+ , ("romansh", \_ -> simpleLang "rm")
193+ , ("romanian", \_ -> simpleLang "ro")
194+ , ("russian", \_ -> simpleLang "ru")
195+ , ("sanskrit", \_ -> simpleLang "sa")
196+ , ("samin", \_ -> simpleLang "se")
197+ , ("slovak", \_ -> simpleLang "sk")
198+ , ("albanian", \_ -> simpleLang "sq")
199+ , ("serbian", \_ -> simpleLang "sr")
200+ , ("swedish", \_ -> simpleLang "sv")
201+ , ("syriac", \_ -> simpleLang "syr")
202+ , ("tamil", \_ -> simpleLang "ta")
203+ , ("telugu", \_ -> simpleLang "te")
204+ , ("thai", \_ -> simpleLang "th")
205+ , ("turkmen", \_ -> simpleLang "tk")
206+ , ("turkish", \_ -> simpleLang "tr")
207+ , ("ukrainian", \_ -> simpleLang "uk")
208+ , ("urdu", \_ -> simpleLang "ur")
209+ , ("vietnamese", \_ -> simpleLang "vi")
134210 ]
135211
212+simpleLang :: Text -> Lang
213+simpleLang l = Lang l Nothing Nothing [] [] []
214+
136215babelLangToBCP47 :: T.Text -> Maybe Lang
137216babelLangToBCP47 s =
138217 case s of
139− "austrian" -> Just $ Lang "de" "" "AT" ["1901"]
140− "naustrian" -> Just $ Lang "de" "" "AT" []
141− "swissgerman" -> Just $ Lang "de" "" "CH" ["1901"]
142− "nswissgerman" -> Just $ Lang "de" "" "CH" []
143− "german" -> Just $ Lang "de" "" "DE" ["1901"]
144− "ngerman" -> Just $ Lang "de" "" "DE" []
145− "lowersorbian" -> Just $ Lang "dsb" "" "" []
146− "uppersorbian" -> Just $ Lang "hsb" "" "" []
147− "polutonikogreek" -> Just $ Lang "el" "" "" ["polyton"]
148− "slovene" -> Just $ Lang "sl" "" "" []
149− "australian" -> Just $ Lang "en" "" "AU" []
150− "canadian" -> Just $ Lang "en" "" "CA" []
151− "british" -> Just $ Lang "en" "" "GB" []
152− "newzealand" -> Just $ Lang "en" "" "NZ" []
153− "american" -> Just $ Lang "en" "" "US" []
154− "classiclatin" -> Just $ Lang "la" "" "" ["x-classic"]
218+ "austrian" -> Just $ Lang "de" Nothing (Just "AT") ["1901"] [] []
219+ "naustrian" -> Just $ Lang "de" Nothing (Just "AT") [] [] []
220+ "swissgerman" -> Just $ Lang "de" Nothing (Just "CH") ["1901"] [] []
221+ "nswissgerman" -> Just $ Lang "de" Nothing (Just "CH") [] [] []
222+ "german" -> Just $ Lang "de" Nothing (Just "DE") ["1901"] [] []
223+ "ngerman" -> Just $ Lang "de" Nothing (Just "DE") [] [] []
224+ "lowersorbian" -> Just $ Lang "dsb" Nothing Nothing [] [] []
225+ "uppersorbian" -> Just $ Lang "hsb" Nothing Nothing [] [] []
226+ "polutonikogreek" -> Just $ Lang "el" Nothing Nothing ["polyton"] [] []
227+ "slovene" -> Just $ simpleLang "sl"
228+ "australian" -> Just $ Lang "en" Nothing (Just "AU") [] [] []
229+ "canadian" -> Just $ Lang "en" Nothing (Just "CA") [] [] []
230+ "british" -> Just $ Lang "en" Nothing (Just "GB") [] [] []
231+ "newzealand" -> Just $ Lang "en" Nothing (Just "NZ") [] [] []
232+ "american" -> Just $ Lang "en" Nothing (Just "US") [] [] []
233+ "classiclatin" -> Just $ Lang "la" Nothing Nothing ["x-classic"] [] []
155234 _ -> ($ "") <$> M.lookup s polyglossiaLangToBCP47
src/Text/Pandoc/Readers/LaTeX/Macro.hsnew file+184
@@ -0,0 +1,184 @@
1+{-# LANGUAGE OverloadedStrings #-}
2+module Text.Pandoc.Readers.LaTeX.Macro
3+ ( macroDef
4+ )
5+where
6+import Text.Pandoc.Extensions (Extension(..))
7+import Text.Pandoc.Logging (LogMessage(MacroAlreadyDefined))
8+import Text.Pandoc.Readers.LaTeX.Parsing
9+import Text.Pandoc.Readers.LaTeX.Types
10+import Text.Pandoc.Class
11+import Text.Pandoc.Shared (safeRead)
12+import Text.Pandoc.Parsing hiding (blankline, mathDisplay, mathInline,
13+ optional, space, spaces, withRaw, (<|>))
14+import Control.Applicative ((<|>), optional)
15+import qualified Data.Map as M
16+import Data.Text (Text)
17+import qualified Data.Text as T
18+
19+macroDef :: (PandocMonad m, Monoid a) => (Text -> a) -> LP m a
20+macroDef constructor = do
21+ (_, s) <- withRaw (commandDef <|> environmentDef)
22+ (constructor (untokenize s) <$
23+ guardDisabled Ext_latex_macros)
24+ <|> return mempty
25+ where commandDef = do
26+ nameMacroPairs <- newcommand <|> letmacro <|> defmacro <|> newif
27+ guardDisabled Ext_latex_macros <|>
28+ mapM_ (\(name, macro') ->
29+ updateState (\s -> s{ sMacros = M.insert name macro'
30+ (sMacros s) })) nameMacroPairs
31+ environmentDef = do
32+ mbenv <- newenvironment
33+ case mbenv of
34+ Nothing -> return ()
35+ Just (name, macro1, macro2) ->
36+ guardDisabled Ext_latex_macros <|>
37+ do updateState $ \s -> s{ sMacros =
38+ M.insert name macro1 (sMacros s) }
39+ updateState $ \s -> s{ sMacros =
40+ M.insert ("end" <> name) macro2 (sMacros s) }
41+ -- @\newenvironment{envname}[n-args][default]{begin}{end}@
42+ -- is equivalent to
43+ -- @\newcommand{\envname}[n-args][default]{begin}@
44+ -- @\newcommand{\endenvname}@
45+
46+letmacro :: PandocMonad m => LP m [(Text, Macro)]
47+letmacro = do
48+ controlSeq "let"
49+ (name, contents) <- withVerbatimMode $ do
50+ Tok _ (CtrlSeq name) _ <- anyControlSeq
51+ optional $ symbol '='
52+ spaces
53+ -- we first parse in verbatim mode, and then expand macros,
54+ -- because we don't want \let\foo\bar to turn into
55+ -- \let\foo hello if we have previously \def\bar{hello}
56+ contents <- bracedOrToken
57+ return (name, contents)
58+ contents' <- doMacros' 0 contents
59+ return [(name, Macro ExpandWhenDefined [] Nothing contents')]
60+
61+defmacro :: PandocMonad m => LP m [(Text, Macro)]
62+defmacro = do
63+ -- we use withVerbatimMode, because macros are to be expanded
64+ -- at point of use, not point of definition
65+ controlSeq "def"
66+ withVerbatimMode $ do
67+ Tok _ (CtrlSeq name) _ <- anyControlSeq
68+ argspecs <- many (argspecArg <|> argspecPattern)
69+ contents <- bracedOrToken
70+ return [(name, Macro ExpandWhenUsed argspecs Nothing contents)]
71+
72+-- \newif\iffoo' defines:
73+-- \iffoo to be \iffalse
74+-- \footrue to be a command that defines \iffoo to be \iftrue
75+-- \foofalse to be a command that defines \iffoo to be \iffalse
76+newif :: PandocMonad m => LP m [(Text, Macro)]
77+newif = do
78+ controlSeq "newif"
79+ withVerbatimMode $ do
80+ Tok pos (CtrlSeq name) _ <- anyControlSeq
81+ -- \def\iffoo\iffalse
82+ -- \def\footrue{\def\iffoo\iftrue}
83+ -- \def\foofalse{\def\iffoo\iffalse}
84+ let base = T.drop 2 name
85+ return [ (name, Macro ExpandWhenUsed [] Nothing
86+ [Tok pos (CtrlSeq "iffalse") "\\iffalse"])
87+ , (base <> "true",
88+ Macro ExpandWhenUsed [] Nothing
89+ [ Tok pos (CtrlSeq "def") "\\def"
90+ , Tok pos (CtrlSeq name) ("\\" <> name)
91+ , Tok pos (CtrlSeq "iftrue") "\\iftrue"
92+ ])
93+ , (base <> "false",
94+ Macro ExpandWhenUsed [] Nothing
95+ [ Tok pos (CtrlSeq "def") "\\def"
96+ , Tok pos (CtrlSeq name) ("\\" <> name)
97+ , Tok pos (CtrlSeq "iffalse") "\\iffalse"
98+ ])
99+ ]
100+
101+argspecArg :: PandocMonad m => LP m ArgSpec
102+argspecArg = do
103+ Tok _ (Arg i) _ <- satisfyTok isArgTok
104+ return $ ArgNum i
105+
106+argspecPattern :: PandocMonad m => LP m ArgSpec
107+argspecPattern =
108+ Pattern <$> many1 (satisfyTok (\(Tok _ toktype' txt) ->
109+ (toktype' == Symbol || toktype' == Word) &&
110+ (txt /= "{" && txt /= "\\" && txt /= "}")))
111+
112+newcommand :: PandocMonad m => LP m [(Text, Macro)]
113+newcommand = do
114+ Tok pos (CtrlSeq mtype) _ <- controlSeq "newcommand" <|>
115+ controlSeq "renewcommand" <|>
116+ controlSeq "providecommand" <|>
117+ controlSeq "DeclareMathOperator" <|>
118+ controlSeq "DeclareRobustCommand"
119+ withVerbatimMode $ do
120+ Tok _ (CtrlSeq name) txt <- do
121+ optional (symbol '*')
122+ anyControlSeq <|>
123+ (symbol '{' *> spaces *> anyControlSeq <* spaces <* symbol '}')
124+ spaces
125+ numargs <- option 0 $ try bracketedNum
126+ let argspecs = map ArgNum [1..numargs]
127+ spaces
128+ optarg <- option Nothing $ Just <$> try bracketedToks
129+ spaces
130+ contents' <- bracedOrToken
131+ let contents =
132+ case mtype of
133+ "DeclareMathOperator" ->
134+ Tok pos (CtrlSeq "mathop") "\\mathop"
135+ : Tok pos Symbol "{"
136+ : Tok pos (CtrlSeq "mathrm") "\\mathrm"
137+ : Tok pos Symbol "{"
138+ : (contents' ++
139+ [ Tok pos Symbol "}", Tok pos Symbol "}" ])
140+ _ -> contents'
141+ macros <- sMacros <$> getState
142+ case M.lookup name macros of
143+ Just macro
144+ | mtype == "newcommand" -> do
145+ report $ MacroAlreadyDefined txt pos
146+ return [(name, macro)]
147+ | mtype == "providecommand" -> return [(name, macro)]
148+ _ -> return [(name, Macro ExpandWhenUsed argspecs optarg contents)]
149+
150+newenvironment :: PandocMonad m => LP m (Maybe (Text, Macro, Macro))
151+newenvironment = do
152+ pos <- getPosition
153+ Tok _ (CtrlSeq mtype) _ <- controlSeq "newenvironment" <|>
154+ controlSeq "renewenvironment" <|>
155+ controlSeq "provideenvironment"
156+ withVerbatimMode $ do
157+ optional $ symbol '*'
158+ spaces
159+ name <- untokenize <$> braced
160+ spaces
161+ numargs <- option 0 $ try bracketedNum
162+ spaces
163+ optarg <- option Nothing $ Just <$> try bracketedToks
164+ let argspecs = map (\i -> ArgNum i) [1..numargs]
165+ startcontents <- spaces >> bracedOrToken
166+ endcontents <- spaces >> bracedOrToken
167+ macros <- sMacros <$> getState
168+ case M.lookup name macros of
169+ Just _
170+ | mtype == "newenvironment" -> do
171+ report $ MacroAlreadyDefined name pos
172+ return Nothing
173+ | mtype == "provideenvironment" ->
174+ return Nothing
175+ _ -> return $ Just (name,
176+ Macro ExpandWhenUsed argspecs optarg startcontents,
177+ Macro ExpandWhenUsed [] Nothing endcontents)
178+
179+bracketedNum :: PandocMonad m => LP m Int
180+bracketedNum = do
181+ ds <- untokenize <$> bracketedToks
182+ case safeRead ds of
183+ Just i -> return i
184+ _ -> return 0
src/Text/Pandoc/Readers/LaTeX/Math.hsnew file+221
@@ -0,0 +1,221 @@
1+{-# LANGUAGE OverloadedStrings #-}
2+module Text.Pandoc.Readers.LaTeX.Math
3+ ( dollarsMath
4+ , inlineEnvironments
5+ , inlineEnvironment
6+ , mathInline
7+ , mathDisplay
8+ , theoremstyle
9+ , theoremEnvironment
10+ , newtheorem
11+ , proof
12+ )
13+where
14+import Data.Maybe (fromMaybe)
15+import Text.Pandoc.Walk (walk)
16+import Text.Pandoc.Builder as B
17+import qualified Data.Sequence as Seq
18+import Text.Pandoc.Readers.LaTeX.Parsing
19+import Text.Pandoc.Readers.LaTeX.Types
20+import Text.Pandoc.Class
21+import Text.Pandoc.Shared (trimMath, stripTrailingNewlines)
22+import Text.Pandoc.Parsing hiding (blankline, mathDisplay, mathInline,
23+ optional, space, spaces, withRaw, (<|>))
24+import Control.Applicative ((<|>), optional)
25+import Control.Monad (guard, mzero)
26+import qualified Data.Map as M
27+import Data.Text (Text)
28+
29+dollarsMath :: PandocMonad m => LP m Inlines
30+dollarsMath = do
31+ symbol '$'
32+ display <- option False (True <$ symbol '$')
33+ (do contents <- try $ untokenize <$> pDollarsMath 0
34+ if display
35+ then mathDisplay contents <$ symbol '$'
36+ else return $ mathInline contents)
37+ <|> (guard display >> return (mathInline ""))
38+
39+-- Int is number of embedded groupings
40+pDollarsMath :: PandocMonad m => Int -> LP m [Tok]
41+pDollarsMath n = do
42+ tk@(Tok _ toktype t) <- anyTok
43+ case toktype of
44+ Symbol | t == "$"
45+ , n == 0 -> return []
46+ | t == "\\" -> do
47+ tk' <- anyTok
48+ (tk :) . (tk' :) <$> pDollarsMath n
49+ | t == "{" -> (tk :) <$> pDollarsMath (n+1)
50+ | t == "}" ->
51+ if n > 0
52+ then (tk :) <$> pDollarsMath (n-1)
53+ else mzero
54+ _ -> (tk :) <$> pDollarsMath n
55+
56+mathDisplay :: Text -> Inlines
57+mathDisplay = displayMath . trimMath
58+
59+mathInline :: Text -> Inlines
60+mathInline = math . trimMath
61+
62+mathEnvWith :: PandocMonad m
63+ => (Inlines -> a) -> Maybe Text -> Text -> LP m a
64+mathEnvWith f innerEnv name = f . mathDisplay . inner <$> mathEnv name
65+ where inner x = case innerEnv of
66+ Nothing -> x
67+ Just y -> "\\begin{" <> y <> "}\n" <> x <>
68+ "\\end{" <> y <> "}"
69+
70+mathEnv :: PandocMonad m => Text -> LP m Text
71+mathEnv name = do
72+ skipopts
73+ optional blankline
74+ res <- manyTill anyTok (end_ name)
75+ return $ stripTrailingNewlines $ untokenize res
76+
77+inlineEnvironment :: PandocMonad m => LP m Inlines
78+inlineEnvironment = try $ do
79+ controlSeq "begin"
80+ name <- untokenize <$> braced
81+ M.findWithDefault mzero name inlineEnvironments
82+
83+inlineEnvironments :: PandocMonad m => M.Map Text (LP m Inlines)
84+inlineEnvironments = M.fromList [
85+ ("displaymath", mathEnvWith id Nothing "displaymath")
86+ , ("math", math <$> mathEnv "math")
87+ , ("equation", mathEnvWith id Nothing "equation")
88+ , ("equation*", mathEnvWith id Nothing "equation*")
89+ , ("gather", mathEnvWith id (Just "gathered") "gather")
90+ , ("gather*", mathEnvWith id (Just "gathered") "gather*")
91+ , ("multline", mathEnvWith id (Just "gathered") "multline")
92+ , ("multline*", mathEnvWith id (Just "gathered") "multline*")
93+ , ("eqnarray", mathEnvWith id (Just "aligned") "eqnarray")
94+ , ("eqnarray*", mathEnvWith id (Just "aligned") "eqnarray*")
95+ , ("align", mathEnvWith id (Just "aligned") "align")
96+ , ("align*", mathEnvWith id (Just "aligned") "align*")
97+ , ("alignat", mathEnvWith id (Just "aligned") "alignat")
98+ , ("alignat*", mathEnvWith id (Just "aligned") "alignat*")
99+ , ("dmath", mathEnvWith id Nothing "dmath")
100+ , ("dmath*", mathEnvWith id Nothing "dmath*")
101+ , ("dgroup", mathEnvWith id (Just "aligned") "dgroup")
102+ , ("dgroup*", mathEnvWith id (Just "aligned") "dgroup*")
103+ , ("darray", mathEnvWith id (Just "aligned") "darray")
104+ , ("darray*", mathEnvWith id (Just "aligned") "darray*")
105+ ]
106+
107+theoremstyle :: PandocMonad m => LP m Blocks
108+theoremstyle = do
109+ stylename <- untokenize <$> braced
110+ let mbstyle = case stylename of
111+ "plain" -> Just PlainStyle
112+ "definition" -> Just DefinitionStyle
113+ "remark" -> Just RemarkStyle
114+ _ -> Nothing
115+ case mbstyle of
116+ Nothing -> return ()
117+ Just sty -> updateState $ \s -> s{ sLastTheoremStyle = sty }
118+ return mempty
119+
120+newtheorem :: PandocMonad m => LP m Inlines -> LP m Blocks
121+newtheorem inline = do
122+ number <- option True (False <$ symbol '*' <* sp)
123+ name <- untokenize <$> braced
124+ sp
125+ series <- option Nothing $ Just . untokenize <$> bracketedToks
126+ sp
127+ showName <- tokWith inline
128+ sp
129+ syncTo <- option Nothing $ Just . untokenize <$> bracketedToks
130+ sty <- sLastTheoremStyle <$> getState
131+ let spec = TheoremSpec { theoremName = showName
132+ , theoremStyle = sty
133+ , theoremSeries = series
134+ , theoremSyncTo = syncTo
135+ , theoremNumber = number
136+ , theoremLastNum = DottedNum [0] }
137+ tmap <- sTheoremMap <$> getState
138+ updateState $ \s -> s{ sTheoremMap =
139+ M.insert name spec tmap }
140+ return mempty
141+
142+theoremEnvironment :: PandocMonad m
143+ => LP m Blocks -> LP m Inlines -> Text -> LP m Blocks
144+theoremEnvironment blocks opt name = do
145+ tmap <- sTheoremMap <$> getState
146+ case M.lookup name tmap of
147+ Nothing -> mzero
148+ Just tspec -> do
149+ optTitle <- option mempty $ (\x -> space <> "(" <> x <> ")") <$> opt
150+ mblabel <- option Nothing $ Just . untokenize <$>
151+ try (spaces >> controlSeq "label" >> spaces >> braced)
152+ bs <- env name blocks
153+ number <-
154+ if theoremNumber tspec
155+ then do
156+ let name' = fromMaybe name $ theoremSeries tspec
157+ num <- getNextNumber
158+ (maybe (DottedNum [0]) theoremLastNum .
159+ M.lookup name' . sTheoremMap)
160+ updateState $ \s ->
161+ s{ sTheoremMap =
162+ M.adjust
163+ (\spec -> spec{ theoremLastNum = num })
164+ name'
165+ (sTheoremMap s)
166+ }
167+
168+ case mblabel of
169+ Just ident ->
170+ updateState $ \s ->
171+ s{ sLabels = M.insert ident
172+ (B.toList $
173+ theoremName tspec <> "\160" <>
174+ str (renderDottedNum num)) (sLabels s) }
175+ Nothing -> return ()
176+ return $ space <> B.text (renderDottedNum num)
177+ else return mempty
178+ let titleEmph = case theoremStyle tspec of
179+ PlainStyle -> B.strong
180+ DefinitionStyle -> B.strong
181+ RemarkStyle -> B.emph
182+ let title = titleEmph (theoremName tspec <> number)
183+ <> optTitle <> "." <> space
184+ return $ divWith (fromMaybe "" mblabel, [name], []) $ addTitle title
185+ $ case theoremStyle tspec of
186+ PlainStyle -> walk italicize bs
187+ _ -> bs
188+
189+
190+
191+proof :: PandocMonad m => LP m Blocks -> LP m Inlines -> LP m Blocks
192+proof blocks opt = do
193+ title <- option (B.text "Proof") opt
194+ bs <- env "proof" blocks
195+ return $
196+ B.divWith ("", ["proof"], []) $
197+ addQed $ addTitle (B.emph (title <> ".")) bs
198+
199+addTitle :: Inlines -> Blocks -> Blocks
200+addTitle ils bs =
201+ case B.toList bs of
202+ (Para xs : rest)
203+ -> B.fromList (Para (B.toList ils ++ (Space : xs)) : rest)
204+ _ -> B.para ils <> bs
205+
206+addQed :: Blocks -> Blocks
207+addQed bs =
208+ case Seq.viewr (B.unMany bs) of
209+ s Seq.:> Para ils
210+ -> B.Many (s Seq.|> Para (ils ++ B.toList qedSign))
211+ _ -> bs <> B.para qedSign
212+ where
213+ qedSign = B.str "\xa0\x25FB"
214+
215+italicize :: Block -> Block
216+italicize x@(Para [Image{}]) = x -- see #6925
217+italicize (Para ils) = Para [Emph ils]
218+italicize (Plain ils) = Plain [Emph ils]
219+italicize x = x
220+
221+
src/Text/Pandoc/Readers/LaTeX/Parsing.hs+95−7
@@ -27,6 +27,7 @@ module Text.Pandoc.Readers.LaTeX.Parsing
2727 , rawLaTeXParser
2828 , applyMacros
2929 , tokenize
30+ , tokenizeSources
3031 , untokenize
3132 , untoken
3233 , totoks
@@ -54,6 +55,7 @@ module Text.Pandoc.Readers.LaTeX.Parsing
5455 , comment
5556 , anyTok
5657 , singleChar
58+ , tokWith
5759 , specialChars
5860 , endline
5961 , blankline
@@ -80,6 +82,11 @@ module Text.Pandoc.Readers.LaTeX.Parsing
8082 , rawopt
8183 , overlaySpecification
8284 , getNextNumber
85+ , label
86+ , setCaption
87+ , resetCaption
88+ , env
89+ , addMeta
8390 ) where
8491
8592import Control.Applicative (many, (<|>))
@@ -106,7 +113,6 @@ import Text.Pandoc.Readers.LaTeX.Types (ExpansionPoint (..), Macro (..),
106113 ArgSpec (..), Tok (..), TokType (..))
107114import Text.Pandoc.Shared
108115import Text.Parsec.Pos
109−-- import Debug.Trace
110116
111117newtype DottedNum = DottedNum [Int]
112118 deriving (Show, Eq)
@@ -242,7 +248,7 @@ withVerbatimMode parser = do
242248
243249rawLaTeXParser :: (PandocMonad m, HasMacros s, HasReaderOptions s)
244250 => [Tok] -> Bool -> LP m a -> LP m a
245− -> ParserT Text s m (a, Text)
251+ -> ParserT Sources s m (a, Text)
246252rawLaTeXParser toks retokenize parser valParser = do
247253 pstate <- getState
248254 let lstate = def{ sOptions = extractReaderOptions pstate }
@@ -262,7 +268,7 @@ rawLaTeXParser toks retokenize parser valParser = do
262268 Left _ -> mzero
263269 Right ((val, raw), st) -> do
264270 updateState (updateMacros (sMacros st <>))
265− _ <- takeP (T.length (untokenize toks'))
271+ void $ count (T.length (untokenize toks')) anyChar
266272 let result = untokenize raw
267273 -- ensure we end with space if input did, see #4442
268274 let result' =
@@ -275,7 +281,7 @@ rawLaTeXParser toks retokenize parser valParser = do
275281 return (val, result')
276282
277283applyMacros :: (PandocMonad m, HasMacros s, HasReaderOptions s)
278− => Text -> ParserT Text s m Text
284+ => Text -> ParserT Sources s m Text
279285applyMacros s = (guardDisabled Ext_latex_macros >> return s) <|>
280286 do let retokenize = untokenize <$> many (satisfyTok (const True))
281287 pstate <- getState
@@ -286,6 +292,20 @@ applyMacros s = (guardDisabled Ext_latex_macros >> return s) <|>
286292 Left e -> Prelude.fail (show e)
287293 Right s' -> return s'
288294
295+{-
296+When tokenize or untokenize change, test with this
297+QuickCheck property:
298+
299+> tokUntokRoundtrip :: String -> Bool
300+> tokUntokRoundtrip s =
301+> let t = T.pack s in untokenize (tokenize "random" t) == t
302+-}
303+
304+tokenizeSources :: Sources -> [Tok]
305+tokenizeSources = concatMap tokenizeSource . unSources
306+ where
307+ tokenizeSource (pos, t) = totoks pos t
308+
289309tokenize :: SourceName -> Text -> [Tok]
290310tokenize sourcename = totoks (initialPos sourcename)
291311
@@ -443,7 +463,7 @@ satisfyTok f = do
443463doMacros :: PandocMonad m => LP m ()
444464doMacros = do
445465 st <- getState
446− unless (sVerbatimMode st || M.null (sMacros st)) $ do
466+ unless (sVerbatimMode st) $
447467 getInput >>= doMacros' 1 >>= setInput
448468
449469doMacros' :: PandocMonad m => Int -> [Tok] -> LP m [Tok]
@@ -505,7 +525,7 @@ doMacros' n inp =
505525 $ throwError $ PandocMacroLoop name
506526 macros <- sMacros <$> getState
507527 case M.lookup name macros of
508− Nothing -> mzero
528+ Nothing -> trySpecialMacro name ts
509529 Just (Macro expansionPoint argspecs optarg newtoks) -> do
510530 let getargs' = do
511531 args <-
@@ -533,6 +553,41 @@ doMacros' n inp =
533553 ExpandWhenUsed -> doMacros' (n' + 1) result
534554 ExpandWhenDefined -> return result
535555
556+-- | Certain macros do low-level tex manipulations that can't
557+-- be represented in our Macro type, so we handle them here.
558+trySpecialMacro :: PandocMonad m => Text -> [Tok] -> LP m [Tok]
559+trySpecialMacro "xspace" ts = do
560+ ts' <- doMacros' 1 ts
561+ case ts' of
562+ Tok pos Word t : _
563+ | startsWithAlphaNum t -> return $ Tok pos Spaces " " : ts'
564+ _ -> return ts'
565+trySpecialMacro "iftrue" ts = handleIf True ts
566+trySpecialMacro "iffalse" ts = handleIf False ts
567+trySpecialMacro _ _ = mzero
568+
569+handleIf :: PandocMonad m => Bool -> [Tok] -> LP m [Tok]
570+handleIf b ts = do
571+ res' <- lift $ runParserT (ifParser b) defaultLaTeXState "tokens" ts
572+ case res' of
573+ Left _ -> Prelude.fail "Could not parse conditional"
574+ Right ts' -> return ts'
575+
576+ifParser :: PandocMonad m => Bool -> LP m [Tok]
577+ifParser b = do
578+ ifToks <- many (notFollowedBy (controlSeq "else" <|> controlSeq "fi")
579+ *> anyTok)
580+ elseToks <- (controlSeq "else" >> manyTill anyTok (controlSeq "fi"))
581+ <|> ([] <$ controlSeq "fi")
582+ rest <- getInput
583+ return $ (if b then ifToks else elseToks) ++ rest
584+
585+startsWithAlphaNum :: Text -> Bool
586+startsWithAlphaNum t =
587+ case T.uncons t of
588+ Just (c, _) | isAlphaNum c -> True
589+ _ -> False
590+
536591setpos :: SourcePos -> Tok -> Tok
537592setpos spos (Tok _ tt txt) = Tok spos tt txt
538593
@@ -768,7 +823,8 @@ withRaw parser = do
768823
769824keyval :: PandocMonad m => LP m (Text, Text)
770825keyval = try $ do
771− Tok _ Word key <- satisfyTok isWordTok
826+ key <- untokenize <$> many1 (notFollowedBy (symbol '=') >>
827+ (symbol '-' <|> symbol '_' <|> satisfyTok isWordTok))
772828 sp
773829 val <- option mempty $ do
774830 symbol '='
@@ -914,3 +970,35 @@ getNextNumber getCurrentNum = do
914970 Just n -> [n, 1]
915971 Nothing -> [1]
916972
973+label :: PandocMonad m => LP m ()
974+label = do
975+ controlSeq "label"
976+ t <- braced
977+ updateState $ \st -> st{ sLastLabel = Just $ untokenize t }
978+
979+setCaption :: PandocMonad m => LP m Inlines -> LP m ()
980+setCaption inline = try $ do
981+ skipopts
982+ ils <- tokWith inline
983+ optional $ try $ spaces *> label
984+ updateState $ \st -> st{ sCaption = Just ils }
985+
986+resetCaption :: PandocMonad m => LP m ()
987+resetCaption = updateState $ \st -> st{ sCaption = Nothing
988+ , sLastLabel = Nothing }
989+
990+env :: PandocMonad m => Text -> LP m a -> LP m a
991+env name p = p <* end_ name
992+
993+tokWith :: PandocMonad m => LP m Inlines -> LP m Inlines
994+tokWith inlineParser = try $ spaces >>
995+ grouped inlineParser
996+ <|> (lookAhead anyControlSeq >> inlineParser)
997+ <|> singleChar'
998+ where singleChar' = do
999+ Tok _ _ t <- singleChar
1000+ return $ str t
1001+
1002+addMeta :: PandocMonad m => ToMetaValue a => Text -> a -> LP m ()
1003+addMeta field val = updateState $ \st ->
1004+ st{ sMeta = addMetaField field val $ sMeta st }
src/Text/Pandoc/Readers/LaTeX/SIunitx.hs+152−71
@@ -1,12 +1,7 @@
1+{-# LANGUAGE ScopedTypeVariables #-}
12{-# LANGUAGE OverloadedStrings #-}
23module Text.Pandoc.Readers.LaTeX.SIunitx
3− ( dosi
4− , doSI
5− , doSIrange
6− , doSInum
7− , doSInumlist
8− , doSIang
9− )
4+ ( siunitxCommands )
105where
116import Text.Pandoc.Builder
127import Text.Pandoc.Readers.LaTeX.Parsing
@@ -15,14 +10,32 @@ import Text.Pandoc.Class
1510import Text.Pandoc.Parsing hiding (blankline, mathDisplay, mathInline,
1611 optional, space, spaces, withRaw, (<|>))
1712import Control.Applicative ((<|>))
13+import Control.Monad (void)
1814import qualified Data.Map as M
1915import Data.Char (isDigit)
2016import Data.Text (Text)
2117import qualified Data.Text as T
2218import Data.List (intersperse)
19+import qualified Data.Sequence as Seq
20+import Text.Pandoc.Walk (walk)
21+
22+siunitxCommands :: PandocMonad m
23+ => LP m Inlines -> M.Map Text (LP m Inlines)
24+siunitxCommands tok = M.fromList
25+ [ ("si", dosi tok)
26+ , ("SI", doSI tok)
27+ , ("SIrange", doSIrange True tok)
28+ , ("numrange", doSIrange False tok)
29+ , ("numlist", doSInumlist)
30+ , ("SIlist", doSIlist tok)
31+ , ("num", doSInum)
32+ , ("ang", doSIang)
33+ ]
2334
2435dosi :: PandocMonad m => LP m Inlines -> LP m Inlines
25−dosi tok = grouped (siUnit tok) <|> siUnit tok
36+dosi tok = do
37+ options <- option [] keyvals
38+ grouped (siUnit options tok) <|> siUnit options tok
2639
2740-- converts e.g. \SI{1}[\$]{} to "$ 1" or \SI{1}{\euro} to "1 €"
2841doSI :: PandocMonad m => LP m Inlines -> LP m Inlines
@@ -57,23 +70,50 @@ doSInumlist = do
5770 mconcat (intersperse (str "," <> space) (init xs)) <>
5871 text ", & " <> last xs
5972
73+doSIlist :: PandocMonad m => LP m Inlines -> LP m Inlines
74+doSIlist tok = do
75+ options <- option [] keyvals
76+ nums <- map tonum . T.splitOn ";" . untokenize <$> braced
77+ unit <- grouped (siUnit options tok) <|> siUnit options tok
78+ let xs = map (<> (str "\xa0" <> unit)) nums
79+ case xs of
80+ [] -> return mempty
81+ [x] -> return x
82+ _ -> return $
83+ mconcat (intersperse (str "," <> space) (init xs)) <>
84+ text ", & " <> last xs
85+
6086parseNum :: Parser Text () Inlines
6187parseNum = (mconcat <$> many parseNumPart) <* eof
6288
89+minus :: Text
90+minus = "\x2212"
91+
92+hyphenToMinus :: Inline -> Inline
93+hyphenToMinus (Str t) = Str (T.replace "-" minus t)
94+hyphenToMinus x = x
95+
6396parseNumPart :: Parser Text () Inlines
6497parseNumPart =
6598 parseDecimalNum <|>
6699 parseComma <|>
67100 parsePlusMinus <|>
101+ parsePM <|>
68102 parseI <|>
69103 parseExp <|>
70104 parseX <|>
71105 parseSpace
72106 where
73− parseDecimalNum = do
74− pref <- option mempty $ (mempty <$ char '+') <|> ("\x2212" <$ char '-')
75− basenum <- (pref <>) . T.pack
76− <$> many1 (satisfy (\c -> isDigit c || c == '.'))
107+ parseDecimalNum, parsePlusMinus, parsePM,
108+ parseComma, parseI, parseX,
109+ parseExp, parseSpace :: Parser Text () Inlines
110+ parseDecimalNum = try $ do
111+ pref <- option mempty $ (mempty <$ char '+') <|> (minus <$ char '-')
112+ basenum' <- many1 (satisfy (\c -> isDigit c || c == '.'))
113+ let basenum = pref <> T.pack
114+ (case basenum' of
115+ '.':_ -> '0':basenum'
116+ _ -> basenum')
77117 uncertainty <- option mempty $ T.pack <$> parseParens
78118 if T.null uncertainty
79119 then return $ str basenum
@@ -91,6 +131,7 @@ parseNumPart =
91131 | otherwise -> "." <> t
92132 parseComma = str "." <$ char ','
93133 parsePlusMinus = str "\xa0\xb1\xa0" <$ try (string "+-")
134+ parsePM = str "\xa0\xb1\xa0" <$ try (string "\\pm")
94135 parseParens =
95136 char '(' *> many1 (satisfy (\c -> isDigit c || c == '.')) <* char ')'
96137 parseI = str "i" <$ char 'i'
@@ -103,11 +144,14 @@ doSIang :: PandocMonad m => LP m Inlines
103144doSIang = do
104145 skipopts
105146 ps <- T.splitOn ";" . untokenize <$> braced
147+ let dropPlus t = case T.uncons t of
148+ Just ('+',t') -> t'
149+ _ -> t
106150 case ps ++ repeat "" of
107151 (d:m:s:_) -> return $
108− (if T.null d then mempty else str d <> str "\xb0") <>
109− (if T.null m then mempty else str m <> str "\x2032") <>
110− (if T.null s then mempty else str s <> str "\x2033")
152+ (if T.null d then mempty else str (dropPlus d) <> str "\xb0") <>
153+ (if T.null m then mempty else str (dropPlus m) <> str "\x2032") <>
154+ (if T.null s then mempty else str (dropPlus s) <> str "\x2033")
111155 _ -> return mempty
112156
113157-- converts e.g. \SIrange{100}{200}{\ms} to "100 ms--200 ms"
@@ -136,40 +180,99 @@ doSIrange includeUnits tok = do
136180emptyOr160 :: Inlines -> Inlines
137181emptyOr160 x = if x == mempty then x else str "\160"
138182
139−siUnit :: PandocMonad m => LP m Inlines -> LP m Inlines
140−siUnit tok = try (do
141− Tok _ (CtrlSeq name) _ <- anyControlSeq
142− case name of
143− "square" -> do
144− unit <- siUnit tok
145− return $ unit <> superscript "2"
146− "cubic" -> do
147− unit <- siUnit tok
148− return $ unit <> superscript "3"
149− "raisetothe" -> do
150− n <- tok
151− unit <- siUnit tok
152− return $ unit <> superscript n
153− _ ->
154− case M.lookup name siUnitMap of
155− Just il ->
156− option il $
157− choice
158− [ (il <> superscript "2") <$ controlSeq "squared"
159− , (il <> superscript "3") <$ controlSeq "cubed"
160− , (\n -> il <> superscript n) <$> (controlSeq "tothe" *> tok)
161− ]
162− Nothing -> fail "not an siunit unit command")
163− <|> (lookAhead anyControlSeq >> tok)
164− <|> (do Tok _ Word t <- satisfyTok isWordTok
165− return $ str t)
166− <|> (symbol '^' *> (superscript <$> tok))
167− <|> (symbol '_' *> (subscript <$> tok))
168− <|> ("\xa0" <$ symbol '.')
169− <|> ("\xa0" <$ symbol '~')
170− <|> tok
171− <|> (do Tok _ _ t <- anyTok
172− return (str t))
183+siUnit :: forall m. PandocMonad m => [(Text,Text)] -> LP m Inlines -> LP m Inlines
184+siUnit options tok = mconcat . intersperse (str "\xa0") <$> many1 siUnitPart
185+ where
186+ siUnitPart :: LP m Inlines
187+ siUnitPart = try $ do
188+ skipMany (void (symbol '.') <|> void (symbol '~') <|> spaces1)
189+ x <- ((siPrefix <*> siBase)
190+ <|> (do u <- siBase <|> tok
191+ option u $ siSuffix <*> pure u))
192+ option x (siInfix x)
193+ siInfix :: Inlines -> LP m Inlines
194+ siInfix u1 = try $
195+ (do _ <- controlSeq "per"
196+ u2 <- siUnitPart
197+ let useSlash = lookup "per-mode" options == Just "symbol"
198+ if useSlash
199+ then return (u1 <> str "/" <> u2)
200+ else return (u1 <> str "\xa0" <> negateExponent u2))
201+ <|> (do _ <- symbol '/'
202+ u2 <- siUnitPart
203+ return (u1 <> str "/" <> u2))
204+ siPrefix :: LP m (Inlines -> Inlines)
205+ siPrefix =
206+ (do _ <- controlSeq "square"
207+ skipopts
208+ return (<> superscript "2"))
209+ <|> (do _ <- controlSeq "cubic"
210+ skipopts
211+ return (<> superscript "3"))
212+ <|> (do _ <- controlSeq "raisetothe"
213+ skipopts
214+ n <- walk hyphenToMinus <$> tok
215+ return (<> superscript n))
216+ siSuffix :: LP m (Inlines -> Inlines)
217+ siSuffix =
218+ (do _ <- controlSeq "squared"
219+ skipopts
220+ return (<> superscript "2"))
221+ <|> (do _ <- controlSeq "cubed"
222+ skipopts
223+ return (<> superscript "3"))
224+ <|> (do _ <- controlSeq "tothe"
225+ skipopts
226+ n <- walk hyphenToMinus <$> tok
227+ return (<> superscript n))
228+ <|> (symbol '^' *> (do n <- walk hyphenToMinus <$> tok
229+ return (<> superscript n)))
230+ <|> (symbol '_' *> (do n <- walk hyphenToMinus <$> tok
231+ return (<> subscript n)))
232+ negateExponent :: Inlines -> Inlines
233+ negateExponent ils =
234+ case Seq.viewr (unMany ils) of
235+ xs Seq.:> Superscript ss -> (Many xs) <>
236+ superscript (str minus <> fromList ss)
237+ _ -> ils <> superscript (str (minus <> "1"))
238+ siBase :: LP m Inlines
239+ siBase =
240+ ((try
241+ (do Tok _ (CtrlSeq name) _ <- anyControlSeq
242+ case M.lookup name siUnitModifierMap of
243+ Just il -> (il <>) <$> siBase
244+ Nothing ->
245+ case M.lookup name siUnitMap of
246+ Just il -> pure il
247+ Nothing -> fail "not a unit command"))
248+ <|> (do Tok _ Word t <- satisfyTok isWordTok
249+ return $ str t)
250+ )
251+
252+siUnitModifierMap :: M.Map Text Inlines
253+siUnitModifierMap = M.fromList
254+ [ ("atto", str "a")
255+ , ("centi", str "c")
256+ , ("deca", str "d")
257+ , ("deci", str "d")
258+ , ("deka", str "d")
259+ , ("exa", str "E")
260+ , ("femto", str "f")
261+ , ("giga", str "G")
262+ , ("hecto", str "h")
263+ , ("kilo", str "k")
264+ , ("mega", str "M")
265+ , ("micro", str "μ")
266+ , ("milli", str "m")
267+ , ("nano", str "n")
268+ , ("peta", str "P")
269+ , ("pico", str "p")
270+ , ("tera", str "T")
271+ , ("yocto", str "y")
272+ , ("yotta", str "Y")
273+ , ("zepto", str "z")
274+ , ("zetta", str "Z")
275+ ]
173276
174277siUnitMap :: M.Map Text Inlines
175278siUnitMap = M.fromList
@@ -269,7 +372,6 @@ siUnitMap = M.fromList
269372 , ("arcsecond", str "″")
270373 , ("astronomicalunit", str "ua")
271374 , ("atomicmassunit", str "u")
272− , ("atto", str "a")
273375 , ("bar", str "bar")
274376 , ("barn", str "b")
275377 , ("becquerel", str "Bq")
@@ -277,51 +379,38 @@ siUnitMap = M.fromList
277379 , ("bohr", emph (str "a") <> subscript (str "0"))
278380 , ("candela", str "cd")
279381 , ("celsius", str "°C")
280− , ("centi", str "c")
281382 , ("clight", emph (str "c") <> subscript (str "0"))
282383 , ("coulomb", str "C")
283384 , ("dalton", str "Da")
284385 , ("day", str "d")
285− , ("deca", str "d")
286− , ("deci", str "d")
287386 , ("decibel", str "db")
288387 , ("degreeCelsius",str "°C")
289388 , ("degree", str "°")
290− , ("deka", str "d")
291389 , ("electronmass", emph (str "m") <> subscript (str "e"))
292390 , ("electronvolt", str "eV")
293391 , ("elementarycharge", emph (str "e"))
294− , ("exa", str "E")
295392 , ("farad", str "F")
296− , ("femto", str "f")
297− , ("giga", str "G")
298393 , ("gram", str "g")
299394 , ("gray", str "Gy")
300395 , ("hartree", emph (str "E") <> subscript (str "h"))
301396 , ("hectare", str "ha")
302− , ("hecto", str "h")
303397 , ("henry", str "H")
304398 , ("hertz", str "Hz")
305399 , ("hour", str "h")
306400 , ("joule", str "J")
307401 , ("katal", str "kat")
308402 , ("kelvin", str "K")
309− , ("kilo", str "k")
310403 , ("kilogram", str "kg")
311404 , ("knot", str "kn")
312405 , ("liter", str "L")
313406 , ("litre", str "l")
314407 , ("lumen", str "lm")
315408 , ("lux", str "lx")
316− , ("mega", str "M")
317409 , ("meter", str "m")
318410 , ("metre", str "m")
319− , ("micro", str "μ")
320− , ("milli", str "m")
321411 , ("minute", str "min")
322412 , ("mmHg", str "mmHg")
323413 , ("mole", str "mol")
324− , ("nano", str "n")
325414 , ("nauticalmile", str "M")
326415 , ("neper", str "Np")
327416 , ("newton", str "N")
@@ -329,25 +418,17 @@ siUnitMap = M.fromList
329418 , ("Pa", str "Pa")
330419 , ("pascal", str "Pa")
331420 , ("percent", str "%")
332− , ("per", str "/")
333− , ("peta", str "P")
334− , ("pico", str "p")
335421 , ("planckbar", emph (str "\x210f"))
336422 , ("radian", str "rad")
337423 , ("second", str "s")
338424 , ("siemens", str "S")
339425 , ("sievert", str "Sv")
340426 , ("steradian", str "sr")
341− , ("tera", str "T")
342427 , ("tesla", str "T")
343428 , ("tonne", str "t")
344429 , ("volt", str "V")
345430 , ("watt", str "W")
346431 , ("weber", str "Wb")
347− , ("yocto", str "y")
348− , ("yotta", str "Y")
349− , ("zepto", str "z")
350− , ("zetta", str "Z")
351432 ]
352433
353434
src/Text/Pandoc/Readers/LaTeX/Table.hsnew file+378
@@ -0,0 +1,378 @@
1+{-# LANGUAGE BangPatterns #-}
2+{-# LANGUAGE OverloadedStrings #-}
3+module Text.Pandoc.Readers.LaTeX.Table
4+ ( tableEnvironments )
5+where
6+
7+import Data.Functor (($>))
8+import Text.Pandoc.Class
9+import Text.Pandoc.Readers.LaTeX.Parsing
10+import Text.Pandoc.Readers.LaTeX.Types
11+import Text.Pandoc.Builder as B
12+import qualified Data.Map as M
13+import Data.Text (Text)
14+import Data.Maybe (fromMaybe)
15+import qualified Data.Text as T
16+import Control.Applicative ((<|>), optional, many)
17+import Control.Monad (when, void)
18+import Text.Pandoc.Shared (safeRead, trim)
19+import Text.Pandoc.Logging (LogMessage(SkippedContent))
20+import Text.Pandoc.Walk (walkM)
21+import Text.Pandoc.Parsing hiding (blankline, many, mathDisplay, mathInline,
22+ optional, space, spaces, withRaw, (<|>))
23+
24+tableEnvironments :: PandocMonad m
25+ => LP m Blocks
26+ -> LP m Inlines
27+ -> M.Map Text (LP m Blocks)
28+tableEnvironments blocks inline =
29+ M.fromList
30+ [ ("longtable", env "longtable" $
31+ resetCaption *>
32+ simpTable blocks inline "longtable" False >>= addTableCaption)
33+ , ("table", env "table" $
34+ skipopts *> resetCaption *> blocks >>= addTableCaption)
35+ , ("tabular*", env "tabular*" $ simpTable blocks inline "tabular*" True)
36+ , ("tabularx", env "tabularx" $ simpTable blocks inline "tabularx" True)
37+ , ("tabular", env "tabular" $ simpTable blocks inline "tabular" False)
38+ ]
39+
40+hline :: PandocMonad m => LP m ()
41+hline = try $ do
42+ spaces
43+ controlSeq "hline" <|>
44+ -- booktabs rules:
45+ controlSeq "toprule" <|>
46+ controlSeq "bottomrule" <|>
47+ controlSeq "midrule" <|>
48+ controlSeq "endhead" <|>
49+ controlSeq "endfirsthead"
50+ spaces
51+ optional rawopt
52+ return ()
53+
54+lbreak :: PandocMonad m => LP m Tok
55+lbreak = (controlSeq "\\" <|> controlSeq "tabularnewline")
56+ <* skipopts <* spaces
57+
58+amp :: PandocMonad m => LP m Tok
59+amp = symbol '&'
60+
61+-- Split a Word into individual Symbols (for parseAligns)
62+splitWordTok :: PandocMonad m => LP m ()
63+splitWordTok = do
64+ inp <- getInput
65+ case inp of
66+ (Tok spos Word t : rest) ->
67+ setInput $ map (Tok spos Symbol . T.singleton) (T.unpack t) <> rest
68+ _ -> return ()
69+
70+parseAligns :: PandocMonad m => LP m [(Alignment, ColWidth, ([Tok], [Tok]))]
71+parseAligns = try $ do
72+ let maybeBar = skipMany
73+ (try $ sp *> (() <$ symbol '|' <|> () <$ (symbol '@' >> braced)))
74+ let cAlign = AlignCenter <$ symbol 'c'
75+ let lAlign = AlignLeft <$ symbol 'l'
76+ let rAlign = AlignRight <$ symbol 'r'
77+ let parAlign = AlignLeft <$ symbol 'p'
78+ -- aligns from tabularx
79+ let xAlign = AlignLeft <$ symbol 'X'
80+ let mAlign = AlignLeft <$ symbol 'm'
81+ let bAlign = AlignLeft <$ symbol 'b'
82+ let alignChar = splitWordTok *> ( cAlign <|> lAlign <|> rAlign <|> parAlign
83+ <|> xAlign <|> mAlign <|> bAlign )
84+ let alignPrefix = symbol '>' >> braced
85+ let alignSuffix = symbol '<' >> braced
86+ let colWidth = try $ do
87+ symbol '{'
88+ ds <- trim . untokenize <$> manyTill anyTok (controlSeq "linewidth")
89+ spaces
90+ symbol '}'
91+ return $ safeRead ds
92+ let alignSpec = do
93+ pref <- option [] alignPrefix
94+ spaces
95+ al <- alignChar
96+ width <- colWidth <|> option Nothing (do s <- untokenize <$> braced
97+ pos <- getPosition
98+ report $ SkippedContent s pos
99+ return Nothing)
100+ spaces
101+ suff <- option [] alignSuffix
102+ return (al, width, (pref, suff))
103+ let starAlign = do -- '*{2}{r}' == 'rr', we just expand like a macro
104+ symbol '*'
105+ spaces
106+ ds <- trim . untokenize <$> braced
107+ spaces
108+ spec <- braced
109+ case safeRead ds of
110+ Just n ->
111+ getInput >>= setInput . (mconcat (replicate n spec) ++)
112+ Nothing -> Prelude.fail $ "Could not parse " <> T.unpack ds <> " as number"
113+ bgroup
114+ spaces
115+ maybeBar
116+ aligns' <- many $ try $ spaces >> optional starAlign >>
117+ (alignSpec <* maybeBar)
118+ spaces
119+ egroup
120+ spaces
121+ return $ map toSpec aligns'
122+ where
123+ toColWidth (Just w) | w > 0 = ColWidth w
124+ toColWidth _ = ColWidthDefault
125+ toSpec (x, y, z) = (x, toColWidth y, z)
126+
127+-- N.B. this parser returns a Row that may have erroneous empty cells
128+-- in it. See the note above fixTableHead for details.
129+parseTableRow :: PandocMonad m
130+ => LP m Blocks -- ^ block parser
131+ -> LP m Inlines -- ^ inline parser
132+ -> Text -- ^ table environment name
133+ -> [([Tok], [Tok])] -- ^ pref/suffixes
134+ -> LP m Row
135+parseTableRow blocks inline envname prefsufs = do
136+ notFollowedBy (spaces *> end_ envname)
137+ -- contexts that can contain & that is not colsep:
138+ let canContainAmp (Tok _ (CtrlSeq "begin") _) = True
139+ canContainAmp (Tok _ (CtrlSeq "verb") _) = True
140+ canContainAmp (Tok _ (CtrlSeq "Verb") _) = True
141+ canContainAmp _ = False
142+ -- add prefixes and suffixes in token stream:
143+ let celltoks (pref, suff) = do
144+ prefpos <- getPosition
145+ contents <- mconcat <$>
146+ many ( snd <$> withRaw
147+ ((lookAhead (controlSeq "parbox") >>
148+ void blocks) -- #5711
149+ <|>
150+ (lookAhead (satisfyTok canContainAmp) >> void inline)
151+ <|>
152+ (lookAhead (symbol '$') >> void inline))
153+ <|>
154+ (do notFollowedBy
155+ (() <$ amp <|> () <$ lbreak <|> end_ envname)
156+ count 1 anyTok) )
157+
158+ suffpos <- getPosition
159+ option [] (count 1 amp)
160+ return $ map (setpos prefpos) pref ++ contents ++ map (setpos suffpos) suff
161+ rawcells <- mapM celltoks prefsufs
162+ cells <- mapM (parseFromToks (parseTableCell blocks)) rawcells
163+ spaces
164+ return $ Row nullAttr cells
165+
166+parseTableCell :: PandocMonad m => LP m Blocks -> LP m Cell
167+parseTableCell blocks = do
168+ spaces
169+ updateState $ \st -> st{ sInTableCell = True }
170+ cell' <- multicolumnCell blocks
171+ <|> multirowCell blocks
172+ <|> parseSimpleCell
173+ <|> parseEmptyCell
174+ updateState $ \st -> st{ sInTableCell = False }
175+ spaces
176+ return cell'
177+ where
178+ -- The parsing of empty cells is important in LaTeX, especially when dealing
179+ -- with multirow/multicolumn. See #6603.
180+ parseEmptyCell = spaces $> emptyCell
181+ parseSimpleCell = simpleCell <$> (plainify <$> blocks)
182+
183+
184+cellAlignment :: PandocMonad m => LP m Alignment
185+cellAlignment = skipMany (symbol '|') *> alignment <* skipMany (symbol '|')
186+ where
187+ alignment = do
188+ c <- untoken <$> singleChar
189+ return $ case c of
190+ "l" -> AlignLeft
191+ "r" -> AlignRight
192+ "c" -> AlignCenter
193+ "*" -> AlignDefault
194+ _ -> AlignDefault
195+
196+plainify :: Blocks -> Blocks
197+plainify bs = case toList bs of
198+ [Para ils] -> plain (fromList ils)
199+ _ -> bs
200+
201+multirowCell :: PandocMonad m => LP m Blocks -> LP m Cell
202+multirowCell blocks = controlSeq "multirow" >> do
203+ -- Full prototype for \multirow macro is:
204+ -- \multirow[vpos]{nrows}[bigstruts]{width}[vmove]{text}
205+ -- However, everything except `nrows` and `text` make
206+ -- sense in the context of the Pandoc AST
207+ _ <- optional $ symbol '[' *> cellAlignment <* symbol ']' -- vertical position
208+ nrows <- fmap (fromMaybe 1 . safeRead . untokenize) braced
209+ _ <- optional $ symbol '[' *> manyTill anyTok (symbol ']') -- bigstrut-related
210+ _ <- symbol '{' *> manyTill anyTok (symbol '}') -- Cell width
211+ _ <- optional $ symbol '[' *> manyTill anyTok (symbol ']') -- Length used for fine-tuning
212+ content <- symbol '{' *> (plainify <$> blocks) <* symbol '}'
213+ return $ cell AlignDefault (RowSpan nrows) (ColSpan 1) content
214+
215+multicolumnCell :: PandocMonad m => LP m Blocks -> LP m Cell
216+multicolumnCell blocks = controlSeq "multicolumn" >> do
217+ span' <- fmap (fromMaybe 1 . safeRead . untokenize) braced
218+ alignment <- symbol '{' *> cellAlignment <* symbol '}'
219+
220+ let singleCell = do
221+ content <- plainify <$> blocks
222+ return $ cell alignment (RowSpan 1) (ColSpan span') content
223+
224+ -- Two possible contents: either a \multirow cell, or content.
225+ -- E.g. \multicol{1}{c}{\multirow{2}{1em}{content}}
226+ -- Note that a \multirow cell can be nested in a \multicolumn,
227+ -- but not the other way around. See #6603
228+ let nestedCell = do
229+ (Cell _ _ (RowSpan rs) _ bs) <- multirowCell blocks
230+ return $ cell
231+ alignment
232+ (RowSpan rs)
233+ (ColSpan span')
234+ (fromList bs)
235+
236+ symbol '{' *> (nestedCell <|> singleCell) <* symbol '}'
237+
238+-- LaTeX tables are stored with empty cells underneath multirow cells
239+-- denoting the grid spaces taken up by them. More specifically, if a
240+-- cell spans m rows, then it will overwrite all the cells in the
241+-- columns it spans for (m-1) rows underneath it, requiring padding
242+-- cells in these places. These padding cells need to be removed for
243+-- proper table reading. See #6603.
244+--
245+-- These fixTable functions do not otherwise fix up malformed
246+-- input tables: that is left to the table builder.
247+fixTableHead :: TableHead -> TableHead
248+fixTableHead (TableHead attr rows) = TableHead attr rows'
249+ where
250+ rows' = fixTableRows rows
251+
252+fixTableBody :: TableBody -> TableBody
253+fixTableBody (TableBody attr rhc th tb)
254+ = TableBody attr rhc th' tb'
255+ where
256+ th' = fixTableRows th
257+ tb' = fixTableRows tb
258+
259+fixTableRows :: [Row] -> [Row]
260+fixTableRows = fixTableRows' $ repeat Nothing
261+ where
262+ fixTableRows' oldHang (Row attr cells : rs)
263+ = let (newHang, cells') = fixTableRow oldHang cells
264+ rs' = fixTableRows' newHang rs
265+ in Row attr cells' : rs'
266+ fixTableRows' _ [] = []
267+
268+-- The overhang is represented as Just (relative cell dimensions) or
269+-- Nothing for an empty grid space.
270+fixTableRow :: [Maybe (ColSpan, RowSpan)] -> [Cell] -> ([Maybe (ColSpan, RowSpan)], [Cell])
271+fixTableRow oldHang cells
272+ -- If there's overhang, drop cells until their total width meets the
273+ -- width of the occupied grid spaces (or we run out)
274+ | (n, prefHang, restHang) <- splitHang oldHang
275+ , n > 0
276+ = let cells' = dropToWidth getCellW n cells
277+ (restHang', cells'') = fixTableRow restHang cells'
278+ in (prefHang restHang', cells'')
279+ -- Otherwise record the overhang of a pending cell and fix the rest
280+ -- of the row
281+ | c@(Cell _ _ h w _):cells' <- cells
282+ = let h' = max 1 h
283+ w' = max 1 w
284+ oldHang' = dropToWidth getHangW w' oldHang
285+ (newHang, cells'') = fixTableRow oldHang' cells'
286+ in (toHang w' h' <> newHang, c : cells'')
287+ | otherwise
288+ = (oldHang, [])
289+ where
290+ getCellW (Cell _ _ _ w _) = w
291+ getHangW = maybe 1 fst
292+ getCS (ColSpan n) = n
293+
294+ toHang c r
295+ | r > 1 = [Just (c, r)]
296+ | otherwise = replicate (getCS c) Nothing
297+
298+ -- Take the prefix of the overhang list representing filled grid
299+ -- spaces. Also return the remainder and the length of this prefix.
300+ splitHang = splitHang' 0 id
301+
302+ splitHang' !n l (Just (c, r):xs)
303+ = splitHang' (n + c) (l . (toHang c (r-1) ++)) xs
304+ splitHang' n l xs = (n, l, xs)
305+
306+ -- Drop list items until the total width of the dropped items
307+ -- exceeds the passed width.
308+ dropToWidth _ n l | n < 1 = l
309+ dropToWidth wproj n (c:cs) = dropToWidth wproj (n - wproj c) cs
310+ dropToWidth _ _ [] = []
311+
312+simpTable :: PandocMonad m
313+ => LP m Blocks
314+ -> LP m Inlines
315+ -> Text
316+ -> Bool
317+ -> LP m Blocks
318+simpTable blocks inline envname hasWidthParameter = try $ do
319+ when hasWidthParameter $ () <$ tokWith inline
320+ skipopts
321+ colspecs <- parseAligns
322+ let (aligns, widths, prefsufs) = unzip3 colspecs
323+ optional $ controlSeq "caption" *> setCaption inline
324+ spaces
325+ optional label
326+ spaces
327+ optional lbreak
328+ spaces
329+ skipMany hline
330+ spaces
331+ header' <- option [] . try . fmap (:[]) $
332+ parseTableRow blocks inline envname prefsufs <*
333+ lbreak <* many1 hline
334+ spaces
335+ rows <- sepEndBy (parseTableRow blocks inline envname prefsufs)
336+ (lbreak <* optional (skipMany hline))
337+ spaces
338+ optional $ controlSeq "caption" *> setCaption inline
339+ spaces
340+ optional label
341+ spaces
342+ optional lbreak
343+ spaces
344+ lookAhead $ controlSeq "end" -- make sure we're at end
345+ let th = fixTableHead $ TableHead nullAttr header'
346+ let tbs = [fixTableBody $ TableBody nullAttr 0 [] rows]
347+ let tf = TableFoot nullAttr []
348+ return $ table emptyCaption (zip aligns widths) th tbs tf
349+
350+addTableCaption :: PandocMonad m => Blocks -> LP m Blocks
351+addTableCaption = walkM go
352+ where go (Table attr c spec th tb tf) = do
353+ st <- getState
354+ let mblabel = sLastLabel st
355+ capt <- case (sCaption st, mblabel) of
356+ (Just ils, Nothing) -> return $ caption Nothing (plain ils)
357+ (Just ils, Just lab) -> do
358+ num <- getNextNumber sLastTableNum
359+ setState
360+ st{ sLastTableNum = num
361+ , sLabels = M.insert lab
362+ [Str (renderDottedNum num)]
363+ (sLabels st) }
364+ return $ caption Nothing (plain ils) -- add number??
365+ (Nothing, _) -> return c
366+ let attr' = case (attr, mblabel) of
367+ ((_,classes,kvs), Just ident) ->
368+ (ident,classes,kvs)
369+ _ -> attr
370+ return $ addAttrDiv attr' $ Table nullAttr capt spec th tb tf
371+ go x = return x
372+
373+-- TODO: For now we add a Div to contain table attributes, since
374+-- most writers don't do anything yet with attributes on Table.
375+-- This can be removed when that changes.
376+addAttrDiv :: Attr -> Block -> Block
377+addAttrDiv ("",[],[]) b = b
378+addAttrDiv attr b = Div attr [b]
src/Text/Pandoc/Readers/LaTeX/Types.hs+14−1
@@ -1,3 +1,4 @@
1+{-# LANGUAGE FlexibleInstances #-}
12{- |
23 Module : Text.Pandoc.Readers.LaTeX.Types
34 Copyright : Copyright (C) 2017-2021 John MacFarlane
@@ -18,7 +19,9 @@ module Text.Pandoc.Readers.LaTeX.Types ( Tok(..)
1819 )
1920where
2021import Data.Text (Text)
21−import Text.Parsec.Pos (SourcePos)
22+import Text.Parsec.Pos (SourcePos, sourceName)
23+import Text.Pandoc.Sources
24+import Data.List (groupBy)
2225
2326data TokType = CtrlSeq Text | Spaces | Newline | Symbol | Word | Comment |
2427 Esc1 | Esc2 | Arg Int
@@ -27,6 +30,16 @@ data TokType = CtrlSeq Text | Spaces | Newline | Symbol | Word | Comment |
2730data Tok = Tok SourcePos TokType Text
2831 deriving (Eq, Ord, Show)
2932
33+instance ToSources [Tok] where
34+ toSources = Sources
35+ . map (\ts -> case ts of
36+ Tok p _ _ : _ -> (p, mconcat $ map tokToText ts)
37+ _ -> error "toSources [Tok] encountered empty group")
38+ . groupBy (\(Tok p1 _ _) (Tok p2 _ _) -> sourceName p1 == sourceName p2)
39+
40+tokToText :: Tok -> Text
41+tokToText (Tok _ _ t) = t
42+
3043data ExpansionPoint = ExpandWhenDefined | ExpandWhenUsed
3144 deriving (Eq, Ord, Show)
3245
src/Text/Pandoc/Readers/Man.hs+18−11
@@ -20,7 +20,7 @@ import Control.Monad (liftM, mzero, guard, void)
2020import Control.Monad.Trans (lift)
2121import Control.Monad.Except (throwError)
2222import Data.Maybe (catMaybes, isJust)
23−import Data.List (intersperse, intercalate)
23+import Data.List (intersperse)
2424import qualified Data.Text as T
2525import Text.Pandoc.Builder as B
2626import Text.Pandoc.Class.PandocMonad (PandocMonad(..), report)
@@ -29,9 +29,8 @@ import Text.Pandoc.Logging (LogMessage(..))
2929import Text.Pandoc.Options
3030import Text.Pandoc.Parsing
3131import Text.Pandoc.Walk (query)
32−import Text.Pandoc.Shared (crFilter, mapLeft)
32+import Text.Pandoc.Shared (mapLeft)
3333import Text.Pandoc.Readers.Roff -- TODO explicit imports
34−import Text.Parsec hiding (tokenPrim)
3534import qualified Text.Parsec as Parsec
3635import Text.Parsec.Pos (updatePosString)
3736import qualified Data.Foldable as Foldable
@@ -50,13 +49,20 @@ type ManParser m = ParserT [RoffToken] ManState m
5049
5150
5251-- | Read man (troff) from an input string and return a Pandoc document.
53−readMan :: PandocMonad m => ReaderOptions -> T.Text -> m Pandoc
54−readMan opts txt = do
55− tokenz <- lexRoff (initialPos "input") (crFilter txt)
52+readMan :: (PandocMonad m, ToSources a)
53+ => ReaderOptions
54+ -> a
55+ -> m Pandoc
56+readMan opts s = do
57+ let Sources inps = toSources s
58+ tokenz <- mconcat <$> mapM (uncurry lexRoff) inps
5659 let state = def {readerOptions = opts} :: ManState
60+ let fixError (PandocParsecError _ e) = PandocParsecError (Sources inps) e
61+ fixError e = e
5762 eitherdoc <- readWithMTokens parseMan state
5863 (Foldable.toList . unRoffTokens $ tokenz)
59− either throwError return eitherdoc
64+ either (throwError . fixError) return eitherdoc
65+
6066
6167readWithMTokens :: PandocMonad m
6268 => ParserT [RoffToken] ManState m a -- ^ parser
@@ -64,9 +70,10 @@ readWithMTokens :: PandocMonad m
6470 -> [RoffToken] -- ^ input
6571 -> m (Either PandocError a)
6672readWithMTokens parser state input =
67− let leftF = PandocParsecError . T.pack . intercalate "\n" $ show <$> input
73+ let leftF = PandocParsecError mempty
6874 in mapLeft leftF `liftM` runParserT parser state "source" input
6975
76+
7077parseMan :: PandocMonad m => ManParser m Pandoc
7178parseMan = do
7279 bs <- many parseBlock <* eof
@@ -89,7 +96,7 @@ parseBlock = choice [ parseList
8996
9097parseTable :: PandocMonad m => ManParser m Blocks
9198parseTable = do
92− modifyState $ \st -> st { tableCellsPlain = True }
99+ updateState $ \st -> st { tableCellsPlain = True }
93100 let isTbl Tbl{} = True
94101 isTbl _ = False
95102 Tbl _opts rows pos <- msatisfy isTbl
@@ -135,7 +142,7 @@ parseTable = do
135142 case res' of
136143 Left _ -> Prelude.fail "Could not parse table cell"
137144 Right x -> do
138− modifyState $ \s -> s{ tableCellsPlain = False }
145+ updateState $ \s -> s{ tableCellsPlain = False }
139146 return x
140147 Right x -> return x
141148
@@ -222,7 +229,7 @@ parseTitle = do
222229 setMeta "section" (linePartsToInlines y)
223230 [x] -> setMeta "title" (linePartsToInlines x)
224231 [] -> id
225− modifyState $ \st -> st{ metadata = adjustMeta $ metadata st }
232+ updateState $ \st -> st{ metadata = adjustMeta $ metadata st }
226233 return mempty
227234
228235linePartsToInlines :: [LinePart] -> Inlines
src/Text/Pandoc/Readers/Markdown.hs+284−238
@@ -21,15 +21,17 @@ module Text.Pandoc.Readers.Markdown (
2121import Control.Monad
2222import Control.Monad.Except (throwError)
2323import Data.Char (isAlphaNum, isPunctuation, isSpace)
24−import Data.List (transpose, elemIndex, sortOn)
24+import Data.List (transpose, elemIndex, sortOn, foldl')
25+import Data.List.NonEmpty (NonEmpty(..))
2526import qualified Data.Map as M
2627import Data.Maybe
2728import qualified Data.Set as Set
2829import Data.Text (Text)
2930import qualified Data.Text as T
30−import qualified Data.Text.Lazy as TL
3131import qualified Data.ByteString.Lazy as BL
32−import System.FilePath (addExtension, takeExtension)
32+import System.FilePath (addExtension, takeExtension, takeDirectory)
33+import qualified System.FilePath.Windows as Windows
34+import qualified System.FilePath.Posix as Posix
3335import Text.HTML.TagSoup hiding (Row)
3436import Text.Pandoc.Builder (Blocks, Inlines)
3537import qualified Text.Pandoc.Builder as B
@@ -45,20 +47,22 @@ import Text.Pandoc.Readers.HTML (htmlInBalanced, htmlTag, isBlockTag,
4547 isCommentTag, isInlineTag, isTextTag)
4648import Text.Pandoc.Readers.LaTeX (applyMacros, rawLaTeXBlock, rawLaTeXInline)
4749import Text.Pandoc.Shared
48−import qualified Text.Pandoc.UTF8 as UTF8
4950import Text.Pandoc.XML (fromEntities)
50−import Text.Pandoc.Readers.Metadata (yamlBsToMeta, yamlBsToRefs)
51+import Text.Pandoc.Readers.Metadata (yamlBsToMeta, yamlBsToRefs, yamlMetaBlock)
52+-- import Debug.Trace (traceShowId)
5153
52−type MarkdownParser m = ParserT Text ParserState m
54+type MarkdownParser m = ParserT Sources ParserState m
55+
56+type F = Future ParserState
5357
5458-- | Read markdown from an input string and return a Pandoc document.
55−readMarkdown :: PandocMonad m
59+readMarkdown :: (PandocMonad m, ToSources a)
5660 => ReaderOptions -- ^ Reader options
57− -> Text -- ^ String to parse (assuming @'\n'@ line endings)
61+ -> a -- ^ Input
5862 -> m Pandoc
5963readMarkdown opts s = do
6064 parsed <- readWithM parseMarkdown def{ stateOptions = opts }
61− (crFilter s <> "\n\n")
65+ (ensureFinalNewlines 3 (toSources s))
6266 case parsed of
6367 Right result -> return result
6468 Left e -> throwError e
@@ -79,7 +83,7 @@ yamlToMeta opts mbfp bstr = do
7983 meta <- yamlBsToMeta (fmap B.toMetaValue <$> parseBlocks) bstr
8084 setPosition oldPos
8185 return $ runF meta defaultParserState
82− parsed <- readWithM parser def{ stateOptions = opts } ""
86+ parsed <- readWithM parser def{ stateOptions = opts } ("" :: Text)
8387 case parsed of
8488 Right result -> return result
8589 Left e -> throwError e
@@ -95,14 +99,12 @@ yamlToRefs :: PandocMonad m
9599 -> m [MetaValue]
96100yamlToRefs idpred opts mbfp bstr = do
97101 let parser = do
98− oldPos <- getPosition
99102 case mbfp of
100103 Nothing -> return ()
101104 Just fp -> setPosition $ initialPos fp
102105 refs <- yamlBsToRefs (fmap B.toMetaValue <$> parseBlocks) idpred bstr
103− setPosition oldPos
104106 return $ runF refs defaultParserState
105− parsed <- readWithM parser def{ stateOptions = opts } ""
107+ parsed <- readWithM parser def{ stateOptions = opts } ("" :: Text)
106108 case parsed of
107109 Right result -> return result
108110 Left e -> throwError e
@@ -145,14 +147,14 @@ inList = do
145147 ctx <- stateParserContext <$> getState
146148 guard (ctx == ListItemState)
147149
148−spnl :: PandocMonad m => ParserT Text st m ()
150+spnl :: PandocMonad m => ParserT Sources st m ()
149151spnl = try $ do
150152 skipSpaces
151153 optional newline
152154 skipSpaces
153155 notFollowedBy (char '\n')
154156
155−spnl' :: PandocMonad m => ParserT Text st m Text
157+spnl' :: PandocMonad m => ParserT Sources st m Text
156158spnl' = try $ do
157159 xs <- many spaceChar
158160 ys <- option "" $ try $ (:) <$> newline
@@ -247,51 +249,48 @@ titleBlock :: PandocMonad m => MarkdownParser m ()
247249titleBlock = pandocTitleBlock <|> mmdTitleBlock
248250
249251pandocTitleBlock :: PandocMonad m => MarkdownParser m ()
250−pandocTitleBlock = try $ do
252+pandocTitleBlock = do
251253 guardEnabled Ext_pandoc_title_block
252254 lookAhead (char '%')
253− title <- option mempty titleLine
254− author <- option (return []) authorsLine
255− date <- option mempty dateLine
256− optional blanklines
257− let meta' = do title' <- title
258− author' <- author
259− date' <- date
260− return $
261− (if null title' then id else B.setMeta "title" title')
262− . (if null author' then id else B.setMeta "author" author')
263− . (if null date' then id else B.setMeta "date" date')
264− $ nullMeta
265− updateState $ \st -> st{ stateMeta' = stateMeta' st <> meta' }
266−
267−yamlMetaBlock :: PandocMonad m => MarkdownParser m (F Blocks)
268−yamlMetaBlock = try $ do
255+ try $ do
256+ title <- option mempty titleLine
257+ author <- option (return []) authorsLine
258+ date <- option mempty dateLine
259+ optional blanklines
260+ let meta' = do title' <- title
261+ author' <- author
262+ date' <- date
263+ return $
264+ (if null title'
265+ then id
266+ else B.setMeta "title" title')
267+ . (if null author'
268+ then id
269+ else B.setMeta "author" author')
270+ . (if null date'
271+ then id
272+ else B.setMeta "date" date')
273+ $ nullMeta
274+ updateState $ \st -> st{ stateMeta' = stateMeta' st <> meta' }
275+
276+yamlMetaBlock' :: PandocMonad m => MarkdownParser m (F Blocks)
277+yamlMetaBlock' = do
269278 guardEnabled Ext_yaml_metadata_block
270− string "---"
271− blankline
272− notFollowedBy blankline -- if --- is followed by a blank it's an HRULE
273− rawYamlLines <- manyTill anyLine stopLine
274− -- by including --- and ..., we allow yaml blocks with just comments:
275− let rawYaml = T.unlines ("---" : (rawYamlLines ++ ["..."]))
276− optional blanklines
277− newMetaF <- yamlBsToMeta (fmap B.toMetaValue <$> parseBlocks)
278− $ UTF8.fromTextLazy $ TL.fromStrict rawYaml
279+ newMetaF <- yamlMetaBlock (fmap B.toMetaValue <$> parseBlocks)
279280 -- Since `<>` is left-biased, existing values are not touched:
280281 updateState $ \st -> st{ stateMeta' = stateMeta' st <> newMetaF }
281282 return mempty
282283
283−stopLine :: PandocMonad m => MarkdownParser m ()
284−stopLine = try $ (string "---" <|> string "...") >> blankline >> return ()
285−
286284mmdTitleBlock :: PandocMonad m => MarkdownParser m ()
287−mmdTitleBlock = try $ do
285+mmdTitleBlock = do
288286 guardEnabled Ext_mmd_title_block
289− firstPair <- kvPair False
290− restPairs <- many (kvPair True)
291− let kvPairs = firstPair : restPairs
292− blanklines
293− updateState $ \st -> st{ stateMeta' = stateMeta' st <>
294− return (Meta $ M.fromList kvPairs) }
287+ try $ do
288+ firstPair <- kvPair False
289+ restPairs <- many (kvPair True)
290+ let kvPairs = firstPair : restPairs
291+ blanklines
292+ updateState $ \st -> st{ stateMeta' = stateMeta' st <>
293+ return (Meta $ M.fromList kvPairs) }
295294
296295kvPair :: PandocMonad m => Bool -> MarkdownParser m (Text, MetaValue)
297296kvPair allowEmpty = try $ do
@@ -300,7 +299,7 @@ kvPair allowEmpty = try $ do
300299 (try $ newline >> lookAhead (blankline <|> nonspaceChar))
301300 guard $ allowEmpty || not (T.null val)
302301 let key' = T.concat $ T.words $ T.toLower key
303− let val' = MetaBlocks $ B.toList $ B.plain $ B.text val
302+ let val' = MetaInlines $ B.toList $ B.text val
304303 return (key',val')
305304
306305parseMarkdown :: PandocMonad m => MarkdownParser m Pandoc
@@ -339,7 +338,9 @@ referenceKey = try $ do
339338 notFollowedBy' (() <$ reference)
340339 many1Char $ notFollowedBy space >> litChar
341340 let betweenAngles = try $ char '<' >> manyTillChar litChar (char '>')
342− src <- try betweenAngles <|> sourceURL
341+ rebase <- option False (True <$ guardEnabled Ext_rebase_relative_paths)
342+ src <- (if rebase then rebasePath pos else id) <$>
343+ (try betweenAngles <|> sourceURL)
343344 tit <- option "" referenceTitle
344345 attr <- option nullAttr $ try $
345346 do guardEnabled Ext_link_attributes
@@ -348,7 +349,7 @@ referenceKey = try $ do
348349 addKvs <- option [] $ guardEnabled Ext_mmd_link_attributes
349350 >> many (try $ spnl >> keyValAttr)
350351 blanklines
351− let attr' = extractIdClass $ foldl (\x f -> f x) attr addKvs
352+ let attr' = extractIdClass $ foldl' (\x f -> f x) attr addKvs
352353 target = (escapeURI $ trimr src, tit)
353354 st <- getState
354355 let oldkeys = stateKeys st
@@ -444,7 +445,7 @@ block :: PandocMonad m => MarkdownParser m (F Blocks)
444445block = do
445446 res <- choice [ mempty <$ blanklines
446447 , codeBlockFenced
447− , yamlMetaBlock
448+ , yamlMetaBlock'
448449 -- note: bulletList needs to be before header because of
449450 -- the possibility of empty list items: -
450451 , bulletList
@@ -570,7 +571,7 @@ registerImplicitHeader raw attr@(ident, _, _)
570571-- hrule block
571572--
572573
573−hrule :: PandocMonad m => ParserT Text st m (F Blocks)
574+hrule :: PandocMonad m => ParserT Sources st m (F Blocks)
574575hrule = try $ do
575576 skipSpaces
576577 start <- satisfy isHruleChar
@@ -590,7 +591,7 @@ indentedLine = indentSpaces >> anyLineNewline
590591blockDelimiter :: PandocMonad m
591592 => (Char -> Bool)
592593 -> Maybe Int
593− -> ParserT Text ParserState m Int
594+ -> ParserT Sources ParserState m Int
594595blockDelimiter f len = try $ do
595596 skipNonindentSpaces
596597 c <- lookAhead (satisfy f)
@@ -604,7 +605,7 @@ attributes = try $ do
604605 spnl
605606 attrs <- many (attribute <* spnl)
606607 char '}'
607− return $ foldl (\x f -> f x) nullAttr attrs
608+ return $ foldl' (\x f -> f x) nullAttr attrs
608609
609610attribute :: PandocMonad m => MarkdownParser m (Attr -> Attr)
610611attribute = identifierAttr <|> classAttr <|> keyValAttr <|> specialAttr
@@ -661,15 +662,15 @@ codeBlockFenced :: PandocMonad m => MarkdownParser m (F Blocks)
661662codeBlockFenced = try $ do
662663 indentchars <- nonindentSpaces
663664 let indentLevel = T.length indentchars
664− c <- try (guardEnabled Ext_fenced_code_blocks >> lookAhead (char '~'))
665+ c <- (guardEnabled Ext_fenced_code_blocks >> lookAhead (char '~'))
665666 <|> (guardEnabled Ext_backtick_code_blocks >> lookAhead (char '`'))
666667 size <- blockDelimiter (== c) Nothing
667668 skipMany spaceChar
668669 rawattr <-
669− (Left <$> try (guardEnabled Ext_raw_attribute >> rawAttribute))
670+ (Left <$> (guardEnabled Ext_raw_attribute >> try rawAttribute))
670671 <|>
671672 (Right <$> option ("",[],[])
672− (try (guardEnabled Ext_fenced_code_attributes >> attributes)
673+ ((guardEnabled Ext_fenced_code_attributes >> try attributes)
673674 <|> ((\x -> ("",[toLanguageId x],[])) <$> many1Char nonspaceChar)))
674675 blankline
675676 contents <- T.intercalate "\n" <$>
@@ -734,7 +735,7 @@ lhsCodeBlockBirdWith c = try $ do
734735 blanklines
735736 return $ T.intercalate "\n" lns'
736737
737−birdTrackLine :: PandocMonad m => Char -> ParserT Text st m Text
738+birdTrackLine :: PandocMonad m => Char -> ParserT Sources st m Text
738739birdTrackLine c = try $ do
739740 char c
740741 -- allow html tags on left margin:
@@ -1027,7 +1028,7 @@ para = try $ do
10271028 option (B.plain <$> result)
10281029 $ try $ do
10291030 newline
1030− (blanklines >> return mempty)
1031+ (mempty <$ blanklines)
10311032 <|> (guardDisabled Ext_blank_before_blockquote >> () <$ lookAhead blockQuote)
10321033 <|> (guardEnabled Ext_backtick_code_blocks >> () <$ lookAhead codeBlockFenced)
10331034 <|> (guardDisabled Ext_blank_before_header >> () <$ lookAhead header)
@@ -1157,11 +1158,12 @@ stripMarkdownAttribute s = renderTags' $ map filterAttrib $ parseTags s
11571158--
11581159
11591160lineBlock :: PandocMonad m => MarkdownParser m (F Blocks)
1160−lineBlock = try $ do
1161+lineBlock = do
11611162 guardEnabled Ext_line_blocks
1162− lines' <- lineBlockLines >>=
1163− mapM (parseFromString' (trimInlinesF <$> inlines))
1164− return $ B.lineBlock <$> sequence lines'
1163+ try $ do
1164+ lines' <- lineBlockLines >>=
1165+ mapM (parseFromString' (trimInlinesF <$> inlines))
1166+ return $ B.lineBlock <$> sequence lines'
11651167
11661168--
11671169-- Tables
@@ -1171,7 +1173,7 @@ lineBlock = try $ do
11711173-- and the length including trailing space.
11721174dashedLine :: PandocMonad m
11731175 => Char
1174− -> ParserT Text st m (Int, Int)
1176+ -> ParserT Sources st m (Int, Int)
11751177dashedLine ch = do
11761178 dashes <- many1 (char ch)
11771179 sp <- many spaceChar
@@ -1240,7 +1242,7 @@ rawTableLine :: PandocMonad m
12401242 -> MarkdownParser m [Text]
12411243rawTableLine indices = do
12421244 notFollowedBy' (blanklines' <|> tableFooter)
1243− line <- take1WhileP (/='\n') <* newline
1245+ line <- anyLine
12441246 return $ map trim $ tail $
12451247 splitTextByIndices (init indices) line
12461248
@@ -1263,11 +1265,12 @@ multilineRow indices = do
12631265-- Parses a table caption: inlines beginning with 'Table:'
12641266-- and followed by blank lines.
12651267tableCaption :: PandocMonad m => MarkdownParser m (F Inlines)
1266−tableCaption = try $ do
1268+tableCaption = do
12671269 guardEnabled Ext_table_captions
1268− skipNonindentSpaces
1269− (string ":" <* notFollowedBy (satisfy isPunctuation)) <|> string "Table:"
1270− trimInlinesF <$> inlines1 <* blanklines
1270+ try $ do
1271+ skipNonindentSpaces
1272+ (string ":" <* notFollowedBy (satisfy isPunctuation)) <|> string "Table:"
1273+ trimInlinesF <$> inlines1 <* blanklines
12711274
12721275-- Parse a simple table with '---' header and one line per row.
12731276simpleTable :: PandocMonad m
@@ -1353,7 +1356,7 @@ pipeTable = try $ do
13531356 lines' <- many pipeTableRow
13541357 let lines'' = map (take (length aligns) <$>) lines'
13551358 let maxlength = maximum $
1356− map (\x -> T.length . stringify $ runF x def) (heads' : lines'')
1359+ fmap (\x -> T.length . stringify $ runF x def) (heads' :| lines'')
13571360 numColumns <- getOption readerColumns
13581361 let widths = if maxlength > numColumns
13591362 then map (\len ->
@@ -1390,7 +1393,7 @@ pipeTableCell =
13901393 return $ B.plain <$> result)
13911394 <|> return mempty
13921395
1393−pipeTableHeaderPart :: PandocMonad m => ParserT Text st m (Alignment, Int)
1396+pipeTableHeaderPart :: PandocMonad m => ParserT Sources st m (Alignment, Int)
13941397pipeTableHeaderPart = try $ do
13951398 skipMany spaceChar
13961399 left <- optionMaybe (char ':')
@@ -1406,10 +1409,14 @@ pipeTableHeaderPart = try $ do
14061409 (Just _,Just _) -> AlignCenter, len)
14071410
14081411-- Succeed only if current line contains a pipe.
1409−scanForPipe :: PandocMonad m => ParserT Text st m ()
1412+scanForPipe :: PandocMonad m => ParserT Sources st m ()
14101413scanForPipe = do
1411− inp <- getInput
1412− case T.break (\c -> c == '\n' || c == '|') inp of
1414+ Sources inps <- getInput
1415+ let ln = case inps of
1416+ [] -> ""
1417+ ((_,t):(_,t'):_) | T.null t -> t'
1418+ ((_,t):_) -> t
1419+ case T.break (\c -> c == '\n' || c == '|') ln of
14131420 (_, T.uncons -> Just ('|', _)) -> return ()
14141421 _ -> mzero
14151422
@@ -1436,15 +1443,14 @@ table :: PandocMonad m => MarkdownParser m (F Blocks)
14361443table = try $ do
14371444 frontCaption <- option Nothing (Just <$> tableCaption)
14381445 (aligns, widths, heads, lns) <-
1439− try (guardEnabled Ext_pipe_tables >> scanForPipe >> pipeTable) <|>
1440− try (guardEnabled Ext_multiline_tables >>
1441− multilineTable False) <|>
1442− try (guardEnabled Ext_simple_tables >>
1443− (simpleTable True <|> simpleTable False)) <|>
1444− try (guardEnabled Ext_multiline_tables >>
1445− multilineTable True) <|>
1446− try (guardEnabled Ext_grid_tables >>
1447− (gridTable False <|> gridTable True)) <?> "table"
1446+ (guardEnabled Ext_pipe_tables >> try (scanForPipe >> pipeTable)) <|>
1447+ (guardEnabled Ext_multiline_tables >> try (multilineTable False)) <|>
1448+ (guardEnabled Ext_simple_tables >>
1449+ try (simpleTable True <|> simpleTable False)) <|>
1450+ (guardEnabled Ext_multiline_tables >>
1451+ try (multilineTable True)) <|>
1452+ (guardEnabled Ext_grid_tables >>
1453+ try (gridTable False <|> gridTable True)) <?> "table"
14481454 optional blanklines
14491455 caption <- case frontCaption of
14501456 Nothing -> option (return mempty) tableCaption
@@ -1478,35 +1484,37 @@ inlines1 :: PandocMonad m => MarkdownParser m (F Inlines)
14781484inlines1 = mconcat <$> many1 inline
14791485
14801486inline :: PandocMonad m => MarkdownParser m (F Inlines)
1481−inline = choice [ whitespace
1482− , bareURL
1483− , str
1484− , endline
1485− , code
1486− , strongOrEmph
1487− , note
1488− , cite
1489− , bracketedSpan
1490− , link
1491− , image
1492− , math
1493− , strikeout
1494− , subscript
1495− , superscript
1496− , inlineNote -- after superscript because of ^[link](/foo)^
1497− , autoLink
1498− , spanHtml
1499− , rawHtmlInline
1500− , escapedNewline
1501− , escapedChar
1502− , rawLaTeXInline'
1503− , exampleRef
1504− , smart
1505− , return . B.singleton <$> charRef
1506− , emoji
1507− , symbol
1508− , ltSign
1509− ] <?> "inline"
1487+inline = do
1488+ c <- lookAhead anyChar
1489+ ((case c of
1490+ ' ' -> whitespace
1491+ '\t' -> whitespace
1492+ '\n' -> endline
1493+ '`' -> code
1494+ '_' -> strongOrEmph
1495+ '*' -> strongOrEmph
1496+ '^' -> superscript <|> inlineNote -- in this order bc ^[link](/foo)^
1497+ '[' -> note <|> cite <|> bracketedSpan <|> link
1498+ '!' -> image
1499+ '$' -> math
1500+ '~' -> strikeout <|> subscript
1501+ '<' -> autoLink <|> spanHtml <|> rawHtmlInline <|> ltSign
1502+ '\\' -> math <|> escapedNewline <|> escapedChar <|> rawLaTeXInline'
1503+ '@' -> cite <|> exampleRef
1504+ '"' -> smart
1505+ '\'' -> smart
1506+ '\8216' -> smart
1507+ '\145' -> smart
1508+ '\8220' -> smart
1509+ '\147' -> smart
1510+ '-' -> smart
1511+ '.' -> smart
1512+ '&' -> return . B.singleton <$> charRef
1513+ ':' -> emoji
1514+ _ -> mzero)
1515+ <|> bareURL
1516+ <|> str
1517+ <|> symbol) <?> "inline"
15101518
15111519escapedChar' :: PandocMonad m => MarkdownParser m Char
15121520escapedChar' = try $ do
@@ -1517,11 +1525,12 @@ escapedChar' = try $ do
15171525 <|> oneOf "\\`*_{}[]()>#+-.!~\""
15181526
15191527escapedNewline :: PandocMonad m => MarkdownParser m (F Inlines)
1520−escapedNewline = try $ do
1528+escapedNewline = do
15211529 guardEnabled Ext_escaped_line_breaks
1522− char '\\'
1523− lookAhead (char '\n') -- don't consume the newline (see #3730)
1524− return $ return B.linebreak
1530+ try $ do
1531+ char '\\'
1532+ lookAhead (char '\n') -- don't consume the newline (see #3730)
1533+ return $ return B.linebreak
15251534
15261535escapedChar :: PandocMonad m => MarkdownParser m (F Inlines)
15271536escapedChar = do
@@ -1543,19 +1552,20 @@ ltSign = do
15431552-- whole document has been parsed. But we need this parser
15441553-- here in case citations is disabled.
15451554exampleRef :: PandocMonad m => MarkdownParser m (F Inlines)
1546−exampleRef = try $ do
1555+exampleRef = do
15471556 guardEnabled Ext_example_lists
1548− char '@'
1549− lab <- mconcat . map T.pack <$>
1550− many (many1 alphaNum <|>
1551− try (do c <- char '_' <|> char '-'
1552− cs <- many1 alphaNum
1553− return (c:cs)))
1554− return $ do
1555− st <- askF
1556− return $ case M.lookup lab (stateExamples st) of
1557− Just n -> B.str $ tshow n
1558− Nothing -> B.str $ "@" <> lab
1557+ try $ do
1558+ char '@'
1559+ lab <- mconcat . map T.pack <$>
1560+ many (many1 alphaNum <|>
1561+ try (do c <- char '_' <|> char '-'
1562+ cs <- many1 alphaNum
1563+ return (c:cs)))
1564+ return $ do
1565+ st <- askF
1566+ return $ case M.lookup lab (stateExamples st) of
1567+ Just n -> B.str $ tshow n
1568+ Nothing -> B.str $ "@" <> lab
15591569
15601570symbol :: PandocMonad m => MarkdownParser m (F Inlines)
15611571symbol = do
@@ -1582,10 +1592,10 @@ code = try $ do
15821592 >> count (length starts) (char '`')
15831593 >> notFollowedBy (char '`'))
15841594 rawattr <-
1585− (Left <$> try (guardEnabled Ext_raw_attribute >> rawAttribute))
1595+ (Left <$> (guardEnabled Ext_raw_attribute >> try rawAttribute))
15861596 <|>
15871597 (Right <$> option ("",[],[])
1588− (try (guardEnabled Ext_inline_code_attributes >> attributes)))
1598+ (guardEnabled Ext_inline_code_attributes >> try attributes))
15891599 return $ return $
15901600 case rawattr of
15911601 Left syn -> B.rawInline syn result
@@ -1678,38 +1688,40 @@ strikeout = fmap B.strikeout <$>
16781688 strikeEnd = try $ string "~~"
16791689
16801690superscript :: PandocMonad m => MarkdownParser m (F Inlines)
1681−superscript = fmap B.superscript <$> try (do
1691+superscript = do
16821692 guardEnabled Ext_superscript
1683− char '^'
1684− mconcat <$> many1Till (do notFollowedBy spaceChar
1685− notFollowedBy newline
1686− inline) (char '^'))
1693+ fmap B.superscript <$> try (do
1694+ char '^'
1695+ mconcat <$> many1Till (do notFollowedBy spaceChar
1696+ notFollowedBy newline
1697+ inline) (char '^'))
16871698
16881699subscript :: PandocMonad m => MarkdownParser m (F Inlines)
1689−subscript = fmap B.subscript <$> try (do
1700+subscript = do
16901701 guardEnabled Ext_subscript
1691− char '~'
1692− mconcat <$> many1Till (do notFollowedBy spaceChar
1693− notFollowedBy newline
1694− inline) (char '~'))
1702+ fmap B.subscript <$> try (do
1703+ char '~'
1704+ mconcat <$> many1Till (do notFollowedBy spaceChar
1705+ notFollowedBy newline
1706+ inline) (char '~'))
16951707
16961708whitespace :: PandocMonad m => MarkdownParser m (F Inlines)
16971709whitespace = spaceChar >> return <$> (lb <|> regsp) <?> "whitespace"
16981710 where lb = spaceChar >> skipMany spaceChar >> option B.space (endline >> return B.linebreak)
16991711 regsp = skipMany spaceChar >> return B.space
17001712
1701−nonEndline :: PandocMonad m => ParserT Text st m Char
1713+nonEndline :: PandocMonad m => ParserT Sources st m Char
17021714nonEndline = satisfy (/='\n')
17031715
17041716str :: PandocMonad m => MarkdownParser m (F Inlines)
17051717str = do
17061718 result <- mconcat <$> many1
1707− ( take1WhileP isAlphaNum
1719+ ( T.pack <$> (many1 alphaNum)
17081720 <|> "." <$ try (char '.' <* notFollowedBy (char '.')) )
17091721 updateLastStrPos
17101722 (do guardEnabled Ext_smart
17111723 abbrevs <- getOption readerAbbreviations
1712− if not (T.null result) && T.last result == '.' && result `Set.member` abbrevs
1724+ if result `Set.member` abbrevs
17131725 then try (do ils <- whitespace
17141726 notFollowedBy (() <$ cite <|> () <$ note)
17151727 -- ?? lookAhead alphaNum
@@ -1792,15 +1804,16 @@ link = try $ do
17921804 regLink B.linkWith lab <|> referenceLink B.linkWith (lab,raw)
17931805
17941806bracketedSpan :: PandocMonad m => MarkdownParser m (F Inlines)
1795−bracketedSpan = try $ do
1807+bracketedSpan = do
17961808 guardEnabled Ext_bracketed_spans
1797− (lab,_) <- reference
1798− attr <- attributes
1799− return $ if isSmallCaps attr
1800− then B.smallcaps <$> lab
1801− else if isUnderline attr
1802− then B.underline <$> lab
1803− else B.spanWith attr <$> lab
1809+ try $ do
1810+ (lab,_) <- reference
1811+ attr <- attributes
1812+ return $ if isSmallCaps attr
1813+ then B.smallcaps <$> lab
1814+ else if isUnderline attr
1815+ then B.underline <$> lab
1816+ else B.spanWith attr <$> lab
18041817
18051818-- | We treat a span as SmallCaps if class is "smallcaps" (and
18061819-- no other attributes are set or if style is "font-variant:small-caps"
@@ -1827,9 +1840,12 @@ regLink :: PandocMonad m
18271840 -> MarkdownParser m (F Inlines)
18281841regLink constructor lab = try $ do
18291842 (src, tit) <- source
1843+ rebase <- option False (True <$ guardEnabled Ext_rebase_relative_paths)
1844+ pos <- getPosition
1845+ let src' = if rebase then rebasePath pos src else src
18301846 attr <- option nullAttr $
18311847 guardEnabled Ext_link_attributes >> attributes
1832− return $ constructor attr src tit <$> lab
1848+ return $ constructor attr src' tit <$> lab
18331849
18341850-- a link like [this][ref] or [this][] or [this]
18351851referenceLink :: PandocMonad m
@@ -1869,7 +1885,8 @@ referenceLink constructor (lab, raw) = do
18691885 Just ((src, tit), _) -> constructor nullAttr src tit <$> lab
18701886 Nothing -> makeFallback
18711887 else makeFallback
1872− Just ((src,tit), attr) -> constructor attr src tit <$> lab
1888+ Just ((src,tit), attr) ->
1889+ constructor attr src tit <$> lab
18731890
18741891dropBrackets :: Text -> Text
18751892dropBrackets = dropRB . dropLB
@@ -1879,12 +1896,13 @@ dropBrackets = dropRB . dropLB
18791896 dropLB xs = xs
18801897
18811898bareURL :: PandocMonad m => MarkdownParser m (F Inlines)
1882−bareURL = try $ do
1899+bareURL = do
18831900 guardEnabled Ext_autolink_bare_uris
18841901 getState >>= guard . stateAllowLinks
1885− (cls, (orig, src)) <- (("uri",) <$> uri) <|> (("email",) <$> emailAddress)
1886− notFollowedBy $ try $ spaces >> htmlTag (~== TagClose ("a" :: Text))
1887− return $ return $ B.linkWith ("",[cls],[]) src "" (B.str orig)
1902+ try $ do
1903+ (cls, (orig, src)) <- (("uri",) <$> uri) <|> (("email",) <$> emailAddress)
1904+ notFollowedBy $ try $ spaces >> htmlTag (~== TagClose ("a" :: Text))
1905+ return $ return $ B.linkWith ("",[cls],[]) src "" (B.str orig)
18881906
18891907autoLink :: PandocMonad m => MarkdownParser m (F Inlines)
18901908autoLink = try $ do
@@ -1901,15 +1919,33 @@ autoLink = try $ do
19011919 return $ return $ B.linkWith attr (src <> escapeURI extra) ""
19021920 (B.str $ orig <> extra)
19031921
1922+-- | Rebase a relative path, by adding the (relative) directory
1923+-- of the containing source position. Absolute links and URLs
1924+-- are untouched.
1925+rebasePath :: SourcePos -> Text -> Text
1926+rebasePath pos path = do
1927+ let fp = sourceName pos
1928+ isFragment = T.take 1 path == "#"
1929+ path' = T.unpack path
1930+ isAbsolutePath = Posix.isAbsolute path' || Windows.isAbsolute path'
1931+ in if T.null path || isFragment || isAbsolutePath || isURI path
1932+ then path
1933+ else
1934+ case takeDirectory fp of
1935+ "" -> path
1936+ "." -> path
1937+ d -> T.pack d <> "/" <> path
1938+
19041939image :: PandocMonad m => MarkdownParser m (F Inlines)
19051940image = try $ do
19061941 char '!'
19071942 (lab,raw) <- reference
19081943 defaultExt <- getOption readerDefaultImageExtension
1909− let constructor attr' src = case takeExtension (T.unpack src) of
1910− "" -> B.imageWith attr' (T.pack $ addExtension (T.unpack src)
1911− $ T.unpack defaultExt)
1912− _ -> B.imageWith attr' src
1944+ let constructor attr' src =
1945+ case takeExtension (T.unpack src) of
1946+ "" -> B.imageWith attr' (T.pack $ addExtension (T.unpack src)
1947+ $ T.unpack defaultExt)
1948+ _ -> B.imageWith attr' src
19131949 regLink constructor lab <|> referenceLink constructor (lab,raw)
19141950
19151951note :: PandocMonad m => MarkdownParser m (F Inlines)
@@ -1937,23 +1973,25 @@ note = try $ do
19371973 return $ B.note $ walk adjustCite contents'
19381974
19391975inlineNote :: PandocMonad m => MarkdownParser m (F Inlines)
1940−inlineNote = try $ do
1976+inlineNote = do
19411977 guardEnabled Ext_inline_notes
1942− char '^'
1943− updateState $ \st -> st{ stateInNote = True
1944− , stateNoteNumber = stateNoteNumber st + 1 }
1945− contents <- inlinesInBalancedBrackets
1946− updateState $ \st -> st{ stateInNote = False }
1947− return $ B.note . B.para <$> contents
1978+ try $ do
1979+ char '^'
1980+ updateState $ \st -> st{ stateInNote = True
1981+ , stateNoteNumber = stateNoteNumber st + 1 }
1982+ contents <- inlinesInBalancedBrackets
1983+ updateState $ \st -> st{ stateInNote = False }
1984+ return $ B.note . B.para <$> contents
19481985
19491986rawLaTeXInline' :: PandocMonad m => MarkdownParser m (F Inlines)
1950−rawLaTeXInline' = try $ do
1987+rawLaTeXInline' = do
19511988 guardEnabled Ext_raw_tex
19521989 notFollowedBy' rawConTeXtEnvironment
1953− s <- rawLaTeXInline
1954− return $ return $ B.rawInline "tex" s -- "tex" because it might be context
1990+ try $ do
1991+ s <- rawLaTeXInline
1992+ return $ return $ B.rawInline "tex" s -- "tex" because it might be context
19551993
1956−rawConTeXtEnvironment :: PandocMonad m => ParserT Text st m Text
1994+rawConTeXtEnvironment :: PandocMonad m => ParserT Sources st m Text
19571995rawConTeXtEnvironment = try $ do
19581996 string "\\start"
19591997 completion <- inBrackets (letter <|> digit <|> spaceChar)
@@ -1962,7 +2000,7 @@ rawConTeXtEnvironment = try $ do
19622000 (try $ string "\\stop" >> textStr completion)
19632001 return $ "\\start" <> completion <> T.concat contents <> "\\stop" <> completion
19642002
1965−inBrackets :: PandocMonad m => ParserT Text st m Char -> ParserT Text st m Text
2003+inBrackets :: PandocMonad m => ParserT Sources st m Char -> ParserT Sources st m Text
19662004inBrackets parser = do
19672005 char '['
19682006 contents <- manyChar parser
@@ -1970,55 +2008,60 @@ inBrackets parser = do
19702008 return $ "[" <> contents <> "]"
19712009
19722010spanHtml :: PandocMonad m => MarkdownParser m (F Inlines)
1973−spanHtml = try $ do
2011+spanHtml = do
19742012 guardEnabled Ext_native_spans
1975− (TagOpen _ attrs, _) <- htmlTag (~== TagOpen ("span" :: Text) [])
1976− contents <- mconcat <$> manyTill inline (htmlTag (~== TagClose ("span" :: Text)))
1977− let ident = fromMaybe "" $ lookup "id" attrs
1978− let classes = maybe [] T.words $ lookup "class" attrs
1979− let keyvals = [(k,v) | (k,v) <- attrs, k /= "id" && k /= "class"]
1980− return $ if isSmallCaps (ident, classes, keyvals)
1981− then B.smallcaps <$> contents
1982− else if isUnderline (ident, classes, keyvals)
1983− then B.underline <$> contents
1984− else B.spanWith (ident, classes, keyvals) <$> contents
2013+ try $ do
2014+ (TagOpen _ attrs, _) <- htmlTag (~== TagOpen ("span" :: Text) [])
2015+ contents <- mconcat <$> manyTill inline (htmlTag (~== TagClose ("span" :: Text)))
2016+ let ident = fromMaybe "" $ lookup "id" attrs
2017+ let classes = maybe [] T.words $ lookup "class" attrs
2018+ let keyvals = [(k,v) | (k,v) <- attrs, k /= "id" && k /= "class"]
2019+ return $ if isSmallCaps (ident, classes, keyvals)
2020+ then B.smallcaps <$> contents
2021+ else if isUnderline (ident, classes, keyvals)
2022+ then B.underline <$> contents
2023+ else B.spanWith (ident, classes, keyvals) <$> contents
19852024
19862025divHtml :: PandocMonad m => MarkdownParser m (F Blocks)
1987−divHtml = try $ do
2026+divHtml = do
19882027 guardEnabled Ext_native_divs
1989− (TagOpen _ attrs, rawtag) <- htmlTag (~== TagOpen ("div" :: Text) [])
1990− -- we set stateInHtmlBlock so that closing tags that can be either block or
1991− -- inline will not be parsed as inline tags
1992− oldInHtmlBlock <- stateInHtmlBlock <$> getState
1993− updateState $ \st -> st{ stateInHtmlBlock = Just "div" }
1994− bls <- option "" (blankline >> option "" blanklines)
1995− contents <- mconcat <$>
1996− many (notFollowedBy' (htmlTag (~== TagClose ("div" :: Text))) >> block)
1997− closed <- option False (True <$ htmlTag (~== TagClose ("div" :: Text)))
1998− if closed
1999− then do
2000− updateState $ \st -> st{ stateInHtmlBlock = oldInHtmlBlock }
2001− let ident = fromMaybe "" $ lookup "id" attrs
2002− let classes = maybe [] T.words $ lookup "class" attrs
2003− let keyvals = [(k,v) | (k,v) <- attrs, k /= "id" && k /= "class"]
2004− return $ B.divWith (ident, classes, keyvals) <$> contents
2005− else -- avoid backtracing
2006− return $ return (B.rawBlock "html" (rawtag <> bls)) <> contents
2028+ try $ do
2029+ (TagOpen _ attrs, rawtag) <- htmlTag (~== TagOpen ("div" :: Text) [])
2030+ -- we set stateInHtmlBlock so that closing tags that can be either block
2031+ -- or inline will not be parsed as inline tags
2032+ oldInHtmlBlock <- stateInHtmlBlock <$> getState
2033+ updateState $ \st -> st{ stateInHtmlBlock = Just "div" }
2034+ bls <- option "" (blankline >> option "" blanklines)
2035+ contents <- mconcat <$>
2036+ many (notFollowedBy' (htmlTag (~== TagClose ("div" :: Text))) >> block)
2037+ closed <- option False (True <$ htmlTag (~== TagClose ("div" :: Text)))
2038+ if closed
2039+ then do
2040+ updateState $ \st -> st{ stateInHtmlBlock = oldInHtmlBlock }
2041+ let ident = fromMaybe "" $ lookup "id" attrs
2042+ let classes = maybe [] T.words $ lookup "class" attrs
2043+ let keyvals = [(k,v) | (k,v) <- attrs, k /= "id" && k /= "class"]
2044+ return $ B.divWith (ident, classes, keyvals) <$> contents
2045+ else -- avoid backtracing
2046+ return $ return (B.rawBlock "html" (rawtag <> bls)) <> contents
20072047
20082048divFenced :: PandocMonad m => MarkdownParser m (F Blocks)
2009−divFenced = try $ do
2049+divFenced = do
20102050 guardEnabled Ext_fenced_divs
2011− string ":::"
2012− skipMany (char ':')
2013− skipMany spaceChar
2014− attribs <- attributes <|> ((\x -> ("",[x],[])) <$> many1Char nonspaceChar)
2015− skipMany spaceChar
2016− skipMany (char ':')
2017− blankline
2018− updateState $ \st -> st{ stateFencedDivLevel = stateFencedDivLevel st + 1 }
2019− bs <- mconcat <$> manyTill block divFenceEnd
2020− updateState $ \st -> st{ stateFencedDivLevel = stateFencedDivLevel st - 1 }
2021− return $ B.divWith attribs <$> bs
2051+ try $ do
2052+ string ":::"
2053+ skipMany (char ':')
2054+ skipMany spaceChar
2055+ attribs <- attributes <|> ((\x -> ("",[x],[])) <$> many1Char nonspaceChar)
2056+ skipMany spaceChar
2057+ skipMany (char ':')
2058+ blankline
2059+ updateState $ \st ->
2060+ st{ stateFencedDivLevel = stateFencedDivLevel st + 1 }
2061+ bs <- mconcat <$> manyTill block divFenceEnd
2062+ updateState $ \st ->
2063+ st{ stateFencedDivLevel = stateFencedDivLevel st - 1 }
2064+ return $ B.divWith attribs <$> bs
20222065
20232066divFenceEnd :: PandocMonad m => MarkdownParser m ()
20242067divFenceEnd = try $ do
@@ -2050,14 +2093,15 @@ emojiChars :: [Char]
20502093emojiChars = ['a'..'z'] ++ ['0'..'9'] ++ ['_','+','-']
20512094
20522095emoji :: PandocMonad m => MarkdownParser m (F Inlines)
2053−emoji = try $ do
2096+emoji = do
20542097 guardEnabled Ext_emoji
2055− char ':'
2056− emojikey <- many1Char (oneOf emojiChars)
2057− char ':'
2058− case emojiToInline emojikey of
2059− Just i -> return (return $ B.singleton i)
2060− Nothing -> mzero
2098+ try $ do
2099+ char ':'
2100+ emojikey <- many1Char (oneOf emojiChars)
2101+ char ':'
2102+ case emojiToInline emojikey of
2103+ Just i -> return (return $ B.singleton i)
2104+ Nothing -> mzero
20612105
20622106-- Citations
20632107
@@ -2076,7 +2120,7 @@ cite = do
20762120
20772121textualCite :: PandocMonad m => MarkdownParser m (F Inlines)
20782122textualCite = try $ do
2079− (suppressAuthor, key) <- citeKey
2123+ (suppressAuthor, key) <- citeKey True
20802124 -- If this is a reference to an earlier example list item,
20812125 -- then don't parse it as a citation. If the example list
20822126 -- item comes later, we'll parse it here and figure out in
@@ -2156,7 +2200,7 @@ prefix = trimInlinesF . mconcat <$>
21562200 manyTill inline (char ']'
21572201 <|> lookAhead
21582202 (try $ do optional (try (char ';' >> spnl))
2159− citeKey
2203+ citeKey True
21602204 return ']'))
21612205
21622206citeList :: PandocMonad m => MarkdownParser m (F [Citation])
@@ -2165,7 +2209,7 @@ citeList = fmap sequence $ sepBy1 citation (try $ char ';' >> spnl)
21652209citation :: PandocMonad m => MarkdownParser m (F Citation)
21662210citation = try $ do
21672211 pref <- prefix
2168− (suppress_author, key) <- citeKey
2212+ (suppress_author, key) <- citeKey True
21692213 suff <- suffix
21702214 noteNum <- stateNoteNumber <$> getState
21712215 return $ do
@@ -2184,28 +2228,30 @@ citation = try $ do
21842228smart :: PandocMonad m => MarkdownParser m (F Inlines)
21852229smart = do
21862230 guardEnabled Ext_smart
2187− doubleQuoted <|> singleQuoted <|>
2188− choice (map (return <$>) [apostrophe, dash, ellipses])
2231+ doubleQuoted <|> singleQuoted <|> (return <$> doubleCloseQuote) <|>
2232+ (return <$> apostrophe) <|> (return <$> dash) <|> (return <$> ellipses)
21892233
21902234singleQuoted :: PandocMonad m => MarkdownParser m (F Inlines)
2191−singleQuoted = try $ do
2235+singleQuoted = do
21922236 singleQuoteStart
2193− withQuoteContext InSingleQuote $
2237+ (try (withQuoteContext InSingleQuote $
21942238 fmap B.singleQuoted . trimInlinesF . mconcat <$>
2195− many1Till inline singleQuoteEnd
2239+ many1Till inline singleQuoteEnd))
2240+ <|> (return (return (B.str "\8217")))
21962241
21972242-- doubleQuoted will handle regular double-quoted sections, as well
21982243-- as dialogues with an open double-quote without a close double-quote
21992244-- in the same paragraph.
22002245doubleQuoted :: PandocMonad m => MarkdownParser m (F Inlines)
2201−doubleQuoted = try $ do
2246+doubleQuoted = do
22022247 doubleQuoteStart
2203− withQuoteContext InDoubleQuote $
2248+ (try (withQuoteContext InDoubleQuote $
22042249 fmap B.doubleQuoted . trimInlinesF . mconcat <$>
2205− many1Till inline doubleQuoteEnd
2250+ many1Till inline doubleQuoteEnd))
2251+ <|> (return (return (B.str "\8220")))
22062252
22072253toRow :: [Blocks] -> Row
22082254toRow = Row nullAttr . map B.simpleCell
22092255
22102256toHeaderRow :: [Blocks] -> [Row]
2211−toHeaderRow l = [toRow l | not (null l)]
2257+toHeaderRow l = [toRow l | not (null l) && not (all null l)]
src/Text/Pandoc/Readers/MediaWiki.hs+16−7
@@ -36,17 +36,18 @@ import Text.Pandoc.Logging
3636import Text.Pandoc.Options
3737import Text.Pandoc.Parsing hiding (nested)
3838import Text.Pandoc.Readers.HTML (htmlTag, isBlockTag, isCommentTag)
39−import Text.Pandoc.Shared (crFilter, safeRead, stringify, stripTrailingNewlines,
39+import Text.Pandoc.Shared (safeRead, stringify, stripTrailingNewlines,
4040 trim, splitTextBy, tshow)
4141import Text.Pandoc.Walk (walk)
4242import Text.Pandoc.XML (fromEntities)
4343
4444-- | Read mediawiki from an input string and return a Pandoc document.
45−readMediaWiki :: PandocMonad m
46− => ReaderOptions -- ^ Reader options
47− -> Text -- ^ String to parse (assuming @'\n'@ line endings)
45+readMediaWiki :: (PandocMonad m, ToSources a)
46+ => ReaderOptions
47+ -> a
4848 -> m Pandoc
4949readMediaWiki opts s = do
50+ let sources = toSources s
5051 parsed <- readWithM parseMediaWiki MWState{ mwOptions = opts
5152 , mwMaxNestingLevel = 4
5253 , mwNextLinkNumber = 1
@@ -55,7 +56,7 @@ readMediaWiki opts s = do
5556 , mwLogMessages = []
5657 , mwInTT = False
5758 }
58− (crFilter s <> "\n")
59+ sources
5960 case parsed of
6061 Right result -> return result
6162 Left e -> throwError e
@@ -69,7 +70,7 @@ data MWState = MWState { mwOptions :: ReaderOptions
6970 , mwInTT :: Bool
7071 }
7172
72−type MWParser m = ParserT Text MWState m
73+type MWParser m = ParserT Sources MWState m
7374
7475instance HasReaderOptions MWState where
7576 extractReaderOptions = mwOptions
@@ -112,12 +113,14 @@ newBlockTags = ["haskell","syntaxhighlight","source","gallery","references"]
112113isBlockTag' :: Tag Text -> Bool
113114isBlockTag' tag@(TagOpen t _) = (isBlockTag tag || t `elem` newBlockTags) &&
114115 t `notElem` eitherBlockOrInline
116+isBlockTag' (TagClose "ref") = True -- needed so 'special' doesn't parse it
115117isBlockTag' tag@(TagClose t) = (isBlockTag tag || t `elem` newBlockTags) &&
116118 t `notElem` eitherBlockOrInline
117119isBlockTag' tag = isBlockTag tag
118120
119121isInlineTag' :: Tag Text -> Bool
120122isInlineTag' (TagComment _) = True
123+isInlineTag' (TagClose "ref") = False -- see below inlineTag
121124isInlineTag' t = not (isBlockTag' t)
122125
123126eitherBlockOrInline :: [Text]
@@ -554,11 +557,17 @@ variable = try $ do
554557 contents <- manyTillChar anyChar (try $ string "}}}")
555558 return $ "{{{" <> contents <> "}}}"
556559
560+singleParaToPlain :: Blocks -> Blocks
561+singleParaToPlain bs =
562+ case B.toList bs of
563+ [Para ils] -> B.fromList [Plain ils]
564+ _ -> bs
565+
557566inlineTag :: PandocMonad m => MWParser m Inlines
558567inlineTag = do
559568 (tag, _) <- lookAhead $ htmlTag isInlineTag'
560569 case tag of
561− TagOpen "ref" _ -> B.note . B.plain <$> inlinesInTags "ref"
570+ TagOpen "ref" _ -> B.note . singleParaToPlain <$> blocksInTags "ref"
562571 TagOpen "nowiki" _ -> try $ do
563572 (_,raw) <- htmlTag (~== tag)
564573 if T.any (== '/') raw
src/Text/Pandoc/Readers/Metadata.hs+44−17
@@ -14,6 +14,7 @@ Parse YAML/JSON metadata to 'Pandoc' 'Meta'.
1414module Text.Pandoc.Readers.Metadata (
1515 yamlBsToMeta,
1616 yamlBsToRefs,
17+ yamlMetaBlock,
1718 yamlMap ) where
1819
1920import Control.Monad
@@ -30,11 +31,13 @@ import Text.Pandoc.Definition
3031import Text.Pandoc.Error
3132import Text.Pandoc.Parsing hiding (tableWith)
3233import Text.Pandoc.Shared
34+import qualified Data.Text.Lazy as TL
35+import qualified Text.Pandoc.UTF8 as UTF8
3336
34−yamlBsToMeta :: PandocMonad m
35− => ParserT Text ParserState m (F MetaValue)
37+yamlBsToMeta :: (PandocMonad m, HasLastStrPosition st)
38+ => ParserT Sources st m (Future st MetaValue)
3639 -> BL.ByteString
37− -> ParserT Text ParserState m (F Meta)
40+ -> ParserT Sources st m (Future st Meta)
3841yamlBsToMeta pMetaValue bstr = do
3942 case YAML.decodeNode' YAML.failsafeSchemaResolver False False bstr of
4043 Right (YAML.Doc (YAML.Mapping _ _ o):_)
@@ -42,6 +45,9 @@ yamlBsToMeta pMetaValue bstr = do
4245 Right [] -> return . return $ mempty
4346 Right [YAML.Doc (YAML.Scalar _ YAML.SNull)]
4447 -> return . return $ mempty
48+ -- the following is what we get from a comment:
49+ Right [YAML.Doc (YAML.Scalar _ (YAML.SUnknown _ ""))]
50+ -> return . return $ mempty
4551 Right _ -> Prelude.fail "expected YAML object"
4652 Left (yamlpos, err')
4753 -> do pos <- getPosition
@@ -63,11 +69,11 @@ lookupYAML t (YAML.Mapping _ _ m) =
6369lookupYAML _ _ = Nothing
6470
6571-- Returns filtered list of references.
66−yamlBsToRefs :: PandocMonad m
67− => ParserT Text ParserState m (F MetaValue)
72+yamlBsToRefs :: (PandocMonad m, HasLastStrPosition st)
73+ => ParserT Sources st m (Future st MetaValue)
6874 -> (Text -> Bool) -- ^ Filter for id
6975 -> BL.ByteString
70− -> ParserT Text ParserState m (F [MetaValue])
76+ -> ParserT Sources st m (Future st [MetaValue])
7177yamlBsToRefs pMetaValue idpred bstr =
7278 case YAML.decodeNode' YAML.failsafeSchemaResolver False False bstr of
7379 Right (YAML.Doc o@YAML.Mapping{}:_)
@@ -95,8 +101,12 @@ yamlBsToRefs pMetaValue idpred bstr =
95101 Right [YAML.Doc (YAML.Scalar _ YAML.SNull)]
96102 -> return . return $ mempty
97103 Right _ -> Prelude.fail "expecting YAML object"
98− Left (_pos, err')
99− -> Prelude.fail err'
104+ Left (yamlpos, err')
105+ -> do pos <- getPosition
106+ setPosition $ incSourceLine
107+ (setSourceColumn pos (YE.posColumn yamlpos))
108+ (YE.posLine yamlpos - 1)
109+ Prelude.fail err'
100110
101111
102112nodeToKey :: YAML.Node YE.Pos -> Maybe Text
@@ -104,10 +114,10 @@ nodeToKey (YAML.Scalar _ (YAML.SStr t)) = Just t
104114nodeToKey (YAML.Scalar _ (YAML.SUnknown _ t)) = Just t
105115nodeToKey _ = Nothing
106116
107−normalizeMetaValue :: PandocMonad m
108− => ParserT Text ParserState m (F MetaValue)
117+normalizeMetaValue :: (PandocMonad m, HasLastStrPosition st)
118+ => ParserT Sources st m (Future st MetaValue)
109119 -> Text
110− -> ParserT Text ParserState m (F MetaValue)
120+ -> ParserT Sources st m (Future st MetaValue)
111121normalizeMetaValue pMetaValue x =
112122 -- Note: a standard quoted or unquoted YAML value will
113123 -- not end in a newline, but a "block" set off with
@@ -129,10 +139,10 @@ checkBoolean t
129139 | t == T.pack "false" || t == T.pack "False" || t == T.pack "FALSE" = Just False
130140 | otherwise = Nothing
131141
132−yamlToMetaValue :: PandocMonad m
133− => ParserT Text ParserState m (F MetaValue)
142+yamlToMetaValue :: (PandocMonad m, HasLastStrPosition st)
143+ => ParserT Sources st m (Future st MetaValue)
134144 -> YAML.Node YE.Pos
135− -> ParserT Text ParserState m (F MetaValue)
145+ -> ParserT Sources st m (Future st MetaValue)
136146yamlToMetaValue pMetaValue (YAML.Scalar _ x) =
137147 case x of
138148 YAML.SStr t -> normalizeMetaValue pMetaValue t
@@ -152,10 +162,10 @@ yamlToMetaValue pMetaValue (YAML.Mapping _ _ o) =
152162 fmap MetaMap <$> yamlMap pMetaValue o
153163yamlToMetaValue _ _ = return $ return $ MetaString ""
154164
155−yamlMap :: PandocMonad m
156− => ParserT Text ParserState m (F MetaValue)
165+yamlMap :: (PandocMonad m, HasLastStrPosition st)
166+ => ParserT Sources st m (Future st MetaValue)
157167 -> M.Map (YAML.Node YE.Pos) (YAML.Node YE.Pos)
158− -> ParserT Text ParserState m (F (M.Map Text MetaValue))
168+ -> ParserT Sources st m (Future st (M.Map Text MetaValue))
159169yamlMap pMetaValue o = do
160170 kvs <- forM (M.toList o) $ \(key, v) -> do
161171 k <- maybe (throwError $ PandocParseError
@@ -171,3 +181,20 @@ yamlMap pMetaValue o = do
171181 return $ do
172182 v' <- fv
173183 return (k, v')
184+
185+-- | Parse a YAML metadata block using the supplied 'MetaValue' parser.
186+yamlMetaBlock :: (HasLastStrPosition st, PandocMonad m)
187+ => ParserT Sources st m (Future st MetaValue)
188+ -> ParserT Sources st m (Future st Meta)
189+yamlMetaBlock parser = try $ do
190+ string "---"
191+ blankline
192+ notFollowedBy blankline -- if --- is followed by a blank it's an HRULE
193+ rawYamlLines <- manyTill anyLine stopLine
194+ -- by including --- and ..., we allow yaml blocks with just comments:
195+ let rawYaml = T.unlines ("---" : (rawYamlLines ++ ["..."]))
196+ optional blanklines
197+ yamlBsToMeta parser $ UTF8.fromTextLazy $ TL.fromStrict rawYaml
198+
199+stopLine :: Monad m => ParserT Sources st m ()
200+stopLine = try $ (string "---" <|> string "...") >> blankline >> return ()
src/Text/Pandoc/Readers/Muse.hs+10−9
@@ -36,19 +36,20 @@ import Text.Pandoc.Definition
3636import Text.Pandoc.Error (PandocError (PandocParsecError))
3737import Text.Pandoc.Logging
3838import Text.Pandoc.Options
39−import Text.Pandoc.Parsing hiding (F)
40−import Text.Pandoc.Shared (crFilter, trimr, tshow)
39+import Text.Pandoc.Parsing
40+import Text.Pandoc.Shared (trimr, tshow)
4141
4242-- | Read Muse from an input string and return a Pandoc document.
43−readMuse :: PandocMonad m
43+readMuse :: (PandocMonad m, ToSources a)
4444 => ReaderOptions
45− -> Text
45+ -> a
4646 -> m Pandoc
4747readMuse opts s = do
48− let input = crFilter s
49− res <- flip runReaderT def $ runParserT parseMuse def{ museOptions = opts } "source" input
48+ let sources = toSources s
49+ res <- flip runReaderT def $ runParserT parseMuse def{ museOptions = opts }
50+ (initialSourceName sources) sources
5051 case res of
51− Left e -> throwError $ PandocParsecError input e
52+ Left e -> throwError $ PandocParsecError sources e
5253 Right d -> return d
5354
5455type F = Future MuseState
@@ -82,7 +83,7 @@ instance Default MuseEnv where
8283 , museInPara = False
8384 }
8485
85−type MuseParser m = ParserT Text MuseState (ReaderT MuseEnv m)
86+type MuseParser m = ParserT Sources MuseState (ReaderT MuseEnv m)
8687
8788instance HasReaderOptions MuseState where
8889 extractReaderOptions = museOptions
@@ -155,7 +156,7 @@ firstColumn = getPosition >>= \pos -> guard (sourceColumn pos == 1)
155156-- * Parsers
156157
157158-- | Parse end-of-line, which can be either a newline or end-of-file.
158−eol :: Stream s m Char => ParserT s st m ()
159+eol :: (Stream s m Char, UpdateSourcePos s Char) => ParserT s st m ()
159160eol = void newline <|> eof
160161
161162getIndent :: PandocMonad m
src/Text/Pandoc/Readers/Native.hs+7−5
@@ -21,6 +21,7 @@ import Control.Monad.Except (throwError)
2121import Data.Text (Text)
2222import Text.Pandoc.Class.PandocMonad (PandocMonad)
2323import Text.Pandoc.Error
24+import Text.Pandoc.Sources (ToSources(..), sourcesToText)
2425
2526-- | Read native formatted text and return a Pandoc document.
2627-- The input may be a full pandoc document, a block list, a block,
@@ -32,14 +33,15 @@ import Text.Pandoc.Error
3233--
3334-- > Pandoc nullMeta [Plain [Str "hi"]]
3435--
35−readNative :: PandocMonad m
36+readNative :: (PandocMonad m, ToSources a)
3637 => ReaderOptions
37− -> Text -- ^ String to parse (assuming @'\n'@ line endings)
38+ -> a
3839 -> m Pandoc
3940readNative _ s =
40− case maybe (Pandoc nullMeta <$> readBlocks s) Right (safeRead s) of
41− Right doc -> return doc
42− Left _ -> throwError $ PandocParseError "couldn't read native"
41+ let t = sourcesToText . toSources $ s
42+ in case maybe (Pandoc nullMeta <$> readBlocks t) Right (safeRead t) of
43+ Right doc -> return doc
44+ Left _ -> throwError $ PandocParseError "couldn't read native"
4345
4446readBlocks :: Text -> Either PandocError [Block]
4547readBlocks s = maybe ((:[]) <$> readBlock s) Right (safeRead s)
src/Text/Pandoc/Readers/OPML.hs+9−4
@@ -24,7 +24,8 @@ import Text.Pandoc.Options
2424import Text.Pandoc.Error (PandocError(..))
2525import Text.Pandoc.Readers.HTML (readHtml)
2626import Text.Pandoc.Readers.Markdown (readMarkdown)
27−import Text.Pandoc.Shared (crFilter, blocksToInlines')
27+import Text.Pandoc.Shared (blocksToInlines')
28+import Text.Pandoc.Sources (ToSources(..), sourcesToText)
2829import Text.Pandoc.XML.Light
2930import Control.Monad.Except (throwError)
3031
@@ -46,10 +47,14 @@ instance Default OPMLState where
4647 , opmlOptions = def
4748 }
4849
49−readOPML :: PandocMonad m => ReaderOptions -> Text -> m Pandoc
50+readOPML :: (PandocMonad m, ToSources a)
51+ => ReaderOptions
52+ -> a
53+ -> m Pandoc
5054readOPML opts inp = do
51− (bs, st') <- runStateT
52− (case parseXMLContents (TL.fromStrict (crFilter inp)) of
55+ let sources = toSources inp
56+ (bs, st') <-
57+ runStateT (case parseXMLContents (TL.fromStrict . sourcesToText $ sources) of
5358 Left msg -> throwError $ PandocXMLError "" msg
5459 Right ns -> mapM parseBlock ns)
5560 def{ opmlOptions = opts }
src/Text/Pandoc/Readers/Odt/Arrows/State.hs+2−2
@@ -22,7 +22,7 @@ module Text.Pandoc.Readers.Odt.Arrows.State where
2222import Control.Arrow
2323import qualified Control.Category as Cat
2424import Control.Monad
25−
25+import Data.List (foldl')
2626import Text.Pandoc.Readers.Odt.Arrows.Utils
2727import Text.Pandoc.Readers.Odt.Generic.Fallible
2828
@@ -122,7 +122,7 @@ iterateS a = ArrowState $ \(s,f) -> foldr a' (s,mzero) f
122122iterateSL :: (Foldable f, MonadPlus m)
123123 => ArrowState s x y
124124 -> ArrowState s (f x) (m y)
125−iterateSL a = ArrowState $ \(s,f) -> foldl a' (s,mzero) f
125+iterateSL a = ArrowState $ \(s,f) -> foldl' a' (s,mzero) f
126126 where a' (s',m) x = second (mplus m.return) $ runArrowState a (s',x)
127127
128128
src/Text/Pandoc/Readers/Odt/ContentReader.hs+12−7
@@ -1,4 +1,5 @@
11{-# LANGUAGE Arrows #-}
2+{-# LANGUAGE CPP #-}
23{-# LANGUAGE DeriveFoldable #-}
34{-# LANGUAGE GeneralizedNewtypeDeriving #-}
45{-# LANGUAGE PatternGuards #-}
@@ -33,7 +34,7 @@ import Data.List (find)
3334import qualified Data.Map as M
3435import qualified Data.Text as T
3536import Data.Maybe
36−import Data.Semigroup (First(..), Option(..))
37+import Data.Monoid (Alt (..))
3738
3839import Text.TeXMath (readMathML, writeTeX)
3940import qualified Text.Pandoc.XML.Light as XML
@@ -505,13 +506,11 @@ type InlineMatcher = ElementMatcher Inlines
505506
506507type BlockMatcher = ElementMatcher Blocks
507508
508−
509−newtype FirstMatch a = FirstMatch (Option (First a))
510− deriving (Foldable, Monoid, Semigroup)
509+newtype FirstMatch a = FirstMatch (Alt Maybe a)
510+ deriving (Foldable, Monoid, Semigroup)
511511
512512firstMatch :: a -> FirstMatch a
513−firstMatch = FirstMatch . Option . Just . First
514−
513+firstMatch = FirstMatch . Alt . Just
515514
516515--
517516matchingElement :: (Monoid e)
@@ -577,7 +576,10 @@ read_spaces = matchingElement NsText "s" (
577576read_line_break :: InlineMatcher
578577read_line_break = matchingElement NsText "line-break"
579578 $ returnV linebreak
580−
579+--
580+read_tab :: InlineMatcher
581+read_tab = matchingElement NsText "tab"
582+ $ returnV space
581583--
582584read_span :: InlineMatcher
583585read_span = matchingElement NsText "span"
@@ -585,6 +587,7 @@ read_span = matchingElement NsText "span"
585587 $ matchChildContent [ read_span
586588 , read_spaces
587589 , read_line_break
590+ , read_tab
588591 , read_link
589592 , read_note
590593 , read_citation
@@ -604,6 +607,7 @@ read_paragraph = matchingElement NsText "p"
604607 $ matchChildContent [ read_span
605608 , read_spaces
606609 , read_line_break
610+ , read_tab
607611 , read_link
608612 , read_note
609613 , read_citation
@@ -630,6 +634,7 @@ read_header = matchingElement NsText "h"
630634 children <- ( matchChildContent [ read_span
631635 , read_spaces
632636 , read_line_break
637+ , read_tab
633638 , read_link
634639 , read_note
635640 , read_citation
src/Text/Pandoc/Readers/Odt/Generic/XMLConverter.hs+2−2
@@ -64,12 +64,12 @@ import qualified Data.Map as M
6464import Data.Text (Text)
6565import Data.Default
6666import Data.Maybe
67+import Data.List (foldl')
6768
6869import qualified Text.Pandoc.XML.Light as XML
6970
7071import Text.Pandoc.Readers.Odt.Arrows.State
7172import Text.Pandoc.Readers.Odt.Arrows.Utils
72−
7373import Text.Pandoc.Readers.Odt.Generic.Namespaces
7474import Text.Pandoc.Readers.Odt.Generic.Utils
7575import Text.Pandoc.Readers.Odt.Generic.Fallible
@@ -293,7 +293,7 @@ readNSattributes = fromState $ \state -> maybe (state, failEmpty )
293293 => XMLConverterState nsID extraState
294294 -> Maybe (XMLConverterState nsID extraState)
295295 extractNSAttrs startState
296− = foldl (\state d -> state >>= addNS d)
296+ = foldl' (\state d -> state >>= addNS d)
297297 (Just startState)
298298 nsAttribs
299299 where nsAttribs = mapMaybe readNSattr (XML.elAttribs element)
src/Text/Pandoc/Readers/Odt/StyleReader.hs+8−7
@@ -44,7 +44,7 @@ import Control.Arrow
4444
4545import Data.Default
4646import qualified Data.Foldable as F
47−import Data.List (unfoldr)
47+import Data.List (unfoldr, foldl')
4848import qualified Data.Map as M
4949import Data.Maybe
5050import Data.Text (Text)
@@ -120,7 +120,7 @@ fontPitchReader = executeInSub NsOffice "font-face-decls" (
120120 &&&
121121 lookupDefaultingAttr NsStyle "font-pitch"
122122 ))
123− >>?^ ( M.fromList . foldl accumLegalPitches [] )
123+ >>?^ ( M.fromList . foldl' accumLegalPitches [] )
124124 ) `ifFailedDo` returnV (Right M.empty)
125125 where accumLegalPitches ls (Nothing,_) = ls
126126 accumLegalPitches ls (Just n,p) = (n,p):ls
@@ -563,12 +563,13 @@ readListLevelStyle levelType = readAttr NsText "level"
563563
564564--
565565chooseMostSpecificListLevelStyle :: S.Set ListLevelStyle -> Maybe ListLevelStyle
566−chooseMostSpecificListLevelStyle ls | ls == mempty = Nothing
567− | otherwise = Just ( F.foldr1 select ls )
566+chooseMostSpecificListLevelStyle ls = F.foldr select Nothing ls
568567 where
569− select ( ListLevelStyle t1 p1 s1 f1 b1 )
570− ( ListLevelStyle t2 p2 s2 f2 _ )
571− = ListLevelStyle (select' t1 t2) (p1 <|> p2) (s1 <|> s2) (selectLinf f1 f2) b1
568+ select l Nothing = Just l
569+ select ( ListLevelStyle t1 p1 s1 f1 b1 )
570+ ( Just ( ListLevelStyle t2 p2 s2 f2 _ ))
571+ = Just $ ListLevelStyle (select' t1 t2) (p1 <|> p2) (s1 <|> s2)
572+ (selectLinf f1 f2) b1
572573 select' LltNumbered _ = LltNumbered
573574 select' _ LltNumbered = LltNumbered
574575 select' _ _ = LltBullet
src/Text/Pandoc/Readers/Org.hs+4−7
@@ -18,22 +18,19 @@ import Text.Pandoc.Class.PandocMonad (PandocMonad)
1818import Text.Pandoc.Definition
1919import Text.Pandoc.Options
2020import Text.Pandoc.Parsing (reportLogMessages)
21−import Text.Pandoc.Shared (crFilter)
22−
21+import Text.Pandoc.Sources (ToSources(..), ensureFinalNewlines)
2322import Control.Monad.Except (throwError)
2423import Control.Monad.Reader (runReaderT)
2524
26−import Data.Text (Text)
27−
2825-- | Parse org-mode string and return a Pandoc document.
29−readOrg :: PandocMonad m
26+readOrg :: (PandocMonad m, ToSources a)
3027 => ReaderOptions -- ^ Reader options
31− -> Text -- ^ String to parse (assuming @'\n'@ line endings)
28+ -> a
3229 -> m Pandoc
3330readOrg opts s = do
3431 parsed <- flip runReaderT def $
3532 readWithM parseOrg (optionsToParserState opts)
36− (crFilter s <> "\n\n")
33+ (ensureFinalNewlines 2 (toSources s))
3734 case parsed of
3835 Right result -> return result
3936 Left e -> throwError e
src/Text/Pandoc/Readers/Org/Blocks.hs+7−4
@@ -39,10 +39,12 @@ import Data.Functor (($>))
3939import Data.List (foldl', intersperse)
4040import Data.Maybe (fromMaybe, isJust, isNothing)
4141import Data.Text (Text)
42−
42+import Data.List.NonEmpty (nonEmpty)
43+import System.FilePath
4344import qualified Data.Text as T
4445import qualified Text.Pandoc.Builder as B
4546import qualified Text.Pandoc.Walk as Walk
47+import Text.Pandoc.Sources (ToSources(..))
4648
4749--
4850-- parsing blocks
@@ -526,7 +528,9 @@ include = try $ do
526528 _ -> nullAttr
527529 return $ pure . B.codeBlockWith attr <$> parseRaw
528530 _ -> return $ return . B.fromList . blockFilter params <$> blockList
529− insertIncludedFileF blocksParser ["."] filename
531+ currentDir <- takeDirectory . sourceName <$> getPosition
532+ insertIncludedFile blocksParser toSources
533+ [currentDir] filename Nothing Nothing
530534 where
531535 includeTarget :: PandocMonad m => OrgParser m FilePath
532536 includeTarget = do
@@ -542,8 +546,7 @@ include = try $ do
542546 in case (minlvl >>= safeRead :: Maybe Int) of
543547 Nothing -> blks
544548 Just lvl -> let levels = Walk.query headerLevel blks
545− -- CAVE: partial function in else
546− curMin = if null levels then 0 else minimum levels
549+ curMin = maybe 0 minimum $ nonEmpty levels
547550 in Walk.walk (shiftHeader (curMin - lvl)) blks
548551
549552 headerLevel :: Block -> [Int]
src/Text/Pandoc/Readers/Org/Inlines.hs+6−5
@@ -29,6 +29,7 @@ import Text.Pandoc.Definition
2929import Text.Pandoc.Options
3030import Text.Pandoc.Readers.LaTeX (inlineCommand, rawLaTeXInline)
3131import Text.TeXMath (DisplayType (..), readTeX, writePandoc)
32+import Text.Pandoc.Sources (ToSources(..))
3233import qualified Text.TeXMath.Readers.MathML.EntityMap as MathMLEntityMap
3334
3435import Control.Monad (guard, mplus, mzero, unless, void, when)
@@ -262,7 +263,7 @@ berkeleyCitationList = try $ do
262263 where
263264 citationListPart :: PandocMonad m => OrgParser m (F Inlines)
264265 citationListPart = fmap (trimInlinesF . mconcat) . try . many1 $ do
265− notFollowedBy' citeKey
266+ notFollowedBy' $ citeKey False
266267 notFollowedBy (oneOf ";]")
267268 inline
268269
@@ -277,7 +278,7 @@ berkeleyBareTag' = try $ void (string "cite")
277278
278279berkeleyTextualCite :: PandocMonad m => OrgParser m (F [Citation])
279280berkeleyTextualCite = try $ do
280− (suppressAuthor, key) <- citeKey
281+ (suppressAuthor, key) <- citeKey False
281282 returnF . return $ Citation
282283 { citationId = key
283284 , citationPrefix = mempty
@@ -350,7 +351,7 @@ citeList = sequence <$> sepEndBy1 citation (try $ char ';' *> skipSpaces)
350351citation :: PandocMonad m => OrgParser m (F Citation)
351352citation = try $ do
352353 pref <- prefix
353− (suppress_author, key) <- citeKey
354+ (suppress_author, key) <- citeKey False
354355 suff <- suffix
355356 return $ do
356357 x <- pref
@@ -367,7 +368,7 @@ citation = try $ do
367368 }
368369 where
369370 prefix = trimInlinesF . mconcat <$>
370− manyTill inline (char ']' <|> (']' <$ lookAhead citeKey))
371+ manyTill inline (char ']' <|> (']' <$ lookAhead (citeKey False)))
371372 suffix = try $ do
372373 hasSpace <- option False (notFollowedBy nonspaceChar >> return True)
373374 skipSpaces
@@ -802,7 +803,7 @@ inlineLaTeX = try $ do
802803 parseAsInlineLaTeX :: PandocMonad m
803804 => Text -> TeXExport -> OrgParser m (Maybe Inlines)
804805 parseAsInlineLaTeX cs = \case
805− TeXExport -> maybeRight <$> runParserT inlineCommand state "" cs
806+ TeXExport -> maybeRight <$> runParserT inlineCommand state "" (toSources cs)
806807 TeXIgnore -> return (Just mempty)
807808 TeXVerbatim -> return (Just $ B.str cs)
808809
src/Text/Pandoc/Readers/Org/Parsing.hs+5−5
@@ -63,8 +63,7 @@ module Text.Pandoc.Readers.Org.Parsing
6363 , ellipses
6464 , citeKey
6565 , gridTableWith
66− , insertIncludedFileF
67− -- * Re-exports from Text.Pandoc.Parsec
66+ , insertIncludedFile
6867 , runParser
6968 , runParserT
7069 , getInput
@@ -100,21 +99,22 @@ module Text.Pandoc.Readers.Org.Parsing
10099 , getState
101100 , updateState
102101 , SourcePos
102+ , sourceName
103103 , getPosition
104104 ) where
105105
106106import Data.Text (Text)
107107import Text.Pandoc.Readers.Org.ParserState
108108
109−import Text.Pandoc.Parsing hiding (F, anyLine, blanklines, newline,
110− parseFromString)
109+import Text.Pandoc.Parsing hiding (anyLine, blanklines, newline,
110+ parseFromString)
111111import qualified Text.Pandoc.Parsing as P
112112
113113import Control.Monad (guard)
114114import Control.Monad.Reader (ReaderT)
115115
116116-- | The parser used to read org files.
117−type OrgParser m = ParserT Text OrgParserState (ReaderT OrgParserLocal m)
117+type OrgParser m = ParserT Sources OrgParserState (ReaderT OrgParserLocal m)
118118
119119--
120120-- Adaptions and specializations of parsing utilities
src/Text/Pandoc/Readers/RST.hs+78−110
@@ -27,8 +27,7 @@ import Data.Text (Text)
2727import qualified Data.Text as T
2828import Text.Pandoc.Builder (Blocks, Inlines, fromList, setMeta, trimInlines)
2929import qualified Text.Pandoc.Builder as B
30−import Text.Pandoc.Class.PandocMonad (PandocMonad, fetchItem,
31− readFileFromDirs, getTimestamp)
30+import Text.Pandoc.Class.PandocMonad (PandocMonad, fetchItem, getTimestamp)
3231import Text.Pandoc.CSV (CSVOptions (..), defaultCSVOptions, parseCSV)
3332import Text.Pandoc.Definition
3433import Text.Pandoc.Error
@@ -38,25 +37,25 @@ import Text.Pandoc.Options
3837import Text.Pandoc.Parsing
3938import Text.Pandoc.Shared
4039import qualified Text.Pandoc.UTF8 as UTF8
41−import Text.Printf (printf)
4240import Data.Time.Format
41+import System.FilePath (takeDirectory)
4342
4443-- TODO:
4544-- [ ] .. parsed-literal
4645
4746-- | Parse reStructuredText string and return Pandoc document.
48−readRST :: PandocMonad m
47+readRST :: (PandocMonad m, ToSources a)
4948 => ReaderOptions -- ^ Reader options
50− -> Text -- ^ Text to parse (assuming @'\n'@ line endings)
49+ -> a
5150 -> m Pandoc
5251readRST opts s = do
5352 parsed <- readWithM parseRST def{ stateOptions = opts }
54− (crFilter s <> "\n\n")
53+ (ensureFinalNewlines 2 (toSources s))
5554 case parsed of
5655 Right result -> return result
5756 Left e -> throwError e
5857
59−type RSTParser m = ParserT Text ParserState m
58+type RSTParser m = ParserT Sources ParserState m
6059
6160--
6261-- Constants and data structure definitions
@@ -151,11 +150,19 @@ parseRST = do
151150 startPos <- getPosition
152151 -- go through once just to get list of reference keys and notes
153152 -- docMinusKeys is the raw document with blanks where the keys were...
154− docMinusKeys <- T.concat <$>
155− manyTill (referenceKey <|> anchorDef <|>
156− noteBlock <|> citationBlock <|>
157− (snd <$> withRaw comment) <|>
158− headerBlock <|> lineClump) eof
153+ let chunk = referenceKey
154+ <|> anchorDef
155+ <|> noteBlock
156+ <|> citationBlock
157+ <|> (snd <$> withRaw comment)
158+ <|> headerBlock
159+ <|> lineClump
160+ docMinusKeys <- Sources <$>
161+ manyTill (do pos <- getPosition
162+ t <- chunk
163+ return (pos, t)) eof
164+ -- UGLY: we collapse source position information.
165+ -- TODO: fix the parser to use the F monad instead of two passes
159166 setInput docMinusKeys
160167 setPosition startPos
161168 st' <- getState
@@ -348,7 +355,7 @@ singleHeader' = try $ do
348355-- hrule block
349356--
350357
351−hrule :: Monad m => ParserT Text st m Blocks
358+hrule :: Monad m => ParserT Sources st m Blocks
352359hrule = try $ do
353360 chr <- oneOf underlineChars
354361 count 3 (char chr)
@@ -363,7 +370,7 @@ hrule = try $ do
363370
364371-- read a line indented by a given string
365372indentedLine :: (HasReaderOptions st, Monad m)
366− => Int -> ParserT Text st m Text
373+ => Int -> ParserT Sources st m Text
367374indentedLine indents = try $ do
368375 lookAhead spaceChar
369376 gobbleAtMostSpaces indents
@@ -372,7 +379,7 @@ indentedLine indents = try $ do
372379-- one or more indented lines, possibly separated by blank lines.
373380-- any amount of indentation will work.
374381indentedBlock :: (HasReaderOptions st, Monad m)
375− => ParserT Text st m Text
382+ => ParserT Sources st m Text
376383indentedBlock = try $ do
377384 indents <- length <$> lookAhead (many1 spaceChar)
378385 lns <- many1 $ try $ do b <- option "" blanklines
@@ -381,20 +388,20 @@ indentedBlock = try $ do
381388 optional blanklines
382389 return $ T.unlines lns
383390
384−quotedBlock :: Monad m => ParserT Text st m Text
391+quotedBlock :: Monad m => ParserT Sources st m Text
385392quotedBlock = try $ do
386393 quote <- lookAhead $ oneOf "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"
387394 lns <- many1 $ lookAhead (char quote) >> anyLine
388395 optional blanklines
389396 return $ T.unlines lns
390397
391−codeBlockStart :: Monad m => ParserT Text st m Char
398+codeBlockStart :: Monad m => ParserT Sources st m Char
392399codeBlockStart = string "::" >> blankline >> blankline
393400
394−codeBlock :: Monad m => ParserT Text ParserState m Blocks
401+codeBlock :: Monad m => ParserT Sources ParserState m Blocks
395402codeBlock = try $ codeBlockStart >> codeBlockBody
396403
397−codeBlockBody :: Monad m => ParserT Text ParserState m Blocks
404+codeBlockBody :: Monad m => ParserT Sources ParserState m Blocks
398405codeBlockBody = do
399406 lang <- stateRstHighlight <$> getState
400407 try $ B.codeBlockWith ("", maybeToList lang, []) . stripTrailingNewlines <$>
@@ -410,14 +417,14 @@ lhsCodeBlock = try $ do
410417 return $ B.codeBlockWith ("", ["haskell","literate"], [])
411418 $ T.intercalate "\n" lns
412419
413−latexCodeBlock :: Monad m => ParserT Text st m [Text]
420+latexCodeBlock :: Monad m => ParserT Sources st m [Text]
414421latexCodeBlock = try $ do
415422 try (latexBlockLine "\\begin{code}")
416423 many1Till anyLine (try $ latexBlockLine "\\end{code}")
417424 where
418425 latexBlockLine s = skipMany spaceChar >> string s >> blankline
419426
420−birdCodeBlock :: Monad m => ParserT Text st m [Text]
427+birdCodeBlock :: Monad m => ParserT Sources st m [Text]
421428birdCodeBlock = filterSpace <$> many1 birdTrackLine
422429 where filterSpace lns =
423430 -- if (as is normal) there is always a space after >, drop it
@@ -425,7 +432,7 @@ birdCodeBlock = filterSpace <$> many1 birdTrackLine
425432 then map (T.drop 1) lns
426433 else lns
427434
428−birdTrackLine :: Monad m => ParserT Text st m Text
435+birdTrackLine :: Monad m => ParserT Sources st m Text
429436birdTrackLine = char '>' >> anyLine
430437
431438--
@@ -446,64 +453,39 @@ encoding
446453-}
447454
448455includeDirective :: PandocMonad m
449− => Text -> [(Text, Text)] -> Text
456+ => Text
457+ -> [(Text, Text)]
458+ -> Text
450459 -> RSTParser m Blocks
451460includeDirective top fields body = do
452− let f = trim top
453− guard $ not (T.null f)
461+ let f = T.unpack $ trim top
462+ guard $ not $ null f
454463 guard $ T.null (trim body)
455− -- options
456− let (startLine :: Maybe Int) = lookup "start-line" fields >>= safeRead
457− let (endLine :: Maybe Int) = lookup "end-line" fields >>= safeRead
458− oldPos <- getPosition
459− oldInput <- getInput
460− containers <- stateContainers <$> getState
461− when (f `elem` containers) $
462− throwError $ PandocParseError $ "Include file loop at " <> tshow oldPos
463− updateState $ \s -> s{ stateContainers = f : stateContainers s }
464− mbContents <- readFileFromDirs ["."] $ T.unpack f
465− contentLines <- case mbContents of
466− Just s -> return $ T.lines s
467− Nothing -> do
468− logMessage $ CouldNotLoadIncludeFile f oldPos
469− return []
470− let numLines = length contentLines
471− let startLine' = case startLine of
472− Nothing -> 1
473− Just x | x >= 0 -> x
474− | otherwise -> numLines + x -- negative from end
475− let endLine' = case endLine of
476− Nothing -> numLines + 1
477− Just x | x >= 0 -> x
478− | otherwise -> numLines + x -- negative from end
479− let contentLines' = drop (startLine' - 1)
480− $ take (endLine' - 1) contentLines
481− let contentLines'' = (case trim <$> lookup "end-before" fields of
482− Just patt -> takeWhile (not . (patt `T.isInfixOf`))
483− Nothing -> id) .
484− (case trim <$> lookup "start-after" fields of
485− Just patt -> drop 1 .
486− dropWhile (not . (patt `T.isInfixOf`))
487− Nothing -> id) $ contentLines'
488− let contents' = T.unlines contentLines''
489− case lookup "code" fields of
490− Just lang -> do
491− let classes = maybe [] T.words (lookup "class" fields)
492− let ident = maybe "" trimr $ lookup "name" fields
493− codeblock ident classes fields (trimr lang) contents' False
494− Nothing -> case lookup "literal" fields of
495− Just _ -> return $ B.rawBlock "rst" contents'
496− Nothing -> do
497− setPosition $ newPos (T.unpack f) 1 1
498− setInput $ contents' <> "\n"
499− bs <- optional blanklines >>
500− (mconcat <$> many block)
501− setInput oldInput
502− setPosition oldPos
503− updateState $ \s -> s{ stateContainers =
504− tail $ stateContainers s }
505− return bs
506−
464+ let startLine = lookup "start-line" fields >>= safeRead
465+ let endLine = lookup "end-line" fields >>= safeRead
466+ let classes = maybe [] T.words (lookup "class" fields)
467+ let ident = maybe "" trimr $ lookup "name" fields
468+ let parser =
469+ case lookup "code" fields of
470+ Just lang ->
471+ (codeblock ident classes fields (trimr lang) False
472+ . sourcesToText) <$> getInput
473+ Nothing ->
474+ case lookup "literal" fields of
475+ Just _ -> B.rawBlock "rst" . sourcesToText <$> getInput
476+ Nothing -> parseBlocks
477+ let selectLines =
478+ (case trim <$> lookup "end-before" fields of
479+ Just patt -> takeWhile (not . (patt `T.isInfixOf`))
480+ Nothing -> id) .
481+ (case trim <$> lookup "start-after" fields of
482+ Just patt -> drop 1 .
483+ dropWhile (not . (patt `T.isInfixOf`))
484+ Nothing -> id)
485+ let toStream t =
486+ toSources [(f, T.unlines . selectLines . T.lines $ t)]
487+ currentDir <- takeDirectory . sourceName <$> getPosition
488+ insertIncludedFile parser toStream [currentDir] f startLine endLine
507489
508490--
509491-- list blocks
@@ -526,7 +508,7 @@ definitionList :: PandocMonad m => RSTParser m Blocks
526508definitionList = B.definitionList <$> many1 definitionListItem
527509
528510-- parses bullet list start and returns its length (inc. following whitespace)
529−bulletListStart :: Monad m => ParserT Text st m Int
511+bulletListStart :: Monad m => ParserT Sources st m Int
530512bulletListStart = try $ do
531513 notFollowedBy' hrule -- because hrules start out just like lists
532514 marker <- oneOf bulletListMarkers
@@ -613,8 +595,9 @@ comment = try $ do
613595 string ".."
614596 skipMany1 spaceChar <|> (() <$ lookAhead newline)
615597 -- notFollowedBy' directiveLabel -- comment comes after directive so unnec.
616− manyTill anyChar blanklines
598+ _ <- anyLine
617599 optional indentedBlock
600+ optional blanklines
618601 return mempty
619602
620603directiveLabel :: Monad m => RSTParser m Text
@@ -731,8 +714,8 @@ directive' = do
731714 "" -> stateRstHighlight def
732715 lang -> Just lang })
733716 x | x == "code" || x == "code-block" || x == "sourcecode" ->
734− codeblock name classes (map (second trimr) fields)
735− (trim top) body True
717+ return $ codeblock name classes (map (second trimr) fields)
718+ (trim top) True body
736719 "aafig" -> do
737720 let attribs = (name, ["aafig"], map (second trimr) fields)
738721 return $ B.codeBlockWith attribs $ stripTrailingNewlines body
@@ -1018,10 +1001,10 @@ toChunks = dropWhile T.null
10181001 then "\\begin{aligned}\n" <> s <> "\n\\end{aligned}"
10191002 else s
10201003
1021−codeblock :: Text -> [Text] -> [(Text, Text)] -> Text -> Text -> Bool
1022− -> RSTParser m Blocks
1023−codeblock ident classes fields lang body rmTrailingNewlines =
1024− return $ B.codeBlockWith attribs $ stripTrailingNewlines' body
1004+codeblock :: Text -> [Text] -> [(Text, Text)] -> Text -> Bool -> Text
1005+ -> Blocks
1006+codeblock ident classes fields lang rmTrailingNewlines body =
1007+ B.codeBlockWith attribs $ stripTrailingNewlines' body
10251008 where stripTrailingNewlines' = if rmTrailingNewlines
10261009 then stripTrailingNewlines
10271010 else id
@@ -1102,7 +1085,7 @@ quotedReferenceName = try $ do
11021085-- plus isolated (no two adjacent) internal hyphens, underscores,
11031086-- periods, colons and plus signs; no whitespace or other characters
11041087-- are allowed.
1105−simpleReferenceName :: Monad m => ParserT Text st m Text
1088+simpleReferenceName :: Monad m => ParserT Sources st m Text
11061089simpleReferenceName = do
11071090 x <- alphaNum
11081091 xs <- many $ alphaNum
@@ -1121,7 +1104,7 @@ referenceKey = do
11211104 -- return enough blanks to replace key
11221105 return $ T.replicate (sourceLine endPos - sourceLine startPos) "\n"
11231106
1124−targetURI :: Monad m => ParserT Text st m Text
1107+targetURI :: Monad m => ParserT Sources st m Text
11251108targetURI = do
11261109 skipSpaces
11271110 optional $ try $ newline >> notFollowedBy blankline
@@ -1159,8 +1142,10 @@ anonymousKey :: Monad m => RSTParser m ()
11591142anonymousKey = try $ do
11601143 oneOfStrings [".. __:", "__"]
11611144 src <- targetURI
1162− pos <- getPosition
1163− let key = toKey $ "_" <> T.pack (printf "%09d" (sourceLine pos))
1145+ -- we need to ensure that the keys are ordered by occurrence in
1146+ -- the document.
1147+ numKeys <- M.size . stateKeys <$> getState
1148+ let key = toKey $ "_" <> T.pack (show numKeys)
11641149 updateState $ \s -> s { stateKeys = M.insert key ((src,""), nullAttr) $
11651150 stateKeys s }
11661151
@@ -1249,13 +1234,13 @@ headerBlock = do
12491234-- Grid tables TODO:
12501235-- - column spans
12511236
1252−dashedLine :: Monad m => Char -> ParserT Text st m (Int, Int)
1237+dashedLine :: Monad m => Char -> ParserT Sources st m (Int, Int)
12531238dashedLine ch = do
12541239 dashes <- many1 (char ch)
12551240 sp <- many (char ' ')
12561241 return (length dashes, length $ dashes ++ sp)
12571242
1258−simpleDashedLines :: Monad m => Char -> ParserT Text st m [(Int,Int)]
1243+simpleDashedLines :: Monad m => Char -> ParserT Sources st m [(Int,Int)]
12591244simpleDashedLines ch = try $ many1 (dashedLine ch)
12601245
12611246-- Parse a table row separator
@@ -1381,7 +1366,7 @@ hyphens = do
13811366 -- don't want to treat endline after hyphen or dash as a space
13821367 return $ B.str result
13831368
1384−escapedChar :: Monad m => ParserT Text st m Inlines
1369+escapedChar :: Monad m => ParserT Sources st m Inlines
13851370escapedChar = do c <- escaped anyChar
13861371 return $ if c == ' ' || c == '\n' || c == '\r'
13871372 -- '\ ' is null in RST
@@ -1657,21 +1642,4 @@ note = try $ do
16571642 return $ B.note contents
16581643
16591644smart :: PandocMonad m => RSTParser m Inlines
1660−smart = do
1661− guardEnabled Ext_smart
1662− doubleQuoted <|> singleQuoted <|>
1663− choice [apostrophe, dash, ellipses]
1664−
1665−singleQuoted :: PandocMonad m => RSTParser m Inlines
1666−singleQuoted = try $ do
1667− singleQuoteStart
1668− withQuoteContext InSingleQuote $
1669− B.singleQuoted . trimInlines . mconcat <$>
1670− many1Till inline singleQuoteEnd
1671−
1672−doubleQuoted :: PandocMonad m => RSTParser m Inlines
1673−doubleQuoted = try $ do
1674− doubleQuoteStart
1675− withQuoteContext InDoubleQuote $
1676− B.doubleQuoted . trimInlines . mconcat <$>
1677− many1Till inline doubleQuoteEnd
1645+smart = smartPunctuation inline
src/Text/Pandoc/Readers/Roff.hs+16−18
@@ -42,7 +42,6 @@ import Text.Pandoc.Logging (LogMessage(..))
4242import Text.Pandoc.Options
4343import Text.Pandoc.Parsing
4444import Text.Pandoc.Shared (safeRead)
45−import Text.Parsec hiding (tokenPrim)
4645import Text.Pandoc.RoffChar (characterCodes, combiningAccents)
4746import qualified Data.Sequence as Seq
4847import qualified Data.Foldable as Foldable
@@ -122,16 +121,16 @@ instance Default RoffState where
122121 , afterConditional = False
123122 }
124123
125−type RoffLexer m = ParserT T.Text RoffState m
124+type RoffLexer m = ParserT Sources RoffState m
126125
127126--
128127-- Lexer: T.Text -> RoffToken
129128--
130129
131−eofline :: Stream s m Char => ParsecT s u m ()
130+eofline :: (Stream s m Char, UpdateSourcePos s Char) => ParserT s u m ()
132131eofline = void newline <|> eof <|> () <$ lookAhead (string "\\}")
133132
134−spacetab :: Stream s m Char => ParsecT s u m Char
133+spacetab :: (Stream s m Char, UpdateSourcePos s Char) => ParserT s u m Char
135134spacetab = char ' ' <|> char '\t'
136135
137136characterCodeMap :: M.Map T.Text Char
@@ -303,8 +302,7 @@ expandString = try $ do
303302 char '*'
304303 cs <- escapeArg <|> countChar 1 anyChar
305304 s <- linePartsToText <$> resolveText cs pos
306− getInput >>= setInput . (s <>)
307− return ()
305+ addToInput s
308306
309307-- Parses: '..'
310308quoteArg :: PandocMonad m => RoffLexer m T.Text
@@ -316,7 +314,7 @@ escFont = do
316314 font' <- if T.null font || font == "P"
317315 then prevFont <$> getState
318316 else return $ foldr processFontLetter defaultFontSpec $ T.unpack font
319− modifyState $ \st -> st{ prevFont = currentFont st
317+ updateState $ \st -> st{ prevFont = currentFont st
320318 , currentFont = font' }
321319 return [Font font']
322320 where
@@ -372,8 +370,8 @@ lexTable pos = do
372370 spaces
373371 opts <- try tableOptions <|> [] <$ optional (char ';')
374372 case lookup "tab" opts of
375− Just (T.uncons -> Just (c, _)) -> modifyState $ \st -> st{ tableTabChar = c }
376− _ -> modifyState $ \st -> st{ tableTabChar = '\t' }
373+ Just (T.uncons -> Just (c, _)) -> updateState $ \st -> st{ tableTabChar = c }
374+ _ -> updateState $ \st -> st{ tableTabChar = '\t' }
377375 spaces
378376 skipMany lexComment
379377 spaces
@@ -489,18 +487,18 @@ lexConditional mname = do
489487 ifPart <- do
490488 optional $ try $ char '\\' >> newline
491489 lexGroup
492− <|> do modifyState $ \s -> s{ afterConditional = True }
490+ <|> do updateState $ \s -> s{ afterConditional = True }
493491 t <- manToken
494− modifyState $ \s -> s{ afterConditional = False }
492+ updateState $ \s -> s{ afterConditional = False }
495493 return t
496494 case mbtest of
497495 Nothing -> do
498− putState st -- reset state, so we don't record macros in skipped section
496+ setState st -- reset state, so we don't record macros in skipped section
499497 report $ SkippedContent (T.cons '.' mname) pos
500498 return mempty
501499 Just True -> return ifPart
502500 Just False -> do
503− putState st
501+ setState st
504502 return mempty
505503
506504expression :: PandocMonad m => RoffLexer m (Maybe Bool)
@@ -515,7 +513,7 @@ expression = do
515513 _ -> Nothing
516514 where
517515 returnValue v = do
518− modifyState $ \st -> st{ lastExpression = v }
516+ updateState $ \st -> st{ lastExpression = v }
519517 return v
520518
521519lexGroup :: PandocMonad m => RoffLexer m RoffTokens
@@ -536,7 +534,7 @@ lexIncludeFile args = do
536534 result <- readFileFromDirs dirs $ T.unpack fp
537535 case result of
538536 Nothing -> report $ CouldNotLoadIncludeFile fp pos
539− Just s -> getInput >>= setInput . (s <>)
537+ Just s -> addToInput s
540538 return mempty
541539 [] -> return mempty
542540
@@ -564,13 +562,13 @@ lexStringDef args = do -- string definition
564562 (x:ys) -> do
565563 let ts = singleTok $ TextLine (intercalate [RoffStr " " ] ys)
566564 let stringName = linePartsToText x
567− modifyState $ \st ->
565+ updateState $ \st ->
568566 st{ customMacros = M.insert stringName ts (customMacros st) }
569567 return mempty
570568
571569lexMacroDef :: PandocMonad m => [Arg] -> RoffLexer m RoffTokens
572570lexMacroDef args = do -- macro definition
573− modifyState $ \st -> st{ roffMode = CopyMode }
571+ updateState $ \st -> st{ roffMode = CopyMode }
574572 (macroName, stopMacro) <-
575573 case args of
576574 (x : y : _) -> return (linePartsToText x, linePartsToText y)
@@ -584,7 +582,7 @@ lexMacroDef args = do -- macro definition
584582 _ <- lexArgs
585583 return ()
586584 ts <- mconcat <$> manyTill manToken stop
587− modifyState $ \st ->
585+ updateState $ \st ->
588586 st{ customMacros = M.insert macroName ts (customMacros st)
589587 , roffMode = NormalMode }
590588 return mempty
src/Text/Pandoc/Readers/TWiki.hs+7−27
@@ -28,22 +28,22 @@ import Text.Pandoc.Definition
2828import Text.Pandoc.Options
2929import Text.Pandoc.Parsing hiding (enclosed, nested)
3030import Text.Pandoc.Readers.HTML (htmlTag, isCommentTag)
31−import Text.Pandoc.Shared (crFilter, tshow)
31+import Text.Pandoc.Shared (tshow)
3232import Text.Pandoc.XML (fromEntities)
3333
3434-- | Read twiki from an input string and return a Pandoc document.
35−readTWiki :: PandocMonad m
35+readTWiki :: (PandocMonad m, ToSources a)
3636 => ReaderOptions
37− -> Text
37+ -> a
3838 -> m Pandoc
3939readTWiki opts s = do
40− res <- readWithM parseTWiki def{ stateOptions = opts }
41− (crFilter s <> "\n\n")
40+ let sources = ensureFinalNewlines 2 (toSources s)
41+ res <- readWithM parseTWiki def{ stateOptions = opts } sources
4242 case res of
4343 Left e -> throwError e
4444 Right d -> return d
4545
46−type TWParser = ParserT Text ParserState
46+type TWParser = ParserT Sources ParserState
4747
4848--
4949-- utility functions
@@ -469,27 +469,7 @@ symbol :: PandocMonad m => TWParser m B.Inlines
469469symbol = B.str <$> countChar 1 nonspaceChar
470470
471471smart :: PandocMonad m => TWParser m B.Inlines
472−smart = do
473− guardEnabled Ext_smart
474− doubleQuoted <|> singleQuoted <|>
475− choice [ apostrophe
476− , dash
477− , ellipses
478− ]
479−
480−singleQuoted :: PandocMonad m => TWParser m B.Inlines
481−singleQuoted = try $ do
482− singleQuoteStart
483− withQuoteContext InSingleQuote
484− (B.singleQuoted . B.trimInlines . mconcat <$> many1Till inline singleQuoteEnd)
485−
486−doubleQuoted :: PandocMonad m => TWParser m B.Inlines
487−doubleQuoted = try $ do
488− doubleQuoteStart
489− contents <- mconcat <$> many (try $ notFollowedBy doubleQuoteEnd >> inline)
490− withQuoteContext InDoubleQuote (doubleQuoteEnd >>
491− return (B.doubleQuoted $ B.trimInlines contents))
492− <|> return (B.str "\8220" B.<> contents)
472+smart = smartPunctuation inline
493473
494474link :: PandocMonad m => TWParser m B.Inlines
495475link = try $ do
src/Text/Pandoc/Readers/Textile.hs+94−88
@@ -38,7 +38,8 @@ module Text.Pandoc.Readers.Textile ( readTextile) where
3838import Control.Monad (guard, liftM)
3939import Control.Monad.Except (throwError)
4040import Data.Char (digitToInt, isUpper)
41−import Data.List (intersperse, transpose)
41+import Data.List (intersperse, transpose, foldl')
42+import Data.List.NonEmpty (NonEmpty(..), nonEmpty)
4243import Data.Text (Text)
4344import qualified Data.Text as T
4445import Text.HTML.TagSoup (Tag (..), fromAttrib)
@@ -52,30 +53,34 @@ import Text.Pandoc.Options
5253import Text.Pandoc.Parsing
5354import Text.Pandoc.Readers.HTML (htmlTag, isBlockTag, isInlineTag)
5455import Text.Pandoc.Readers.LaTeX (rawLaTeXBlock, rawLaTeXInline)
55−import Text.Pandoc.Shared (crFilter, trim, tshow)
56+import Text.Pandoc.Shared (trim, tshow)
5657
5758-- | Parse a Textile text and return a Pandoc document.
58−readTextile :: PandocMonad m
59+readTextile :: (PandocMonad m, ToSources a)
5960 => ReaderOptions -- ^ Reader options
60− -> Text -- ^ String to parse (assuming @'\n'@ line endings)
61+ -> a
6162 -> m Pandoc
6263readTextile opts s = do
63− parsed <- readWithM parseTextile def{ stateOptions = opts }
64− (crFilter s <> "\n\n")
64+ let sources = ensureFinalNewlines 2 (toSources s)
65+ parsed <- readWithM parseTextile def{ stateOptions = opts } sources
6566 case parsed of
6667 Right result -> return result
6768 Left e -> throwError e
6869
70+type TextileParser = ParserT Sources ParserState
6971
7072-- | Generate a Pandoc ADT from a textile document
71−parseTextile :: PandocMonad m => ParserT Text ParserState m Pandoc
73+parseTextile :: PandocMonad m => TextileParser m Pandoc
7274parseTextile = do
7375 many blankline
7476 startPos <- getPosition
7577 -- go through once just to get list of reference keys and notes
7678 -- docMinusKeys is the raw document with blanks where the keys/notes were...
77− let firstPassParser = noteBlock <|> lineClump
78− manyTill firstPassParser eof >>= setInput . T.concat
79+ let firstPassParser = do
80+ pos <- getPosition
81+ t <- noteBlock <|> lineClump
82+ return (pos, t)
83+ manyTill firstPassParser eof >>= setInput . Sources
7984 setPosition startPos
8085 st' <- getState
8186 let reversedNotes = stateNotes st'
@@ -83,10 +88,10 @@ parseTextile = do
8388 -- now parse it for real...
8489 Pandoc nullMeta . B.toList <$> parseBlocks -- FIXME
8590
86−noteMarker :: PandocMonad m => ParserT Text ParserState m Text
91+noteMarker :: PandocMonad m => TextileParser m Text
8792noteMarker = skipMany spaceChar >> string "fn" >> T.pack <$> manyTill digit (char '.')
8893
89−noteBlock :: PandocMonad m => ParserT Text ParserState m Text
94+noteBlock :: PandocMonad m => TextileParser m Text
9095noteBlock = try $ do
9196 startPos <- getPosition
9297 ref <- noteMarker
@@ -101,11 +106,11 @@ noteBlock = try $ do
101106 return $ T.replicate (sourceLine endPos - sourceLine startPos) "\n"
102107
103108-- | Parse document blocks
104−parseBlocks :: PandocMonad m => ParserT Text ParserState m Blocks
109+parseBlocks :: PandocMonad m => TextileParser m Blocks
105110parseBlocks = mconcat <$> manyTill block eof
106111
107112-- | Block parsers list tried in definition order
108−blockParsers :: PandocMonad m => [ParserT Text ParserState m Blocks]
113+blockParsers :: PandocMonad m => [TextileParser m Blocks]
109114blockParsers = [ codeBlock
110115 , header
111116 , blockQuote
@@ -120,22 +125,22 @@ blockParsers = [ codeBlock
120125 ]
121126
122127-- | Any block in the order of definition of blockParsers
123−block :: PandocMonad m => ParserT Text ParserState m Blocks
128+block :: PandocMonad m => TextileParser m Blocks
124129block = do
125130 res <- choice blockParsers <?> "block"
126131 trace (T.take 60 $ tshow $ B.toList res)
127132 return res
128133
129−commentBlock :: PandocMonad m => ParserT Text ParserState m Blocks
134+commentBlock :: PandocMonad m => TextileParser m Blocks
130135commentBlock = try $ do
131136 string "###."
132137 manyTill anyLine blanklines
133138 return mempty
134139
135−codeBlock :: PandocMonad m => ParserT Text ParserState m Blocks
140+codeBlock :: PandocMonad m => TextileParser m Blocks
136141codeBlock = codeBlockTextile <|> codeBlockHtml
137142
138−codeBlockTextile :: PandocMonad m => ParserT Text ParserState m Blocks
143+codeBlockTextile :: PandocMonad m => TextileParser m Blocks
139144codeBlockTextile = try $ do
140145 string "bc." <|> string "pre."
141146 extended <- option False (True <$ char '.')
@@ -155,7 +160,7 @@ trimTrailingNewlines :: Text -> Text
155160trimTrailingNewlines = T.dropWhileEnd (=='\n')
156161
157162-- | Code Blocks in Textile are between <pre> and </pre>
158−codeBlockHtml :: PandocMonad m => ParserT Text ParserState m Blocks
163+codeBlockHtml :: PandocMonad m => TextileParser m Blocks
159164codeBlockHtml = try $ do
160165 (t@(TagOpen _ attrs),_) <- htmlTag (tagOpen (=="pre") (const True))
161166 result' <- T.pack <$> manyTill anyChar (htmlTag (tagClose (=="pre")))
@@ -173,7 +178,7 @@ codeBlockHtml = try $ do
173178 return $ B.codeBlockWith (ident,classes,kvs) result'''
174179
175180-- | Header of the form "hN. content" with N in 1..6
176−header :: PandocMonad m => ParserT Text ParserState m Blocks
181+header :: PandocMonad m => TextileParser m Blocks
177182header = try $ do
178183 char 'h'
179184 level <- digitToInt <$> oneOf "123456"
@@ -185,14 +190,14 @@ header = try $ do
185190 return $ B.headerWith attr' level name
186191
187192-- | Blockquote of the form "bq. content"
188−blockQuote :: PandocMonad m => ParserT Text ParserState m Blocks
193+blockQuote :: PandocMonad m => TextileParser m Blocks
189194blockQuote = try $ do
190195 string "bq" >> attributes >> char '.' >> whitespace
191196 B.blockQuote <$> para
192197
193198-- Horizontal rule
194199
195−hrule :: PandocMonad m => ParserT Text st m Blocks
200+hrule :: PandocMonad m => TextileParser m Blocks
196201hrule = try $ do
197202 skipSpaces
198203 start <- oneOf "-*"
@@ -207,39 +212,39 @@ hrule = try $ do
207212-- | Can be a bullet list or an ordered list. This implementation is
208213-- strict in the nesting, sublist must start at exactly "parent depth
209214-- plus one"
210−anyList :: PandocMonad m => ParserT Text ParserState m Blocks
215+anyList :: PandocMonad m => TextileParser m Blocks
211216anyList = try $ anyListAtDepth 1 <* blanklines
212217
213218-- | This allow one type of list to be nested into an other type,
214219-- provided correct nesting
215−anyListAtDepth :: PandocMonad m => Int -> ParserT Text ParserState m Blocks
220+anyListAtDepth :: PandocMonad m => Int -> TextileParser m Blocks
216221anyListAtDepth depth = choice [ bulletListAtDepth depth,
217222 orderedListAtDepth depth,
218223 definitionList ]
219224
220225-- | Bullet List of given depth, depth being the number of leading '*'
221−bulletListAtDepth :: PandocMonad m => Int -> ParserT Text ParserState m Blocks
226+bulletListAtDepth :: PandocMonad m => Int -> TextileParser m Blocks
222227bulletListAtDepth depth = try $ B.bulletList <$> many1 (bulletListItemAtDepth depth)
223228
224229-- | Bullet List Item of given depth, depth being the number of
225230-- leading '*'
226−bulletListItemAtDepth :: PandocMonad m => Int -> ParserT Text ParserState m Blocks
231+bulletListItemAtDepth :: PandocMonad m => Int -> TextileParser m Blocks
227232bulletListItemAtDepth = genericListItemAtDepth '*'
228233
229234-- | Ordered List of given depth, depth being the number of
230235-- leading '#'
231−orderedListAtDepth :: PandocMonad m => Int -> ParserT Text ParserState m Blocks
236+orderedListAtDepth :: PandocMonad m => Int -> TextileParser m Blocks
232237orderedListAtDepth depth = try $ do
233238 items <- many1 (orderedListItemAtDepth depth)
234239 return $ B.orderedList items
235240
236241-- | Ordered List Item of given depth, depth being the number of
237242-- leading '#'
238−orderedListItemAtDepth :: PandocMonad m => Int -> ParserT Text ParserState m Blocks
243+orderedListItemAtDepth :: PandocMonad m => Int -> TextileParser m Blocks
239244orderedListItemAtDepth = genericListItemAtDepth '#'
240245
241246-- | Common implementation of list items
242−genericListItemAtDepth :: PandocMonad m => Char -> Int -> ParserT Text ParserState m Blocks
247+genericListItemAtDepth :: PandocMonad m => Char -> Int -> TextileParser m Blocks
243248genericListItemAtDepth c depth = try $ do
244249 count depth (char c) >> attributes >> whitespace
245250 contents <- mconcat <$> many ((B.plain . mconcat <$> many1 inline) <|>
@@ -249,25 +254,25 @@ genericListItemAtDepth c depth = try $ do
249254 return $ contents <> sublist
250255
251256-- | A definition list is a set of consecutive definition items
252−definitionList :: PandocMonad m => ParserT Text ParserState m Blocks
257+definitionList :: PandocMonad m => TextileParser m Blocks
253258definitionList = try $ B.definitionList <$> many1 definitionListItem
254259
255260-- | List start character.
256−listStart :: PandocMonad m => ParserT Text ParserState m ()
261+listStart :: PandocMonad m => TextileParser m ()
257262listStart = genericListStart '*'
258263 <|> () <$ genericListStart '#'
259264 <|> () <$ definitionListStart
260265
261−genericListStart :: PandocMonad m => Char -> ParserT Text st m ()
266+genericListStart :: PandocMonad m => Char -> TextileParser m ()
262267genericListStart c = () <$ try (many1 (char c) >> whitespace)
263268
264−basicDLStart :: PandocMonad m => ParserT Text ParserState m ()
269+basicDLStart :: PandocMonad m => TextileParser m ()
265270basicDLStart = do
266271 char '-'
267272 whitespace
268273 notFollowedBy newline
269274
270−definitionListStart :: PandocMonad m => ParserT Text ParserState m Inlines
275+definitionListStart :: PandocMonad m => TextileParser m Inlines
271276definitionListStart = try $ do
272277 basicDLStart
273278 trimInlines . mconcat <$>
@@ -280,15 +285,15 @@ definitionListStart = try $ do
280285-- the term defined, then spaces and ":=". The definition follows, on
281286-- the same single line, or spaned on multiple line, after a line
282287-- break.
283−definitionListItem :: PandocMonad m => ParserT Text ParserState m (Inlines, [Blocks])
288+definitionListItem :: PandocMonad m => TextileParser m (Inlines, [Blocks])
284289definitionListItem = try $ do
285290 term <- mconcat . intersperse B.linebreak <$> many1 definitionListStart
286291 def' <- string ":=" *> optional whitespace *> (multilineDef <|> inlineDef)
287292 return (term, def')
288− where inlineDef :: PandocMonad m => ParserT Text ParserState m [Blocks]
293+ where inlineDef :: PandocMonad m => TextileParser m [Blocks]
289294 inlineDef = liftM (\d -> [B.plain d])
290295 $ optional whitespace >> (trimInlines . mconcat <$> many inline) <* newline
291− multilineDef :: PandocMonad m => ParserT Text ParserState m [Blocks]
296+ multilineDef :: PandocMonad m => TextileParser m [Blocks]
292297 multilineDef = try $ do
293298 optional whitespace >> newline
294299 s <- T.pack <$> many1Till anyChar (try (string "=:" >> newline))
@@ -299,7 +304,7 @@ definitionListItem = try $ do
299304-- raw content
300305
301306-- | A raw Html Block, optionally followed by blanklines
302−rawHtmlBlock :: PandocMonad m => ParserT Text ParserState m Blocks
307+rawHtmlBlock :: PandocMonad m => TextileParser m Blocks
303308rawHtmlBlock = try $ do
304309 skipMany spaceChar
305310 (_,b) <- htmlTag isBlockTag
@@ -307,14 +312,14 @@ rawHtmlBlock = try $ do
307312 return $ B.rawBlock "html" b
308313
309314-- | Raw block of LaTeX content
310−rawLaTeXBlock' :: PandocMonad m => ParserT Text ParserState m Blocks
315+rawLaTeXBlock' :: PandocMonad m => TextileParser m Blocks
311316rawLaTeXBlock' = do
312317 guardEnabled Ext_raw_tex
313318 B.rawBlock "latex" <$> (rawLaTeXBlock <* spaces)
314319
315320
316321-- | In textile, paragraphs are separated by blank lines.
317−para :: PandocMonad m => ParserT Text ParserState m Blocks
322+para :: PandocMonad m => TextileParser m Blocks
318323para = B.para . trimInlines . mconcat <$> many1 inline
319324
320325-- Tables
@@ -325,7 +330,7 @@ toAlignment '>' = AlignRight
325330toAlignment '=' = AlignCenter
326331toAlignment _ = AlignDefault
327332
328−cellAttributes :: PandocMonad m => ParserT Text ParserState m (Bool, Alignment)
333+cellAttributes :: PandocMonad m => TextileParser m (Bool, Alignment)
329334cellAttributes = try $ do
330335 isHeader <- option False (True <$ char '_')
331336 -- we just ignore colspan and rowspan markers:
@@ -338,7 +343,7 @@ cellAttributes = try $ do
338343 return (isHeader, alignment)
339344
340345-- | A table cell spans until a pipe |
341−tableCell :: PandocMonad m => ParserT Text ParserState m ((Bool, Alignment), Blocks)
346+tableCell :: PandocMonad m => TextileParser m ((Bool, Alignment), Blocks)
342347tableCell = try $ do
343348 char '|'
344349 (isHeader, alignment) <- option (False, AlignDefault) cellAttributes
@@ -349,7 +354,7 @@ tableCell = try $ do
349354 return ((isHeader, alignment), B.plain content)
350355
351356-- | A table row is made of many table cells
352−tableRow :: PandocMonad m => ParserT Text ParserState m [((Bool, Alignment), Blocks)]
357+tableRow :: PandocMonad m => TextileParser m [((Bool, Alignment), Blocks)]
353358tableRow = try $ do
354359 -- skip optional row attributes
355360 optional $ try $ do
@@ -359,7 +364,7 @@ tableRow = try $ do
359364 many1 tableCell <* char '|' <* blankline
360365
361366-- | A table with an optional header.
362−table :: PandocMonad m => ParserT Text ParserState m Blocks
367+table :: PandocMonad m => TextileParser m Blocks
363368table = try $ do
364369 -- ignore table attributes
365370 caption <- option mempty $ try $ do
@@ -375,8 +380,9 @@ table = try $ do
375380 (toprow:rest) | any (fst . fst) toprow ->
376381 (toprow, rest)
377382 _ -> (mempty, rawrows)
378− let nbOfCols = maximum $ map length (headers:rows)
379− let aligns = map minimum $ transpose $ map (map (snd . fst)) (headers:rows)
383+ let nbOfCols = maximum $ fmap length (headers :| rows)
384+ let aligns = map (maybe AlignDefault minimum . nonEmpty) $
385+ transpose $ map (map (snd . fst)) (headers:rows)
380386 let toRow = Row nullAttr . map B.simpleCell
381387 toHeaderRow l = [toRow l | not (null l)]
382388 return $ B.table (B.simpleCaption $ B.plain caption)
@@ -386,7 +392,7 @@ table = try $ do
386392 (TableFoot nullAttr [])
387393
388394-- | Ignore markers for cols, thead, tfoot.
389−ignorableRow :: PandocMonad m => ParserT Text ParserState m ()
395+ignorableRow :: PandocMonad m => TextileParser m ()
390396ignorableRow = try $ do
391397 char '|'
392398 oneOf ":^-~"
@@ -395,7 +401,7 @@ ignorableRow = try $ do
395401 _ <- anyLine
396402 return ()
397403
398−explicitBlockStart :: PandocMonad m => Text -> ParserT Text ParserState m ()
404+explicitBlockStart :: PandocMonad m => Text -> TextileParser m ()
399405explicitBlockStart name = try $ do
400406 string (T.unpack name)
401407 attributes
@@ -407,8 +413,8 @@ explicitBlockStart name = try $ do
407413-- However, they can be used to set HTML/CSS attributes when needed.
408414maybeExplicitBlock :: PandocMonad m
409415 => Text -- ^ block tag name
410− -> ParserT Text ParserState m Blocks -- ^ implicit block
411− -> ParserT Text ParserState m Blocks
416+ -> TextileParser m Blocks -- ^ implicit block
417+ -> TextileParser m Blocks
412418maybeExplicitBlock name blk = try $ do
413419 optional $ explicitBlockStart name
414420 blk
@@ -421,11 +427,11 @@ maybeExplicitBlock name blk = try $ do
421427
422428
423429-- | Any inline element
424−inline :: PandocMonad m => ParserT Text ParserState m Inlines
430+inline :: PandocMonad m => TextileParser m Inlines
425431inline = choice inlineParsers <?> "inline"
426432
427433-- | Inline parsers tried in order
428−inlineParsers :: PandocMonad m => [ParserT Text ParserState m Inlines]
434+inlineParsers :: PandocMonad m => [TextileParser m Inlines]
429435inlineParsers = [ str
430436 , whitespace
431437 , endline
@@ -445,7 +451,7 @@ inlineParsers = [ str
445451 ]
446452
447453-- | Inline markups
448−inlineMarkup :: PandocMonad m => ParserT Text ParserState m Inlines
454+inlineMarkup :: PandocMonad m => TextileParser m Inlines
449455inlineMarkup = choice [ simpleInline (string "??") (B.cite [])
450456 , simpleInline (string "**") B.strong
451457 , simpleInline (string "__") B.emph
@@ -459,29 +465,29 @@ inlineMarkup = choice [ simpleInline (string "??") (B.cite [])
459465 ]
460466
461467-- | Trademark, registered, copyright
462−mark :: PandocMonad m => ParserT Text st m Inlines
468+mark :: PandocMonad m => TextileParser m Inlines
463469mark = try $ char '(' >> (try tm <|> try reg <|> copy)
464470
465−reg :: PandocMonad m => ParserT Text st m Inlines
471+reg :: PandocMonad m => TextileParser m Inlines
466472reg = do
467473 oneOf "Rr"
468474 char ')'
469475 return $ B.str "\174"
470476
471−tm :: PandocMonad m => ParserT Text st m Inlines
477+tm :: PandocMonad m => TextileParser m Inlines
472478tm = do
473479 oneOf "Tt"
474480 oneOf "Mm"
475481 char ')'
476482 return $ B.str "\8482"
477483
478−copy :: PandocMonad m => ParserT Text st m Inlines
484+copy :: PandocMonad m => TextileParser m Inlines
479485copy = do
480486 oneOf "Cc"
481487 char ')'
482488 return $ B.str "\169"
483489
484−note :: PandocMonad m => ParserT Text ParserState m Inlines
490+note :: PandocMonad m => TextileParser m Inlines
485491note = try $ do
486492 ref <- char '[' *> many1 digit <* char ']'
487493 notes <- stateNotes <$> getState
@@ -505,13 +511,13 @@ wordBoundaries :: [Char]
505511wordBoundaries = markupChars <> stringBreakers
506512
507513-- | Parse a hyphened sequence of words
508−hyphenedWords :: PandocMonad m => ParserT Text ParserState m Text
514+hyphenedWords :: PandocMonad m => TextileParser m Text
509515hyphenedWords = do
510516 x <- wordChunk
511517 xs <- many (try $ char '-' >> wordChunk)
512518 return $ T.intercalate "-" (x:xs)
513519
514−wordChunk :: PandocMonad m => ParserT Text ParserState m Text
520+wordChunk :: PandocMonad m => TextileParser m Text
515521wordChunk = try $ do
516522 hd <- noneOf wordBoundaries
517523 tl <- many ( noneOf wordBoundaries <|>
@@ -520,7 +526,7 @@ wordChunk = try $ do
520526 return $ T.pack $ hd:tl
521527
522528-- | Any string
523−str :: PandocMonad m => ParserT Text ParserState m Inlines
529+str :: PandocMonad m => TextileParser m Inlines
524530str = do
525531 baseStr <- hyphenedWords
526532 -- RedCloth compliance : if parsed word is uppercase and immediately
@@ -533,11 +539,11 @@ str = do
533539 return $ B.str fullStr
534540
535541-- | Some number of space chars
536−whitespace :: PandocMonad m => ParserT Text st m Inlines
542+whitespace :: PandocMonad m => TextileParser m Inlines
537543whitespace = many1 spaceChar >> return B.space <?> "whitespace"
538544
539545-- | In Textile, an isolated endline character is a line break
540−endline :: PandocMonad m => ParserT Text ParserState m Inlines
546+endline :: PandocMonad m => TextileParser m Inlines
541547endline = try $ do
542548 newline
543549 notFollowedBy blankline
@@ -545,18 +551,18 @@ endline = try $ do
545551 notFollowedBy rawHtmlBlock
546552 return B.linebreak
547553
548−rawHtmlInline :: PandocMonad m => ParserT Text ParserState m Inlines
554+rawHtmlInline :: PandocMonad m => TextileParser m Inlines
549555rawHtmlInline = B.rawInline "html" . snd <$> htmlTag isInlineTag
550556
551557-- | Raw LaTeX Inline
552−rawLaTeXInline' :: PandocMonad m => ParserT Text ParserState m Inlines
558+rawLaTeXInline' :: PandocMonad m => TextileParser m Inlines
553559rawLaTeXInline' = try $ do
554560 guardEnabled Ext_raw_tex
555561 B.rawInline "latex" <$> rawLaTeXInline
556562
557563-- | Textile standard link syntax is "label":target. But we
558564-- can also have ["label":target].
559−link :: PandocMonad m => ParserT Text ParserState m Inlines
565+link :: PandocMonad m => TextileParser m Inlines
560566link = try $ do
561567 bracketed <- (True <$ char '[') <|> return False
562568 char '"' *> notFollowedBy (oneOf " \t\n\r")
@@ -576,7 +582,7 @@ link = try $ do
576582 else B.spanWith attr $ B.link url "" name'
577583
578584-- | image embedding
579−image :: PandocMonad m => ParserT Text ParserState m Inlines
585+image :: PandocMonad m => TextileParser m Inlines
580586image = try $ do
581587 char '!' >> notFollowedBy space
582588 (ident, cls, kvs) <- attributes
@@ -588,51 +594,51 @@ image = try $ do
588594 char '!'
589595 return $ B.imageWith attr src alt (B.str alt)
590596
591−escapedInline :: PandocMonad m => ParserT Text ParserState m Inlines
597+escapedInline :: PandocMonad m => TextileParser m Inlines
592598escapedInline = escapedEqs <|> escapedTag
593599
594−escapedEqs :: PandocMonad m => ParserT Text ParserState m Inlines
600+escapedEqs :: PandocMonad m => TextileParser m Inlines
595601escapedEqs = B.str . T.pack <$>
596602 try (string "==" *> manyTill anyChar' (try $ string "=="))
597603
598604-- | literal text escaped btw <notextile> tags
599−escapedTag :: PandocMonad m => ParserT Text ParserState m Inlines
605+escapedTag :: PandocMonad m => TextileParser m Inlines
600606escapedTag = B.str . T.pack <$>
601607 try (string "<notextile>" *>
602608 manyTill anyChar' (try $ string "</notextile>"))
603609
604610-- | Any special symbol defined in wordBoundaries
605−symbol :: PandocMonad m => ParserT Text ParserState m Inlines
611+symbol :: PandocMonad m => TextileParser m Inlines
606612symbol = B.str . T.singleton <$> (notFollowedBy newline *>
607613 notFollowedBy rawHtmlBlock *>
608614 oneOf wordBoundaries)
609615
610616-- | Inline code
611−code :: PandocMonad m => ParserT Text ParserState m Inlines
617+code :: PandocMonad m => TextileParser m Inlines
612618code = code1 <|> code2
613619
614620-- any character except a newline before a blank line
615−anyChar' :: PandocMonad m => ParserT Text ParserState m Char
621+anyChar' :: PandocMonad m => TextileParser m Char
616622anyChar' =
617623 satisfy (/='\n') <|>
618624 try (char '\n' <* notFollowedBy blankline)
619625
620−code1 :: PandocMonad m => ParserT Text ParserState m Inlines
626+code1 :: PandocMonad m => TextileParser m Inlines
621627code1 = B.code . T.pack <$> surrounded (char '@') anyChar'
622628
623−code2 :: PandocMonad m => ParserT Text ParserState m Inlines
629+code2 :: PandocMonad m => TextileParser m Inlines
624630code2 = do
625631 htmlTag (tagOpen (=="tt") null)
626632 B.code . T.pack <$> manyTill anyChar' (try $ htmlTag $ tagClose (=="tt"))
627633
628634-- | Html / CSS attributes
629−attributes :: PandocMonad m => ParserT Text ParserState m Attr
630−attributes = foldl (flip ($)) ("",[],[]) <$>
635+attributes :: PandocMonad m => TextileParser m Attr
636+attributes = foldl' (flip ($)) ("",[],[]) <$>
631637 try (do special <- option id specialAttribute
632638 attrs <- many attribute
633639 return (special : attrs))
634640
635−specialAttribute :: PandocMonad m => ParserT Text ParserState m (Attr -> Attr)
641+specialAttribute :: PandocMonad m => TextileParser m (Attr -> Attr)
636642specialAttribute = do
637643 alignStr <- ("center" <$ char '=') <|>
638644 ("justify" <$ try (string "<>")) <|>
@@ -641,11 +647,11 @@ specialAttribute = do
641647 notFollowedBy spaceChar
642648 return $ addStyle $ T.pack $ "text-align:" ++ alignStr
643649
644−attribute :: PandocMonad m => ParserT Text ParserState m (Attr -> Attr)
650+attribute :: PandocMonad m => TextileParser m (Attr -> Attr)
645651attribute = try $
646652 (classIdAttr <|> styleAttr <|> langAttr) <* notFollowedBy spaceChar
647653
648−classIdAttr :: PandocMonad m => ParserT Text ParserState m (Attr -> Attr)
654+classIdAttr :: PandocMonad m => TextileParser m (Attr -> Attr)
649655classIdAttr = try $ do -- (class class #id)
650656 char '('
651657 ws <- T.words `fmap` T.pack <$> manyTill anyChar' (char ')')
@@ -657,7 +663,7 @@ classIdAttr = try $ do -- (class class #id)
657663 classes'
658664 -> return $ \(_,_,keyvals) -> ("",classes',keyvals)
659665
660−styleAttr :: PandocMonad m => ParserT Text ParserState m (Attr -> Attr)
666+styleAttr :: PandocMonad m => TextileParser m (Attr -> Attr)
661667styleAttr = do
662668 style <- try $ enclosed (char '{') (char '}') anyChar'
663669 return $ addStyle $ T.pack style
@@ -668,23 +674,23 @@ addStyle style (id',classes,keyvals) =
668674 where keyvals' = ("style", style') : [(k,v) | (k,v) <- keyvals, k /= "style"]
669675 style' = style <> ";" <> T.concat [v | ("style",v) <- keyvals]
670676
671−langAttr :: PandocMonad m => ParserT Text ParserState m (Attr -> Attr)
677+langAttr :: PandocMonad m => TextileParser m (Attr -> Attr)
672678langAttr = do
673679 lang <- try $ enclosed (char '[') (char ']') alphaNum
674680 return $ \(id',classes,keyvals) -> (id',classes,("lang",T.pack lang):keyvals)
675681
676682-- | Parses material surrounded by a parser.
677683surrounded :: (PandocMonad m, Show t)
678− => ParserT Text st m t -- ^ surrounding parser
679− -> ParserT Text st m a -- ^ content parser (to be used repeatedly)
680− -> ParserT Text st m [a]
684+ => ParserT Sources st m t -- ^ surrounding parser
685+ -> ParserT Sources st m a -- ^ content parser (to be used repeatedly)
686+ -> ParserT Sources st m [a]
681687surrounded border =
682688 enclosed (border *> notFollowedBy (oneOf " \t\n\r")) (try border)
683689
684690simpleInline :: PandocMonad m
685− => ParserT Text ParserState m t -- ^ surrounding parser
691+ => TextileParser m t -- ^ surrounding parser
686692 -> (Inlines -> Inlines) -- ^ Inline constructor
687− -> ParserT Text ParserState m Inlines -- ^ content parser (to be used repeatedly)
693+ -> TextileParser m Inlines -- ^ content parser (to be used repeatedly)
688694simpleInline border construct = try $ do
689695 notAfterString
690696 border *> notFollowedBy (oneOf " \t\n\r")
@@ -698,7 +704,7 @@ simpleInline border construct = try $ do
698704 then body
699705 else B.spanWith attr body
700706
701−groupedInlineMarkup :: PandocMonad m => ParserT Text ParserState m Inlines
707+groupedInlineMarkup :: PandocMonad m => TextileParser m Inlines
702708groupedInlineMarkup = try $ do
703709 char '['
704710 sp1 <- option mempty $ B.space <$ whitespace
@@ -707,5 +713,5 @@ groupedInlineMarkup = try $ do
707713 char ']'
708714 return $ sp1 <> result <> sp2
709715
710−eof' :: Monad m => ParserT Text s m Char
716+eof' :: Monad m => ParserT Sources s m Char
711717eof' = '\n' <$ eof
src/Text/Pandoc/Readers/TikiWiki.hs+6−6
@@ -30,23 +30,23 @@ import Text.Pandoc.Definition
3030import Text.Pandoc.Logging (Verbosity (..))
3131import Text.Pandoc.Options
3232import Text.Pandoc.Parsing hiding (enclosed, nested)
33−import Text.Pandoc.Shared (crFilter, safeRead)
33+import Text.Pandoc.Shared (safeRead)
3434import Text.Pandoc.XML (fromEntities)
3535import Text.Printf (printf)
3636
3737-- | Read TikiWiki from an input string and return a Pandoc document.
38−readTikiWiki :: PandocMonad m
38+readTikiWiki :: (PandocMonad m, ToSources a)
3939 => ReaderOptions
40− -> Text
40+ -> a
4141 -> m Pandoc
4242readTikiWiki opts s = do
43− res <- readWithM parseTikiWiki def{ stateOptions = opts }
44− (crFilter s <> "\n\n")
43+ let sources = ensureFinalNewlines 2 (toSources s)
44+ res <- readWithM parseTikiWiki def{ stateOptions = opts } sources
4545 case res of
4646 Left e -> throwError e
4747 Right d -> return d
4848
49−type TikiWikiParser = ParserT Text ParserState
49+type TikiWikiParser = ParserT Sources ParserState
5050
5151--
5252-- utility functions
src/Text/Pandoc/Readers/Txt2Tags.hs+47−21
@@ -1,4 +1,5 @@
11{-# LANGUAGE OverloadedStrings #-}
2+{-# LANGUAGE LambdaCase #-}
23{- |
34 Module : Text.Pandoc.Readers.Txt2Tags
45 Copyright : Copyright (C) 2014 Matthew Pickering
@@ -19,6 +20,7 @@ import Control.Monad.Except (catchError, throwError)
1920import Control.Monad.Reader (Reader, asks, runReader)
2021import Data.Default
2122import Data.List (intercalate, transpose)
23+import Data.List.NonEmpty (nonEmpty)
2224import Data.Maybe (fromMaybe)
2325import Data.Text (Text)
2426import qualified Data.Text as T
@@ -31,9 +33,9 @@ import Data.Time (defaultTimeLocale)
3133import Text.Pandoc.Definition
3234import Text.Pandoc.Options
3335import Text.Pandoc.Parsing hiding (space, spaces, uri)
34−import Text.Pandoc.Shared (compactify, compactifyDL, crFilter, escapeURI)
36+import Text.Pandoc.Shared (compactify, compactifyDL, escapeURI)
3537
36−type T2T = ParserT Text ParserState (Reader T2TMeta)
38+type T2T = ParserT Sources ParserState (Reader T2TMeta)
3739
3840-- | An object for the T2T macros meta information
3941-- the contents of each field is simply substituted verbatim into the file
@@ -53,25 +55,28 @@ getT2TMeta = do
5355 inps <- P.getInputFiles
5456 outp <- fromMaybe "" <$> P.getOutputFile
5557 curDate <- formatTime defaultTimeLocale "%F" <$> P.getZonedTime
56− let getModTime = fmap (formatTime defaultTimeLocale "%T") .
57− P.getModificationTime
58− curMtime <- case inps of
59− [] -> formatTime defaultTimeLocale "%T" <$> P.getZonedTime
60− _ -> catchError
61− (maximum <$> mapM getModTime inps)
62− (const (return ""))
63− return $ T2TMeta (T.pack curDate) (T.pack curMtime) (intercalate ", " inps) outp
58+ curMtime <- catchError
59+ (mapM P.getModificationTime inps >>=
60+ (\case
61+ Nothing ->
62+ formatTime defaultTimeLocale "%T" <$> P.getZonedTime
63+ Just ts -> return $
64+ formatTime defaultTimeLocale "%T" $ maximum ts)
65+ . nonEmpty)
66+ (const (return ""))
67+ return $ T2TMeta (T.pack curDate) (T.pack curMtime)
68+ (intercalate ", " inps) outp
6469
6570-- | Read Txt2Tags from an input string returning a Pandoc document
66−readTxt2Tags :: PandocMonad m
71+readTxt2Tags :: (PandocMonad m, ToSources a)
6772 => ReaderOptions
68− -> Text
73+ -> a
6974 -> m Pandoc
7075readTxt2Tags opts s = do
76+ let sources = ensureFinalNewlines 2 (toSources s)
7177 meta <- getT2TMeta
7278 let parsed = flip runReader meta $
73− readWithM parseT2T (def {stateOptions = opts}) $
74− crFilter s <> "\n\n"
79+ readWithM parseT2T (def {stateOptions = opts}) sources
7580 case parsed of
7681 Right result -> return result
7782 Left e -> throwError e
@@ -261,9 +266,9 @@ table = try $ do
261266 rows <- many1 (many commentLine *> tableRow)
262267 let columns = transpose rows
263268 let ncolumns = length columns
264− let aligns = map (foldr1 findAlign . map fst) columns
269+ let aligns = map (fromMaybe AlignDefault . foldr findAlign Nothing) columns
265270 let rows' = map (map snd) rows
266− let size = maximum (map length rows')
271+ let size = maybe 0 maximum $ nonEmpty $ map length rows'
267272 let rowsPadded = map (pad size) rows'
268273 let headerPadded = if null tableHeader then mempty else pad size tableHeader
269274 let toRow = Row nullAttr . map B.simpleCell
@@ -278,10 +283,11 @@ pad :: (Monoid a) => Int -> [a] -> [a]
278283pad n xs = xs ++ replicate (n - length xs) mempty
279284
280285
281−findAlign :: Alignment -> Alignment -> Alignment
282−findAlign x y
283− | x == y = x
284− | otherwise = AlignDefault
286+findAlign :: (Alignment, a) -> Maybe Alignment -> Maybe Alignment
287+findAlign (x,_) (Just y)
288+ | x == y = Just x
289+ | otherwise = Just AlignDefault
290+findAlign (x,_) Nothing = Just x
285291
286292headerRow :: T2T [(Alignment, Blocks)]
287293headerRow = genericRow (string "||")
@@ -472,9 +478,29 @@ macro = try $ do
472478-- raw URLs in text are automatically linked
473479url :: T2T Inlines
474480url = try $ do
475− (rawUrl, escapedUrl) <- try uri <|> emailAddress
481+ (rawUrl, escapedUrl) <- try uri <|> emailAddress'
476482 return $ B.link rawUrl "" (B.str escapedUrl)
477483
484+emailAddress' :: T2T (Text, Text)
485+emailAddress' = do
486+ (base, mailURI) <- emailAddress
487+ query <- option "" emailQuery
488+ return (base <> query, mailURI <> query)
489+
490+emailQuery :: T2T Text
491+emailQuery = do
492+ char '?'
493+ parts <- kv `sepBy1` (char '&')
494+ return $ "?" <> T.intercalate "&" parts
495+
496+kv :: T2T Text
497+kv = do
498+ k <- T.pack <$> many1 alphaNum
499+ char '='
500+ let vchar = alphaNum <|> try (oneOf "%._/~:,=$@&+-;*" <* lookAhead alphaNum)
501+ v <- T.pack <$> many1 vchar
502+ return (k <> "=" <> v)
503+
478504uri :: T2T (Text, Text)
479505uri = try $ do
480506 address <- t2tURI
src/Text/Pandoc/Readers/Vimwiki.hs+12−7
@@ -74,23 +74,28 @@ import Text.Pandoc.Parsing (ParserState, ParserT, blanklines, emailAddress,
7474 many1Till, orderedListMarker, readWithM,
7575 registerHeader, spaceChar, stateMeta,
7676 stateOptions, uri, manyTillChar, manyChar, textStr,
77− many1Char, countChar, many1TillChar)
78−import Text.Pandoc.Shared (crFilter, splitTextBy, stringify, stripFirstAndLast,
77+ many1Char, countChar, many1TillChar,
78+ alphaNum, anyChar, char, newline, noneOf, oneOf,
79+ space, spaces, string)
80+import Text.Pandoc.Sources (ToSources(..), Sources)
81+import Text.Pandoc.Shared (splitTextBy, stringify, stripFirstAndLast,
7982 isURI, tshow)
80−import Text.Parsec.Char (alphaNum, anyChar, char, newline, noneOf, oneOf, space,
81− spaces, string)
8283import Text.Parsec.Combinator (between, choice, eof, lookAhead, many1,
8384 manyTill, notFollowedBy, option, skipMany1)
8485import Text.Parsec.Prim (getState, many, try, updateState, (<|>))
8586
86−readVimwiki :: PandocMonad m => ReaderOptions -> Text -> m Pandoc
87+readVimwiki :: (PandocMonad m, ToSources a)
88+ => ReaderOptions
89+ -> a
90+ -> m Pandoc
8791readVimwiki opts s = do
88− res <- readWithM parseVimwiki def{ stateOptions = opts } $ crFilter s
92+ let sources = toSources s
93+ res <- readWithM parseVimwiki def{ stateOptions = opts } sources
8994 case res of
9095 Left e -> throwError e
9196 Right result -> return result
9297
93−type VwParser = ParserT Text ParserState
98+type VwParser = ParserT Sources ParserState
9499
95100
96101-- constants
src/Text/Pandoc/SelfContained.hs+4−7
@@ -16,7 +16,6 @@ the HTML using data URIs.
1616module Text.Pandoc.SelfContained ( makeDataURI, makeSelfContained ) where
1717import Codec.Compression.GZip as Gzip
1818import Control.Applicative ((<|>))
19−import Control.Monad.Except (throwError)
2019import Control.Monad.Trans (lift)
2120import Data.ByteString (ByteString)
2221import Data.ByteString.Base64
@@ -29,7 +28,6 @@ import System.FilePath (takeDirectory, takeExtension, (</>))
2928import Text.HTML.TagSoup
3029import Text.Pandoc.Class.PandocMonad (PandocMonad (..), fetchItem,
3130 getInputFiles, report, setInputFiles)
32−import Text.Pandoc.Error
3331import Text.Pandoc.Logging
3432import Text.Pandoc.MIME (MimeType)
3533import Text.Pandoc.Shared (isURI, renderTags', trim)
@@ -244,11 +242,10 @@ getData mimetype src
244242 let raw' = if ext `elem` [".gz", ".svgz"]
245243 then B.concat $ L.toChunks $ Gzip.decompress $ L.fromChunks [raw]
246244 else raw
247− mime <- case (mimetype, respMime) of
248− ("",Nothing) -> throwError $ PandocSomeError
249− $ "Could not determine mime type for `" <> src <> "'"
250− (x, Nothing) -> return x
251− (_, Just x ) -> return x
245+ let mime = case (mimetype, respMime) of
246+ ("",Nothing) -> "application/octet-stream"
247+ (x, Nothing) -> x
248+ (_, Just x ) -> x
252249 result <- if "text/css" `T.isPrefixOf` mime
253250 then do
254251 oldInputs <- getInputFiles
src/Text/Pandoc/Shared.hs+41−64
@@ -25,11 +25,7 @@ module Text.Pandoc.Shared (
2525 ordNub,
2626 findM,
2727 -- * Text processing
28− ToString (..),
29− ToText (..),
3028 tshow,
31− backslashEscapes,
32− escapeStringUsing,
3329 elemText,
3430 notElemText,
3531 stripTrailingNewlines,
@@ -95,7 +91,7 @@ module Text.Pandoc.Shared (
9591 safeRead,
9692 safeStrRead,
9793 -- * User data directory
98− defaultUserDataDirs,
94+ defaultUserDataDir,
9995 -- * Version
10096 pandocVersion
10197 ) where
@@ -109,7 +105,7 @@ import qualified Data.Bifunctor as Bifunctor
109105import Data.Char (isAlpha, isLower, isSpace, isUpper, toLower, isAlphaNum,
110106 generalCategory, GeneralCategory(NonSpacingMark,
111107 SpacingCombiningMark, EnclosingMark, ConnectorPunctuation))
112−import Data.List (find, intercalate, intersperse, sortOn)
108+import Data.List (find, intercalate, intersperse, sortOn, foldl')
113109import qualified Data.Map as M
114110import Data.Maybe (mapMaybe, fromMaybe)
115111import Data.Monoid (Any (..))
@@ -127,7 +123,7 @@ import Text.HTML.TagSoup (RenderOptions (..), Tag (..), renderOptions,
127123import Text.Pandoc.Builder (Blocks, Inlines, ToMetaValue (..))
128124import qualified Text.Pandoc.Builder as B
129125import Data.Time
130−import Text.Pandoc.Asciify (toAsciiChar)
126+import Text.Pandoc.Asciify (toAsciiText)
131127import Text.Pandoc.Definition
132128import Text.Pandoc.Extensions (Extensions, Extension(..), extensionEnabled)
133129import Text.Pandoc.Generic (bottomUp)
@@ -157,12 +153,20 @@ splitTextBy isSep t
157153 in first : splitTextBy isSep (T.dropWhile isSep rest)
158154
159155splitTextByIndices :: [Int] -> T.Text -> [T.Text]
160−splitTextByIndices ns = splitTextByRelIndices (zipWith (-) ns (0:ns))
156+splitTextByIndices ns = splitTextByRelIndices (zipWith (-) ns (0:ns)) . T.unpack
161157 where
162− splitTextByRelIndices [] t = [t]
163− splitTextByRelIndices (x:xs) t =
164− let (first, rest) = T.splitAt x t
165− in first : splitTextByRelIndices xs rest
158+ splitTextByRelIndices [] cs = [T.pack cs]
159+ splitTextByRelIndices (x:xs) cs =
160+ let (first, rest) = splitAt' x cs
161+ in T.pack first : splitTextByRelIndices xs rest
162+
163+-- Note: don't replace this with T.splitAt, which is not sensitive
164+-- to character widths!
165+splitAt' :: Int -> [Char] -> ([Char],[Char])
166+splitAt' _ [] = ([],[])
167+splitAt' n xs | n <= 0 = ([],xs)
168+splitAt' n (x:xs) = (x:ys,zs)
169+ where (ys,zs) = splitAt' (n - charWidth x) xs
166170
167171ordNub :: (Ord a) => [a] -> [a]
168172ordNub l = go Set.empty l
@@ -183,38 +187,9 @@ findM p = foldr go (pure Nothing)
183187-- Text processing
184188--
185189
186−class ToString a where
187− toString :: a -> String
188−
189−instance ToString String where
190− toString = id
191−
192−instance ToString T.Text where
193− toString = T.unpack
194−
195−class ToText a where
196− toText :: a -> T.Text
197−
198−instance ToText String where
199− toText = T.pack
200−
201−instance ToText T.Text where
202− toText = id
203−
204190tshow :: Show a => a -> T.Text
205191tshow = T.pack . show
206192
207−-- | Returns an association list of backslash escapes for the
208−-- designated characters.
209−backslashEscapes :: [Char] -- ^ list of special characters to escape
210− -> [(Char, T.Text)]
211−backslashEscapes = map (\ch -> (ch, T.pack ['\\',ch]))
212−
213−-- | Escape a string of characters, using an association list of
214−-- characters and strings.
215−escapeStringUsing :: [(Char, T.Text)] -> T.Text -> T.Text
216−escapeStringUsing tbl = T.concatMap $ \c -> fromMaybe (T.singleton c) $ lookup c tbl
217−
218193-- | @True@ exactly when the @Char@ appears in the @Text@.
219194elemText :: Char -> T.Text -> Bool
220195elemText c = T.any (== c)
@@ -323,6 +298,7 @@ tabFilter tabStop = T.unlines . map go . T.lines
323298 (tabStop - (T.length s1 `mod` tabStop)) (T.pack " ")
324299 <> go (T.drop 1 s2)
325300
301+{-# DEPRECATED crFilter "readers filter crs automatically" #-}
326302-- | Strip out DOS line endings.
327303crFilter :: T.Text -> T.Text
328304crFilter = T.filter (/= '\r')
@@ -464,22 +440,20 @@ plainToPara :: Block -> Block
464440plainToPara (Plain ils) = Para ils
465441plainToPara x = x
466442
443+
467444-- | Like @compactify@, but acts on items of definition lists.
468445compactifyDL :: [(Inlines, [Blocks])] -> [(Inlines, [Blocks])]
469446compactifyDL items =
470− let defs = concatMap snd items
471− in case reverse (concatMap B.toList defs) of
472− (Para x:xs)
473− | not (any isPara xs) ->
474− let (t,ds) = last items
475− lastDef = B.toList $ last ds
476− ds' = init ds ++
477− if null lastDef
478− then [B.fromList lastDef]
479− else [B.fromList $ init lastDef ++ [Plain x]]
480− in init items ++ [(t, ds')]
481− | otherwise -> items
482− _ -> items
447+ case reverse items of
448+ ((t,ds):ys) ->
449+ case reverse (map (reverse . B.toList) ds) of
450+ ((Para x:xs) : zs) | not (any isPara xs) ->
451+ reverse ys ++
452+ [(t, reverse (map B.fromList zs) ++
453+ [B.fromList (reverse (Plain x:xs))])]
454+ _ -> items
455+ _ -> items
456+
483457
484458-- | Combine a list of lines by adding hard linebreaks.
485459combineLines :: [[Inline]] -> [Inline]
@@ -513,7 +487,7 @@ inlineListToIdentifier exts =
513487 | otherwise = T.dropWhile (not . isAlpha)
514488 filterAscii
515489 | extensionEnabled Ext_ascii_identifiers exts
516− = T.pack . mapMaybe toAsciiChar . T.unpack
490+ = toAsciiText
517491 | otherwise = id
518492 toIdent
519493 | extensionEnabled Ext_gfm_auto_identifiers exts =
@@ -842,7 +816,7 @@ mapLeft = Bifunctor.first
842816-- > collapseFilePath "parent/foo/.." == "parent"
843817-- > collapseFilePath "/parent/foo/../../bar" == "/bar"
844818collapseFilePath :: FilePath -> FilePath
845−collapseFilePath = Posix.joinPath . reverse . foldl go [] . splitDirectories
819+collapseFilePath = Posix.joinPath . reverse . foldl' go [] . splitDirectories
846820 where
847821 go rs "." = rs
848822 go r@(p:rs) ".." = case p of
@@ -879,7 +853,6 @@ filteredFilesFromArchive zf f =
879853 fileAndBinary :: Archive -> FilePath -> Maybe (FilePath, BL.ByteString)
880854 fileAndBinary a fp = findEntryByPath fp a >>= \e -> Just (fp, fromEntry e)
881855
882−
883856--
884857-- IANA URIs
885858--
@@ -1012,12 +985,16 @@ safeStrRead s = case reads s of
1012985--
1013986
1014987-- | Return appropriate user data directory for platform. We use
1015−-- XDG_DATA_HOME (or its default value), but fall back to the
1016−-- legacy user data directory ($HOME/.pandoc on *nix) if this is
1017−-- missing.
1018−defaultUserDataDirs :: IO [FilePath]
1019−defaultUserDataDirs = E.catch (do
988+-- XDG_DATA_HOME (or its default value), but for backwards compatibility,
989+-- we fall back to the legacy user data directory ($HOME/.pandoc on *nix)
990+-- if the XDG_DATA_HOME is missing and this exists. If neither directory
991+-- is present, we return the XDG data directory.
992+defaultUserDataDir :: IO FilePath
993+defaultUserDataDir = do
1020994 xdgDir <- getXdgDirectory XdgData "pandoc"
1021995 legacyDir <- getAppUserDataDirectory "pandoc"
1022− return $ ordNub [xdgDir, legacyDir])
1023− (\(_ :: E.SomeException) -> return [])
996+ xdgExists <- doesDirectoryExist xdgDir
997+ legacyDirExists <- doesDirectoryExist legacyDir
998+ if not xdgExists && legacyDirExists
999+ then return legacyDir
1000+ else return xdgDir
src/Text/Pandoc/Sources.hsnew file+195
@@ -0,0 +1,195 @@
1+{-# LANGUAGE FlexibleInstances #-}
2+{-# LANGUAGE FlexibleContexts #-}
3+{-# LANGUAGE MultiParamTypeClasses #-}
4+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
5+{-# LANGUAGE OverloadedStrings #-}
6+{- |
7+ Module : Text.Pandoc.Sources
8+ Copyright : Copyright (C) 2021 John MacFarlane
9+ License : GNU GPL, version 2 or above
10+
11+ Maintainer : John MacFarlane <jgm@berkeley.edu>
12+ Stability : alpha
13+ Portability : portable
14+
15+Defines Sources object to be used as input to pandoc parsers and redefines Char
16+parsers so they get source position information from it.
17+-}
18+
19+module Text.Pandoc.Sources
20+ ( Sources(..)
21+ , ToSources(..)
22+ , UpdateSourcePos(..)
23+ , sourcesToText
24+ , initialSourceName
25+ , addToSources
26+ , ensureFinalNewlines
27+ , addToInput
28+ , satisfy
29+ , oneOf
30+ , noneOf
31+ , anyChar
32+ , char
33+ , string
34+ , newline
35+ , space
36+ , spaces
37+ , letter
38+ , digit
39+ , hexDigit
40+ , alphaNum
41+ )
42+where
43+import qualified Text.Parsec as P
44+import Text.Parsec (Stream(..), ParsecT)
45+import Text.Parsec.Pos as P
46+import Data.Text (Text)
47+import qualified Data.Text as T
48+import Data.Char (isSpace, isLetter, isAlphaNum, isDigit, isHexDigit)
49+import Data.String (IsString(..))
50+import qualified Data.List.NonEmpty as NonEmpty
51+
52+-- | A list of inputs labeled with source positions. It is assumed
53+-- that the 'Text's have @\n@ line endings.
54+newtype Sources = Sources { unSources :: [(SourcePos, Text)] }
55+ deriving (Show, Semigroup, Monoid)
56+
57+instance Monad m => Stream Sources m Char where
58+ uncons (Sources []) = return Nothing
59+ uncons (Sources ((pos,t):rest)) =
60+ case T.uncons t of
61+ Nothing -> uncons (Sources rest)
62+ Just (c,t') -> return $ Just (c, Sources ((pos,t'):rest))
63+
64+instance IsString Sources where
65+ fromString s = Sources [(P.initialPos "", T.pack (filter (/='\r') s))]
66+
67+class ToSources a where
68+ toSources :: a -> Sources
69+
70+instance ToSources Text where
71+ toSources t = Sources [(P.initialPos "", T.filter (/='\r') t)]
72+
73+instance ToSources [(FilePath, Text)] where
74+ toSources = Sources
75+ . map (\(fp,t) ->
76+ (P.initialPos fp, T.snoc (T.filter (/='\r') t) '\n'))
77+
78+instance ToSources Sources where
79+ toSources = id
80+
81+sourcesToText :: Sources -> Text
82+sourcesToText (Sources xs) = mconcat $ map snd xs
83+
84+addToSources :: Monad m => SourcePos -> Text -> ParsecT Sources u m ()
85+addToSources pos t = do
86+ curpos <- P.getPosition
87+ Sources xs <- P.getInput
88+ let xs' = case xs of
89+ [] -> []
90+ ((_,t'):rest) -> (curpos,t'):rest
91+ P.setInput $ Sources ((pos, T.filter (/='\r') t):xs')
92+
93+ensureFinalNewlines :: Int -- ^ number of trailing newlines
94+ -> Sources
95+ -> Sources
96+ensureFinalNewlines n (Sources xs) =
97+ case NonEmpty.nonEmpty xs of
98+ Nothing -> Sources [(initialPos "", T.replicate n "\n")]
99+ Just lst ->
100+ case NonEmpty.last lst of
101+ (spos, t) ->
102+ case T.length (T.takeWhileEnd (=='\n') t) of
103+ len | len >= n -> Sources xs
104+ | otherwise -> Sources (NonEmpty.init lst ++
105+ [(spos,
106+ t <> T.replicate (n - len) "\n")])
107+
108+class UpdateSourcePos s c where
109+ updateSourcePos :: SourcePos -> c -> s -> SourcePos
110+
111+instance UpdateSourcePos Text Char where
112+ updateSourcePos pos c _ = updatePosChar pos c
113+
114+instance UpdateSourcePos Sources Char where
115+ updateSourcePos pos c sources =
116+ case sources of
117+ Sources [] -> updatePosChar pos c
118+ Sources ((_,t):(pos',_):_)
119+ | T.null t -> pos'
120+ Sources _ ->
121+ case c of
122+ '\n' -> incSourceLine (setSourceColumn pos 1) 1
123+ '\t' -> incSourceColumn pos (4 - ((sourceColumn pos - 1) `mod` 4))
124+ _ -> incSourceColumn pos 1
125+
126+-- | Get name of first source in 'Sources'.
127+initialSourceName :: Sources -> FilePath
128+initialSourceName (Sources []) = ""
129+initialSourceName (Sources ((pos,_):_)) = sourceName pos
130+
131+-- | Add some text to the beginning of the input sources.
132+-- This simplifies code that expands macros.
133+addToInput :: Monad m => Text -> ParsecT Sources u m ()
134+addToInput t = do
135+ Sources xs <- P.getInput
136+ case xs of
137+ [] -> P.setInput $ Sources [(initialPos "",t)]
138+ (pos,t'):rest -> P.setInput $ Sources ((pos, t <> t'):rest)
139+
140+-- We need to redefine the parsers in Text.Parsec.Char so that they
141+-- update source positions properly from the Sources stream.
142+
143+satisfy :: (Monad m, Stream s m Char, UpdateSourcePos s Char)
144+ => (Char -> Bool) -> ParsecT s u m Char
145+satisfy f = P.tokenPrim show updateSourcePos matcher
146+ where
147+ matcher c = if f c then Just c else Nothing
148+
149+oneOf :: (Monad m, Stream s m Char, UpdateSourcePos s Char)
150+ => [Char] -> ParsecT s u m Char
151+oneOf cs = satisfy (`elem` cs)
152+
153+noneOf :: (Monad m, Stream s m Char, UpdateSourcePos s Char)
154+ => [Char] -> ParsecT s u m Char
155+noneOf cs = satisfy (`notElem` cs)
156+
157+anyChar :: (Monad m, Stream s m Char, UpdateSourcePos s Char)
158+ => ParsecT s u m Char
159+anyChar = satisfy (const True)
160+
161+char :: (Monad m, Stream s m Char, UpdateSourcePos s Char)
162+ => Char -> ParsecT s u m Char
163+char c = satisfy (== c)
164+
165+string :: (Monad m, Stream s m Char, UpdateSourcePos s Char)
166+ => [Char] -> ParsecT s u m [Char]
167+string = mapM char
168+
169+newline :: (Monad m, Stream s m Char, UpdateSourcePos s Char)
170+ => ParsecT s u m Char
171+newline = satisfy (== '\n')
172+
173+space :: (Monad m, Stream s m Char, UpdateSourcePos s Char)
174+ => ParsecT s u m Char
175+space = satisfy isSpace
176+
177+spaces :: (Monad m, Stream s m Char, UpdateSourcePos s Char)
178+ => ParsecT s u m ()
179+spaces = P.skipMany space P.<?> "white space"
180+
181+letter :: (Monad m, Stream s m Char, UpdateSourcePos s Char)
182+ => ParsecT s u m Char
183+letter = satisfy isLetter
184+
185+alphaNum :: (Monad m, Stream s m Char, UpdateSourcePos s Char)
186+ => ParsecT s u m Char
187+alphaNum = satisfy isAlphaNum
188+
189+digit :: (Monad m, Stream s m Char, UpdateSourcePos s Char)
190+ => ParsecT s u m Char
191+digit = satisfy isDigit
192+
193+hexDigit :: (Monad m, Stream s m Char, UpdateSourcePos s Char)
194+ => ParsecT s u m Char
195+hexDigit = satisfy isHexDigit
src/Text/Pandoc/Templates.hs+4
@@ -34,6 +34,7 @@ import Control.Monad.Except (catchError, throwError)
3434import Data.Text (Text)
3535import qualified Data.Text as T
3636import Text.Pandoc.Error
37+import System.IO.Error (isDoesNotExistError)
3738
3839-- | Wrap a Monad in this if you want partials to
3940-- be taken only from the default data files.
@@ -70,6 +71,9 @@ getTemplate tp = UTF8.toText <$>
7071 PandocResourceNotFound _ ->
7172 -- see #5987 on reason for takeFileName
7273 readDataFile ("templates" </> takeFileName tp)
74+ PandocIOError _ ioe | isDoesNotExistError ioe ->
75+ -- see #5987 on reason for takeFileName
76+ readDataFile ("templates" </> takeFileName tp)
7377 _ -> throwError e))
7478
7579-- | Get default template for the specified writer.
src/Text/Pandoc/Writers.hs+3−3
@@ -81,6 +81,7 @@ import Data.Aeson
8181import qualified Data.ByteString.Lazy as BL
8282import Data.Text (Text)
8383import qualified Data.Text as T
84+import Text.Pandoc.Shared (tshow)
8485import Text.Pandoc.Class
8586import Text.Pandoc.Definition
8687import Text.Pandoc.Options
@@ -122,7 +123,6 @@ import Text.Pandoc.Writers.Texinfo
122123import Text.Pandoc.Writers.Textile
123124import Text.Pandoc.Writers.XWiki
124125import Text.Pandoc.Writers.ZimWiki
125−import Text.Parsec.Error
126126
127127data Writer m = TextWriter (WriterOptions -> Pandoc -> m Text)
128128 | ByteStringWriter (WriterOptions -> Pandoc -> m BL.ByteString)
@@ -196,8 +196,8 @@ writers = [
196196getWriter :: PandocMonad m => Text -> m (Writer m, Extensions)
197197getWriter s =
198198 case parseFormatSpec s of
199− Left e -> throwError $ PandocAppError
200− $ T.intercalate "\n" [T.pack m | Message m <- errorMessages e]
199+ Left e -> throwError $ PandocAppError $
200+ "Error parsing writer format " <> tshow s <> ": " <> tshow e
201201 Right (writerName, extsToEnable, extsToDisable) ->
202202 case lookup writerName writers of
203203 Nothing -> throwError $
src/Text/Pandoc/Writers/AsciiDoc.hs+10−4
@@ -22,6 +22,7 @@ module Text.Pandoc.Writers.AsciiDoc (writeAsciiDoc, writeAsciiDoctor) where
2222import Control.Monad.State.Strict
2323import Data.Char (isPunctuation, isSpace)
2424import Data.List (intercalate, intersperse)
25+import Data.List.NonEmpty (NonEmpty(..))
2526import Data.Maybe (fromMaybe, isJust)
2627import qualified Data.Set as Set
2728import qualified Data.Text as T
@@ -104,8 +105,11 @@ pandocToAsciiDoc opts (Pandoc meta blocks) = do
104105
105106-- | Escape special characters for AsciiDoc.
106107escapeString :: Text -> Text
107−escapeString = escapeStringUsing escs
108− where escs = backslashEscapes "{"
108+escapeString t
109+ | T.any (== '{') t = T.concatMap escChar t
110+ | otherwise = t
111+ where escChar '{' = "\\{"
112+ escChar c = T.singleton c
109113
110114-- | Ordered list start parser for use in Para below.
111115olMarker :: Parser Text ParserState Char
@@ -274,7 +278,7 @@ blockToAsciiDoc opts block@(Table _ blkCapt specs thead tbody tfoot) = do
274278 let colwidth = if writerWrapText opts == WrapAuto
275279 then writerColumns opts
276280 else 100000
277− let maxwidth = maximum $ map offset (head':rows')
281+ let maxwidth = maximum $ fmap offset (head' :| rows')
278282 let body = if maxwidth > colwidth then vsep rows' else vcat rows'
279283 let border = separator <> text "==="
280284 return $
@@ -495,7 +499,9 @@ inlineToAsciiDoc opts (Quoted qt lst) = do
495499 | otherwise -> [Str "``"] ++ lst ++ [Str "''"]
496500inlineToAsciiDoc _ (Code _ str) = do
497501 isAsciidoctor <- gets asciidoctorVariant
498− let contents = literal (escapeStringUsing (backslashEscapes "`") str)
502+ let escChar '`' = "\\'"
503+ escChar c = T.singleton c
504+ let contents = literal (T.concatMap escChar str)
499505 return $
500506 if isAsciidoctor
501507 then text "`+" <> contents <> "+`"
src/Text/Pandoc/Writers/BibTeX.hs+1−1
@@ -43,7 +43,7 @@ writeBibTeX' :: PandocMonad m => Variant -> WriterOptions -> Pandoc -> m Text
4343writeBibTeX' variant opts (Pandoc meta _) = do
4444 let mblang = case lookupMetaString "lang" meta of
4545 "" -> Nothing
46− t -> Just $ parseLang t
46+ t -> either (const Nothing) Just $ parseLang t
4747 let refs = case lookupMeta "references" meta of
4848 Just (MetaList xs) -> mapMaybe metaValueToReference xs
4949 _ -> []
src/Text/Pandoc/Writers/ConTeXt.hs+44−38
@@ -20,7 +20,7 @@ import Data.Maybe (mapMaybe)
2020import Data.Text (Text)
2121import qualified Data.Text as T
2222import Network.URI (unEscapeString)
23−import Text.Pandoc.BCP47
23+import Text.Collate.Lang (Lang(..))
2424import Text.Pandoc.Class.PandocMonad (PandocMonad, report, toLang)
2525import Text.Pandoc.Definition
2626import Text.Pandoc.ImageSize
@@ -177,8 +177,12 @@ blockToConTeXt (Para lst) = do
177177 contents <- inlineListToConTeXt lst
178178 return $ contents <> blankline
179179blockToConTeXt (LineBlock lns) = do
180− doclines <- nowrap . vcat <$> mapM inlineListToConTeXt lns
181− return $ "\\startlines" $$ doclines $$ "\\stoplines" <> blankline
180+ let emptyToBlankline doc = if isEmpty doc
181+ then blankline
182+ else doc
183+ doclines <- mapM inlineListToConTeXt lns
184+ let contextLines = vcat . map emptyToBlankline $ doclines
185+ return $ "\\startlines" $$ contextLines $$ "\\stoplines" <> blankline
182186blockToConTeXt (BlockQuote lst) = do
183187 contents <- blockListToConTeXt lst
184188 return $ "\\startblockquote" $$ nest 0 contents $$ "\\stopblockquote" <> blankline
@@ -228,13 +232,7 @@ blockToConTeXt (OrderedList (start, style', delim) lst) = do
228232 Period -> "stopper=."
229233 OneParen -> "stopper=)"
230234 TwoParens -> "left=(,stopper=)"
231− let width = maximum $ map T.length $ take (length contents)
232− (orderedListMarkers (start, style', delim))
233− let width' = (toEnum width + 1) / 2
234− let width'' = if width' > (1.5 :: Double)
235− then "width=" <> tshow width' <> "em"
236− else ""
237− let specs2Items = filter (not . T.null) [start', delim', width'']
235+ let specs2Items = filter (not . T.null) [start', delim']
238236 let specs2 = if null specs2Items
239237 then ""
240238 else "[" <> T.intercalate "," specs2Items <> "]"
@@ -248,8 +246,8 @@ blockToConTeXt (OrderedList (start, style', delim) lst) = do
248246 UpperAlpha -> 'A') :
249247 if isTightList lst then ",packed]" else "]"
250248 let specs = T.pack style'' <> specs2
251− return $ "\\startitemize" <> literal specs $$ vcat contents $$
252− "\\stopitemize" <> blankline
249+ return $ "\\startenumerate" <> literal specs $$ vcat contents $$
250+ "\\stopenumerate" <> blankline
253251blockToConTeXt (DefinitionList lst) =
254252 liftM vcat $ mapM defListItemToConTeXt lst
255253blockToConTeXt HorizontalRule = return $ "\\thinrule" <> blankline
@@ -432,9 +430,13 @@ inlineToConTeXt (Link _ txt (src, _)) = do
432430 put $ st {stNextRef = next + 1}
433431 let ref = "url" <> tshow next
434432 contents <- inlineListToConTeXt txt
433+ let escChar '#' = "\\#"
434+ escChar '%' = "\\%"
435+ escChar c = T.singleton c
436+ let escContextURL = T.concatMap escChar
435437 return $ "\\useURL"
436438 <> brackets (literal ref)
437− <> brackets (literal $ escapeStringUsing [('#',"\\#"),('%',"\\%")] src)
439+ <> brackets (literal $ escContextURL src)
438440 <> (if isAutolink
439441 then empty
440442 else brackets empty <> brackets contents)
@@ -477,7 +479,7 @@ inlineToConTeXt (Note contents) = do
477479 then literal "\\footnote{" <> nest 2 (chomp contents') <> char '}'
478480 else literal "\\startbuffer " <> nest 2 (chomp contents') <>
479481 literal "\\stopbuffer\\footnote{\\getbuffer}"
480−inlineToConTeXt (Span (_,_,kvs) ils) = do
482+inlineToConTeXt (Span (ident,_,kvs) ils) = do
481483 mblang <- fromBCP47 (lookup "lang" kvs)
482484 let wrapDir txt = case lookup "dir" kvs of
483485 Just "rtl" -> braces $ "\\righttoleft " <> txt
@@ -487,7 +489,11 @@ inlineToConTeXt (Span (_,_,kvs) ils) = do
487489 Just lng -> braces ("\\language" <>
488490 brackets (literal lng) <> txt)
489491 Nothing -> txt
490− wrapLang . wrapDir <$> inlineListToConTeXt ils
492+ addReference =
493+ if T.null ident
494+ then id
495+ else (("\\reference" <> brackets (literal ident) <> "{}") <>)
496+ addReference . wrapLang . wrapDir <$> inlineListToConTeXt ils
491497
492498-- | Craft the section header, inserting the section reference, if supplied.
493499sectionHeader :: PandocMonad m
@@ -549,26 +555,26 @@ fromBCP47 mbs = fromBCP47' <$> toLang mbs
549555-- https://tools.ietf.org/html/bcp47#section-2.1
550556-- http://wiki.contextgarden.net/Language_Codes
551557fromBCP47' :: Maybe Lang -> Maybe Text
552−fromBCP47' (Just (Lang "ar" _ "SY" _) ) = Just "ar-sy"
553−fromBCP47' (Just (Lang "ar" _ "IQ" _) ) = Just "ar-iq"
554−fromBCP47' (Just (Lang "ar" _ "JO" _) ) = Just "ar-jo"
555−fromBCP47' (Just (Lang "ar" _ "LB" _) ) = Just "ar-lb"
556−fromBCP47' (Just (Lang "ar" _ "DZ" _) ) = Just "ar-dz"
557−fromBCP47' (Just (Lang "ar" _ "MA" _) ) = Just "ar-ma"
558−fromBCP47' (Just (Lang "de" _ _ ["1901"]) ) = Just "deo"
559−fromBCP47' (Just (Lang "de" _ "DE" _) ) = Just "de-de"
560−fromBCP47' (Just (Lang "de" _ "AT" _) ) = Just "de-at"
561−fromBCP47' (Just (Lang "de" _ "CH" _) ) = Just "de-ch"
562−fromBCP47' (Just (Lang "el" _ _ ["poly"]) ) = Just "agr"
563−fromBCP47' (Just (Lang "en" _ "US" _) ) = Just "en-us"
564−fromBCP47' (Just (Lang "en" _ "GB" _) ) = Just "en-gb"
565−fromBCP47' (Just (Lang "grc"_ _ _) ) = Just "agr"
566−fromBCP47' (Just (Lang "el" _ _ _) ) = Just "gr"
567−fromBCP47' (Just (Lang "eu" _ _ _) ) = Just "ba"
568−fromBCP47' (Just (Lang "he" _ _ _) ) = Just "il"
569−fromBCP47' (Just (Lang "jp" _ _ _) ) = Just "ja"
570−fromBCP47' (Just (Lang "uk" _ _ _) ) = Just "ua"
571−fromBCP47' (Just (Lang "vi" _ _ _) ) = Just "vn"
572−fromBCP47' (Just (Lang "zh" _ _ _) ) = Just "cn"
573−fromBCP47' (Just (Lang l _ _ _) ) = Just l
574−fromBCP47' Nothing = Nothing
558+fromBCP47' (Just (Lang "ar" _ (Just "SY") _ _ _)) = Just "ar-sy"
559+fromBCP47' (Just (Lang "ar" _ (Just "IQ") _ _ _)) = Just "ar-iq"
560+fromBCP47' (Just (Lang "ar" _ (Just "JO") _ _ _)) = Just "ar-jo"
561+fromBCP47' (Just (Lang "ar" _ (Just "LB") _ _ _)) = Just "ar-lb"
562+fromBCP47' (Just (Lang "ar" _ (Just "DZ") _ _ _)) = Just "ar-dz"
563+fromBCP47' (Just (Lang "ar" _ (Just "MA") _ _ _)) = Just "ar-ma"
564+fromBCP47' (Just (Lang "de" _ _ ["1901"] _ _)) = Just "deo"
565+fromBCP47' (Just (Lang "de" _ (Just "DE") _ _ _)) = Just "de-de"
566+fromBCP47' (Just (Lang "de" _ (Just "AT") _ _ _)) = Just "de-at"
567+fromBCP47' (Just (Lang "de" _ (Just "CH") _ _ _)) = Just "de-ch"
568+fromBCP47' (Just (Lang "el" _ _ ["poly"] _ _)) = Just "agr"
569+fromBCP47' (Just (Lang "en" _ (Just "US") _ _ _)) = Just "en-us"
570+fromBCP47' (Just (Lang "en" _ (Just "GB") _ _ _)) = Just "en-gb"
571+fromBCP47' (Just (Lang "grc"_ _ _ _ _)) = Just "agr"
572+fromBCP47' (Just (Lang "el" _ _ _ _ _)) = Just "gr"
573+fromBCP47' (Just (Lang "eu" _ _ _ _ _)) = Just "ba"
574+fromBCP47' (Just (Lang "he" _ _ _ _ _)) = Just "il"
575+fromBCP47' (Just (Lang "jp" _ _ _ _ _)) = Just "ja"
576+fromBCP47' (Just (Lang "uk" _ _ _ _ _)) = Just "ua"
577+fromBCP47' (Just (Lang "vi" _ _ _ _ _)) = Just "vn"
578+fromBCP47' (Just (Lang "zh" _ _ _ _ _)) = Just "cn"
579+fromBCP47' (Just (Lang l _ _ _ _ _)) = Just l
580+fromBCP47' Nothing = Nothing
src/Text/Pandoc/Writers/CslJson.hs+4−3
@@ -34,15 +34,16 @@ import Control.Monad.Identity
3434import Citeproc.Locale (getLocale)
3535import Citeproc.CslJson
3636import Text.Pandoc.Options (WriterOptions)
37−import Data.Maybe (mapMaybe)
37+import Data.Maybe (mapMaybe, fromMaybe)
3838import Data.Aeson.Encode.Pretty (Config (..), Indent (Spaces),
3939 NumberFormat (Generic),
4040 defConfig, encodePretty')
4141
4242writeCslJson :: PandocMonad m => WriterOptions -> Pandoc -> m Text
4343writeCslJson _opts (Pandoc meta _) = do
44− let lang = maybe (Lang "en" (Just "US")) parseLang
45− (lookupMeta "lang" meta >>= metaValueToText)
44+ let lang = fromMaybe (Lang "en" Nothing (Just "US") [] [] [])
45+ (lookupMeta "lang" meta >>= metaValueToText >>=
46+ either (const Nothing) Just . parseLang)
4647 locale <- case getLocale lang of
4748 Left e -> throwError $ PandocCiteprocError e
4849 Right l -> return l
src/Text/Pandoc/Writers/Docbook.hs+50−7
@@ -168,7 +168,7 @@ blockToDocbook :: PandocMonad m => WriterOptions -> Block -> DB m (Doc Text)
168168blockToDocbook _ Null = return empty
169169-- Add ids to paragraphs in divs with ids - this is needed for
170170-- pandoc-citeproc to get link anchors in bibliographies:
171−blockToDocbook opts (Div (id',"section":_,_) (Header lvl _ ils : xs)) = do
171+blockToDocbook opts (Div (id',"section":_,_) (Header lvl (_,_,attrs) ils : xs)) = do
172172 version <- ask
173173 -- Docbook doesn't allow sections with no content, so insert some if needed
174174 let bs = if null xs
@@ -188,15 +188,17 @@ blockToDocbook opts (Div (id',"section":_,_) (Header lvl _ ils : xs)) = do
188188 -- standalone documents will include them in the template.
189189 then [("xmlns", "http://docbook.org/ns/docbook"),("xmlns:xlink", "http://www.w3.org/1999/xlink")]
190190 else []
191− attribs = nsAttr <> idAttr
191+
192+ -- Populate miscAttr with Header.Attr.attributes, filtering out non-valid DocBook section attributes, id, and xml:id
193+ miscAttr = filter (isSectionAttr version) attrs
194+ attribs = nsAttr <> idAttr <> miscAttr
192195 title' <- inlinesToDocbook opts ils
193196 contents <- blocksToDocbook opts bs
194197 return $ inTags True tag attribs $ inTagsSimple "title" title' $$ contents
195198blockToDocbook opts (Div (ident,classes,_) bs) = do
196199 version <- ask
197200 let identAttribs = [(idName version, ident) | not (T.null ident)]
198− admonitions = ["attention","caution","danger","error","hint",
199− "important","note","tip","warning"]
201+ admonitions = ["caution","danger","important","note","tip","warning"]
200202 case classes of
201203 (l:_) | l `elem` admonitions -> do
202204 let (mTitleBs, bodyBs) =
@@ -250,17 +252,18 @@ blockToDocbook opts (LineBlock lns) =
250252 blockToDocbook opts $ linesToPara lns
251253blockToDocbook opts (BlockQuote blocks) =
252254 inTagsIndented "blockquote" <$> blocksToDocbook opts blocks
253−blockToDocbook _ (CodeBlock (_,classes,_) str) = return $
255+blockToDocbook opts (CodeBlock (_,classes,_) str) = return $
254256 literal ("<programlisting" <> lang <> ">") <> cr <>
255257 flush (literal (escapeStringForXML str) <> cr <> literal "</programlisting>")
256258 where lang = if null langs
257259 then ""
258260 else " language=\"" <> escapeStringForXML (head langs) <>
259261 "\""
260− isLang l = T.toLower l `elem` map T.toLower languages
262+ syntaxMap = writerSyntaxMap opts
263+ isLang l = T.toLower l `elem` map T.toLower (languages syntaxMap)
261264 langsFrom s = if isLang s
262265 then [s]
263− else languagesByExtension . T.toLower $ s
266+ else (languagesByExtension syntaxMap) . T.toLower $ s
264267 langs = concatMap langsFrom classes
265268blockToDocbook opts (BulletList lst) = do
266269 let attribs = [("spacing", "compact") | isTightList lst]
@@ -451,3 +454,43 @@ idAndRole (id',cls,_) = ident <> role
451454 where
452455 ident = [("id", id') | not (T.null id')]
453456 role = [("role", T.unwords cls) | not (null cls)]
457+
458+isSectionAttr :: DocBookVersion -> (Text, Text) -> Bool
459+isSectionAttr _ ("label",_) = True
460+isSectionAttr _ ("status",_) = True
461+isSectionAttr DocBook5 ("annotations",_) = True
462+isSectionAttr DocBook5 ("dir","ltr") = True
463+isSectionAttr DocBook5 ("dir","rtl") = True
464+isSectionAttr DocBook5 ("dir","lro") = True
465+isSectionAttr DocBook5 ("dir","rlo") = True
466+isSectionAttr _ ("remap",_) = True
467+isSectionAttr _ ("revisionflag","changed") = True
468+isSectionAttr _ ("revisionflag","added") = True
469+isSectionAttr _ ("revisionflag","deleted") = True
470+isSectionAttr _ ("revisionflag","off") = True
471+isSectionAttr _ ("role",_) = True
472+isSectionAttr DocBook5 ("version",_) = True
473+isSectionAttr DocBook5 ("xml:base",_) = True
474+isSectionAttr DocBook5 ("xml:lang",_) = True
475+isSectionAttr _ ("xreflabel",_) = True
476+isSectionAttr DocBook5 ("linkend",_) = True
477+isSectionAttr DocBook5 ("linkends",_) = True
478+isSectionAttr DocBook5 ("xlink:actuate",_) = True
479+isSectionAttr DocBook5 ("xlink:arcrole",_) = True
480+isSectionAttr DocBook5 ("xlink:from",_) = True
481+isSectionAttr DocBook5 ("xlink:href",_) = True
482+isSectionAttr DocBook5 ("xlink:label",_) = True
483+isSectionAttr DocBook5 ("xlink:role",_) = True
484+isSectionAttr DocBook5 ("xlink:show",_) = True
485+isSectionAttr DocBook5 ("xlink:title",_) = True
486+isSectionAttr DocBook5 ("xlink:to",_) = True
487+isSectionAttr DocBook5 ("xlink:type",_) = True
488+isSectionAttr DocBook4 ("arch",_) = True
489+isSectionAttr DocBook4 ("condition",_) = True
490+isSectionAttr DocBook4 ("conformance",_) = True
491+isSectionAttr DocBook4 ("lang",_) = True
492+isSectionAttr DocBook4 ("os",_) = True
493+isSectionAttr DocBook4 ("revision",_) = True
494+isSectionAttr DocBook4 ("security",_) = True
495+isSectionAttr DocBook4 ("vendor",_) = True
496+isSectionAttr _ (_,_) = False
src/Text/Pandoc/Writers/Docx.hs+60−244
@@ -22,7 +22,6 @@ import Control.Applicative ((<|>))
2222import Control.Monad.Except (catchError, throwError)
2323import Control.Monad.Reader
2424import Control.Monad.State.Strict
25−import qualified Data.ByteString as B
2625import qualified Data.ByteString.Lazy as BL
2726import Data.Char (isSpace, isLetter)
2827import Data.List (intercalate, isPrefixOf, isSuffixOf)
@@ -36,9 +35,9 @@ import qualified Data.Text.Lazy as TL
3635import Data.Time.Clock.POSIX
3736import Data.Digest.Pure.SHA (sha1, showDigest)
3837import Skylighting
39−import System.Random (randomRs, mkStdGen)
40−import Text.Pandoc.BCP47 (getLang, renderLang)
41−import Text.Pandoc.Class.PandocMonad (PandocMonad, report, toLang)
38+import Text.Collate.Lang (renderLang)
39+import Text.Pandoc.Class.PandocMonad (PandocMonad, report, toLang, translateTerm)
40+import qualified Text.Pandoc.Translations as Term
4241import qualified Text.Pandoc.Class.PandocMonad as P
4342import Data.Time
4443import Text.Pandoc.UTF8 (fromTextLazy)
@@ -48,123 +47,25 @@ import Text.Pandoc.Highlighting (highlight)
4847import Text.Pandoc.Error
4948import Text.Pandoc.ImageSize
5049import Text.Pandoc.Logging
51−import Text.Pandoc.MIME (MimeType, extensionFromMimeType, getMimeType,
52− getMimeTypeDef)
50+import Text.Pandoc.MIME (extensionFromMimeType, getMimeType, getMimeTypeDef)
5351import Text.Pandoc.Options
5452import Text.Pandoc.Writers.Docx.StyleMap
53+import Text.Pandoc.Writers.Docx.Table
54+import Text.Pandoc.Writers.Docx.Types
5555import Text.Pandoc.Shared
5656import Text.Pandoc.Walk
57+import qualified Text.Pandoc.Writers.GridTable as Grid
5758import Text.Pandoc.Writers.Math
5859import Text.Pandoc.Writers.Shared
59−import Text.Printf (printf)
6060import Text.TeXMath
6161import Text.Pandoc.Writers.OOXML
6262import Text.Pandoc.XML.Light as XML
6363import Data.Generics (mkT, everywhere)
6464
65−data ListMarker = NoMarker
66− | BulletMarker
67− | NumberMarker ListNumberStyle ListNumberDelim Int
68− deriving (Show, Read, Eq, Ord)
69−
70−listMarkerToId :: ListMarker -> Text
71−listMarkerToId NoMarker = "990"
72−listMarkerToId BulletMarker = "991"
73−listMarkerToId (NumberMarker sty delim n) = T.pack $
74− '9' : '9' : styNum : delimNum : show n
75− where styNum = case sty of
76− DefaultStyle -> '2'
77− Example -> '3'
78− Decimal -> '4'
79− LowerRoman -> '5'
80− UpperRoman -> '6'
81− LowerAlpha -> '7'
82− UpperAlpha -> '8'
83− delimNum = case delim of
84− DefaultDelim -> '0'
85− Period -> '1'
86− OneParen -> '2'
87− TwoParens -> '3'
88−
89−data EnvProps = EnvProps{ styleElement :: Maybe Element
90− , otherElements :: [Element]
91− }
92−
93−instance Semigroup EnvProps where
94− EnvProps s es <> EnvProps s' es' = EnvProps (s <|> s') (es ++ es')
95−
96−instance Monoid EnvProps where
97− mempty = EnvProps Nothing []
98− mappend = (<>)
99−
10065squashProps :: EnvProps -> [Element]
10166squashProps (EnvProps Nothing es) = es
10267squashProps (EnvProps (Just e) es) = e : es
10368
104−data WriterEnv = WriterEnv{ envTextProperties :: EnvProps
105− , envParaProperties :: EnvProps
106− , envRTL :: Bool
107− , envListLevel :: Int
108− , envListNumId :: Int
109− , envInDel :: Bool
110− , envChangesAuthor :: Text
111− , envChangesDate :: Text
112− , envPrintWidth :: Integer
113− }
114−
115−defaultWriterEnv :: WriterEnv
116−defaultWriterEnv = WriterEnv{ envTextProperties = mempty
117− , envParaProperties = mempty
118− , envRTL = False
119− , envListLevel = -1
120− , envListNumId = 1
121− , envInDel = False
122− , envChangesAuthor = "unknown"
123− , envChangesDate = "1969-12-31T19:00:00Z"
124− , envPrintWidth = 1
125− }
126−
127−data WriterState = WriterState{
128− stFootnotes :: [Element]
129− , stComments :: [([(Text, Text)], [Inline])]
130− , stSectionIds :: Set.Set Text
131− , stExternalLinks :: M.Map Text Text
132− , stImages :: M.Map FilePath (String, String, Maybe MimeType, B.ByteString)
133− , stLists :: [ListMarker]
134− , stInsId :: Int
135− , stDelId :: Int
136− , stStyleMaps :: StyleMaps
137− , stFirstPara :: Bool
138− , stInTable :: Bool
139− , stInList :: Bool
140− , stTocTitle :: [Inline]
141− , stDynamicParaProps :: Set.Set ParaStyleName
142− , stDynamicTextProps :: Set.Set CharStyleName
143− , stCurId :: Int
144− }
145−
146−defaultWriterState :: WriterState
147−defaultWriterState = WriterState{
148− stFootnotes = defaultFootnotes
149− , stComments = []
150− , stSectionIds = Set.empty
151− , stExternalLinks = M.empty
152− , stImages = M.empty
153− , stLists = [NoMarker]
154− , stInsId = 1
155− , stDelId = 1
156− , stStyleMaps = StyleMaps M.empty M.empty
157− , stFirstPara = False
158− , stInTable = False
159− , stInList = False
160− , stTocTitle = [Str "Table of Contents"]
161− , stDynamicParaProps = Set.empty
162− , stDynamicTextProps = Set.empty
163− , stCurId = 20
164− }
165−
166−type WS m = ReaderT WriterEnv (StateT WriterState m)
167−
16869renumIdMap :: Int -> [Element] -> M.Map Text Text
16970renumIdMap _ [] = M.empty
17071renumIdMap n (e:es)
@@ -569,12 +470,27 @@ writeDocx opts doc = do
569470 -- adds references to footnotes or endnotes we don't have...
570471 -- we do, however, copy some settings over from reference
571472 let settingsPath = "word/settings.xml"
572− settingsList = [ "w:autoHyphenation"
573− , "w:consecutiveHyphenLimit"
574− , "w:hyphenationZone"
575− , "w:doNotHyphenateCap"
576− , "w:evenAndOddHeaders"
577− , "w:proofState"
473+ settingsList = [ "zoom"
474+ , "embedSystemFonts"
475+ , "doNotTrackMoves"
476+ , "defaultTabStop"
477+ , "drawingGridHorizontalSpacing"
478+ , "drawingGridVerticalSpacing"
479+ , "displayHorizontalDrawingGridEvery"
480+ , "displayVerticalDrawingGridEvery"
481+ , "characterSpacingControl"
482+ , "savePreviewPicture"
483+ , "mathPr"
484+ , "themeFontLang"
485+ , "decimalSymbol"
486+ , "listSeparator"
487+ , "autoHyphenation"
488+ , "consecutiveHyphenLimit"
489+ , "hyphenationZone"
490+ , "doNotHyphenateCap"
491+ , "evenAndOddHeaders"
492+ , "proofState"
493+ , "compat"
578494 ]
579495 settingsEntry <- copyChildren refArchive distArchive settingsPath epochtime settingsList
580496
@@ -677,16 +593,17 @@ copyChildren :: (PandocMonad m)
677593copyChildren refArchive distArchive path timestamp elNames = do
678594 ref <- parseXml refArchive distArchive path
679595 dist <- parseXml distArchive distArchive path
596+ let elsToCopy =
597+ map cleanElem $ filterChildrenName (\e -> qName e `elem` elNames) ref
598+ let elsToKeep =
599+ [e | Elem e <- elContent dist, not (any (hasSameNameAs e) elsToCopy)]
680600 return $ toEntry path timestamp $ renderXml dist{
681− elContent = elContent dist ++ copyContent ref
601+ elContent = map Elem elsToKeep ++ map Elem elsToCopy
682602 }
683603 where
684− strName QName{qName=name, qPrefix=prefix}
685− | Just p <- prefix = p <> ":" <> name
686− | otherwise = name
687− shouldCopy = (`elem` elNames) . strName
688− cleanElem el@Element{elName=name} = Elem el{elName=name{qURI=Nothing}}
689− copyContent = map cleanElem . filterChildrenName shouldCopy
604+ hasSameNameAs (Element {elName = n1}) (Element {elName = n2}) =
605+ qName n1 == qName n2
606+ cleanElem el@Element{elName=name} = el{elName=name{qURI=Nothing}}
690607
691608-- this is the lowest number used for a list numId
692609baseListId :: Int
@@ -695,8 +612,7 @@ baseListId = 1000
695612mkNumbering :: [ListMarker] -> [Element]
696613mkNumbering lists =
697614 elts ++ zipWith mkNum lists [baseListId..(baseListId + length lists - 1)]
698− where elts = zipWith mkAbstractNum (ordNub lists) $
699− randomRs (0x10000000, 0xFFFFFFFF) $ mkStdGen 1848
615+ where elts = map mkAbstractNum (ordNub lists)
700616
701617maxListLevel :: Int
702618maxListLevel = 8
@@ -713,10 +629,10 @@ mkNum marker numid =
713629 $ mknode "w:startOverride" [("w:val",tshow start)] ())
714630 [0..maxListLevel]
715631
716−mkAbstractNum :: ListMarker -> Integer -> Element
717−mkAbstractNum marker nsid =
632+mkAbstractNum :: ListMarker -> Element
633+mkAbstractNum marker =
718634 mknode "w:abstractNum" [("w:abstractNumId",listMarkerToId marker)]
719− $ mknode "w:nsid" [("w:val", T.pack $ printf "%8x" nsid)] ()
635+ $ mknode "w:nsid" [("w:val", "A" <> listMarkerToId marker)] ()
720636 : mknode "w:multiLevelType" [("w:val","multilevel")] ()
721637 : map (mkLvl marker)
722638 [0..maxListLevel]
@@ -860,12 +776,6 @@ separateTables (x@Table{}:xs@(Table{}:_)) =
860776 x : RawBlock (Format "openxml") "<w:p />" : separateTables xs
861777separateTables (x:xs) = x : separateTables xs
862778
863−pStyleM :: (PandocMonad m) => ParaStyleName -> WS m XML.Element
864−pStyleM styleName = do
865− pStyleMap <- gets (smParaStyle . stStyleMaps)
866− let sty' = getStyleIdFromName styleName pStyleMap
867− return $ mknode "w:pStyle" [("w:val", fromStyleId sty')] ()
868−
869779rStyleM :: (PandocMonad m) => CharStyleName -> WS m XML.Element
870780rStyleM styleName = do
871781 cStyleMap <- gets (smCharStyle . stStyleMaps)
@@ -945,14 +855,28 @@ blockToOpenXML' opts (Plain lst) = do
945855-- title beginning with fig: indicates that the image is a figure
946856blockToOpenXML' opts (Para [Image attr alt (src,T.stripPrefix "fig:" -> Just tit)]) = do
947857 setFirstPara
858+ fignum <- gets stNextFigureNum
859+ unless (null alt) $ modify $ \st -> st{ stNextFigureNum = fignum + 1 }
860+ let figid = "fig" <> tshow fignum
861+ figname <- translateTerm Term.Figure
948862 prop <- pStyleM $
949863 if null alt
950864 then "Figure"
951865 else "Captioned Figure"
952866 paraProps <- local (\env -> env { envParaProperties = EnvProps (Just prop) [] <> envParaProperties env }) (getParaProps False)
953867 contents <- inlinesToOpenXML opts [Image attr alt (src,tit)]
954− captionNode <- withParaPropM (pStyleM "Image Caption")
955− $ blockToOpenXML opts (Para alt)
868+ captionNode <- if null alt
869+ then return []
870+ else withParaPropM (pStyleM "Image Caption")
871+ $ blockToOpenXML opts
872+ (Para $ Span (figid,[],[])
873+ [Str (figname <> "\160"),
874+ RawInline (Format "openxml")
875+ ("<w:fldSimple w:instr=\"SEQ Figure"
876+ <> " \\* ARABIC \"><w:r><w:t>"
877+ <> tshow fignum
878+ <> "</w:t></w:r></w:fldSimple>"),
879+ Str ":", Space] : alt)
956880 return $
957881 Elem (mknode "w:p" [] (map Elem paraProps ++ contents))
958882 : captionNode
@@ -997,78 +921,9 @@ blockToOpenXML' _ HorizontalRule = do
997921 $ mknode "v:rect" [("style","width:0;height:1.5pt"),
998922 ("o:hralign","center"),
999923 ("o:hrstd","t"),("o:hr","t")] () ]
1000−blockToOpenXML' opts (Table _ blkCapt specs thead tbody tfoot) = do
1001− let (caption, aligns, widths, headers, rows) = toLegacyTable blkCapt specs thead tbody tfoot
1002− setFirstPara
1003− modify $ \s -> s { stInTable = True }
1004− let captionStr = stringify caption
1005− caption' <- if null caption
1006− then return []
1007− else withParaPropM (pStyleM "Table Caption")
1008− $ blockToOpenXML opts (Para caption)
1009− let alignmentFor al = mknode "w:jc" [("w:val",alignmentToString al)] ()
1010− -- Table cells require a <w:p> element, even an empty one!
1011− -- Not in the spec but in Word 2007, 2010. See #4953. And
1012− -- apparently the last element must be a <w:p>, see #6983.
1013− let cellToOpenXML (al, cell) = do
1014− es <- withParaProp (alignmentFor al) $ blocksToOpenXML opts cell
1015− return $
1016− case reverse (onlyElems es) of
1017− b:e:_ | qName (elName b) == "bookmarkEnd"
1018− , qName (elName e) == "p" -> es
1019− e:_ | qName (elName e) == "p" -> es
1020− _ -> es ++ [Elem $ mknode "w:p" [] ()]
1021− headers' <- mapM cellToOpenXML $ zip aligns headers
1022− rows' <- mapM (mapM cellToOpenXML . zip aligns) rows
1023− compactStyle <- pStyleM "Compact"
1024− let emptyCell' = [Elem $ mknode "w:p" [] [mknode "w:pPr" [] [compactStyle]]]
1025− let mkcell contents = mknode "w:tc" []
1026− $ if null contents
1027− then emptyCell'
1028− else contents
1029− let mkrow cells =
1030− mknode "w:tr" [] $
1031− map mkcell cells
1032− let textwidth = 7920 -- 5.5 in in twips, 1/20 pt
1033− let fullrow = 5000 -- 100% specified in pct
1034− let rowwidth = fullrow * sum widths
1035− let mkgridcol w = mknode "w:gridCol"
1036− [("w:w", tshow (floor (textwidth * w) :: Integer))] ()
1037− let hasHeader = not $ all null headers
1038− modify $ \s -> s { stInTable = False }
1039− -- for compatibility with Word <= 2007, we include a val with a bitmask
1040− -- 0×0020 Apply first row conditional formatting
1041− -- 0×0040 Apply last row conditional formatting
1042− -- 0×0080 Apply first column conditional formatting
1043− -- 0×0100 Apply last column conditional formatting
1044− -- 0×0200 Do not apply row banding conditional formatting
1045− -- 0×0400 Do not apply column banding conditional formattin
1046− let tblLookVal :: Int
1047− tblLookVal = if hasHeader then 0x20 else 0
1048− return $
1049− caption' ++
1050− [Elem $
1051− mknode "w:tbl" []
1052− ( mknode "w:tblPr" []
1053− ( mknode "w:tblStyle" [("w:val","Table")] () :
1054− mknode "w:tblW" [("w:type", "pct"), ("w:w", tshow rowwidth)] () :
1055− mknode "w:tblLook" [("w:firstRow",if hasHeader then "1" else "0")
1056− ,("w:lastRow","0")
1057− ,("w:firstColumn","0")
1058− ,("w:lastColumn","0")
1059− ,("w:noHBand","0")
1060− ,("w:noVBand","0")
1061− ,("w:val", T.pack $ printf "%04x" tblLookVal)
1062− ] () :
1063− [ mknode "w:tblCaption" [("w:val", captionStr)] ()
1064− | not (null caption) ] )
1065− : mknode "w:tblGrid" []
1066− (if all (==0) widths
1067− then []
1068− else map mkgridcol widths)
1069− : [ mkrow headers' | hasHeader ] ++
1070− map mkrow rows'
1071− )]
924+blockToOpenXML' opts (Table attr caption colspecs thead tbodies tfoot) =
925+ tableToOpenXML (blocksToOpenXML opts)
926+ (Grid.toTable attr caption colspecs thead tbodies tfoot)
1072927blockToOpenXML' opts el
1073928 | BulletList lst <- el = addOpenXMLList BulletMarker lst
1074929 | OrderedList (start, numstyle, numdelim) lst <- el
@@ -1123,13 +978,6 @@ listItemToOpenXML opts numid (first:rest) = do
1123978 modify $ \st -> st{ stInList = oldInList }
1124979 return $ first'' ++ rest''
1125980
1126−alignmentToString :: Alignment -> Text
1127−alignmentToString alignment = case alignment of
1128− AlignLeft -> "left"
1129− AlignRight -> "right"
1130− AlignCenter -> "center"
1131− AlignDefault -> "left"
1132−
1133981-- | Convert a list of inline elements to OpenXML.
1134982inlinesToOpenXML :: PandocMonad m => WriterOptions -> [Inline] -> WS m [Content]
1135983inlinesToOpenXML opts lst = concat `fmap` mapM (inlineToOpenXML opts) lst
@@ -1140,10 +988,6 @@ withNumId numid = local $ \env -> env{ envListNumId = numid }
1140988asList :: (PandocMonad m) => WS m a -> WS m a
1141989asList = local $ \env -> env{ envListLevel = envListLevel env + 1 }
1142990
1143−isStyle :: Element -> Bool
1144−isStyle e = isElem [] "w" "rStyle" e ||
1145− isElem [] "w" "pStyle" e
1146−
1147991getTextProps :: (PandocMonad m) => WS m [Element]
1148992getTextProps = do
1149993 props <- asks envTextProperties
@@ -1172,16 +1016,6 @@ getParaProps displayMathPara = do
11721016 [] -> []
11731017 ps -> [mknode "w:pPr" [] ps]
11741018
1175−withParaProp :: PandocMonad m => Element -> WS m a -> WS m a
1176−withParaProp d p =
1177− local (\env -> env {envParaProperties = ep <> envParaProperties env}) p
1178− where ep = if isStyle d then EnvProps (Just d) [] else EnvProps Nothing [d]
1179−
1180−withParaPropM :: PandocMonad m => WS m Element -> WS m a -> WS m a
1181−withParaPropM md p = do
1182− d <- md
1183− withParaProp d p
1184−
11851019formattedString :: PandocMonad m => Text -> WS m [Element]
11861020formattedString str =
11871021 -- properly handle soft hyphens
@@ -1202,9 +1036,6 @@ formattedRun els = do
12021036 props <- getTextProps
12031037 return [ mknode "w:r" [] $ props ++ els ]
12041038
1205−setFirstPara :: PandocMonad m => WS m ()
1206−setFirstPara = modify $ \s -> s { stFirstPara = True }
1207−
12081039-- | Convert an inline element to OpenXML.
12091040inlineToOpenXML :: PandocMonad m => WriterOptions -> Inline -> WS m [Content]
12101041inlineToOpenXML opts il = withDirection $ inlineToOpenXML' opts il
@@ -1473,6 +1304,7 @@ inlineToOpenXML' opts (Image attr@(imgident, _, _) alt (src, title)) = do
14731304 Just Eps -> ".eps"
14741305 Just Svg -> ".svg"
14751306 Just Emf -> ".emf"
1307+ Just Tiff -> ".tiff"
14761308 Nothing -> ""
14771309 imgpath = "media/" <> ident <> imgext
14781310 mbMimeType = mt <|> getMimeType (T.unpack imgpath)
@@ -1496,22 +1328,6 @@ inlineToOpenXML' opts (Image attr@(imgident, _, _) alt (src, title)) = do
14961328br :: Element
14971329br = mknode "w:r" [] [mknode "w:br" [] ()]
14981330
1499−-- Word will insert these footnotes into the settings.xml file
1500−-- (whether or not they're visible in the document). If they're in the
1501−-- file, but not in the footnotes.xml file, it will produce
1502−-- problems. So we want to make sure we insert them into our document.
1503−defaultFootnotes :: [Element]
1504−defaultFootnotes = [ mknode "w:footnote"
1505− [("w:type", "separator"), ("w:id", "-1")]
1506− [ mknode "w:p" []
1507− [mknode "w:r" []
1508− [ mknode "w:separator" [] ()]]]
1509− , mknode "w:footnote"
1510− [("w:type", "continuationSeparator"), ("w:id", "0")]
1511− [ mknode "w:p" []
1512− [ mknode "w:r" []
1513− [ mknode "w:continuationSeparator" [] ()]]]]
1514−
15151331
15161332withDirection :: PandocMonad m => WS m a -> WS m a
15171333withDirection x = do
src/Text/Pandoc/Writers/Docx/Table.hsnew file+227
@@ -0,0 +1,227 @@
1+{-# LANGUAGE LambdaCase #-}
2+{-# LANGUAGE OverloadedStrings #-}
3+{-# LANGUAGE ScopedTypeVariables #-}
4+{- |
5+Module : Text.Pandoc.Writers.Docx.Table
6+Copyright : Copyright (C) 2012-2021 John MacFarlane
7+License : GNU GPL, version 2 or above
8+Maintainer : John MacFarlane <jgm@berkeley.edu>
9+
10+Conversion of table blocks to docx.
11+-}
12+module Text.Pandoc.Writers.Docx.Table
13+ ( tableToOpenXML
14+ ) where
15+
16+import Control.Monad.State.Strict
17+import Data.Array
18+import Data.Text (Text)
19+import Text.Pandoc.Definition
20+import Text.Pandoc.Class.PandocMonad (PandocMonad, translateTerm)
21+import Text.Pandoc.Writers.Docx.Types
22+import Text.Pandoc.Shared
23+import Text.Printf (printf)
24+import Text.Pandoc.Writers.GridTable hiding (Table)
25+import Text.Pandoc.Writers.OOXML
26+import Text.Pandoc.XML.Light as XML hiding (Attr)
27+import qualified Data.Text as T
28+import qualified Text.Pandoc.Translations as Term
29+import qualified Text.Pandoc.Writers.GridTable as Grid
30+
31+tableToOpenXML :: PandocMonad m
32+ => ([Block] -> WS m [Content])
33+ -> Grid.Table
34+ -> WS m [Content]
35+tableToOpenXML blocksToOpenXML gridTable = do
36+ setFirstPara
37+ let (Grid.Table (ident,_,_) caption colspecs _rowheads thead tbodies tfoot) =
38+ gridTable
39+ let (Caption _maybeShortCaption captionBlocks) = caption
40+ tablenum <- gets stNextTableNum
41+ unless (null captionBlocks) $
42+ modify $ \st -> st{ stNextTableNum = tablenum + 1 }
43+ let tableid = if T.null ident
44+ then "table" <> tshow tablenum
45+ else ident
46+ tablename <- translateTerm Term.Table
47+ let captionStr = stringify captionBlocks
48+ let aligns = map fst $ elems colspecs
49+ captionXml <- if null captionBlocks
50+ then return []
51+ else withParaPropM (pStyleM "Table Caption")
52+ $ blocksToOpenXML
53+ $ addLabel tableid tablename tablenum captionBlocks
54+ -- We set "in table" after processing the caption, because we don't
55+ -- want the "Table Caption" style to be overwritten with "Compact".
56+ modify $ \s -> s { stInTable = True }
57+ head' <- cellGridToOpenXML blocksToOpenXML HeadRow aligns thead
58+ bodies <- mapM (cellGridToOpenXML blocksToOpenXML BodyRow aligns) tbodies
59+ foot' <- cellGridToOpenXML blocksToOpenXML FootRow aligns tfoot
60+
61+ let hasHeader = not . null . indices . partRowAttrs $ thead
62+ let hasFooter = not . null . indices . partRowAttrs $ tfoot
63+ -- for compatibility with Word <= 2007, we include a val with a bitmask
64+ -- 0×0020 Apply first row conditional formatting
65+ -- 0×0040 Apply last row conditional formatting
66+ -- 0×0080 Apply first column conditional formatting
67+ -- 0×0100 Apply last column conditional formatting
68+ -- 0×0200 Do not apply row banding conditional formatting
69+ -- 0×0400 Do not apply column banding conditional formattin
70+ let tblLookVal = if hasHeader then (0x20 :: Int) else 0
71+ let (gridCols, tblWattr) = tableLayout (elems colspecs)
72+ let tbl = mknode "w:tbl" []
73+ ( mknode "w:tblPr" []
74+ ( mknode "w:tblStyle" [("w:val","Table")] () :
75+ mknode "w:tblW" tblWattr () :
76+ mknode "w:tblLook" [("w:firstRow",if hasHeader then "1" else "0")
77+ ,("w:lastRow",if hasFooter then "1" else "0")
78+ ,("w:firstColumn","0")
79+ ,("w:lastColumn","0")
80+ ,("w:noHBand","0")
81+ ,("w:noVBand","0")
82+ ,("w:val", T.pack $ printf "%04x" tblLookVal)
83+ ] () :
84+ [ mknode "w:tblCaption" [("w:val", captionStr)] ()
85+ | not (T.null captionStr) ]
86+ )
87+ : mknode "w:tblGrid" [] gridCols
88+ : head' ++ mconcat bodies ++ foot'
89+ )
90+ modify $ \s -> s { stInTable = False }
91+ return $ captionXml ++ [Elem tbl]
92+
93+addLabel :: Text -> Text -> Int -> [Block] -> [Block]
94+addLabel tableid tablename tablenum bs =
95+ case bs of
96+ (Para ils : rest) -> Para (label : Space : ils) : rest
97+ (Plain ils : rest) -> Plain (label : Space : ils) : rest
98+ _ -> Para [label] : bs
99+ where
100+ label = Span (tableid,[],[])
101+ [Str (tablename <> "\160"),
102+ RawInline (Format "openxml")
103+ ("<w:fldSimple w:instr=\"SEQ Table"
104+ <> " \\* ARABIC \"><w:r><w:t>"
105+ <> tshow tablenum
106+ <> "</w:t></w:r></w:fldSimple>"),
107+ Str ":"]
108+
109+-- | Parts of a table
110+data RowType = HeadRow | BodyRow | FootRow
111+
112+alignmentToString :: Alignment -> Text
113+alignmentToString = \case
114+ AlignLeft -> "left"
115+ AlignRight -> "right"
116+ AlignCenter -> "center"
117+ AlignDefault -> "left"
118+
119+tableLayout :: [ColSpec] -> ([Element], [(Text, Text)])
120+tableLayout specs =
121+ let
122+ textwidth = 7920 -- 5.5 in in twips (1 twip == 1/20 pt)
123+ fullrow = 5000 -- 100% specified in pct (1 pct == 1/50th of a percent)
124+ ncols = length specs
125+ getWidth = \case
126+ ColWidth n -> n
127+ _ -> 0
128+ widths = map (getWidth . snd) specs
129+ rowwidth = round (fullrow * sum widths) :: Int
130+ widthToTwips w = floor (textwidth * w) :: Int
131+ mkGridCol w = mknode "w:gridCol" [("w:w", tshow (widthToTwips w))] ()
132+ in if all (== 0) widths
133+ then ( replicate ncols $ mkGridCol (1.0 / fromIntegral ncols)
134+ , [ ("w:type", "auto"), ("w:w", "0")])
135+ else ( map mkGridCol widths
136+ , [ ("w:type", "pct"), ("w:w", tshow rowwidth) ])
137+
138+cellGridToOpenXML :: PandocMonad m
139+ => ([Block] -> WS m [Content])
140+ -> RowType
141+ -> [Alignment]
142+ -> Part
143+ -> WS m [Element]
144+cellGridToOpenXML blocksToOpenXML rowType aligns part@(Part _ cellArray _) =
145+ if null (elems cellArray)
146+ then return mempty
147+ else mapM (rowToOpenXML blocksToOpenXML) $
148+ partToRows rowType aligns part
149+
150+data OOXMLCell
151+ = OOXMLCell Attr Alignment RowSpan ColSpan [Block]
152+ | OOXMLCellMerge ColSpan
153+
154+data OOXMLRow = OOXMLRow RowType Attr [OOXMLCell]
155+
156+partToRows :: RowType -> [Alignment] -> Part -> [OOXMLRow]
157+partToRows rowType aligns part =
158+ let
159+ toOOXMLCell :: Alignment -> RowIndex -> ColIndex -> GridCell -> [OOXMLCell]
160+ toOOXMLCell columnAlign ridx cidx = \case
161+ ContentCell attr align rowspan colspan blocks ->
162+ -- Respect non-default, cell specific alignment.
163+ let align' = case align of
164+ AlignDefault -> columnAlign
165+ _ -> align
166+ in [OOXMLCell attr align' rowspan colspan blocks]
167+ ContinuationCell idx'@(ridx',cidx') | ridx /= ridx', cidx == cidx' ->
168+ case (partCellArray part)!idx' of
169+ (ContentCell _ _ _ colspan _) -> [OOXMLCellMerge colspan]
170+ x -> error $ "Content cell expected, got, " ++ show x ++
171+ " at index " ++ show idx'
172+ _ -> mempty
173+ mkRow :: (RowIndex, Attr) -> OOXMLRow
174+ mkRow (ridx, attr) = OOXMLRow rowType attr
175+ . mconcat
176+ . zipWith (\align -> uncurry $ toOOXMLCell align ridx)
177+ aligns
178+ . assocs
179+ . rowArray ridx
180+ $ partCellArray part
181+ in map mkRow $ assocs (partRowAttrs part)
182+
183+rowToOpenXML :: PandocMonad m
184+ => ([Block] -> WS m [Content])
185+ -> OOXMLRow
186+ -> WS m Element
187+rowToOpenXML blocksToOpenXML (OOXMLRow rowType _attr cells) = do
188+ xmlcells <- mapM (ooxmlCellToOpenXML blocksToOpenXML) cells
189+ let addTrPr = case rowType of
190+ HeadRow -> (mknode "w:trPr" []
191+ [mknode "w:tblHeader" [("w:val", "true")] ()] :)
192+ BodyRow -> id
193+ FootRow -> id
194+ return $ mknode "w:tr" [] (addTrPr xmlcells)
195+
196+ooxmlCellToOpenXML :: PandocMonad m
197+ => ([Block] -> WS m [Content])
198+ -> OOXMLCell
199+ -> WS m Element
200+ooxmlCellToOpenXML blocksToOpenXML = \case
201+ OOXMLCellMerge (ColSpan colspan) -> do
202+ return $ mknode "w:tc" []
203+ [ mknode "w:tcPr" [] [ mknode "w:gridSpan" [("w:val", tshow colspan)] ()
204+ , mknode "w:vMerge" [("w:val", "continue")] () ]
205+ , mknode "w:p" [] [mknode "w:pPr" [] ()]]
206+ OOXMLCell _attr align rowspan (ColSpan colspan) contents -> do
207+ compactStyle <- pStyleM "Compact"
208+ es <- withParaProp (alignmentFor align) $ blocksToOpenXML contents
209+ -- Table cells require a <w:p> element, even an empty one!
210+ -- Not in the spec but in Word 2007, 2010. See #4953. And
211+ -- apparently the last element must be a <w:p>, see #6983.
212+ return . mknode "w:tc" [] $
213+ Elem
214+ (mknode "w:tcPr" [] ([ mknode "w:gridSpan" [("w:val", tshow colspan)] ()
215+ | colspan > 1] ++
216+ [ mknode "w:vMerge" [("w:val", "restart")] ()
217+ | rowspan > RowSpan 1 ])) :
218+ if null contents
219+ then [Elem $ mknode "w:p" [] [mknode "w:pPr" [] [compactStyle]]]
220+ else case reverse (onlyElems es) of
221+ b:e:_ | qName (elName b) == "bookmarkEnd" -- y tho?
222+ , qName (elName e) == "p" -> es
223+ e:_ | qName (elName e) == "p" -> es
224+ _ -> es ++ [Elem $ mknode "w:p" [] ()]
225+
226+alignmentFor :: Alignment -> Element
227+alignmentFor al = mknode "w:jc" [("w:val",alignmentToString al)] ()
src/Text/Pandoc/Writers/Docx/Types.hsnew file+185
@@ -0,0 +1,185 @@
1+{-# LANGUAGE OverloadedStrings #-}
2+{- |
3+Module : Text.Pandoc.Writers.Docx
4+Copyright : Copyright (C) 2012-2021 John MacFarlane
5+License : GNU GPL, version 2 or above
6+Maintainer : John MacFarlane <jgm@berkeley.edu>
7+
8+Conversion of table blocks to docx.
9+-}
10+module Text.Pandoc.Writers.Docx.Types
11+ ( EnvProps (..)
12+ , WriterEnv (..)
13+ , defaultWriterEnv
14+ , WriterState (..)
15+ , defaultWriterState
16+ , WS
17+ , ListMarker (..)
18+ , listMarkerToId
19+ , pStyleM
20+ , isStyle
21+ , setFirstPara
22+ , withParaProp
23+ , withParaPropM
24+ ) where
25+
26+import Control.Applicative ((<|>))
27+import Control.Monad.Reader
28+import Control.Monad.State.Strict
29+import Data.Text (Text)
30+import Text.Pandoc.Class.PandocMonad (PandocMonad)
31+import Text.Pandoc.Definition
32+import Text.Pandoc.MIME (MimeType)
33+import Text.Pandoc.Writers.Docx.StyleMap
34+import Text.Pandoc.Writers.OOXML
35+import Text.Pandoc.XML.Light as XML
36+import qualified Data.ByteString as B
37+import qualified Data.Map as M
38+import qualified Data.Set as Set
39+import qualified Data.Text as T
40+
41+data ListMarker = NoMarker
42+ | BulletMarker
43+ | NumberMarker ListNumberStyle ListNumberDelim Int
44+ deriving (Show, Read, Eq, Ord)
45+
46+listMarkerToId :: ListMarker -> Text
47+listMarkerToId NoMarker = "990"
48+listMarkerToId BulletMarker = "991"
49+listMarkerToId (NumberMarker sty delim n) = T.pack $
50+ '9' : '9' : styNum : delimNum : show n
51+ where styNum = case sty of
52+ DefaultStyle -> '2'
53+ Example -> '3'
54+ Decimal -> '4'
55+ LowerRoman -> '5'
56+ UpperRoman -> '6'
57+ LowerAlpha -> '7'
58+ UpperAlpha -> '8'
59+ delimNum = case delim of
60+ DefaultDelim -> '0'
61+ Period -> '1'
62+ OneParen -> '2'
63+ TwoParens -> '3'
64+
65+
66+data EnvProps = EnvProps{ styleElement :: Maybe Element
67+ , otherElements :: [Element]
68+ }
69+
70+instance Semigroup EnvProps where
71+ EnvProps s es <> EnvProps s' es' = EnvProps (s <|> s') (es ++ es')
72+
73+instance Monoid EnvProps where
74+ mempty = EnvProps Nothing []
75+ mappend = (<>)
76+
77+data WriterEnv = WriterEnv
78+ { envTextProperties :: EnvProps
79+ , envParaProperties :: EnvProps
80+ , envRTL :: Bool
81+ , envListLevel :: Int
82+ , envListNumId :: Int
83+ , envInDel :: Bool
84+ , envChangesAuthor :: Text
85+ , envChangesDate :: Text
86+ , envPrintWidth :: Integer
87+ }
88+
89+defaultWriterEnv :: WriterEnv
90+defaultWriterEnv = WriterEnv
91+ { envTextProperties = mempty
92+ , envParaProperties = mempty
93+ , envRTL = False
94+ , envListLevel = -1
95+ , envListNumId = 1
96+ , envInDel = False
97+ , envChangesAuthor = "unknown"
98+ , envChangesDate = "1969-12-31T19:00:00Z"
99+ , envPrintWidth = 1
100+ }
101+
102+
103+data WriterState = WriterState{
104+ stFootnotes :: [Element]
105+ , stComments :: [([(Text, Text)], [Inline])]
106+ , stSectionIds :: Set.Set Text
107+ , stExternalLinks :: M.Map Text Text
108+ , stImages :: M.Map FilePath (String, String, Maybe MimeType, B.ByteString)
109+ , stLists :: [ListMarker]
110+ , stInsId :: Int
111+ , stDelId :: Int
112+ , stStyleMaps :: StyleMaps
113+ , stFirstPara :: Bool
114+ , stInTable :: Bool
115+ , stInList :: Bool
116+ , stTocTitle :: [Inline]
117+ , stDynamicParaProps :: Set.Set ParaStyleName
118+ , stDynamicTextProps :: Set.Set CharStyleName
119+ , stCurId :: Int
120+ , stNextFigureNum :: Int
121+ , stNextTableNum :: Int
122+ }
123+
124+defaultWriterState :: WriterState
125+defaultWriterState = WriterState{
126+ stFootnotes = defaultFootnotes
127+ , stComments = []
128+ , stSectionIds = Set.empty
129+ , stExternalLinks = M.empty
130+ , stImages = M.empty
131+ , stLists = [NoMarker]
132+ , stInsId = 1
133+ , stDelId = 1
134+ , stStyleMaps = StyleMaps M.empty M.empty
135+ , stFirstPara = False
136+ , stInTable = False
137+ , stInList = False
138+ , stTocTitle = [Str "Table of Contents"]
139+ , stDynamicParaProps = Set.empty
140+ , stDynamicTextProps = Set.empty
141+ , stCurId = 20
142+ , stNextFigureNum = 1
143+ , stNextTableNum = 1
144+ }
145+
146+setFirstPara :: PandocMonad m => WS m ()
147+setFirstPara = modify $ \s -> s { stFirstPara = True }
148+
149+type WS m = ReaderT WriterEnv (StateT WriterState m)
150+
151+-- Word will insert these footnotes into the settings.xml file
152+-- (whether or not they're visible in the document). If they're in the
153+-- file, but not in the footnotes.xml file, it will produce
154+-- problems. So we want to make sure we insert them into our document.
155+defaultFootnotes :: [Element]
156+defaultFootnotes = [ mknode "w:footnote"
157+ [("w:type", "separator"), ("w:id", "-1")]
158+ [ mknode "w:p" []
159+ [mknode "w:r" []
160+ [ mknode "w:separator" [] ()]]]
161+ , mknode "w:footnote"
162+ [("w:type", "continuationSeparator"), ("w:id", "0")]
163+ [ mknode "w:p" []
164+ [ mknode "w:r" []
165+ [ mknode "w:continuationSeparator" [] ()]]]]
166+
167+pStyleM :: (PandocMonad m) => ParaStyleName -> WS m XML.Element
168+pStyleM styleName = do
169+ pStyleMap <- gets (smParaStyle . stStyleMaps)
170+ let sty' = getStyleIdFromName styleName pStyleMap
171+ return $ mknode "w:pStyle" [("w:val", fromStyleId sty')] ()
172+
173+withParaProp :: PandocMonad m => Element -> WS m a -> WS m a
174+withParaProp d p =
175+ local (\env -> env {envParaProperties = ep <> envParaProperties env}) p
176+ where ep = if isStyle d then EnvProps (Just d) [] else EnvProps Nothing [d]
177+
178+withParaPropM :: PandocMonad m => WS m Element -> WS m a -> WS m a
179+withParaPropM md p = do
180+ d <- md
181+ withParaProp d p
182+
183+isStyle :: Element -> Bool
184+isStyle e = isElem [] "w" "rStyle" e ||
185+ isElem [] "w" "pStyle" e
src/Text/Pandoc/Writers/DokuWiki.hs+3−1
@@ -27,6 +27,7 @@ import Control.Monad.Reader (ReaderT, asks, local, runReaderT)
2727import Control.Monad.State.Strict (StateT, evalStateT)
2828import Data.Default (Default (..))
2929import Data.List (transpose)
30+import Data.List.NonEmpty (nonEmpty)
3031import Data.Text (Text)
3132import qualified Data.Text as T
3233import Text.Pandoc.Class.PandocMonad (PandocMonad, report)
@@ -172,7 +173,8 @@ blockToDokuWiki opts (Table _ blkCapt specs thead tbody tfoot) = do
172173 then return []
173174 else zipWithM (tableItemToDokuWiki opts) aligns headers
174175 rows' <- mapM (zipWithM (tableItemToDokuWiki opts) aligns) rows
175− let widths = map (maximum . map T.length) $ transpose (headers':rows')
176+ let widths = map (maybe 0 maximum . nonEmpty . map T.length)
177+ $ transpose (headers':rows')
176178 let padTo (width, al) s =
177179 case width - T.length s of
178180 x | x > 0 ->
src/Text/Pandoc/Writers/EPUB.hs+3−3
@@ -991,12 +991,12 @@ metadataElement version md currentTime =
991991 showDateTimeISO8601 currentTime | version == EPUB3 ]
992992 belongsToCollectionNodes =
993993 maybe []
994− (\belongsToCollection -> (unode "meta" ! [("property", "belongs-to-collection"), ("id", "epub-id-1")] $ belongsToCollection )
994+ (\belongsToCollection -> (unode "meta" ! [("property", "belongs-to-collection"), ("id", "epub-collection-1")] $ belongsToCollection )
995995 :
996− [unode "meta" ! [("refines", "#epub-id-1"), ("property", "collection-type")] $ ("series" :: Text) ])
996+ [unode "meta" ! [("refines", "#epub-collection-1"), ("property", "collection-type")] $ ("series" :: Text) ])
997997 (epubBelongsToCollection md)++
998998 maybe []
999− (\groupPosition -> [unode "meta" ! [("refines", "#epub-id-1"), ("property", "group-position")] $ groupPosition ])
999+ (\groupPosition -> [unode "meta" ! [("refines", "#epub-collection-1"), ("property", "group-position")] $ groupPosition ])
10001000 (epubGroupPosition md)
10011001 dcTag n s = unode ("dc:" <> n) s
10021002 dcTag' n s = [dcTag n s]
src/Text/Pandoc/Writers/GridTable.hsnew file+157
@@ -0,0 +1,157 @@
1+{-# LANGUAGE FlexibleContexts #-}
2+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
3+{-# LANGUAGE LambdaCase #-}
4+{-# LANGUAGE TupleSections #-}
5+
6+{- |
7+Module : Text.Pandoc.Writers.GridTable
8+Copyright : © 2020-2021 Albert Krewinkel
9+License : GNU GPL, version 2 or above
10+
11+Maintainer : Albert Krewinkel <albert@zeitkraut.de>
12+
13+Grid representation of pandoc tables.
14+-}
15+module Text.Pandoc.Writers.GridTable
16+ ( Table (..)
17+ , GridCell (..)
18+ , RowIndex (..)
19+ , ColIndex (..)
20+ , CellIndex
21+ , Part (..)
22+ , toTable
23+ , rowArray
24+ ) where
25+
26+import Control.Monad (forM_)
27+import Control.Monad.ST
28+import Data.Array
29+import Data.Array.MArray
30+import Data.Array.ST
31+import Data.Maybe (listToMaybe)
32+import Data.STRef
33+import Text.Pandoc.Definition hiding (Table)
34+import qualified Text.Pandoc.Builder as B
35+
36+-- | A grid cell contains either a real table cell, or is the
37+-- continuation of a column or row-spanning cell. In the latter case,
38+-- the index of the continued cell is provided.
39+data GridCell
40+ = ContentCell Attr Alignment RowSpan ColSpan [Block]
41+ | ContinuationCell CellIndex
42+ deriving (Show)
43+
44+-- | Row index in a table part.
45+newtype RowIndex = RowIndex Int deriving (Enum, Eq, Ix, Ord, Show)
46+-- | Column index in a table part.
47+newtype ColIndex = ColIndex Int deriving (Enum, Eq, Ix, Ord, Show)
48+
49+-- | Index to a cell in a table part.
50+type CellIndex = (RowIndex, ColIndex)
51+
52+-- | Cells are placed on a grid. Row attributes are stored in a separate
53+-- array.
54+data Part = Part
55+ { partAttr :: Attr
56+ , partCellArray :: Array (RowIndex,ColIndex) GridCell
57+ , partRowAttrs :: Array RowIndex Attr
58+ }
59+
60+data Table = Table
61+ { tableAttr :: Attr
62+ , tableCaption :: Caption
63+ , tableColSpecs :: Array ColIndex ColSpec
64+ , tableRowHeads :: RowHeadColumns
65+ , tableHead :: Part
66+ , tableBodies :: [Part]
67+ , tableFoot :: Part
68+ }
69+
70+toTable
71+ :: B.Attr
72+ -> B.Caption
73+ -> [B.ColSpec]
74+ -> B.TableHead
75+ -> [B.TableBody]
76+ -> B.TableFoot
77+ -> Table
78+toTable attr caption colSpecs thead tbodies tfoot =
79+ Table attr caption colSpecs' rowHeads thGrid tbGrids tfGrid
80+ where
81+ colSpecs' = listArray (ColIndex 1, ColIndex $ length colSpecs) colSpecs
82+ rowHeads = case listToMaybe tbodies of
83+ Nothing -> RowHeadColumns 0
84+ Just (TableBody _attr rowHeadCols _headerRows _rows) -> rowHeadCols
85+ thGrid = let (TableHead headAttr rows) = thead
86+ in rowsToPart headAttr rows
87+ tbGrids = map bodyToGrid tbodies
88+ tfGrid = let (TableFoot footAttr rows) = tfoot
89+ in rowsToPart footAttr rows
90+ bodyToGrid (TableBody bodyAttr _rowHeadCols headRows rows) =
91+ rowsToPart bodyAttr (headRows ++ rows)
92+
93+data BuilderCell
94+ = FilledCell GridCell
95+ | FreeCell
96+
97+fromBuilderCell :: BuilderCell -> GridCell
98+fromBuilderCell = \case
99+ FilledCell c -> c
100+ FreeCell -> error "Found an unassigned cell."
101+
102+rowsToPart :: Attr -> [B.Row] -> Part
103+rowsToPart attr = \case
104+ [] -> Part
105+ attr
106+ (listArray ((RowIndex 1, ColIndex 1), (RowIndex 0, ColIndex 0)) [])
107+ (listArray (RowIndex 1, RowIndex 0) [])
108+ rows@(Row _attr firstRow:_) ->
109+ let nrows = length rows
110+ ncols = sum $ map (\(Cell _ _ _ (ColSpan cs) _) -> cs) firstRow
111+ gbounds = ((RowIndex 1, ColIndex 1), (RowIndex nrows, ColIndex ncols))
112+ mutableGrid :: ST s (STArray s CellIndex GridCell)
113+ mutableGrid = do
114+ grid <- newArray gbounds FreeCell
115+ ridx <- newSTRef (RowIndex 1)
116+ forM_ rows $ \(Row _attr cells) -> do
117+ cidx <- newSTRef (ColIndex 1)
118+ forM_ cells $ \(Cell cellAttr align rs cs blks) -> do
119+ ridx' <- readSTRef ridx
120+ let nextFreeInRow colindex@(ColIndex c) = do
121+ readArray grid (ridx', colindex) >>= \case
122+ FreeCell -> pure colindex
123+ _ -> nextFreeInRow $ ColIndex (c + 1)
124+ cidx' <- readSTRef cidx >>= nextFreeInRow
125+ writeArray grid (ridx', cidx') . FilledCell $
126+ ContentCell cellAttr align rs cs blks
127+ forM_ (continuationIndices ridx' cidx' rs cs) $ \idx -> do
128+ writeArray grid idx . FilledCell $
129+ ContinuationCell (ridx', cidx')
130+ -- go to new column
131+ writeSTRef cidx cidx'
132+ -- go to next row
133+ modifySTRef ridx (incrRowIndex 1)
134+ -- Swap BuilderCells with normal GridCells.
135+ mapArray fromBuilderCell grid
136+ in Part
137+ { partCellArray = runSTArray mutableGrid
138+ , partRowAttrs = listArray (RowIndex 1, RowIndex nrows) $
139+ map (\(Row rowAttr _) -> rowAttr) rows
140+ , partAttr = attr
141+ }
142+
143+continuationIndices :: RowIndex -> ColIndex -> RowSpan -> ColSpan -> [CellIndex]
144+continuationIndices (RowIndex ridx) (ColIndex cidx) rowspan colspan =
145+ let (RowSpan rs) = rowspan
146+ (ColSpan cs) = colspan
147+ in [ (RowIndex r, ColIndex c) | r <- [ridx..(ridx + rs - 1)]
148+ , c <- [cidx..(cidx + cs - 1)]
149+ , (r, c) /= (ridx, cidx)]
150+
151+rowArray :: RowIndex -> Array CellIndex GridCell -> Array ColIndex GridCell
152+rowArray ridx grid =
153+ let ((_minRidx, minCidx), (_maxRidx, maxCidx)) = bounds grid
154+ in ixmap (minCidx, maxCidx) (ridx,) grid
155+
156+incrRowIndex :: RowSpan -> RowIndex -> RowIndex
157+incrRowIndex (RowSpan n) (RowIndex r) = RowIndex $ r + n
src/Text/Pandoc/Writers/HTML.hs+107−34
@@ -26,13 +26,18 @@ module Text.Pandoc.Writers.HTML (
2626 writeSlideous,
2727 writeDZSlides,
2828 writeRevealJs,
29− tagWithAttributes
29+ tagWithAttributes,
30+ inlineToHtml,
31+ blockToHtml,
32+ WriterState(..),
33+ defaultWriterState
3034 ) where
35+
3136import Control.Monad.State.Strict
3237import Data.Char (ord)
33−import Data.List (intercalate, intersperse, partition, delete, (\\))
38+import Data.List (intercalate, intersperse, partition, delete, (\\), foldl')
3439import Data.List.NonEmpty (NonEmpty((:|)))
35−import Data.Maybe (fromMaybe, isJust, isNothing, mapMaybe)
40+import Data.Maybe (fromMaybe, isJust, isNothing)
3641import qualified Data.Set as Set
3742import Data.Text (Text)
3843import qualified Data.Text as T
@@ -344,6 +349,52 @@ pandocToHtml opts (Pandoc meta blocks) = do
344349 PlainMath -> defField "displaymath-css" True
345350 WebTeX _ -> defField "displaymath-css" True
346351 _ -> id) .
352+ (if slideVariant == RevealJsSlides
353+ then -- set boolean options explicitly, since
354+ -- template can't distinguish False/undefined
355+ defField "controls" True .
356+ defField "controlsTutorial" True .
357+ defField "controlsLayout" ("bottom-right" :: Text) .
358+ defField "controlsBackArrows" ("faded" :: Text) .
359+ defField "progress" True .
360+ defField "slideNumber" False .
361+ defField "showSlideNumber" ("all" :: Text) .
362+ defField "hashOneBasedIndex" False .
363+ defField "hash" False .
364+ defField "respondToHashChanges" True .
365+ defField "history" False .
366+ defField "keyboard" True .
367+ defField "overview" True .
368+ defField "disableLayout" False .
369+ defField "center" True .
370+ defField "touch" True .
371+ defField "loop" False .
372+ defField "rtl" False .
373+ defField "navigationMode" ("default" :: Text) .
374+ defField "shuffle" False .
375+ defField "fragments" True .
376+ defField "fragmentInURL" True .
377+ defField "embedded" False .
378+ defField "help" True .
379+ defField "pause" True .
380+ defField "showNotes" False .
381+ defField "autoPlayMedia" ("null" :: Text) .
382+ defField "preloadIframes" ("null" :: Text) .
383+ defField "autoSlide" ("0" :: Text) .
384+ defField "autoSlideStoppable" True .
385+ defField "autoSlideMethod" ("null" :: Text) .
386+ defField "defaultTiming" ("null" :: Text) .
387+ defField "mouseWheel" False .
388+ defField "display" ("block" :: Text) .
389+ defField "hideInactiveCursor" True .
390+ defField "hideCursorTime" ("5000" :: Text) .
391+ defField "previewLinks" False .
392+ defField "transition" ("slide" :: Text) .
393+ defField "transitionSpeed" ("default" :: Text) .
394+ defField "backgroundTransition" ("fade" :: Text) .
395+ defField "viewDistance" ("3" :: Text) .
396+ defField "mobileViewDistance" ("2" :: Text)
397+ else id) .
347398 defField "document-css" (isNothing mCss && slideVariant == NoSlides) .
348399 defField "quotes" (stQuotes st) .
349400 -- for backwards compatibility we populate toc
@@ -544,30 +595,35 @@ tagWithAttributes opts html5 selfClosing tagname attr =
544595
545596addAttrs :: PandocMonad m
546597 => WriterOptions -> Attr -> Html -> StateT WriterState m Html
547−addAttrs opts attr h = foldl (!) h <$> attrsToHtml opts attr
598+addAttrs opts attr h = foldl' (!) h <$> attrsToHtml opts attr
548599
549600toAttrs :: PandocMonad m
550601 => [(Text, Text)] -> StateT WriterState m [Attribute]
551602toAttrs kvs = do
552603 html5 <- gets stHtml5
553604 mbEpubVersion <- gets stEPUBVersion
554− return $ mapMaybe (\(x,y) ->
555− if html5
556− then
557− if x `Set.member` (html5Attributes <> rdfaAttributes)
558− || T.any (== ':') x -- e.g. epub: namespace
559− || "data-" `T.isPrefixOf` x
560− || "aria-" `T.isPrefixOf` x
561− then Just $ customAttribute (textTag x) (toValue y)
562− else Just $ customAttribute (textTag ("data-" <> x))
563− (toValue y)
564− else
565− if mbEpubVersion == Just EPUB2 &&
566− not (x `Set.member` (html4Attributes <> rdfaAttributes) ||
567− "xml:" `T.isPrefixOf` x)
568− then Nothing
569− else Just $ customAttribute (textTag x) (toValue y))
570− kvs
605+ reverse . snd <$> foldM (go html5 mbEpubVersion) (Set.empty, []) kvs
606+ where
607+ go html5 mbEpubVersion (keys, attrs) (k,v) = do
608+ if k `Set.member` keys
609+ then do
610+ report $ DuplicateAttribute k v
611+ return (keys, attrs)
612+ else return (Set.insert k keys, addAttr html5 mbEpubVersion k v attrs)
613+ addAttr html5 mbEpubVersion x y
614+ | html5
615+ = if x `Set.member` (html5Attributes <> rdfaAttributes)
616+ || T.any (== ':') x -- e.g. epub: namespace
617+ || "data-" `T.isPrefixOf` x
618+ || "aria-" `T.isPrefixOf` x
619+ then (customAttribute (textTag x) (toValue y) :)
620+ else (customAttribute (textTag ("data-" <> x)) (toValue y) :)
621+ | mbEpubVersion == Just EPUB2
622+ , not (x `Set.member` (html4Attributes <> rdfaAttributes) ||
623+ "xml:" `T.isPrefixOf` x)
624+ = id
625+ | otherwise
626+ = (customAttribute (textTag x) (toValue y) :)
571627
572628attrsToHtml :: PandocMonad m
573629 => WriterOptions -> Attr -> StateT WriterState m [Attribute]
@@ -608,17 +664,20 @@ dimensionsToAttrList attr = consolidateStyles $ go Width ++ go Height
608664figure :: PandocMonad m
609665 => WriterOptions -> Attr -> [Inline] -> (Text, Text)
610666 -> StateT WriterState m Html
611−figure opts attr txt (s,tit) = do
667+figure opts attr@(_, _, attrList) txt (s,tit) = do
612668 html5 <- gets stHtml5
613669 -- Screen-readers will normally read the @alt@ text and the figure; we
614670 -- want to avoid them reading the same text twice. With HTML5 we can
615671 -- use aria-hidden for the caption; with HTML4, we use an empty
616672 -- alt-text instead.
673+ -- When the alt text differs from the caption both should be read.
617674 let alt = if html5 then txt else [Str ""]
618675 let tocapt = if html5
619− then H5.figcaption !
620− H5.customAttribute (textTag "aria-hidden")
621− (toValue @Text "true")
676+ then (H5.figcaption !) $
677+ if isJust (lookup "alt" attrList)
678+ then mempty
679+ else H5.customAttribute (textTag "aria-hidden")
680+ (toValue @Text "true")
622681 else H.p ! A.class_ "caption"
623682 img <- inlineToHtml opts (Image attr alt (s,tit))
624683 capt <- if null txt
@@ -765,9 +824,10 @@ blockToHtml opts (Div attr@(ident, classes, kvs') bs) = do
765824 lookup "entry-spacing" kvs' >>=
766825 safeRead }
767826 let isCslBibEntry = "csl-entry" `elem` classes
768− let kvs = [(k,v) | (k,v) <- kvs', k /= "width"] ++
769− [("style", "width:" <> w <> ";") | "column" `elem` classes,
770− ("width", w) <- kvs'] ++
827+ let kvs = [(k,v) | (k,v) <- kvs'
828+ , k /= "width" || "column" `notElem` classes] ++
829+ [("style", "width:" <> w <> ";") | "column" `elem` classes
830+ , ("width", w) <- kvs'] ++
771831 [("role", "doc-bibliography") | isCslBibBody && html5] ++
772832 [("role", "doc-biblioentry") | isCslBibEntry && html5]
773833 let speakerNotes = "notes" `elem` classes
@@ -877,7 +937,7 @@ blockToHtml opts (BlockQuote blocks) = do
877937 else do
878938 contents <- blockListToHtml opts blocks
879939 return $ H.blockquote $ nl opts >> contents >> nl opts
880−blockToHtml opts (Header level attr@(_,classes,kvs) lst) = do
940+blockToHtml opts (Header level (ident,classes,kvs) lst) = do
881941 contents <- inlineListToHtml opts lst
882942 let secnum = fromMaybe mempty $ lookup "number" kvs
883943 let contents' = if writerNumberSections opts && not (T.null secnum)
@@ -885,7 +945,13 @@ blockToHtml opts (Header level attr@(_,classes,kvs) lst) = do
885945 then (H.span ! A.class_ "header-section-number"
886946 $ toHtml secnum) >> strToHtml " " >> contents
887947 else contents
888− addAttrs opts attr
948+ html5 <- gets stHtml5
949+ let kvs' = if html5
950+ then kvs
951+ else [ (k, v) | (k, v) <- kvs
952+ , k `elem` (["lang", "dir", "title", "style"
953+ , "align"] ++ intrinsicEventsHTML4)]
954+ addAttrs opts (ident,classes,kvs')
889955 $ case level of
890956 1 -> H.h1 contents'
891957 2 -> H.h2 contents'
@@ -921,7 +987,7 @@ blockToHtml opts (OrderedList (startnum, numstyle, _) lst) = do
921987 numstyle']
922988 else [])
923989 l <- ordList opts contents
924− return $ foldl (!) l attribs
990+ return $ foldl' (!) l attribs
925991blockToHtml opts (DefinitionList lst) = do
926992 contents <- mapM (\(term, defs) ->
927993 do term' <- liftM H.dt $ inlineListToHtml opts term
@@ -1375,7 +1441,7 @@ inlineToHtml opts inline = do
13751441 return $ if T.null tit
13761442 then link'
13771443 else link' ! A.title (toValue tit)
1378− (Image attr txt (s,tit)) -> do
1444+ (Image attr@(_, _, attrList) txt (s, tit)) -> do
13791445 let alternate = stringify txt
13801446 slideVariant <- gets stSlideVariant
13811447 let isReveal = slideVariant == RevealJsSlides
@@ -1388,7 +1454,8 @@ inlineToHtml opts inline = do
13881454 [A.title $ toValue tit | not (T.null tit)] ++
13891455 attrs
13901456 imageTag = (if html5 then H5.img else H.img
1391− , [A.alt $ toValue alternate | not (null txt)] )
1457+ , [A.alt $ toValue alternate | not (null txt) &&
1458+ isNothing (lookup "alt" attrList)] )
13921459 mediaTag tg fallbackTxt =
13931460 let linkTxt = if null txt
13941461 then fallbackTxt
@@ -1402,7 +1469,7 @@ inlineToHtml opts inline = do
14021469 Just "audio" -> mediaTag H5.audio "Audio"
14031470 Just _ -> (H5.embed, [])
14041471 _ -> imageTag
1405− return $ foldl (!) tag $ attributes ++ specAttrs
1472+ return $ foldl' (!) tag $ attributes ++ specAttrs
14061473 -- note: null title included, as in Markdown.pl
14071474 (Note contents) -> do
14081475 notes <- gets stNotes
@@ -1521,6 +1588,12 @@ allowsMathEnvironments MathML = True
15211588allowsMathEnvironments (WebTeX _) = True
15221589allowsMathEnvironments _ = False
15231590
1591+-- | List of intrinsic event attributes allowed on all elements in HTML4.
1592+intrinsicEventsHTML4 :: [Text]
1593+intrinsicEventsHTML4 =
1594+ [ "onclick", "ondblclick", "onmousedown", "onmouseup", "onmouseover"
1595+ , "onmouseout", "onmouseout", "onkeypress", "onkeydown", "onkeyup"]
1596+
15241597isRawHtml :: PandocMonad m => Format -> StateT WriterState m Bool
15251598isRawHtml f = do
15261599 html5 <- gets stHtml5
src/Text/Pandoc/Writers/Haddock.hs+13−2
@@ -15,6 +15,7 @@ Haddock: <http://www.haskell.org/haddock/doc/html/>
1515-}
1616module Text.Pandoc.Writers.Haddock (writeHaddock) where
1717import Control.Monad.State.Strict
18+import Data.Char (isAlphaNum)
1819import Data.Default
1920import Data.Text (Text)
2021import qualified Data.Text as T
@@ -71,8 +72,18 @@ notesToHaddock opts notes =
7172
7273-- | Escape special characters for Haddock.
7374escapeString :: Text -> Text
74−escapeString = escapeStringUsing haddockEscapes
75− where haddockEscapes = backslashEscapes "\\/'`\"@<"
75+escapeString t
76+ | T.all isAlphaNum t = t
77+ | otherwise = T.concatMap escChar t
78+ where
79+ escChar '\\' = "\\\\"
80+ escChar '/' = "\\/"
81+ escChar '\'' = "\\'"
82+ escChar '`' = "\\`"
83+ escChar '"' = "\\\""
84+ escChar '@' = "\\@"
85+ escChar '<' = "\\<"
86+ escChar c = T.singleton c
7687
7788-- | Convert Pandoc block element to haddock.
7889blockToHaddock :: PandocMonad m
src/Text/Pandoc/Writers/JATS.hs+67−44
@@ -1,6 +1,7 @@
1+{-# LANGUAGE LambdaCase #-}
2+{-# LANGUAGE OverloadedStrings #-}
13{-# LANGUAGE ScopedTypeVariables #-}
2−{-# LANGUAGE OverloadedStrings #-}
3−{-# LANGUAGE ViewPatterns #-}
4+{-# LANGUAGE ViewPatterns #-}
45{- |
56 Module : Text.Pandoc.Writers.JATS
67 Copyright : 2017-2021 John MacFarlane
@@ -20,12 +21,13 @@ module Text.Pandoc.Writers.JATS
2021 , writeJatsPublishing
2122 , writeJatsArticleAuthoring
2223 ) where
24+import Control.Applicative ((<|>))
2325import Control.Monad.Reader
2426import Control.Monad.State
2527import Data.Generics (everywhere, mkT)
2628import Data.List (partition)
2729import qualified Data.Map as M
28−import Data.Maybe (fromMaybe)
30+import Data.Maybe (fromMaybe, listToMaybe)
2931import Data.Time (toGregorian, Day, parseTimeM, defaultTimeLocale, formatTime)
3032import qualified Data.Text as T
3133import Data.Text (Text)
@@ -80,7 +82,7 @@ writeJats tagSet opts d = do
8082 let environment = JATSEnv
8183 { jatsTagSet = tagSet
8284 , jatsInlinesWriter = inlinesToJATS
83− , jatsBlockWriter = blockToJATS
85+ , jatsBlockWriter = wrappedBlocksToJATS
8486 , jatsReferences = refs
8587 }
8688 let initialState = JATSState { jatsNotes = [] }
@@ -162,11 +164,9 @@ wrappedBlocksToJATS needsWrap opts =
162164 wrappedBlockToJATS b = do
163165 inner <- blockToJATS opts b
164166 return $
165− if needsWrap b || isBlockQuote b -- see #7041
167+ if needsWrap b
166168 then inTags True "p" [("specific-use","wrapper")] inner
167169 else inner
168− isBlockQuote (BlockQuote _) = True
169− isBlockQuote _ = False
170170
171171-- | Auxiliary function to convert Plain block to Para.
172172plainToPara :: Block -> Block
@@ -225,33 +225,36 @@ imageMimeType src kvs =
225225 (T.drop 1 . T.dropWhile (/='/') <$> mbMT)
226226 in (maintype, subtype)
227227
228−languageFor :: [Text] -> Text
229−languageFor classes =
228+languageFor :: WriterOptions -> [Text] -> Text
229+languageFor opts classes =
230230 case langs of
231231 (l:_) -> escapeStringForXML l
232232 [] -> ""
233− where isLang l = T.toLower l `elem` map T.toLower languages
233+ where
234+ syntaxMap = writerSyntaxMap opts
235+ isLang l = T.toLower l `elem` map T.toLower (languages syntaxMap)
234236 langsFrom s = if isLang s
235237 then [s]
236− else languagesByExtension . T.toLower $ s
238+ else (languagesByExtension syntaxMap) . T.toLower $ s
237239 langs = concatMap langsFrom classes
238240
239−codeAttr :: Attr -> (Text, [(Text, Text)])
240−codeAttr (ident,classes,kvs) = (lang, attr)
241+codeAttr :: WriterOptions -> Attr -> (Text, [(Text, Text)])
242+codeAttr opts (ident,classes,kvs) = (lang, attr)
241243 where
242− attr = [("id",ident) | not (T.null ident)] ++
244+ attr = [("id", escapeNCName ident) | not (T.null ident)] ++
243245 [("language",lang) | not (T.null lang)] ++
244246 [(k,v) | (k,v) <- kvs, k `elem` ["code-type",
245247 "code-version", "executable",
246248 "language-version", "orientation",
247249 "platforms", "position", "specific-use"]]
248− lang = languageFor classes
250+ lang = languageFor opts classes
249251
250252-- | Convert a Pandoc block element to JATS.
251253blockToJATS :: PandocMonad m => WriterOptions -> Block -> JATS m (Doc Text)
252254blockToJATS _ Null = return empty
253255blockToJATS opts (Div (id',"section":_,kvs) (Header _lvl _ ils : xs)) = do
254− let idAttr = [("id", writerIdentifierPrefix opts <> id') | not (T.null id')]
256+ let idAttr = [ ("id", writerIdentifierPrefix opts <> escapeNCName id')
257+ | not (T.null id')]
255258 let otherAttrs = ["sec-type", "specific-use"]
256259 let attribs = idAttr ++ [(k,v) | (k,v) <- kvs, k `elem` otherAttrs]
257260 title' <- inlinesToJATS opts ils
@@ -260,7 +263,7 @@ blockToJATS opts (Div (id',"section":_,kvs) (Header _lvl _ ils : xs)) = do
260263 inTagsSimple "title" title' $$ contents
261264-- Bibliography reference:
262265blockToJATS opts (Div (ident,_,_) [Para lst]) | "ref-" `T.isPrefixOf` ident =
263− inTags True "ref" [("id", ident)] .
266+ inTags True "ref" [("id", escapeNCName ident)] .
264267 inTagsSimple "mixed-citation" <$>
265268 inlinesToJATS opts lst
266269blockToJATS opts (Div ("refs",_,_) xs) = do
@@ -271,14 +274,14 @@ blockToJATS opts (Div ("refs",_,_) xs) = do
271274 return $ inTagsIndented "ref-list" contents
272275blockToJATS opts (Div (ident,[cls],kvs) bs) | cls `elem` ["fig", "caption", "table-wrap"] = do
273276 contents <- blocksToJATS opts bs
274− let attr = [("id", ident) | not (T.null ident)] ++
277+ let attr = [("id", escapeNCName ident) | not (T.null ident)] ++
275278 [("xml:lang",l) | ("lang",l) <- kvs] ++
276279 [(k,v) | (k,v) <- kvs, k `elem` ["specific-use",
277280 "content-type", "orientation", "position"]]
278281 return $ inTags True cls attr contents
279282blockToJATS opts (Div (ident,_,kvs) bs) = do
280283 contents <- blocksToJATS opts bs
281− let attr = [("id", ident) | not (T.null ident)] ++
284+ let attr = [("id", escapeNCName ident) | not (T.null ident)] ++
282285 [("xml:lang",l) | ("lang",l) <- kvs] ++
283286 [(k,v) | (k,v) <- kvs, k `elem` ["specific-use",
284287 "content-type", "orientation", "position"]]
@@ -296,7 +299,7 @@ blockToJATS opts (Para [Image (ident,_,kvs) txt
296299 let capt = if null txt
297300 then empty
298301 else inTagsSimple "caption" $ inTagsSimple "p" alt
299− let attr = [("id", ident) | not (T.null ident)] ++
302+ let attr = [("id", escapeNCName ident) | not (T.null ident)] ++
300303 [(k,v) | (k,v) <- kvs, k `elem` ["fig-type", "orientation",
301304 "position", "specific-use"]]
302305 let graphicattr = [("mimetype",maintype),
@@ -307,7 +310,7 @@ blockToJATS opts (Para [Image (ident,_,kvs) txt
307310 capt $$ selfClosingTag "graphic" graphicattr
308311blockToJATS _ (Para [Image (ident,_,kvs) _ (src, tit)]) = do
309312 let (maintype, subtype) = imageMimeType src kvs
310− let attr = [("id", ident) | not (T.null ident)] ++
313+ let attr = [("id", escapeNCName ident) | not (T.null ident)] ++
311314 [("mimetype", maintype),
312315 ("mime-subtype", subtype),
313316 ("xlink:href", src)] ++
@@ -323,13 +326,16 @@ blockToJATS opts (LineBlock lns) =
323326 blockToJATS opts $ linesToPara lns
324327blockToJATS opts (BlockQuote blocks) = do
325328 tagSet <- asks jatsTagSet
326− let blocksToJats' = if tagSet == TagSetArticleAuthoring
327− then wrappedBlocksToJATS (not . isPara)
328− else blocksToJATS
329− inTagsIndented "disp-quote" <$> blocksToJats' opts blocks
330−blockToJATS _ (CodeBlock a str) = return $
329+ let needsWrap = if tagSet == TagSetArticleAuthoring
330+ then not . isPara
331+ else \case
332+ Header{} -> True
333+ HorizontalRule -> True
334+ _ -> False
335+ inTagsIndented "disp-quote" <$> wrappedBlocksToJATS needsWrap opts blocks
336+blockToJATS opts (CodeBlock a str) = return $
331337 inTags False tag attr (flush (text (T.unpack $ escapeStringForXML str)))
332− where (lang, attr) = codeAttr a
338+ where (lang, attr) = codeAttr opts a
333339 tag = if T.null lang then "preformat" else "code"
334340blockToJATS _ (BulletList []) = return empty
335341blockToJATS opts (BulletList lst) =
@@ -409,9 +415,9 @@ inlineToJATS opts (Quoted SingleQuote lst) = do
409415inlineToJATS opts (Quoted DoubleQuote lst) = do
410416 contents <- inlinesToJATS opts lst
411417 return $ char '“' <> contents <> char '”'
412−inlineToJATS _ (Code a str) =
418+inlineToJATS opts (Code a str) =
413419 return $ inTags False tag attr $ literal (escapeStringForXML str)
414− where (lang, attr) = codeAttr a
420+ where (lang, attr) = codeAttr opts a
415421 tag = if T.null lang then "monospace" else "code"
416422inlineToJATS _ il@(RawInline f x)
417423 | f == "jats" = return $ literal x
@@ -434,7 +440,8 @@ inlineToJATS opts (Note contents) = do
434440 let notenum = case notes of
435441 (n, _):_ -> n + 1
436442 [] -> 1
437− thenote <- inTags True "fn" [("id","fn" <> tshow notenum)]
443+ thenote <- inTags True "fn" [("id", "fn" <> tshow notenum)]
444+ . (inTagsSimple "label" (literal $ tshow notenum) <>)
438445 <$> wrappedBlocksToJATS (not . isPara) opts
439446 (walk demoteHeaderAndRefs contents)
440447 modify $ \st -> st{ jatsNotes = (notenum, thenote) : notes }
@@ -442,18 +449,34 @@ inlineToJATS opts (Note contents) = do
442449 ("rid", "fn" <> tshow notenum)]
443450 $ text (show notenum)
444451inlineToJATS opts (Cite _ lst) =
445− -- TODO revisit this after examining the jats.csl pipeline
446452 inlinesToJATS opts lst
447−inlineToJATS opts (Span ("",_,[]) ils) = inlinesToJATS opts ils
448−inlineToJATS opts (Span (ident,_,kvs) ils) = do
453+inlineToJATS opts (Span (ident,classes,kvs) ils) = do
449454 contents <- inlinesToJATS opts ils
450− let attr = [("id",ident) | not (T.null ident)] ++
451− [("xml:lang",l) | ("lang",l) <- kvs] ++
452− [(k,v) | (k,v) <- kvs
453− , k `elem` ["content-type", "rationale",
454− "rid", "specific-use"]]
455− return $ selfClosingTag "milestone-start" attr <> contents <>
456− selfClosingTag "milestone-end" []
455+ let commonAttr = [("id", escapeNCName ident) | not (T.null ident)] ++
456+ [("xml:lang",l) | ("lang",l) <- kvs] ++
457+ [(k,v) | (k,v) <- kvs, k `elem` ["alt", "specific-use"]]
458+ -- A named-content element is a good fit for spans, but requires a
459+ -- content-type attribute to be present. We use either the explicit
460+ -- attribute or the first class as content type. If neither is
461+ -- available, then we fall back to using a @styled-content@ element.
462+ let (tag, specificAttr) =
463+ case lookup "content-type" kvs <|> listToMaybe classes of
464+ Just ct -> ( "named-content"
465+ , ("content-type", ct) :
466+ [(k, v) | (k, v) <- kvs
467+ , k `elem` ["rid", "vocab", "vocab-identifier",
468+ "vocab-term", "vocab-term-identifier"]])
469+ -- Fall back to styled-content
470+ Nothing -> ("styled-content"
471+ , [(k, v) | (k,v) <- kvs
472+ , k `elem` ["style", "style-type", "style-detail",
473+ "toggle"]])
474+ let attr = commonAttr ++ specificAttr
475+ -- unwrap if wrapping element would have no attributes
476+ return $
477+ if null attr
478+ then contents
479+ else inTags False tag attr contents
457480inlineToJATS _ (Math t str) = do
458481 let addPref (Xml.Attr q v)
459482 | Xml.qName q == "xmlns" = Xml.Attr q{ Xml.qName = "xmlns:mml" } v
@@ -488,9 +511,9 @@ inlineToJATS _ (Link _attr [Str t] (T.stripPrefix "mailto:" -> Just email, _))
488511 return $ inTagsSimple "email" $ literal (escapeStringForXML email)
489512inlineToJATS opts (Link (ident,_,kvs) txt (T.uncons -> Just ('#', src), _)) = do
490513 let attr = mconcat
491− [ [("id", ident) | not (T.null ident)]
514+ [ [("id", escapeNCName ident) | not (T.null ident)]
492515 , [("alt", stringify txt) | not (null txt)]
493− , [("rid", src)]
516+ , [("rid", escapeNCName src)]
494517 , [(k,v) | (k,v) <- kvs, k `elem` ["ref-type", "specific-use"]]
495518 , [("ref-type", "bibr") | "ref-" `T.isPrefixOf` src]
496519 ]
@@ -500,7 +523,7 @@ inlineToJATS opts (Link (ident,_,kvs) txt (T.uncons -> Just ('#', src), _)) = do
500523 contents <- inlinesToJATS opts txt
501524 return $ inTags False "xref" attr contents
502525inlineToJATS opts (Link (ident,_,kvs) txt (src, tit)) = do
503− let attr = [("id", ident) | not (T.null ident)] ++
526+ let attr = [("id", escapeNCName ident) | not (T.null ident)] ++
504527 [("ext-link-type", "uri"),
505528 ("xlink:href", src)] ++
506529 [("xlink:title", tit) | not (T.null tit)] ++
@@ -518,7 +541,7 @@ inlineToJATS _ (Image (ident,_,kvs) _ (src, tit)) = do
518541 let subtype = fromMaybe "" $
519542 lookup "mime-subtype" kvs `mplus`
520543 (T.drop 1 . T.dropWhile (/='/') <$> mbMT)
521− let attr = [("id", ident) | not (T.null ident)] ++
544+ let attr = [("id", escapeNCName ident) | not (T.null ident)] ++
522545 [("mimetype", maintype),
523546 ("mime-subtype", subtype),
524547 ("xlink:href", src)] ++
src/Text/Pandoc/Writers/JATS/References.hs+3−2
@@ -29,7 +29,7 @@ import Text.Pandoc.Builder (Inlines)
2929import Text.Pandoc.Options (WriterOptions)
3030import Text.Pandoc.Shared (tshow)
3131import Text.Pandoc.Writers.JATS.Types
32−import Text.Pandoc.XML (escapeStringForXML, inTags)
32+import Text.Pandoc.XML (escapeNCName, escapeStringForXML, inTags)
3333import qualified Data.Text as T
3434
3535referencesToJATS :: PandocMonad m
@@ -46,7 +46,8 @@ referenceToJATS :: PandocMonad m
4646referenceToJATS _opts ref = do
4747 let refType = referenceType ref
4848 let pubType = [("publication-type", refType) | not (T.null refType)]
49− let wrap = inTags True "ref" [("id", "ref-" <> unItemId (referenceId ref))]
49+ let ident = escapeNCName $ "ref-" <> unItemId (referenceId ref)
50+ let wrap = inTags True "ref" [("id", ident)]
5051 . inTags True "element-citation" pubType
5152 return . wrap . vcat $
5253 [ authors
src/Text/Pandoc/Writers/JATS/Table.hs+25−5
@@ -24,7 +24,7 @@ import Text.Pandoc.Definition
2424import Text.Pandoc.Options (WriterOptions)
2525import Text.Pandoc.Shared (tshow)
2626import Text.Pandoc.Writers.JATS.Types
27−import Text.Pandoc.XML (inTags, inTagsIndented, selfClosingTag)
27+import Text.Pandoc.XML (escapeNCName, inTags, inTagsIndented, selfClosingTag)
2828import qualified Data.Text as T
2929import qualified Text.Pandoc.Writers.AnnotatedTable as Ann
3030
@@ -34,13 +34,19 @@ tableToJATS :: PandocMonad m
3434 -> JATS m (Doc Text)
3535tableToJATS opts (Ann.Table attr caption colspecs thead tbodies tfoot) = do
3636 let (Caption _maybeShortCaption captionBlocks) = caption
37+ -- Only paragraphs are allowed in captions, all other blocks must be
38+ -- wrapped in @<p>@ elements.
39+ let needsWrapping = \case
40+ Plain{} -> False
41+ Para{} -> False
42+ _ -> True
3743 tbl <- captionlessTable opts attr colspecs thead tbodies tfoot
3844 captionDoc <- if null captionBlocks
3945 then return empty
4046 else do
4147 blockToJATS <- asks jatsBlockWriter
42− inTagsIndented "caption" . vcat <$>
43− mapM (blockToJATS opts) captionBlocks
48+ inTagsIndented "caption" <$>
49+ blockToJATS needsWrapping opts captionBlocks
4450 return $ inTags True "table-wrap" [] $ captionDoc $$ tbl
4551
4652captionlessTable :: PandocMonad m
@@ -216,7 +222,7 @@ cellToJats opts celltype (Ann.Cell (colspec :| _) _colNum cell) =
216222
217223toAttribs :: Attr -> [Text] -> [(Text, Text)]
218224toAttribs (ident, _classes, kvs) knownAttribs =
219− (if T.null ident then id else (("id", ident) :)) $
225+ (if T.null ident then id else (("id", escapeNCName ident) :)) $
220226 filter ((`elem` knownAttribs) . fst) kvs
221227
222228tableCellToJats :: PandocMonad m
@@ -230,7 +236,7 @@ tableCellToJats opts ctype colAlign (Cell attr align rowspan colspan item) = do
230236 inlinesToJats <- asks jatsInlinesWriter
231237 let cellContents = \case
232238 [Plain inlines] -> inlinesToJats opts inlines
233− blocks -> vcat <$> mapM (blockToJats opts) blocks
239+ blocks -> blockToJats needsWrapInCell opts blocks
234240 let tag' = case ctype of
235241 BodyCell -> "td"
236242 HeaderCell -> "th"
@@ -246,3 +252,17 @@ tableCellToJats opts ctype colAlign (Cell attr align rowspan colspan item) = do
246252 . maybeCons (colspanAttrib colspan)
247253 $ toAttribs attr validAttribs
248254 inTags False tag' attribs <$> cellContents item
255+
256+-- | Whether the JATS produced from this block should be wrapped in a
257+-- @<p>@ element when put directly below a @<td>@ element.
258+needsWrapInCell :: Block -> Bool
259+needsWrapInCell = \case
260+ Plain{} -> False -- should be unwrapped anyway
261+ Para{} -> False
262+ BulletList{} -> False
263+ OrderedList{} -> False
264+ DefinitionList{} -> False
265+ HorizontalRule -> False
266+ CodeBlock{} -> False
267+ RawBlock{} -> False -- responsibility of the user
268+ _ -> True
src/Text/Pandoc/Writers/JATS/Types.hs+12−3
@@ -37,11 +37,20 @@ newtype JATSState = JATSState
3737 { jatsNotes :: [(Int, Doc Text)]
3838 }
3939
40+-- | Environment containing all information relevant for rendering.
4041data JATSEnv m = JATSEnv
41− { jatsTagSet :: JATSTagSet
42+ { jatsTagSet :: JATSTagSet -- ^ The tag set that's being ouput
43+
44+ , jatsBlockWriter :: (Block -> Bool)
45+ -> WriterOptions -> [Block] -> JATS m (Doc Text)
46+ -- ^ Converts a block list to JATS, wrapping top-level blocks into a
47+ -- @<p>@ element if the property evaluates to @True@.
48+ -- See #7227.
49+
4250 , jatsInlinesWriter :: WriterOptions -> [Inline] -> JATS m (Doc Text)
43− , jatsBlockWriter :: WriterOptions -> Block -> JATS m (Doc Text)
44− , jatsReferences :: [Reference Inlines]
51+ -- ^ Converts an inline list to JATS.
52+
53+ , jatsReferences :: [Reference Inlines] -- ^ List of references
4554 }
4655
4756-- | JATS writer type
src/Text/Pandoc/Writers/Jira.hs+41−16
@@ -39,11 +39,17 @@ writeJira :: PandocMonad m => WriterOptions -> Pandoc -> m Text
3939writeJira opts = runDefaultConverter (writerWrapText opts) (pandocToJira opts)
4040
4141-- | State to keep track of footnotes.
42−newtype ConverterState = ConverterState { stNotes :: [Text] }
42+data ConverterState = ConverterState
43+ { stNotes :: [Text] -- ^ Footnotes to be appended to the end of the text
44+ , stInPanel :: Bool -- ^ whether we are in a @{panel}@ block
45+ }
4346
4447-- | Initial converter state.
4548startState :: ConverterState
46−startState = ConverterState { stNotes = [] }
49+startState = ConverterState
50+ { stNotes = []
51+ , stInPanel = False
52+ }
4753
4854-- | Converter monad
4955type JiraConverter m = ReaderT WrapOption (StateT ConverterState m)
@@ -126,13 +132,19 @@ toJiraCode :: PandocMonad m
126132 -> Text
127133 -> JiraConverter m [Jira.Block]
128134toJiraCode (ident, classes, _attribs) code = do
129− let lang = case find (\c -> T.toLower c `elem` knownLanguages) classes of
130− Nothing -> Jira.Language "java"
131− Just l -> Jira.Language l
132− let addAnchor b = if T.null ident
133− then b
134− else [Jira.Para (singleton (Jira.Anchor ident))] <> b
135− return . addAnchor . singleton $ Jira.Code lang mempty code
135+ return . addAnchor ident . singleton $
136+ case find (\c -> T.toLower c `elem` knownLanguages) classes of
137+ Nothing -> Jira.NoFormat mempty code
138+ Just l -> Jira.Code (Jira.Language l) mempty code
139+
140+-- | Prepends an anchor with the given identifier.
141+addAnchor :: Text -> [Jira.Block] -> [Jira.Block]
142+addAnchor ident =
143+ if T.null ident
144+ then id
145+ else \case
146+ Jira.Para xs : bs -> (Jira.Para (Jira.Anchor ident : xs) : bs)
147+ bs -> (Jira.Para (singleton (Jira.Anchor ident)) : bs)
136148
137149-- | Creates a Jira definition list
138150toJiraDefinitionList :: PandocMonad m
@@ -149,11 +161,16 @@ toJiraDefinitionList defItems = do
149161toJiraPanel :: PandocMonad m
150162 => Attr -> [Block]
151163 -> JiraConverter m [Jira.Block]
152−toJiraPanel attr blocks = do
153− jiraBlocks <- toJiraBlocks blocks
154− return $ if attr == nullAttr
155− then jiraBlocks
156− else singleton (Jira.Panel [] jiraBlocks)
164+toJiraPanel (ident, classes, attribs) blocks = do
165+ inPanel <- gets stInPanel
166+ if inPanel || ("panel" `notElem` classes && null attribs)
167+ then addAnchor ident <$> toJiraBlocks blocks
168+ else do
169+ modify $ \st -> st{ stInPanel = True }
170+ jiraBlocks <- toJiraBlocks blocks
171+ modify $ \st -> st{ stInPanel = inPanel }
172+ let params = map (uncurry Jira.Parameter) attribs
173+ return $ singleton (Jira.Panel params $ addAnchor ident jiraBlocks)
157174
158175-- | Creates a Jira header
159176toJiraHeader :: PandocMonad m
@@ -263,6 +280,8 @@ toJiraLink (_, classes, _) (url, _) alias = do
263280 | Just email <- T.stripPrefix "mailto:" url' = (Jira.Email, email)
264281 | "user-account" `elem` classes = (Jira.User, dropTilde url)
265282 | "attachment" `elem` classes = (Jira.Attachment, url)
283+ | "smart-card" `elem` classes = (Jira.SmartCard, url)
284+ | "smart-link" `elem` classes = (Jira.SmartLink, url)
266285 | otherwise = (Jira.External, url)
267286 dropTilde txt = case T.uncons txt of
268287 Just ('~', username) -> username
@@ -292,7 +311,13 @@ quotedToJira qtype xs = do
292311spanToJira :: PandocMonad m
293312 => Attr -> [Inline]
294313 -> JiraConverter m [Jira.Inline]
295−spanToJira (_, _classes, _) = toJiraInlines
314+spanToJira (ident, _classes, attribs) inls =
315+ let wrap = case lookup "color" attribs of
316+ Nothing -> id
317+ Just color -> singleton . Jira.ColorInline (Jira.ColorName color)
318+ in wrap <$> case ident of
319+ "" -> toJiraInlines inls
320+ _ -> (Jira.Anchor ident :) <$> toJiraInlines inls
296321
297322registerNotes :: PandocMonad m => [Block] -> JiraConverter m [Jira.Inline]
298323registerNotes contents = do
@@ -308,7 +333,7 @@ registerNotes contents = do
308333knownLanguages :: [Text]
309334knownLanguages =
310335 [ "actionscript", "ada", "applescript", "bash", "c", "c#", "c++"
311− , "css", "erlang", "go", "groovy", "haskell", "html", "javascript"
336+ , "css", "erlang", "go", "groovy", "haskell", "html", "java", "javascript"
312337 , "json", "lua", "nyan", "objc", "perl", "php", "python", "r", "ruby"
313338 , "scala", "sql", "swift", "visualbasic", "xml", "yaml"
314339 ]
src/Text/Pandoc/Writers/LaTeX.hs+50−563
@@ -1,4 +1,5 @@
11{-# LANGUAGE OverloadedStrings #-}
2+{-# LANGUAGE LambdaCase #-}
23{-# LANGUAGE TupleSections #-}
34{-# LANGUAGE PatternGuards #-}
45{-# LANGUAGE ScopedTypeVariables #-}
@@ -18,11 +19,9 @@ module Text.Pandoc.Writers.LaTeX (
1819 writeLaTeX
1920 , writeBeamer
2021 ) where
21−import Control.Applicative ((<|>))
2222import Control.Monad.State.Strict
23−import Data.Char (isAlphaNum, isAscii, isDigit, isLetter, isSpace,
24− isPunctuation, ord)
25−import Data.List (foldl', intersperse, nubBy, (\\), uncons)
23+import Data.Char (isDigit)
24+import Data.List (intersperse, nubBy, (\\))
2625import Data.Maybe (catMaybes, fromMaybe, isJust, mapMaybe, isNothing)
2726import qualified Data.Map as M
2827import Data.Text (Text)
@@ -30,11 +29,11 @@ import qualified Data.Text as T
3029import Network.URI (unEscapeString)
3130import Text.DocTemplates (FromContext(lookupContext), renderTemplate,
3231 Val(..), Context(..))
33−import Text.Pandoc.BCP47 (Lang (..), getLang, renderLang)
32+import Text.Collate.Lang (Lang (..), renderLang)
3433import Text.Pandoc.Class.PandocMonad (PandocMonad, report, toLang)
3534import Text.Pandoc.Definition
3635import Text.Pandoc.Highlighting (formatLaTeXBlock, formatLaTeXInline, highlight,
37− styleToLaTeX, toListingsLanguage)
36+ styleToLaTeX)
3837import Text.Pandoc.ImageSize
3938import Text.Pandoc.Logging
4039import Text.Pandoc.Options
@@ -44,10 +43,15 @@ import Text.Pandoc.Slides
4443import Text.Pandoc.Walk (query, walk, walkM)
4544import Text.Pandoc.Writers.LaTeX.Caption (getCaption)
4645import Text.Pandoc.Writers.LaTeX.Table (tableToLaTeX)
46+import Text.Pandoc.Writers.LaTeX.Citation (citationsToNatbib,
47+ citationsToBiblatex)
4748import Text.Pandoc.Writers.LaTeX.Types (LW, WriterState (..), startingState)
49+import Text.Pandoc.Writers.LaTeX.Lang (toPolyglossia, toBabel)
50+import Text.Pandoc.Writers.LaTeX.Util (stringToLaTeX, StringContext(..),
51+ toLabel, inCmd,
52+ wrapDiv, hypertarget, labelFor,
53+ getListingsLanguage, mbBraced)
4854import Text.Pandoc.Writers.Shared
49−import Text.Printf (printf)
50−import qualified Data.Text.Normalize as Normalize
5155import qualified Text.Pandoc.Writers.AnnotatedTable as Ann
5256
5357-- | Convert Pandoc to LaTeX.
@@ -142,6 +146,11 @@ pandocToLaTeX options (Pandoc meta blocks) = do
142146
143147 let dirs = query (extract "dir") blocks
144148
149+ let nociteIds = query (\case
150+ Cite cs _ -> map citationId cs
151+ _ -> [])
152+ $ lookupMetaInlines "nocite" meta
153+
145154 let context = defField "toc" (writerTableOfContents options) $
146155 defField "toc-depth" (tshow
147156 (writerTOCDepth options -
@@ -164,6 +173,7 @@ pandocToLaTeX options (Pandoc meta blocks) = do
164173 defField "has-chapters" (stHasChapters st) $
165174 defField "has-frontmatter" (documentClass `elem` frontmatterClasses) $
166175 defField "listings" (writerListings options || stLHS st) $
176+ defField "zero-width-non-joiner" (stZwnj st) $
167177 defField "beamer" beamer $
168178 (if stHighlighting st
169179 then case writerHighlightStyle options of
@@ -174,9 +184,11 @@ pandocToLaTeX options (Pandoc meta blocks) = do
174184 else id) $
175185 (case writerCiteMethod options of
176186 Natbib -> defField "biblio-title" biblioTitle .
177− defField "natbib" True
187+ defField "natbib" True .
188+ defField "nocite-ids" nociteIds
178189 Biblatex -> defField "biblio-title" biblioTitle .
179− defField "biblatex" True
190+ defField "biblatex" True .
191+ defField "nocite-ids" nociteIds
180192 _ -> id) $
181193 defField "colorlinks" (any hasStringValue
182194 ["citecolor", "urlcolor", "linkcolor", "toccolor",
@@ -241,154 +253,6 @@ pandocToLaTeX options (Pandoc meta blocks) = do
241253 Nothing -> main
242254 Just tpl -> renderTemplate tpl context'
243255
244−data StringContext = TextString
245− | URLString
246− | CodeString
247− deriving (Eq)
248−
249−-- escape things as needed for LaTeX
250−stringToLaTeX :: PandocMonad m => StringContext -> Text -> LW m Text
251−stringToLaTeX context zs = do
252− opts <- gets stOptions
253− return $ T.pack $
254− foldr (go opts context) mempty $ T.unpack $
255− if writerPreferAscii opts
256− then Normalize.normalize Normalize.NFD zs
257− else zs
258− where
259− go :: WriterOptions -> StringContext -> Char -> String -> String
260− go opts ctx x xs =
261− let ligatures = isEnabled Ext_smart opts && ctx == TextString
262− isUrl = ctx == URLString
263− mbAccentCmd =
264− if writerPreferAscii opts && ctx == TextString
265− then uncons xs >>= \(c,_) -> M.lookup c accents
266− else Nothing
267− emits s =
268− case mbAccentCmd of
269− Just cmd ->
270− cmd <> "{" <> s <> "}" <> drop 1 xs -- drop combining accent
271− Nothing -> s <> xs
272− emitc c =
273− case mbAccentCmd of
274− Just cmd ->
275− cmd <> "{" <> [c] <> "}" <> drop 1 xs -- drop combining accent
276− Nothing -> c : xs
277− emitcseq cs =
278− case xs of
279− c:_ | isLetter c
280− , ctx == TextString
281− -> cs <> " " <> xs
282− | isSpace c -> cs <> "{}" <> xs
283− | ctx == TextString
284− -> cs <> xs
285− _ -> cs <> "{}" <> xs
286− emitquote cs =
287− case xs of
288− '`':_ -> cs <> "\\," <> xs -- add thin space
289− '\'':_ -> cs <> "\\," <> xs -- add thin space
290− _ -> cs <> xs
291− in case x of
292− '?' | ligatures -> -- avoid ?` ligature
293− case xs of
294− '`':_ -> emits "?{}"
295− _ -> emitc x
296− '!' | ligatures -> -- avoid !` ligature
297− case xs of
298− '`':_ -> emits "!{}"
299− _ -> emitc x
300− '{' -> emits "\\{"
301− '}' -> emits "\\}"
302− '`' | ctx == CodeString -> emitcseq "\\textasciigrave"
303− '$' | not isUrl -> emits "\\$"
304− '%' -> emits "\\%"
305− '&' -> emits "\\&"
306− '_' | not isUrl -> emits "\\_"
307− '#' -> emits "\\#"
308− '-' | not isUrl -> case xs of
309− -- prevent adjacent hyphens from forming ligatures
310− ('-':_) -> emits "-\\/"
311− _ -> emitc '-'
312− '~' | not isUrl -> emitcseq "\\textasciitilde"
313− '^' -> emits "\\^{}"
314− '\\'| isUrl -> emitc '/' -- NB. / works as path sep even on Windows
315− | otherwise -> emitcseq "\\textbackslash"
316− '|' | not isUrl -> emitcseq "\\textbar"
317− '<' -> emitcseq "\\textless"
318− '>' -> emitcseq "\\textgreater"
319− '[' -> emits "{[}" -- to avoid interpretation as
320− ']' -> emits "{]}" -- optional arguments
321− '\'' | ctx == CodeString -> emitcseq "\\textquotesingle"
322− '\160' -> emits "~"
323− '\x200B' -> emits "\\hspace{0pt}" -- zero-width space
324− '\x202F' -> emits "\\,"
325− '\x2026' -> emitcseq "\\ldots"
326− '\x2018' | ligatures -> emitquote "`"
327− '\x2019' | ligatures -> emitquote "'"
328− '\x201C' | ligatures -> emitquote "``"
329− '\x201D' | ligatures -> emitquote "''"
330− '\x2014' | ligatures -> emits "---"
331− '\x2013' | ligatures -> emits "--"
332− _ | writerPreferAscii opts
333− -> case x of
334− 'ı' -> emitcseq "\\i"
335− 'ȷ' -> emitcseq "\\j"
336− 'å' -> emitcseq "\\aa"
337− 'Å' -> emitcseq "\\AA"
338− 'ß' -> emitcseq "\\ss"
339− 'ø' -> emitcseq "\\o"
340− 'Ø' -> emitcseq "\\O"
341− 'Ł' -> emitcseq "\\L"
342− 'ł' -> emitcseq "\\l"
343− 'æ' -> emitcseq "\\ae"
344− 'Æ' -> emitcseq "\\AE"
345− 'œ' -> emitcseq "\\oe"
346− 'Œ' -> emitcseq "\\OE"
347− '£' -> emitcseq "\\pounds"
348− '€' -> emitcseq "\\euro"
349− '©' -> emitcseq "\\copyright"
350− _ -> emitc x
351− | otherwise -> emitc x
352−
353−accents :: M.Map Char String
354−accents = M.fromList
355− [ ('\779' , "\\H")
356− , ('\768' , "\\`")
357− , ('\769' , "\\'")
358− , ('\770' , "\\^")
359− , ('\771' , "\\~")
360− , ('\776' , "\\\"")
361− , ('\775' , "\\.")
362− , ('\772' , "\\=")
363− , ('\781' , "\\|")
364− , ('\817' , "\\b")
365− , ('\807' , "\\c")
366− , ('\783' , "\\G")
367− , ('\777' , "\\h")
368− , ('\803' , "\\d")
369− , ('\785' , "\\f")
370− , ('\778' , "\\r")
371− , ('\865' , "\\t")
372− , ('\782' , "\\U")
373− , ('\780' , "\\v")
374− , ('\774' , "\\u")
375− , ('\808' , "\\k")
376− , ('\785' , "\\newtie")
377− , ('\8413', "\\textcircled")
378− ]
379−
380−toLabel :: PandocMonad m => Text -> LW m Text
381−toLabel z = go `fmap` stringToLaTeX URLString z
382− where
383− go = T.concatMap $ \x -> case x of
384− _ | (isLetter x || isDigit x) && isAscii x -> T.singleton x
385− | x `elemText` "_-+=:;." -> T.singleton x
386− | otherwise -> T.pack $ "ux" <> printf "%x" (ord x)
387−
388−-- | Puts contents into LaTeX command.
389−inCmd :: Text -> Doc Text -> Doc Text
390−inCmd cmd contents = char '\\' <> literal cmd <> braces contents
391−
392256toSlides :: PandocMonad m => [Block] -> LW m [Block]
393257toSlides bs = do
394258 opts <- gets stOptions
@@ -427,7 +291,12 @@ blockToLaTeX :: PandocMonad m
427291 => Block -- ^ Block to convert
428292 -> LW m (Doc Text)
429293blockToLaTeX Null = return empty
430−blockToLaTeX (Div attr@(identifier,"block":_,_) (Header _ _ ils : bs)) = do
294+blockToLaTeX (Div attr@(identifier,"block":dclasses,_)
295+ (Header _ _ ils : bs)) = do
296+ let blockname
297+ | "example" `elem` dclasses = "exampleblock"
298+ | "alert" `elem` dclasses = "alertblock"
299+ | otherwise = "block"
431300 ref <- toLabel identifier
432301 let anchor = if T.null identifier
433302 then empty
@@ -435,8 +304,8 @@ blockToLaTeX (Div attr@(identifier,"block":_,_) (Header _ _ ils : bs)) = do
435304 braces (literal ref) <> braces empty
436305 title' <- inlineListToLaTeX ils
437306 contents <- blockListToLaTeX bs
438− wrapDiv attr $ ("\\begin{block}" <> braces title' <> anchor) $$
439− contents $$ "\\end{block}"
307+ wrapDiv attr $ ("\\begin" <> braces blockname <> braces title' <> anchor) $$
308+ contents $$ "\\end" <> braces blockname
440309blockToLaTeX (Div (identifier,"slide":dclasses,dkvs)
441310 (Header _ (_,hclasses,hkvs) ils : bs)) = do
442311 -- note: [fragile] is required or verbatim breaks
@@ -853,81 +722,6 @@ sectionHeader classes ident level lst = do
853722 braces txtNoNotes
854723 else empty
855724
856−mapAlignment :: Text -> Text
857−mapAlignment a = case a of
858− "top" -> "T"
859− "top-baseline" -> "t"
860− "bottom" -> "b"
861− "center" -> "c"
862− _ -> a
863−
864−wrapDiv :: PandocMonad m => Attr -> Doc Text -> LW m (Doc Text)
865−wrapDiv (_,classes,kvs) t = do
866− beamer <- gets stBeamer
867− let align dir txt = inCmd "begin" dir $$ txt $$ inCmd "end" dir
868− lang <- toLang $ lookup "lang" kvs
869− let wrapColumns = if beamer && "columns" `elem` classes
870− then \contents ->
871− let valign = maybe "T" mapAlignment (lookup "align" kvs)
872− totalwidth = maybe [] (\x -> ["totalwidth=" <> x])
873− (lookup "totalwidth" kvs)
874− onlytextwidth = filter ("onlytextwidth" ==) classes
875− options = text $ T.unpack $ T.intercalate "," $
876− valign : totalwidth ++ onlytextwidth
877− in inCmd "begin" "columns" <> brackets options
878− $$ contents
879− $$ inCmd "end" "columns"
880− else id
881− wrapColumn = if beamer && "column" `elem` classes
882− then \contents ->
883− let valign =
884− maybe ""
885− (brackets . text . T.unpack . mapAlignment)
886− (lookup "align" kvs)
887− w = maybe "0.48" fromPct (lookup "width" kvs)
888− in inCmd "begin" "column" <>
889− valign <>
890− braces (literal w <> "\\textwidth")
891− $$ contents
892− $$ inCmd "end" "column"
893− else id
894− fromPct xs =
895− case T.unsnoc xs of
896− Just (ds, '%') -> case safeRead ds of
897− Just digits -> showFl (digits / 100 :: Double)
898− Nothing -> xs
899− _ -> xs
900− wrapDir = case lookup "dir" kvs of
901− Just "rtl" -> align "RTL"
902− Just "ltr" -> align "LTR"
903− _ -> id
904− wrapLang txt = case lang of
905− Just lng -> let (l, o) = toPolyglossiaEnv lng
906− ops = if T.null o
907− then ""
908− else brackets $ literal o
909− in inCmd "begin" (literal l) <> ops
910− $$ blankline <> txt <> blankline
911− $$ inCmd "end" (literal l)
912− Nothing -> txt
913− return $ wrapColumns . wrapColumn . wrapDir . wrapLang $ t
914−
915−hypertarget :: PandocMonad m => Bool -> Text -> Doc Text -> LW m (Doc Text)
916−hypertarget _ "" x = return x
917−hypertarget addnewline ident x = do
918− ref <- literal `fmap` toLabel ident
919− return $ text "\\hypertarget"
920− <> braces ref
921− <> braces ((if addnewline && not (isEmpty x)
922− then "%" <> cr
923− else empty) <> x)
924−
925−labelFor :: PandocMonad m => Text -> LW m (Doc Text)
926−labelFor "" = return empty
927−labelFor ident = do
928− ref <- literal `fmap` toLabel ident
929− return $ text "\\label" <> braces ref
930−
931725-- | Convert list of inline elements to LaTeX.
932726inlineListToLaTeX :: PandocMonad m
933727 => [Inline] -- ^ Inlines to convert
@@ -952,10 +746,6 @@ inlineListToLaTeX lst = hcat <$>
952746 fixInitialLineBreaks xs
953747 fixInitialLineBreaks xs = xs
954748
955−isQuoted :: Inline -> Bool
956−isQuoted (Quoted _ _) = True
957−isQuoted _ = False
958−
959749-- | Convert inline element to LaTeX
960750inlineToLaTeX :: PandocMonad m
961751 => Inline -- ^ Inline to convert
@@ -1016,8 +806,8 @@ inlineToLaTeX (Cite cits lst) = do
1016806 st <- get
1017807 let opts = stOptions st
1018808 case writerCiteMethod opts of
1019− Natbib -> citationsToNatbib cits
1020− Biblatex -> citationsToBiblatex cits
809+ Natbib -> citationsToNatbib inlineListToLaTeX cits
810+ Biblatex -> citationsToBiblatex inlineListToLaTeX cits
1021811 _ -> inlineListToLaTeX lst
1022812
1023813inlineToLaTeX (Code (_,classes,kvs) str) = do
@@ -1041,7 +831,19 @@ inlineToLaTeX (Code (_,classes,kvs) str) = do
1041831 let chr = case "!\"'()*,-./:;?@" \\ T.unpack str of
1042832 (c:_) -> c
1043833 [] -> '!'
1044− let str' = escapeStringUsing (backslashEscapes "\\{}%~_&#^") str
834+ let isEscapable '\\' = True
835+ isEscapable '{' = True
836+ isEscapable '}' = True
837+ isEscapable '%' = True
838+ isEscapable '~' = True
839+ isEscapable '_' = True
840+ isEscapable '&' = True
841+ isEscapable '#' = True
842+ isEscapable '^' = True
843+ isEscapable _ = False
844+ let escChar c | isEscapable c = T.pack ['\\',c]
845+ | otherwise = T.singleton c
846+ let str' = T.concatMap escChar str
1045847 -- we always put lstinline in a dummy 'passthrough' command
1046848 -- (defined in the default template) so that we don't have
1047849 -- to change the way we escape characters depending on whether
@@ -1091,6 +893,10 @@ inlineToLaTeX (Quoted qt lst) = do
1091893 if isEnabled Ext_smart opts
1092894 then char '`' <> inner <> char '\''
1093895 else char '\x2018' <> inner <> char '\x2019'
896+ where
897+ isQuoted (Span _ (x:_)) = isQuoted x
898+ isQuoted (Quoted _ _) = True
899+ isQuoted _ = False
1094900inlineToLaTeX (Str str) = do
1095901 setEmptyLine False
1096902 liftM literal $ stringToLaTeX TextString str
@@ -1113,7 +919,7 @@ inlineToLaTeX il@(RawInline f str) = do
1113919inlineToLaTeX LineBreak = do
1114920 emptyLine <- gets stEmptyLine
1115921 setEmptyLine True
1116− return $ (if emptyLine then "~" else "") <> "\\\\" <> cr
922+ return $ (if emptyLine then "\\strut " else "") <> "\\\\" <> cr
1117923inlineToLaTeX SoftBreak = do
1118924 wrapText <- gets (writerWrapText . stOptions)
1119925 case wrapText of
@@ -1228,153 +1034,6 @@ protectCode x = [x]
12281034setEmptyLine :: PandocMonad m => Bool -> LW m ()
12291035setEmptyLine b = modify $ \st -> st{ stEmptyLine = b }
12301036
1231−citationsToNatbib :: PandocMonad m => [Citation] -> LW m (Doc Text)
1232−citationsToNatbib
1233− [one]
1234− = citeCommand c p s k
1235− where
1236− Citation { citationId = k
1237− , citationPrefix = p
1238− , citationSuffix = s
1239− , citationMode = m
1240− }
1241− = one
1242− c = case m of
1243− AuthorInText -> "citet"
1244− SuppressAuthor -> "citeyearpar"
1245− NormalCitation -> "citep"
1246−
1247−citationsToNatbib cits
1248− | noPrefix (tail cits) && noSuffix (init cits) && ismode NormalCitation cits
1249− = citeCommand "citep" p s ks
1250− where
1251− noPrefix = all (null . citationPrefix)
1252− noSuffix = all (null . citationSuffix)
1253− ismode m = all ((==) m . citationMode)
1254− p = citationPrefix $
1255− head cits
1256− s = citationSuffix $
1257− last cits
1258− ks = T.intercalate ", " $ map citationId cits
1259−
1260−citationsToNatbib (c:cs) | citationMode c == AuthorInText = do
1261− author <- citeCommand "citeauthor" [] [] (citationId c)
1262− cits <- citationsToNatbib (c { citationMode = SuppressAuthor } : cs)
1263− return $ author <+> cits
1264−
1265−citationsToNatbib cits = do
1266− cits' <- mapM convertOne cits
1267− return $ text "\\citetext{" <> foldl' combineTwo empty cits' <> text "}"
1268− where
1269− combineTwo a b | isEmpty a = b
1270− | otherwise = a <> text "; " <> b
1271− convertOne Citation { citationId = k
1272− , citationPrefix = p
1273− , citationSuffix = s
1274− , citationMode = m
1275− }
1276− = case m of
1277− AuthorInText -> citeCommand "citealt" p s k
1278− SuppressAuthor -> citeCommand "citeyear" p s k
1279− NormalCitation -> citeCommand "citealp" p s k
1280−
1281−citeCommand :: PandocMonad m
1282− => Text -> [Inline] -> [Inline] -> Text -> LW m (Doc Text)
1283−citeCommand c p s k = do
1284− args <- citeArguments p s k
1285− return $ literal ("\\" <> c) <> args
1286−
1287−type Prefix = [Inline]
1288−type Suffix = [Inline]
1289−type CiteId = Text
1290−data CiteGroup = CiteGroup Prefix Suffix [CiteId]
1291−
1292−citeArgumentsList :: PandocMonad m
1293− => CiteGroup -> LW m (Doc Text)
1294−citeArgumentsList (CiteGroup _ _ []) = return empty
1295−citeArgumentsList (CiteGroup pfxs sfxs ids) = do
1296− pdoc <- inlineListToLaTeX pfxs
1297− sdoc <- inlineListToLaTeX sfxs'
1298− return $ optargs pdoc sdoc <>
1299− braces (literal (T.intercalate "," (reverse ids)))
1300− where sfxs' = stripLocatorBraces $ case sfxs of
1301− (Str t : r) -> case T.uncons t of
1302− Just (x, xs)
1303− | T.null xs
1304− , isPunctuation x -> dropWhile (== Space) r
1305− | isPunctuation x -> Str xs : r
1306− _ -> sfxs
1307− _ -> sfxs
1308− optargs pdoc sdoc = case (isEmpty pdoc, isEmpty sdoc) of
1309− (True, True ) -> empty
1310− (True, False) -> brackets sdoc
1311− (_ , _ ) -> brackets pdoc <> brackets sdoc
1312−
1313−citeArguments :: PandocMonad m
1314− => [Inline] -> [Inline] -> Text -> LW m (Doc Text)
1315−citeArguments p s k = citeArgumentsList (CiteGroup p s [k])
1316−
1317−-- strip off {} used to define locator in pandoc-citeproc; see #5722
1318−stripLocatorBraces :: [Inline] -> [Inline]
1319−stripLocatorBraces = walk go
1320− where go (Str xs) = Str $ T.filter (\c -> c /= '{' && c /= '}') xs
1321− go x = x
1322−
1323−citationsToBiblatex :: PandocMonad m => [Citation] -> LW m (Doc Text)
1324−citationsToBiblatex
1325− [one]
1326− = citeCommand cmd p s k
1327− where
1328− Citation { citationId = k
1329− , citationPrefix = p
1330− , citationSuffix = s
1331− , citationMode = m
1332− } = one
1333− cmd = case m of
1334− SuppressAuthor -> "autocite*"
1335− AuthorInText -> "textcite"
1336− NormalCitation -> "autocite"
1337−
1338−citationsToBiblatex (c:cs)
1339− | all (\cit -> null (citationPrefix cit) && null (citationSuffix cit)) (c:cs)
1340− = do
1341− let cmd = case citationMode c of
1342− SuppressAuthor -> "\\autocite*"
1343− AuthorInText -> "\\textcite"
1344− NormalCitation -> "\\autocite"
1345− return $ text cmd <>
1346− braces (literal (T.intercalate "," (map citationId (c:cs))))
1347− | otherwise
1348− = do
1349− let cmd = case citationMode c of
1350− SuppressAuthor -> "\\autocites*"
1351− AuthorInText -> "\\textcites"
1352− NormalCitation -> "\\autocites"
1353−
1354− groups <- mapM citeArgumentsList (reverse (foldl' grouper [] (c:cs)))
1355−
1356− return $ text cmd <> mconcat groups
1357−
1358− where grouper prev cit = case prev of
1359− ((CiteGroup oPfx oSfx ids):rest)
1360− | null oSfx && null pfx -> CiteGroup oPfx sfx (cid:ids) : rest
1361− _ -> CiteGroup pfx sfx [cid] : prev
1362− where pfx = citationPrefix cit
1363− sfx = citationSuffix cit
1364− cid = citationId cit
1365−
1366−citationsToBiblatex _ = return empty
1367−
1368−-- Determine listings language from list of class attributes.
1369−getListingsLanguage :: [Text] -> Maybe Text
1370−getListingsLanguage xs
1371− = foldr ((<|>) . toListingsLanguage) Nothing xs
1372−
1373−mbBraced :: Text -> Text
1374−mbBraced x = if not (T.all isAlphaNum x)
1375− then "{" <> x <> "}"
1376− else x
1377−
13781037-- Extract a key from divs and spans
13791038extract :: Text -> Block -> [Text]
13801039extract key (Div attr _) = lookKey key attr
@@ -1391,175 +1050,3 @@ extractInline _ _ = []
13911050-- Look up a key in an attribute and give a list of its values
13921051lookKey :: Text -> Attr -> [Text]
13931052lookKey key (_,_,kvs) = maybe [] T.words $ lookup key kvs
1394−
1395−-- In environments \Arabic instead of \arabic is used
1396−toPolyglossiaEnv :: Lang -> (Text, Text)
1397−toPolyglossiaEnv l =
1398− case toPolyglossia l of
1399− ("arabic", o) -> ("Arabic", o)
1400− x -> x
1401−
1402−-- Takes a list of the constituents of a BCP 47 language code and
1403−-- converts it to a Polyglossia (language, options) tuple
1404−-- http://mirrors.ctan.org/macros/latex/contrib/polyglossia/polyglossia.pdf
1405−toPolyglossia :: Lang -> (Text, Text)
1406−toPolyglossia (Lang "ar" _ "DZ" _) = ("arabic", "locale=algeria")
1407−toPolyglossia (Lang "ar" _ "IQ" _) = ("arabic", "locale=mashriq")
1408−toPolyglossia (Lang "ar" _ "JO" _) = ("arabic", "locale=mashriq")
1409−toPolyglossia (Lang "ar" _ "LB" _) = ("arabic", "locale=mashriq")
1410−toPolyglossia (Lang "ar" _ "LY" _) = ("arabic", "locale=libya")
1411−toPolyglossia (Lang "ar" _ "MA" _) = ("arabic", "locale=morocco")
1412−toPolyglossia (Lang "ar" _ "MR" _) = ("arabic", "locale=mauritania")
1413−toPolyglossia (Lang "ar" _ "PS" _) = ("arabic", "locale=mashriq")
1414−toPolyglossia (Lang "ar" _ "SY" _) = ("arabic", "locale=mashriq")
1415−toPolyglossia (Lang "ar" _ "TN" _) = ("arabic", "locale=tunisia")
1416−toPolyglossia (Lang "de" _ _ vars)
1417− | "1901" `elem` vars = ("german", "spelling=old")
1418−toPolyglossia (Lang "de" _ "AT" vars)
1419− | "1901" `elem` vars = ("german", "variant=austrian, spelling=old")
1420−toPolyglossia (Lang "de" _ "AT" _) = ("german", "variant=austrian")
1421−toPolyglossia (Lang "de" _ "CH" vars)
1422− | "1901" `elem` vars = ("german", "variant=swiss, spelling=old")
1423−toPolyglossia (Lang "de" _ "CH" _) = ("german", "variant=swiss")
1424−toPolyglossia (Lang "de" _ _ _) = ("german", "")
1425−toPolyglossia (Lang "dsb" _ _ _) = ("lsorbian", "")
1426−toPolyglossia (Lang "el" _ "polyton" _) = ("greek", "variant=poly")
1427−toPolyglossia (Lang "en" _ "AU" _) = ("english", "variant=australian")
1428−toPolyglossia (Lang "en" _ "CA" _) = ("english", "variant=canadian")
1429−toPolyglossia (Lang "en" _ "GB" _) = ("english", "variant=british")
1430−toPolyglossia (Lang "en" _ "NZ" _) = ("english", "variant=newzealand")
1431−toPolyglossia (Lang "en" _ "UK" _) = ("english", "variant=british")
1432−toPolyglossia (Lang "en" _ "US" _) = ("english", "variant=american")
1433−toPolyglossia (Lang "grc" _ _ _) = ("greek", "variant=ancient")
1434−toPolyglossia (Lang "hsb" _ _ _) = ("usorbian", "")
1435−toPolyglossia (Lang "la" _ _ vars)
1436− | "x-classic" `elem` vars = ("latin", "variant=classic")
1437−toPolyglossia (Lang "pt" _ "BR" _) = ("portuguese", "variant=brazilian")
1438−toPolyglossia (Lang "sl" _ _ _) = ("slovenian", "")
1439−toPolyglossia x = (commonFromBcp47 x, "")
1440−
1441−-- Takes a list of the constituents of a BCP 47 language code and
1442−-- converts it to a Babel language string.
1443−-- http://mirrors.ctan.org/macros/latex/required/babel/base/babel.pdf
1444−-- List of supported languages (slightly outdated):
1445−-- http://tug.ctan.org/language/hyph-utf8/doc/generic/hyph-utf8/hyphenation.pdf
1446−toBabel :: Lang -> Text
1447−toBabel (Lang "de" _ "AT" vars)
1448− | "1901" `elem` vars = "austrian"
1449− | otherwise = "naustrian"
1450−toBabel (Lang "de" _ "CH" vars)
1451− | "1901" `elem` vars = "swissgerman"
1452− | otherwise = "nswissgerman"
1453−toBabel (Lang "de" _ _ vars)
1454− | "1901" `elem` vars = "german"
1455− | otherwise = "ngerman"
1456−toBabel (Lang "dsb" _ _ _) = "lowersorbian"
1457−toBabel (Lang "el" _ _ vars)
1458− | "polyton" `elem` vars = "polutonikogreek"
1459−toBabel (Lang "en" _ "AU" _) = "australian"
1460−toBabel (Lang "en" _ "CA" _) = "canadian"
1461−toBabel (Lang "en" _ "GB" _) = "british"
1462−toBabel (Lang "en" _ "NZ" _) = "newzealand"
1463−toBabel (Lang "en" _ "UK" _) = "british"
1464−toBabel (Lang "en" _ "US" _) = "american"
1465−toBabel (Lang "fr" _ "CA" _) = "canadien"
1466−toBabel (Lang "fra" _ _ vars)
1467− | "aca" `elem` vars = "acadian"
1468−toBabel (Lang "grc" _ _ _) = "polutonikogreek"
1469−toBabel (Lang "hsb" _ _ _) = "uppersorbian"
1470−toBabel (Lang "la" _ _ vars)
1471− | "x-classic" `elem` vars = "classiclatin"
1472−toBabel (Lang "pt" _ "BR" _) = "brazilian"
1473−toBabel (Lang "sl" _ _ _) = "slovene"
1474−toBabel x = commonFromBcp47 x
1475−
1476−-- Takes a list of the constituents of a BCP 47 language code
1477−-- and converts it to a string shared by Babel and Polyglossia.
1478−-- https://tools.ietf.org/html/bcp47#section-2.1
1479−commonFromBcp47 :: Lang -> Text
1480−commonFromBcp47 (Lang "sr" "Cyrl" _ _) = "serbianc"
1481−commonFromBcp47 (Lang "zh" "Latn" _ vars)
1482− | "pinyin" `elem` vars = "pinyin"
1483−commonFromBcp47 (Lang l _ _ _) = fromIso l
1484− where
1485− fromIso "af" = "afrikaans"
1486− fromIso "am" = "amharic"
1487− fromIso "ar" = "arabic"
1488− fromIso "as" = "assamese"
1489− fromIso "ast" = "asturian"
1490− fromIso "bg" = "bulgarian"
1491− fromIso "bn" = "bengali"
1492− fromIso "bo" = "tibetan"
1493− fromIso "br" = "breton"
1494− fromIso "ca" = "catalan"
1495− fromIso "cy" = "welsh"
1496− fromIso "cs" = "czech"
1497− fromIso "cop" = "coptic"
1498− fromIso "da" = "danish"
1499− fromIso "dv" = "divehi"
1500− fromIso "el" = "greek"
1501− fromIso "en" = "english"
1502− fromIso "eo" = "esperanto"
1503− fromIso "es" = "spanish"
1504− fromIso "et" = "estonian"
1505− fromIso "eu" = "basque"
1506− fromIso "fa" = "farsi"
1507− fromIso "fi" = "finnish"
1508− fromIso "fr" = "french"
1509− fromIso "fur" = "friulan"
1510− fromIso "ga" = "irish"
1511− fromIso "gd" = "scottish"
1512− fromIso "gez" = "ethiopic"
1513− fromIso "gl" = "galician"
1514− fromIso "he" = "hebrew"
1515− fromIso "hi" = "hindi"
1516− fromIso "hr" = "croatian"
1517− fromIso "hu" = "magyar"
1518− fromIso "hy" = "armenian"
1519− fromIso "ia" = "interlingua"
1520− fromIso "id" = "indonesian"
1521− fromIso "ie" = "interlingua"
1522− fromIso "is" = "icelandic"
1523− fromIso "it" = "italian"
1524− fromIso "ja" = "japanese"
1525− fromIso "km" = "khmer"
1526− fromIso "kmr" = "kurmanji"
1527− fromIso "kn" = "kannada"
1528− fromIso "ko" = "korean"
1529− fromIso "la" = "latin"
1530− fromIso "lo" = "lao"
1531− fromIso "lt" = "lithuanian"
1532− fromIso "lv" = "latvian"
1533− fromIso "ml" = "malayalam"
1534− fromIso "mn" = "mongolian"
1535− fromIso "mr" = "marathi"
1536− fromIso "nb" = "norsk"
1537− fromIso "nl" = "dutch"
1538− fromIso "nn" = "nynorsk"
1539− fromIso "no" = "norsk"
1540− fromIso "nqo" = "nko"
1541− fromIso "oc" = "occitan"
1542− fromIso "pa" = "panjabi"
1543− fromIso "pl" = "polish"
1544− fromIso "pms" = "piedmontese"
1545− fromIso "pt" = "portuguese"
1546− fromIso "rm" = "romansh"
1547− fromIso "ro" = "romanian"
1548− fromIso "ru" = "russian"
1549− fromIso "sa" = "sanskrit"
1550− fromIso "se" = "samin"
1551− fromIso "sk" = "slovak"
1552− fromIso "sq" = "albanian"
1553− fromIso "sr" = "serbian"
1554− fromIso "sv" = "swedish"
1555− fromIso "syr" = "syriac"
1556− fromIso "ta" = "tamil"
1557− fromIso "te" = "telugu"
1558− fromIso "th" = "thai"
1559− fromIso "ti" = "ethiopic"
1560− fromIso "tk" = "turkmen"
1561− fromIso "tr" = "turkish"
1562− fromIso "uk" = "ukrainian"
1563− fromIso "ur" = "urdu"
1564− fromIso "vi" = "vietnamese"
1565− fromIso _ = ""
src/Text/Pandoc/Writers/LaTeX/Caption.hs−1
@@ -1,4 +1,3 @@
1−{-# LANGUAGE OverloadedStrings #-}
21{- |
32 Module : Text.Pandoc.Writers.LaTeX.Caption
43 Copyright : Copyright (C) 2006-2021 John MacFarlane
src/Text/Pandoc/Writers/LaTeX/Citation.hsnew file+181
@@ -0,0 +1,181 @@
1+{-# LANGUAGE OverloadedStrings #-}
2+{- |
3+ Module : Text.Pandoc.Writers.LaTeX.Citation
4+ Copyright : Copyright (C) 2006-2021 John MacFarlane
5+ License : GNU GPL, version 2 or above
6+
7+ Maintainer : John MacFarlane <jgm@berkeley.edu>
8+ Stability : alpha
9+ Portability : portable
10+-}
11+module Text.Pandoc.Writers.LaTeX.Citation
12+ ( citationsToNatbib,
13+ citationsToBiblatex
14+ ) where
15+
16+import Data.Text (Text)
17+import Data.Char (isPunctuation)
18+import qualified Data.Text as T
19+import Text.Pandoc.Class.PandocMonad (PandocMonad)
20+import Text.Pandoc.Definition
21+import Data.List (foldl')
22+import Text.DocLayout (Doc, brackets, empty, (<+>), text, isEmpty, literal,
23+ braces)
24+import Text.Pandoc.Walk
25+import Text.Pandoc.Writers.LaTeX.Types ( LW )
26+
27+citationsToNatbib :: PandocMonad m
28+ => ([Inline] -> LW m (Doc Text))
29+ -> [Citation]
30+ -> LW m (Doc Text)
31+citationsToNatbib inlineListToLaTeX [one]
32+ = citeCommand inlineListToLaTeX c p s k
33+ where
34+ Citation { citationId = k
35+ , citationPrefix = p
36+ , citationSuffix = s
37+ , citationMode = m
38+ }
39+ = one
40+ c = case m of
41+ AuthorInText -> "citet"
42+ SuppressAuthor -> "citeyearpar"
43+ NormalCitation -> "citep"
44+
45+citationsToNatbib inlineListToLaTeX cits
46+ | noPrefix (tail cits) && noSuffix (init cits) && ismode NormalCitation cits
47+ = citeCommand inlineListToLaTeX "citep" p s ks
48+ where
49+ noPrefix = all (null . citationPrefix)
50+ noSuffix = all (null . citationSuffix)
51+ ismode m = all ((==) m . citationMode)
52+ p = citationPrefix $
53+ head cits
54+ s = citationSuffix $
55+ last cits
56+ ks = T.intercalate ", " $ map citationId cits
57+
58+citationsToNatbib inlineListToLaTeX (c:cs)
59+ | citationMode c == AuthorInText = do
60+ author <- citeCommand inlineListToLaTeX "citeauthor" [] [] (citationId c)
61+ cits <- citationsToNatbib inlineListToLaTeX
62+ (c { citationMode = SuppressAuthor } : cs)
63+ return $ author <+> cits
64+
65+citationsToNatbib inlineListToLaTeX cits = do
66+ cits' <- mapM convertOne cits
67+ return $ text "\\citetext{" <> foldl' combineTwo empty cits' <> text "}"
68+ where
69+ citeCommand' = citeCommand inlineListToLaTeX
70+ combineTwo a b | isEmpty a = b
71+ | otherwise = a <> text "; " <> b
72+ convertOne Citation { citationId = k
73+ , citationPrefix = p
74+ , citationSuffix = s
75+ , citationMode = m
76+ }
77+ = case m of
78+ AuthorInText -> citeCommand' "citealt" p s k
79+ SuppressAuthor -> citeCommand' "citeyear" p s k
80+ NormalCitation -> citeCommand' "citealp" p s k
81+
82+citeCommand :: PandocMonad m
83+ => ([Inline] -> LW m (Doc Text))
84+ -> Text
85+ -> [Inline]
86+ -> [Inline]
87+ -> Text
88+ -> LW m (Doc Text)
89+citeCommand inlineListToLaTeX c p s k = do
90+ args <- citeArguments inlineListToLaTeX p s k
91+ return $ literal ("\\" <> c) <> args
92+
93+type Prefix = [Inline]
94+type Suffix = [Inline]
95+type CiteId = Text
96+data CiteGroup = CiteGroup Prefix Suffix [CiteId]
97+
98+citeArgumentsList :: PandocMonad m
99+ => ([Inline] -> LW m (Doc Text))
100+ -> CiteGroup
101+ -> LW m (Doc Text)
102+citeArgumentsList _inlineListToLaTeX (CiteGroup _ _ []) = return empty
103+citeArgumentsList inlineListToLaTeX (CiteGroup pfxs sfxs ids) = do
104+ pdoc <- inlineListToLaTeX pfxs
105+ sdoc <- inlineListToLaTeX sfxs'
106+ return $ optargs pdoc sdoc <>
107+ braces (literal (T.intercalate "," (reverse ids)))
108+ where sfxs' = stripLocatorBraces $ case sfxs of
109+ (Str t : r) -> case T.uncons t of
110+ Just (x, xs)
111+ | T.null xs
112+ , isPunctuation x -> dropWhile (== Space) r
113+ | isPunctuation x -> Str xs : r
114+ _ -> sfxs
115+ _ -> sfxs
116+ optargs pdoc sdoc = case (isEmpty pdoc, isEmpty sdoc) of
117+ (True, True ) -> empty
118+ (True, False) -> brackets sdoc
119+ (_ , _ ) -> brackets pdoc <> brackets sdoc
120+
121+citeArguments :: PandocMonad m
122+ => ([Inline] -> LW m (Doc Text))
123+ -> [Inline]
124+ -> [Inline]
125+ -> Text
126+ -> LW m (Doc Text)
127+citeArguments inlineListToLaTeX p s k =
128+ citeArgumentsList inlineListToLaTeX (CiteGroup p s [k])
129+
130+-- strip off {} used to define locator in pandoc-citeproc; see #5722
131+stripLocatorBraces :: [Inline] -> [Inline]
132+stripLocatorBraces = walk go
133+ where go (Str xs) = Str $ T.filter (\c -> c /= '{' && c /= '}') xs
134+ go x = x
135+
136+citationsToBiblatex :: PandocMonad m
137+ => ([Inline] -> LW m (Doc Text))
138+ -> [Citation] -> LW m (Doc Text)
139+citationsToBiblatex inlineListToLaTeX [one]
140+ = citeCommand inlineListToLaTeX cmd p s k
141+ where
142+ Citation { citationId = k
143+ , citationPrefix = p
144+ , citationSuffix = s
145+ , citationMode = m
146+ } = one
147+ cmd = case m of
148+ SuppressAuthor -> "autocite*"
149+ AuthorInText -> "textcite"
150+ NormalCitation -> "autocite"
151+
152+citationsToBiblatex inlineListToLaTeX (c:cs)
153+ | all (\cit -> null (citationPrefix cit) && null (citationSuffix cit)) (c:cs)
154+ = do
155+ let cmd = case citationMode c of
156+ SuppressAuthor -> "\\autocite*"
157+ AuthorInText -> "\\textcite"
158+ NormalCitation -> "\\autocite"
159+ return $ text cmd <>
160+ braces (literal (T.intercalate "," (map citationId (c:cs))))
161+ | otherwise
162+ = do
163+ let cmd = case citationMode c of
164+ SuppressAuthor -> "\\autocites*"
165+ AuthorInText -> "\\textcites"
166+ NormalCitation -> "\\autocites"
167+
168+ groups <- mapM (citeArgumentsList inlineListToLaTeX)
169+ (reverse (foldl' grouper [] (c:cs)))
170+
171+ return $ text cmd <> mconcat groups
172+
173+ where grouper prev cit = case prev of
174+ ((CiteGroup oPfx oSfx ids):rest)
175+ | null oSfx && null pfx -> CiteGroup oPfx sfx (cid:ids) : rest
176+ _ -> CiteGroup pfx sfx [cid] : prev
177+ where pfx = citationPrefix cit
178+ sfx = citationSuffix cit
179+ cid = citationId cit
180+
181+citationsToBiblatex _ _ = return empty
src/Text/Pandoc/Writers/LaTeX/Lang.hsnew file+192
@@ -0,0 +1,192 @@
1+{-# LANGUAGE OverloadedStrings #-}
2+{-# LANGUAGE ScopedTypeVariables #-}
3+{- |
4+ Module : Text.Pandoc.Writers.LaTeX.Lang
5+ Copyright : Copyright (C) 2006-2021 John MacFarlane
6+ License : GNU GPL, version 2 or above
7+
8+ Maintainer : John MacFarlane <jgm@berkeley.edu>
9+ Stability : alpha
10+ Portability : portable
11+-}
12+module Text.Pandoc.Writers.LaTeX.Lang
13+ ( toPolyglossiaEnv,
14+ toPolyglossia,
15+ toBabel
16+ ) where
17+import Data.Text (Text)
18+import Text.Collate.Lang (Lang(..))
19+
20+
21+-- In environments \Arabic instead of \arabic is used
22+toPolyglossiaEnv :: Lang -> (Text, Text)
23+toPolyglossiaEnv l =
24+ case toPolyglossia l of
25+ ("arabic", o) -> ("Arabic", o)
26+ x -> x
27+
28+-- Takes a list of the constituents of a BCP47 language code and
29+-- converts it to a Polyglossia (language, options) tuple
30+-- http://mirrors.ctan.org/macros/latex/contrib/polyglossia/polyglossia.pdf
31+toPolyglossia :: Lang -> (Text, Text)
32+toPolyglossia (Lang "ar" _ (Just "DZ") _ _ _) = ("arabic", "locale=algeria")
33+toPolyglossia (Lang "ar" _ (Just "IQ") _ _ _) = ("arabic", "locale=mashriq")
34+toPolyglossia (Lang "ar" _ (Just "JO") _ _ _) = ("arabic", "locale=mashriq")
35+toPolyglossia (Lang "ar" _ (Just "LB") _ _ _) = ("arabic", "locale=mashriq")
36+toPolyglossia (Lang "ar" _ (Just "LY") _ _ _) = ("arabic", "locale=libya")
37+toPolyglossia (Lang "ar" _ (Just "MA") _ _ _) = ("arabic", "locale=morocco")
38+toPolyglossia (Lang "ar" _ (Just "MR") _ _ _) = ("arabic", "locale=mauritania")
39+toPolyglossia (Lang "ar" _ (Just "PS") _ _ _) = ("arabic", "locale=mashriq")
40+toPolyglossia (Lang "ar" _ (Just "SY") _ _ _) = ("arabic", "locale=mashriq")
41+toPolyglossia (Lang "ar" _ (Just "TN") _ _ _) = ("arabic", "locale=tunisia")
42+toPolyglossia (Lang "de" _ _ vars _ _)
43+ | "1901" `elem` vars = ("german", "spelling=old")
44+toPolyglossia (Lang "de" _ (Just "AT") vars _ _)
45+ | "1901" `elem` vars = ("german", "variant=austrian, spelling=old")
46+toPolyglossia (Lang "de" _ (Just "AT") _ _ _) = ("german", "variant=austrian")
47+toPolyglossia (Lang "de" _ (Just "CH") vars _ _)
48+ | "1901" `elem` vars = ("german", "variant=swiss, spelling=old")
49+toPolyglossia (Lang "de" _ (Just "CH") _ _ _) = ("german", "variant=swiss")
50+toPolyglossia (Lang "de" _ _ _ _ _) = ("german", "")
51+toPolyglossia (Lang "dsb" _ _ _ _ _) = ("lsorbian", "")
52+toPolyglossia (Lang "el" _ _ vars _ _)
53+ | "polyton" `elem` vars = ("greek", "variant=poly")
54+toPolyglossia (Lang "en" _ (Just "AU") _ _ _) = ("english", "variant=australian")
55+toPolyglossia (Lang "en" _ (Just "CA") _ _ _) = ("english", "variant=canadian")
56+toPolyglossia (Lang "en" _ (Just "GB") _ _ _) = ("english", "variant=british")
57+toPolyglossia (Lang "en" _ (Just "NZ") _ _ _) = ("english", "variant=newzealand")
58+toPolyglossia (Lang "en" _ (Just "UK") _ _ _) = ("english", "variant=british")
59+toPolyglossia (Lang "en" _ (Just "US") _ _ _) = ("english", "variant=american")
60+toPolyglossia (Lang "grc" _ _ _ _ _) = ("greek", "variant=ancient")
61+toPolyglossia (Lang "hsb" _ _ _ _ _) = ("usorbian", "")
62+toPolyglossia (Lang "la" _ _ vars _ _)
63+ | "x-classic" `elem` vars = ("latin", "variant=classic")
64+toPolyglossia (Lang "pt" _ (Just "BR") _ _ _) = ("portuguese", "variant=brazilian")
65+toPolyglossia (Lang "sl" _ _ _ _ _) = ("slovenian", "")
66+toPolyglossia x = (commonFromBcp47 x, "")
67+
68+-- Takes a list of the constituents of a BCP47 language code and
69+-- converts it to a Babel language string.
70+-- http://mirrors.ctan.org/macros/latex/required/babel/base/babel.pdf
71+-- List of supported languages (slightly outdated):
72+-- http://tug.ctan.org/language/hyph-utf8/doc/generic/hyph-utf8/hyphenation.pdf
73+toBabel :: Lang -> Text
74+toBabel (Lang "de" _ (Just "AT") vars _ _)
75+ | "1901" `elem` vars = "austrian"
76+ | otherwise = "naustrian"
77+toBabel (Lang "de" _ (Just "CH") vars _ _)
78+ | "1901" `elem` vars = "swissgerman"
79+ | otherwise = "nswissgerman"
80+toBabel (Lang "de" _ _ vars _ _)
81+ | "1901" `elem` vars = "german"
82+ | otherwise = "ngerman"
83+toBabel (Lang "dsb" _ _ _ _ _) = "lowersorbian"
84+toBabel (Lang "el" _ _ vars _ _)
85+ | "polyton" `elem` vars = "polutonikogreek"
86+toBabel (Lang "en" _ (Just "AU") _ _ _) = "australian"
87+toBabel (Lang "en" _ (Just "CA") _ _ _) = "canadian"
88+toBabel (Lang "en" _ (Just "GB") _ _ _) = "british"
89+toBabel (Lang "en" _ (Just "NZ") _ _ _) = "newzealand"
90+toBabel (Lang "en" _ (Just "UK") _ _ _) = "british"
91+toBabel (Lang "en" _ (Just "US") _ _ _) = "american"
92+toBabel (Lang "fr" _ (Just "CA") _ _ _) = "canadien"
93+toBabel (Lang "fra" _ _ vars _ _)
94+ | "aca" `elem` vars = "acadian"
95+toBabel (Lang "grc" _ _ _ _ _) = "polutonikogreek"
96+toBabel (Lang "hsb" _ _ _ _ _) = "uppersorbian"
97+toBabel (Lang "la" _ _ vars _ _)
98+ | "x-classic" `elem` vars = "classiclatin"
99+toBabel (Lang "pt" _ (Just "BR") _ _ _) = "brazilian"
100+toBabel (Lang "sl" _ _ _ _ _) = "slovene"
101+toBabel x = commonFromBcp47 x
102+
103+-- Takes a list of the constituents of a BCP47 language code
104+-- and converts it to a string shared by Babel and Polyglossia.
105+-- https://tools.ietf.org/html/bcp47#section-2.1
106+commonFromBcp47 :: Lang -> Text
107+commonFromBcp47 (Lang "sr" (Just "Cyrl") _ _ _ _) = "serbianc"
108+commonFromBcp47 (Lang "zh" (Just "Latn") _ vars _ _)
109+ | "pinyin" `elem` vars = "pinyin"
110+commonFromBcp47 (Lang l _ _ _ _ _) = fromIso l
111+ where
112+ fromIso "af" = "afrikaans"
113+ fromIso "am" = "amharic"
114+ fromIso "ar" = "arabic"
115+ fromIso "as" = "assamese"
116+ fromIso "ast" = "asturian"
117+ fromIso "bg" = "bulgarian"
118+ fromIso "bn" = "bengali"
119+ fromIso "bo" = "tibetan"
120+ fromIso "br" = "breton"
121+ fromIso "ca" = "catalan"
122+ fromIso "cy" = "welsh"
123+ fromIso "cs" = "czech"
124+ fromIso "cop" = "coptic"
125+ fromIso "da" = "danish"
126+ fromIso "dv" = "divehi"
127+ fromIso "el" = "greek"
128+ fromIso "en" = "english"
129+ fromIso "eo" = "esperanto"
130+ fromIso "es" = "spanish"
131+ fromIso "et" = "estonian"
132+ fromIso "eu" = "basque"
133+ fromIso "fa" = "farsi"
134+ fromIso "fi" = "finnish"
135+ fromIso "fr" = "french"
136+ fromIso "fur" = "friulan"
137+ fromIso "ga" = "irish"
138+ fromIso "gd" = "scottish"
139+ fromIso "gez" = "ethiopic"
140+ fromIso "gl" = "galician"
141+ fromIso "he" = "hebrew"
142+ fromIso "hi" = "hindi"
143+ fromIso "hr" = "croatian"
144+ fromIso "hu" = "magyar"
145+ fromIso "hy" = "armenian"
146+ fromIso "ia" = "interlingua"
147+ fromIso "id" = "indonesian"
148+ fromIso "ie" = "interlingua"
149+ fromIso "is" = "icelandic"
150+ fromIso "it" = "italian"
151+ fromIso "ja" = "japanese"
152+ fromIso "km" = "khmer"
153+ fromIso "kmr" = "kurmanji"
154+ fromIso "kn" = "kannada"
155+ fromIso "ko" = "korean"
156+ fromIso "la" = "latin"
157+ fromIso "lo" = "lao"
158+ fromIso "lt" = "lithuanian"
159+ fromIso "lv" = "latvian"
160+ fromIso "ml" = "malayalam"
161+ fromIso "mn" = "mongolian"
162+ fromIso "mr" = "marathi"
163+ fromIso "nb" = "norsk"
164+ fromIso "nl" = "dutch"
165+ fromIso "nn" = "nynorsk"
166+ fromIso "no" = "norsk"
167+ fromIso "nqo" = "nko"
168+ fromIso "oc" = "occitan"
169+ fromIso "pa" = "panjabi"
170+ fromIso "pl" = "polish"
171+ fromIso "pms" = "piedmontese"
172+ fromIso "pt" = "portuguese"
173+ fromIso "rm" = "romansh"
174+ fromIso "ro" = "romanian"
175+ fromIso "ru" = "russian"
176+ fromIso "sa" = "sanskrit"
177+ fromIso "se" = "samin"
178+ fromIso "sk" = "slovak"
179+ fromIso "sq" = "albanian"
180+ fromIso "sr" = "serbian"
181+ fromIso "sv" = "swedish"
182+ fromIso "syr" = "syriac"
183+ fromIso "ta" = "tamil"
184+ fromIso "te" = "telugu"
185+ fromIso "th" = "thai"
186+ fromIso "ti" = "ethiopic"
187+ fromIso "tk" = "turkmen"
188+ fromIso "tr" = "turkish"
189+ fromIso "uk" = "ukrainian"
190+ fromIso "ur" = "urdu"
191+ fromIso "vi" = "vietnamese"
192+ fromIso _ = ""
src/Text/Pandoc/Writers/LaTeX/Table.hs+21−8
@@ -16,6 +16,7 @@ module Text.Pandoc.Writers.LaTeX.Table
1616 ) where
1717import Control.Monad.State.Strict
1818import Data.List (intersperse)
19+import qualified Data.List.NonEmpty as NonEmpty
1920import Data.List.NonEmpty (NonEmpty ((:|)))
2021import Data.Text (Text)
2122import qualified Data.Text as T
@@ -25,7 +26,8 @@ import Text.DocLayout
2526 ( Doc, braces, cr, empty, hcat, hsep, isEmpty, literal, nest
2627 , text, vcat, ($$) )
2728import Text.Pandoc.Shared (blocksToInlines, splitBy, tshow)
28−import Text.Pandoc.Walk (walk)
29+import Text.Pandoc.Walk (walk, query)
30+import Data.Monoid (Any(..))
2931import Text.Pandoc.Writers.LaTeX.Caption (getCaption)
3032import Text.Pandoc.Writers.LaTeX.Notes (notesToLaTeX)
3133import Text.Pandoc.Writers.LaTeX.Types
@@ -219,9 +221,7 @@ footRows (Ann.TableFoot _attr rows) = map headerRowCells rows
219221-- we need to go to some lengths to get line breaks working:
220222-- as LineBreak bs = \vtop{\hbox{\strut as}\hbox{\strut bs}}.
221223fixLineBreaks :: Block -> Block
222−fixLineBreaks (Para ils) = Para $ fixLineBreaks' ils
223−fixLineBreaks (Plain ils) = Plain $ fixLineBreaks' ils
224−fixLineBreaks x = x
224+fixLineBreaks = walk fixLineBreaks'
225225
226226fixLineBreaks' :: [Inline] -> [Inline]
227227fixLineBreaks' ils = case splitBy (== LineBreak) ils of
@@ -245,8 +245,13 @@ cellToLaTeX :: PandocMonad m
245245 -> Ann.Cell
246246 -> LW m (Doc Text)
247247cellToLaTeX blockListToLaTeX celltype annotatedCell = do
248− let (Ann.Cell _specs _colnum cell) = annotatedCell
249− let (Cell _attr align rowspan colspan blocks) = cell
248+ let (Ann.Cell specs _colnum cell) = annotatedCell
249+ let hasWidths = snd (NonEmpty.head specs) /= ColWidthDefault
250+ let specAlign = fst (NonEmpty.head specs)
251+ let (Cell _attr align' rowspan colspan blocks) = cell
252+ let align = case align' of
253+ AlignDefault -> specAlign
254+ _ -> align'
250255 beamer <- gets stBeamer
251256 externalNotes <- gets stExternalNotes
252257 inMinipage <- gets stInMinipage
@@ -257,8 +262,13 @@ cellToLaTeX blockListToLaTeX celltype annotatedCell = do
257262 Para{} -> True
258263 Plain{} -> True
259264 _ -> False
265+ let hasLineBreak LineBreak = Any True
266+ hasLineBreak _ = Any False
267+ let hasLineBreaks = getAny $ query hasLineBreak blocks
260268 result <-
261− if all isPlainOrPara blocks
269+ if not hasWidths || (celltype /= HeaderCell
270+ && all isPlainOrPara blocks
271+ && not hasLineBreaks)
262272 then
263273 blockListToLaTeX $ walk fixLineBreaks $ walk displayMathToInline blocks
264274 else do
@@ -271,7 +281,9 @@ cellToLaTeX blockListToLaTeX celltype annotatedCell = do
271281 let halign = literal $ alignCommand align
272282 return $ "\\begin{minipage}" <> valign <>
273283 braces "\\linewidth" <> halign <> cr <>
274− cellContents <> cr <>
284+ cellContents <>
285+ (if hasLineBreaks then "\\strut" else mempty)
286+ <> cr <>
275287 "\\end{minipage}"
276288 modify $ \st -> st{ stExternalNotes = externalNotes }
277289 when (rowspan /= RowSpan 1) $
@@ -292,3 +304,4 @@ cellToLaTeX blockListToLaTeX celltype annotatedCell = do
292304data CellType
293305 = HeaderCell
294306 | BodyCell
307+ deriving Eq
src/Text/Pandoc/Writers/LaTeX/Types.hs+2−1
@@ -40,7 +40,7 @@ data WriterState =
4040 , stCsquotes :: Bool -- ^ true if document uses csquotes
4141 , stHighlighting :: Bool -- ^ true if document has highlighted code
4242 , stIncremental :: Bool -- ^ true if beamer lists should be
43− -- displayed bit by bit
43+ , stZwnj :: Bool -- ^ true if document has a ZWNJ character
4444 , stInternalLinks :: [Text] -- ^ list of internal link targets
4545 , stBeamer :: Bool -- ^ produce beamer
4646 , stEmptyLine :: Bool -- ^ true if no content on line
@@ -74,6 +74,7 @@ startingState options =
7474 , stCsquotes = False
7575 , stHighlighting = False
7676 , stIncremental = writerIncremental options
77+ , stZwnj = False
7778 , stInternalLinks = []
7879 , stBeamer = False
7980 , stEmptyLine = True
src/Text/Pandoc/Writers/LaTeX/Util.hsnew file+275
@@ -0,0 +1,275 @@
1+{-# LANGUAGE OverloadedStrings #-}
2+{- |
3+ Module : Text.Pandoc.Writers.LaTeX.Util
4+ Copyright : Copyright (C) 2006-2021 John MacFarlane
5+ License : GNU GPL, version 2 or above
6+
7+ Maintainer : John MacFarlane <jgm@berkeley.edu>
8+ Stability : alpha
9+ Portability : portable
10+-}
11+module Text.Pandoc.Writers.LaTeX.Util (
12+ stringToLaTeX
13+ , StringContext(..)
14+ , toLabel
15+ , inCmd
16+ , wrapDiv
17+ , hypertarget
18+ , labelFor
19+ , getListingsLanguage
20+ , mbBraced
21+ )
22+where
23+
24+import Control.Applicative ((<|>))
25+import Control.Monad (when)
26+import Text.Pandoc.Class (PandocMonad, toLang)
27+import Text.Pandoc.Options (WriterOptions(..), isEnabled)
28+import Text.Pandoc.Writers.LaTeX.Types (LW, WriterState(..))
29+import Text.Pandoc.Writers.LaTeX.Lang (toPolyglossiaEnv)
30+import Text.Pandoc.Highlighting (toListingsLanguage)
31+import Text.DocLayout
32+import Text.Pandoc.Definition
33+import Text.Pandoc.ImageSize (showFl)
34+import Control.Monad.State.Strict (gets, modify)
35+import Data.Text (Text)
36+import qualified Data.Text as T
37+import Text.Pandoc.Extensions (Extension(Ext_smart))
38+import Data.Char (isLetter, isSpace, isDigit, isAscii, ord, isAlphaNum)
39+import Text.Printf (printf)
40+import Text.Pandoc.Shared (safeRead, elemText)
41+import qualified Data.Text.Normalize as Normalize
42+import Data.List (uncons)
43+
44+data StringContext = TextString
45+ | URLString
46+ | CodeString
47+ deriving (Eq)
48+
49+-- escape things as needed for LaTeX
50+stringToLaTeX :: PandocMonad m => StringContext -> Text -> LW m Text
51+stringToLaTeX context zs = do
52+ opts <- gets stOptions
53+ when ('\x200c' `elemText` zs) $
54+ modify (\s -> s { stZwnj = True })
55+ return $ T.pack $
56+ foldr (go opts context) mempty $ T.unpack $
57+ if writerPreferAscii opts
58+ then Normalize.normalize Normalize.NFD zs
59+ else zs
60+ where
61+ go :: WriterOptions -> StringContext -> Char -> String -> String
62+ go opts ctx x xs =
63+ let ligatures = isEnabled Ext_smart opts && ctx == TextString
64+ isUrl = ctx == URLString
65+ mbAccentCmd =
66+ if writerPreferAscii opts && ctx == TextString
67+ then uncons xs >>= \(c,_) -> lookupAccent c
68+ else Nothing
69+ emits s =
70+ case mbAccentCmd of
71+ Just cmd ->
72+ cmd <> "{" <> s <> "}" <> drop 1 xs -- drop combining accent
73+ Nothing -> s <> xs
74+ emitc c =
75+ case mbAccentCmd of
76+ Just cmd ->
77+ cmd <> "{" <> [c] <> "}" <> drop 1 xs -- drop combining accent
78+ Nothing -> c : xs
79+ emitcseq cs =
80+ case xs of
81+ c:_ | isLetter c
82+ , ctx == TextString
83+ -> cs <> " " <> xs
84+ | isSpace c -> cs <> "{}" <> xs
85+ | ctx == TextString
86+ -> cs <> xs
87+ _ -> cs <> "{}" <> xs
88+ emitquote cs =
89+ case xs of
90+ '`':_ -> cs <> "\\," <> xs -- add thin space
91+ '\'':_ -> cs <> "\\," <> xs -- add thin space
92+ _ -> cs <> xs
93+ in case x of
94+ '?' | ligatures -> -- avoid ?` ligature
95+ case xs of
96+ '`':_ -> emits "?{}"
97+ _ -> emitc x
98+ '!' | ligatures -> -- avoid !` ligature
99+ case xs of
100+ '`':_ -> emits "!{}"
101+ _ -> emitc x
102+ '{' -> emits "\\{"
103+ '}' -> emits "\\}"
104+ '`' | ctx == CodeString -> emitcseq "\\textasciigrave"
105+ '$' | not isUrl -> emits "\\$"
106+ '%' -> emits "\\%"
107+ '&' -> emits "\\&"
108+ '_' | not isUrl -> emits "\\_"
109+ '#' -> emits "\\#"
110+ '-' | not isUrl -> case xs of
111+ -- prevent adjacent hyphens from forming ligatures
112+ ('-':_) -> emits "-\\/"
113+ _ -> emitc '-'
114+ '~' | not isUrl -> emitcseq "\\textasciitilde"
115+ '^' -> emits "\\^{}"
116+ '\\'| isUrl -> emitc '/' -- NB. / works as path sep even on Windows
117+ | otherwise -> emitcseq "\\textbackslash"
118+ '|' | not isUrl -> emitcseq "\\textbar"
119+ '<' -> emitcseq "\\textless"
120+ '>' -> emitcseq "\\textgreater"
121+ '[' -> emits "{[}" -- to avoid interpretation as
122+ ']' -> emits "{]}" -- optional arguments
123+ '\'' | ctx == CodeString -> emitcseq "\\textquotesingle"
124+ '\160' -> emits "~"
125+ '\x200B' -> emits "\\hspace{0pt}" -- zero-width space
126+ '\x202F' -> emits "\\,"
127+ '\x2026' -> emitcseq "\\ldots"
128+ '\x2018' | ligatures -> emitquote "`"
129+ '\x2019' | ligatures -> emitquote "'"
130+ '\x201C' | ligatures -> emitquote "``"
131+ '\x201D' | ligatures -> emitquote "''"
132+ '\x2014' | ligatures -> emits "---"
133+ '\x2013' | ligatures -> emits "--"
134+ _ | writerPreferAscii opts
135+ -> case x of
136+ 'ı' -> emitcseq "\\i"
137+ 'ȷ' -> emitcseq "\\j"
138+ 'å' -> emitcseq "\\aa"
139+ 'Å' -> emitcseq "\\AA"
140+ 'ß' -> emitcseq "\\ss"
141+ 'ø' -> emitcseq "\\o"
142+ 'Ø' -> emitcseq "\\O"
143+ 'Ł' -> emitcseq "\\L"
144+ 'ł' -> emitcseq "\\l"
145+ 'æ' -> emitcseq "\\ae"
146+ 'Æ' -> emitcseq "\\AE"
147+ 'œ' -> emitcseq "\\oe"
148+ 'Œ' -> emitcseq "\\OE"
149+ '£' -> emitcseq "\\pounds"
150+ '€' -> emitcseq "\\euro"
151+ '©' -> emitcseq "\\copyright"
152+ _ -> emitc x
153+ | otherwise -> emitc x
154+
155+lookupAccent :: Char -> Maybe String
156+lookupAccent '\779' = Just "\\H"
157+lookupAccent '\768' = Just "\\`"
158+lookupAccent '\769' = Just "\\'"
159+lookupAccent '\770' = Just "\\^"
160+lookupAccent '\771' = Just "\\~"
161+lookupAccent '\776' = Just "\\\""
162+lookupAccent '\775' = Just "\\."
163+lookupAccent '\772' = Just "\\="
164+lookupAccent '\781' = Just "\\|"
165+lookupAccent '\817' = Just "\\b"
166+lookupAccent '\807' = Just "\\c"
167+lookupAccent '\783' = Just "\\G"
168+lookupAccent '\777' = Just "\\h"
169+lookupAccent '\803' = Just "\\d"
170+lookupAccent '\785' = Just "\\f"
171+lookupAccent '\778' = Just "\\r"
172+lookupAccent '\865' = Just "\\t"
173+lookupAccent '\782' = Just "\\U"
174+lookupAccent '\780' = Just "\\v"
175+lookupAccent '\774' = Just "\\u"
176+lookupAccent '\808' = Just "\\k"
177+lookupAccent '\8413' = Just "\\textcircled"
178+lookupAccent _ = Nothing
179+
180+toLabel :: PandocMonad m => Text -> LW m Text
181+toLabel z = go `fmap` stringToLaTeX URLString z
182+ where
183+ go = T.concatMap $ \x -> case x of
184+ _ | (isLetter x || isDigit x) && isAscii x -> T.singleton x
185+ | x `elemText` "_-+=:;." -> T.singleton x
186+ | otherwise -> T.pack $ "ux" <> printf "%x" (ord x)
187+
188+-- | Puts contents into LaTeX command.
189+inCmd :: Text -> Doc Text -> Doc Text
190+inCmd cmd contents = char '\\' <> literal cmd <> braces contents
191+
192+mapAlignment :: Text -> Text
193+mapAlignment a = case a of
194+ "top" -> "T"
195+ "top-baseline" -> "t"
196+ "bottom" -> "b"
197+ "center" -> "c"
198+ _ -> a
199+
200+wrapDiv :: PandocMonad m => Attr -> Doc Text -> LW m (Doc Text)
201+wrapDiv (_,classes,kvs) t = do
202+ beamer <- gets stBeamer
203+ let align dir txt = inCmd "begin" dir $$ txt $$ inCmd "end" dir
204+ lang <- toLang $ lookup "lang" kvs
205+ let wrapColumns = if beamer && "columns" `elem` classes
206+ then \contents ->
207+ let valign = maybe "T" mapAlignment (lookup "align" kvs)
208+ totalwidth = maybe [] (\x -> ["totalwidth=" <> x])
209+ (lookup "totalwidth" kvs)
210+ onlytextwidth = filter ("onlytextwidth" ==) classes
211+ options = text $ T.unpack $ T.intercalate "," $
212+ valign : totalwidth ++ onlytextwidth
213+ in inCmd "begin" "columns" <> brackets options
214+ $$ contents
215+ $$ inCmd "end" "columns"
216+ else id
217+ wrapColumn = if beamer && "column" `elem` classes
218+ then \contents ->
219+ let valign =
220+ maybe ""
221+ (brackets . text . T.unpack . mapAlignment)
222+ (lookup "align" kvs)
223+ w = maybe "0.48" fromPct (lookup "width" kvs)
224+ in inCmd "begin" "column" <>
225+ valign <>
226+ braces (literal w <> "\\textwidth")
227+ $$ contents
228+ $$ inCmd "end" "column"
229+ else id
230+ fromPct xs =
231+ case T.unsnoc xs of
232+ Just (ds, '%') -> case safeRead ds of
233+ Just digits -> showFl (digits / 100 :: Double)
234+ Nothing -> xs
235+ _ -> xs
236+ wrapDir = case lookup "dir" kvs of
237+ Just "rtl" -> align "RTL"
238+ Just "ltr" -> align "LTR"
239+ _ -> id
240+ wrapLang txt = case lang of
241+ Just lng -> let (l, o) = toPolyglossiaEnv lng
242+ ops = if T.null o
243+ then ""
244+ else brackets $ literal o
245+ in inCmd "begin" (literal l) <> ops
246+ $$ blankline <> txt <> blankline
247+ $$ inCmd "end" (literal l)
248+ Nothing -> txt
249+ return $ wrapColumns . wrapColumn . wrapDir . wrapLang $ t
250+
251+hypertarget :: PandocMonad m => Bool -> Text -> Doc Text -> LW m (Doc Text)
252+hypertarget _ "" x = return x
253+hypertarget addnewline ident x = do
254+ ref <- literal `fmap` toLabel ident
255+ return $ text "\\hypertarget"
256+ <> braces ref
257+ <> braces ((if addnewline && not (isEmpty x)
258+ then "%" <> cr
259+ else empty) <> x)
260+
261+labelFor :: PandocMonad m => Text -> LW m (Doc Text)
262+labelFor "" = return empty
263+labelFor ident = do
264+ ref <- literal `fmap` toLabel ident
265+ return $ text "\\label" <> braces ref
266+
267+-- Determine listings language from list of class attributes.
268+getListingsLanguage :: [Text] -> Maybe Text
269+getListingsLanguage xs
270+ = foldr ((<|>) . toListingsLanguage) Nothing xs
271+
272+mbBraced :: Text -> Text
273+mbBraced x = if not (T.all isAlphaNum x)
274+ then "{" <> x <> "}"
275+ else x
src/Text/Pandoc/Writers/Man.hs+2−2

This diff is too big to show here.

src/Text/Pandoc/Writers/Markdown.hs+59−646

This diff is too big to show here.

src/Text/Pandoc/Writers/Markdown/Inline.hsnew file+616

This diff is too big to show here.

src/Text/Pandoc/Writers/Markdown/Types.hsnew file+81

This diff is too big to show here.

src/Text/Pandoc/Writers/Ms.hs+24−8

This diff is too big to show here.

src/Text/Pandoc/Writers/Muse.hs+6−3

This diff is too big to show here.

src/Text/Pandoc/Writers/ODT.hs+4−3

This diff is too big to show here.

src/Text/Pandoc/Writers/OpenDocument.hs+50−54

This diff is too big to show here.

src/Text/Pandoc/Writers/Org.hs+24−14

This diff is too big to show here.

src/Text/Pandoc/Writers/Powerpoint.hs+1−1

This diff is too big to show here.

src/Text/Pandoc/Writers/Powerpoint/Output.hs+43−31

This diff is too big to show here.

src/Text/Pandoc/Writers/Powerpoint/Presentation.hs+2−3

This diff is too big to show here.

src/Text/Pandoc/Writers/RST.hs+14−10

This diff is too big to show here.

src/Text/Pandoc/Writers/RTF.hs+16−10

This diff is too big to show here.

src/Text/Pandoc/Writers/Shared.hs+18−3

This diff is too big to show here.

src/Text/Pandoc/Writers/TEI.hs+4−3

This diff is too big to show here.

src/Text/Pandoc/Writers/Texinfo.hs+22−15

This diff is too big to show here.

src/Text/Pandoc/Writers/ZimWiki.hs+4−2

This diff is too big to show here.

src/Text/Pandoc/XML.hs+28−2

This diff is too big to show here.

src/Text/Pandoc/XML/Light/Proc.hs−1

This diff is too big to show here.

src/Text/Pandoc/XML/Light/Types.hs+4−4

This diff is too big to show here.

stack.yaml+11−14

This diff is too big to show here.

test/Tests/Command.hs+7−14

This diff is too big to show here.

test/Tests/Helpers.hs+23

This diff is too big to show here.

test/Tests/Old.hs+3−12

This diff is too big to show here.

test/Tests/Readers/Docx.hs+25−5

This diff is too big to show here.

test/Tests/Readers/EPUB.hs+1−1

This diff is too big to show here.

test/Tests/Readers/HTML.hs+20−5

This diff is too big to show here.

test/Tests/Readers/Jira.hs+14

This diff is too big to show here.

test/Tests/Readers/LaTeX.hs+1−18

This diff is too big to show here.

test/Tests/Readers/Markdown.hs+3−3

This diff is too big to show here.

test/Tests/Readers/Odt.hs+1

This diff is too big to show here.

test/Tests/Writers/ConTeXt.hs+122−113

This diff is too big to show here.

test/Tests/Writers/Docbook.hs+43−6

This diff is too big to show here.

test/Tests/Writers/Docx.hs+5

This diff is too big to show here.

test/Tests/Writers/HTML.hs+57−52

This diff is too big to show here.

test/Tests/Writers/JATS.hs+135−91

This diff is too big to show here.

test/Tests/Writers/Jira.hs+60−1

This diff is too big to show here.

test/Tests/Writers/OOXML.hs+3−1

This diff is too big to show here.

test/command/1279.md+1−1

This diff is too big to show here.

test/command/2103.mdnew file+8

This diff is too big to show here.

test/command/2874.md+2−2

This diff is too big to show here.

test/command/3752.mdnew file+60

This diff is too big to show here.

test/command/3792.md+1−1

This diff is too big to show here.

test/command/4063.mdnew file+29

This diff is too big to show here.

test/command/4164.md+1−1

This diff is too big to show here.

test/command/4442.md+1−1

This diff is too big to show here.

test/command/4465.mdnew file+15

This diff is too big to show here.

test/command/5304.md+1−1

This diff is too big to show here.

test/command/5367.md+6−2

This diff is too big to show here.

test/command/5519.md+1−1

This diff is too big to show here.

test/command/6026.mdnew file+19

This diff is too big to show here.

test/command/6541.mdnew file+27

This diff is too big to show here.

test/command/6620.md+3

This diff is too big to show here.

test/command/6658.mdnew file+75

This diff is too big to show here.

test/command/6709.mdnew file+11

This diff is too big to show here.

test/command/6890.md+2−2

This diff is too big to show here.

test/command/6925.md+2−2

This diff is too big to show here.

test/command/6958.mdnew file+10

This diff is too big to show here.

test/command/7041.mdnew file+23

This diff is too big to show here.

test/command/7099.md+1−1

This diff is too big to show here.

test/command/7129.mdnew file+27

This diff is too big to show here.

test/command/7132.mdnew file+10

This diff is too big to show here.

test/command/7134.mdnew file+16

This diff is too big to show here.

test/command/7145.mdnew file+12

This diff is too big to show here.

test/command/7155.mdnew file+15

This diff is too big to show here.

test/command/7173.mdnew file+137

This diff is too big to show here.

test/command/7208.mdnew file+6

This diff is too big to show here.

test/command/7214.mdnew file+28

This diff is too big to show here.

test/command/7216.mdnew file+19

This diff is too big to show here.

test/command/7266.mdnew file+10

This diff is too big to show here.

test/command/7272.mdnew file+27

This diff is too big to show here.

test/command/7278.mdnew file+38

This diff is too big to show here.

test/command/7282.mdnew file+7

This diff is too big to show here.

test/command/7288.mdnew file+40

This diff is too big to show here.

test/command/7299.mdnew file+23

This diff is too big to show here.

test/command/7321.mdnew file+24

This diff is too big to show here.

test/command/7323.mdnew file+29

This diff is too big to show here.

test/command/7324.mdnew file+25

This diff is too big to show here.

test/command/7339.mdnew file+11

This diff is too big to show here.

test/command/7340.mdnew file+6

This diff is too big to show here.

test/command/7376.mdnew file+16

This diff is too big to show here.

test/command/7394.mdnew file+85

This diff is too big to show here.

test/command/7397.mdnew file+14

This diff is too big to show here.

test/command/7400.mdnew file+9

This diff is too big to show here.

test/command/7416.mdnew file+19

This diff is too big to show here.

test/command/averroes.bibnew file+95

This diff is too big to show here.

test/command/biblatex-baez-article.md+1−1

This diff is too big to show here.

test/command/biblatex-baez-online.md+1−1

This diff is too big to show here.

test/command/biblatex-basic.md+5−3

This diff is too big to show here.

test/command/biblatex-examples.bibdeleted−1674

This diff is too big to show here.

test/command/biblatex-inproceedings.md+1−1

This diff is too big to show here.

test/command/biblatex-itzhaki.md+1−1

This diff is too big to show here.

test/command/biblatex-jaffe.md+2−2

This diff is too big to show here.

test/command/biblatex-moraux.md+1−1

This diff is too big to show here.

test/command/biblatex-nussbaum.mddeleted−63

This diff is too big to show here.

test/command/biblatex-quotes.md+1−1

This diff is too big to show here.

test/command/biblatex-sigfridsson.md+1−1

This diff is too big to show here.

test/command/biblatex-spiegelberg.md+2−2

This diff is too big to show here.

test/command/biblatex-test-case-conversion.md+2−2

This diff is too big to show here.

test/command/biblatex-textnormal.md+1−1

This diff is too big to show here.

test/command/biblatex-wassenberg.md+1−1

This diff is too big to show here.

test/command/biblatex-wilde.md+1−1

This diff is too big to show here.

test/command/chap1/spider.pngnew file

Binary file not shown.

test/command/chap1/text.mdnew file+17

This diff is too big to show here.

test/command/chap2/spider.pngnew file

Binary file not shown.

test/command/chap2/text.mdnew file+5

This diff is too big to show here.

test/command/defaults-inheritance-2.md+1−1

This diff is too big to show here.

test/command/duplicate_attributes.mdnew file+7

This diff is too big to show here.

test/command/mmd-metadata.mdnew file+20

This diff is too big to show here.

test/command/newif.mdnew file+55

This diff is too big to show here.

test/command/pandoc-citeproc-119.md+1−1

This diff is too big to show here.

test/command/pandoc-citeproc-320a.md+3−3

This diff is too big to show here.

test/command/pandoc-citeproc-322.md+1−1

This diff is too big to show here.

test/command/pandoc-citeproc-356.md+2−7

This diff is too big to show here.

test/command/pandoc-citeproc-65.md+1−1

This diff is too big to show here.

test/command/pandoc-citeproc-70.md+2−2

This diff is too big to show here.

test/command/pandoc-citeproc-chicago-author-date.md+7−7

This diff is too big to show here.

test/command/pandoc-citeproc-chicago-fullnote-bibliography.md+6−7

This diff is too big to show here.

test/command/svg.md+1−1

This diff is too big to show here.

test/command/toc.md+2−2

This diff is too big to show here.

test/command/unicode-collation.mdnew file+130

This diff is too big to show here.

test/docbook-reader.docbook+3−1

This diff is too big to show here.

test/docx/0_level_headers.native+2−2

This diff is too big to show here.

test/docx/golden/block_quotes.docx

Binary file not shown.

test/docx/golden/codeblock.docx

Binary file not shown.

test/docx/golden/comments.docx

Binary file not shown.

test/docx/golden/custom_style_no_reference.docx

Binary file not shown.

test/docx/golden/custom_style_preserve.docx

Binary file not shown.

test/docx/golden/custom_style_reference.docx

Binary file not shown.

test/docx/golden/definition_list.docx

Binary file not shown.

test/docx/golden/document-properties-short-desc.docx

Binary file not shown.

test/docx/golden/document-properties.docx

Binary file not shown.

test/docx/golden/headers.docx

Binary file not shown.

test/docx/golden/image.docx

Binary file not shown.

test/docx/golden/inline_code.docx

Binary file not shown.

test/docx/golden/inline_formatting.docx

Binary file not shown.

test/docx/golden/inline_images.docx

Binary file not shown.

test/docx/golden/link_in_notes.docx

Binary file not shown.

test/docx/golden/links.docx

Binary file not shown.

test/docx/golden/lists.docx

Binary file not shown.

test/docx/golden/lists_continuing.docx

Binary file not shown.

test/docx/golden/lists_multiple_initial.docx

Binary file not shown.

test/docx/golden/lists_restarting.docx

Binary file not shown.

test/docx/golden/nested_anchors_in_header.docx

Binary file not shown.

test/docx/golden/notes.docx

Binary file not shown.

test/docx/golden/raw-blocks.docx

Binary file not shown.

test/docx/golden/raw-bookmarks.docx

Binary file not shown.

test/docx/golden/table_one_row.docx

Binary file not shown.

test/docx/golden/table_with_list_cell.docx

Binary file not shown.

test/docx/golden/tables-default-widths.docxnew file

Binary file not shown.

test/docx/golden/tables.docx

Binary file not shown.

test/docx/golden/track_changes_deletion.docx

Binary file not shown.

test/docx/golden/track_changes_insertion.docx

Binary file not shown.

test/docx/golden/track_changes_move.docx

Binary file not shown.

test/docx/golden/track_changes_scrubbed_metadata.docx

Binary file not shown.

test/docx/golden/unicode.docx

Binary file not shown.

test/docx/golden/verbatim_subsuper.docx

Binary file not shown.

test/docx/image_vml_as_object.docxnew file

Binary file not shown.

test/docx/image_vml_as_object.nativenew file+2

This diff is too big to show here.

test/docx/sdt_elements.native+9−10

This diff is too big to show here.

test/docx/table_captions_no_field.docxnew file

Binary file not shown.

test/docx/table_captions_no_field.nativenew file+34

This diff is too big to show here.

test/docx/table_captions_with_field.docxnew file

Binary file not shown.

test/docx/table_captions_with_field.nativenew file+54

This diff is too big to show here.

test/docx/table_header_rowspan.docxnew file

Binary file not shown.

test/docx/table_header_rowspan.nativenew file+189

This diff is too big to show here.

test/docx/table_one_header_row.docxnew file

Binary file not shown.

test/docx/table_one_header_row.nativenew file+18

This diff is too big to show here.

test/docx/table_one_row.docx

Binary file not shown.

test/docx/table_one_row.native+4−4

This diff is too big to show here.

test/docx/table_variable_width.native+12−17

This diff is too big to show here.

test/docx/table_with_list_cell.native+3−3

This diff is too big to show here.

test/docx/tables-default-widths.nativenew file+92

This diff is too big to show here.

test/docx/tables.native+9−9

This diff is too big to show here.

test/epub/features.native+2−2

This diff is too big to show here.

test/epub/wasteland.epub

Binary file not shown.

test/fb2/images.fb2+1−1

This diff is too big to show here.

test/fb2/test.jpg

Binary file not shown.

test/html-reader.native+2−1

This diff is too big to show here.

test/jira-reader.native+1−1

This diff is too big to show here.

test/lhs-test.html+2−1

This diff is too big to show here.

test/lhs-test.html+lhs+2−1

This diff is too big to show here.

test/odt/native/tab.nativenew file+1

This diff is too big to show here.

test/odt/odt/tab.odtnew file

Binary file not shown.

test/pipe-tables.native+2−10

This diff is too big to show here.

test/pptx/code-custom_templated.pptx

Binary file not shown.

test/pptx/code_templated.pptx

Binary file not shown.

test/pptx/document-properties-short-desc_templated.pptx

Binary file not shown.

test/pptx/document-properties_templated.pptx

Binary file not shown.

test/pptx/endnotes_templated.pptx

Binary file not shown.

test/pptx/endnotes_toc_templated.pptx

Binary file not shown.

test/pptx/images_templated.pptx

Binary file not shown.

test/pptx/inline_formatting_templated.pptx

Binary file not shown.

test/pptx/lists_templated.pptx

Binary file not shown.

test/pptx/raw_ooxml_templated.pptx

Binary file not shown.

test/pptx/reference_depth.pptx

Binary file not shown.

test/pptx/remove_empty_slides_templated.pptx

Binary file not shown.

test/pptx/slide_breaks_slide_level_1_templated.pptx

Binary file not shown.

test/pptx/slide_breaks_templated.pptx

Binary file not shown.

test/pptx/slide_breaks_toc_templated.pptx

Binary file not shown.

test/pptx/speaker_notes_after_metadata_templated.pptx

Binary file not shown.

test/pptx/speaker_notes_afterheader_templated.pptx

Binary file not shown.

test/pptx/speaker_notes_afterseps_templated.pptx

Binary file not shown.

test/pptx/speaker_notes_templated.pptx

Binary file not shown.

test/pptx/start_numbering_at_templated.pptx

Binary file not shown.

test/pptx/tables_templated.pptx

Binary file not shown.

test/pptx/two_column_templated.pptx

Binary file not shown.

test/tables.latex+27−3

This diff is too big to show here.

test/tables.ms+30

This diff is too big to show here.

test/tables/nordics.latex+22−4

This diff is too big to show here.

test/tables/planets.latex+4−4

This diff is too big to show here.

test/tables/students.latex+10−2

This diff is too big to show here.

test/test-pandoc.hs+1−2

This diff is too big to show here.

test/txt2tags.native+1−1

This diff is too big to show here.

test/writer.context+42−38

This diff is too big to show here.

test/writer.html4+2−1

This diff is too big to show here.

test/writer.html5+2−1

This diff is too big to show here.

test/writer.jats_archiving+37−47

This diff is too big to show here.

test/writer.jats_articleauthoring+41−49

This diff is too big to show here.

test/writer.jats_publishing+37−47

This diff is too big to show here.

test/writer.jira+23−35

This diff is too big to show here.

test/writer.ms+1−1

This diff is too big to show here.

test/writer.opml+1−1

This diff is too big to show here.

test/writer.org+7−7

This diff is too big to show here.

test/writer.zimwiki+3−3

This diff is too big to show here.

test/writers-lang-and-dir.context+4

This diff is too big to show here.

tools/build-arm.shnew file+110

This diff is too big to show here.

tools/parseTimings.plnew file+33

This diff is too big to show here.

trypandoc/trypandoc.hs+2−5

This diff is too big to show here.