Merge branch 'master' into patch-1

This commit is contained in:
Andrew Dunning 2017-09-08 07:06:50 +01:00 committed by GitHub
commit 51bb7453e4
24 changed files with 1193 additions and 222 deletions

View file

@ -135,7 +135,7 @@ end
-- @section document -- @section document
--- A complete pandoc document --- A complete pandoc document
-- @function Panoc -- @function Pandoc
-- @tparam {Block,...} blocks document content -- @tparam {Block,...} blocks document content
-- @tparam[opt] Meta meta document meta data -- @tparam[opt] Meta meta document meta data
function M.Pandoc(blocks, meta) function M.Pandoc(blocks, meta)
@ -772,7 +772,7 @@ M.UpperAlpha = "UpperAlpha"
-- `--from` command line option. -- `--from` command line option.
-- @tparam string markup the markup to be parsed -- @tparam string markup the markup to be parsed
-- @tparam[opt] string format format specification, defaults to "markdown". -- @tparam[opt] string format format specification, defaults to "markdown".
-- @return Doc pandoc document -- @treturn Pandoc pandoc document
-- @usage -- @usage
-- local org_markup = "/emphasis/" -- Input to be read -- local org_markup = "/emphasis/" -- Input to be read
-- local document = pandoc.read(org_markup, "org") -- local document = pandoc.read(org_markup, "org")

View file

@ -259,6 +259,15 @@ $else$
\fi \fi
$endif$ $endif$
$endif$ $endif$
% set default figure placement to htbp
\makeatletter
\def\fps@figure{htbp}
\makeatother
$for(header-includes)$
$header-includes$
$endfor$
$if(lang)$ $if(lang)$
\ifnum 0\ifxetex 1\fi\ifluatex 1\fi=0 % if pdftex \ifnum 0\ifxetex 1\fi\ifluatex 1\fi=0 % if pdftex
\usepackage[shorthands=off,$for(babel-otherlangs)$$babel-otherlangs$,$endfor$main=$babel-lang$]{babel} \usepackage[shorthands=off,$for(babel-otherlangs)$$babel-otherlangs$,$endfor$main=$babel-lang$]{babel}
@ -292,15 +301,6 @@ $if(dir)$
\fi \fi
$endif$ $endif$
% set default figure placement to htbp
\makeatletter
\def\fps@figure{htbp}
\makeatother
$for(header-includes)$
$header-includes$
$endfor$
$if(title)$ $if(title)$
\title{$title$$if(thanks)$\thanks{$thanks$}$endif$} \title{$title$$if(thanks)$\thanks{$thanks$}$endif$}
$endif$ $endif$

38
doc/ldoc.ltp Normal file
View file

@ -0,0 +1,38 @@
# local iter = ldoc.modules.iter
# local M = ldoc.markup
<h1>Module $(module.name)</h1>
<p>$(M(module.summary))</p>
# for kind, items in module.kinds() do
<h2>$(kind)</h2>
<dl>
# for item in items() do ldoc.item = item -- provides context for M()
<dt><span id="$(item.name)"><code>$(ldoc.display_name(item))</code></span></dt>
<dd>
<p>$(item.summary)</p>
# if item.params and #item.params > 0 then
$(module.kinds:type_of(item).subnames):
<dl>
# for p in iter(item.params) do
<dt><code>$(p)</code>:</dt>
<dd>$(M(item.params.map[p]))</dd>
# end -- for
</dl>
# end -- if params
# if item.ret then
<p>Returns: $(item.ret[1])</p>
# end -- if returns
# if item.usage then
<p>Usage:</p>
<pre><code>$(item.usage[1])</code></pre>
# end -- if usage
# if item.see then
See also: <a href="#$(item.see[1].label)">$(item.see[1].label)</a>
# end -- if see
# end -- for items
</dl>
# end -- for kinds

View file

@ -1,6 +1,6 @@
% Pandoc Lua Filters % Pandoc Lua Filters
% Albert Krewinkel, John MacFarlane % Albert Krewinkel, John MacFarlane
% August 21, 2017 % August 31, 2017
# Introduction # Introduction
@ -111,6 +111,11 @@ inline element must return an inline, and a block element must
remain a block element after filter application. Pandoc will remain a block element after filter application. Pandoc will
throw an error if this condition is violated. throw an error if this condition is violated.
If there is no function matching the element's node type, then
the filtering system will look for a more general fallback
function. Two fallback functions are supported, `Inline` and
`Block`. Each matches elements of the respective type.
Elements without matching functions are left untouched. Elements without matching functions are left untouched.
See [module documentation](pandoc-module.html) for a list of pandoc See [module documentation](pandoc-module.html) for a list of pandoc
@ -304,3 +309,738 @@ then running `pandoc --lua-filter=meta-vars.lua occupations.md` will output:
</dd> </dd>
</dl> </dl>
``` ```
# Module pandoc
Lua functions for pandoc scripts.
## Pandoc Document
[`Pandoc (blocks[, meta])`]{#Pandoc}
: A complete pandoc document
Parameters:
`blocks`:
: document content
`meta`:
: document meta data
## MetaValue
[`MetaBlocks (blocks)`]{#MetaBlocks}
: Meta blocks
Parameters:
`blocks`:
: blocks
[`MetaInlines (inlines)`]{#MetaInlines}
: Meta inlines
Parameters:
`inlines`:
: inlines
[`MetaList (meta_values)`]{#MetaList}
: Meta list
Parameters:
`meta_values`:
: list of meta values
[`MetaMap (key_value_map)`]{#MetaMap}
: Meta map
Parameters:
`key_value_map`:
: a string-indexed map of meta values
[`MetaString (str)`]{#MetaString}
: Creates string to be used in meta data.
Parameters:
`str`:
: string value
[`MetaBool (bool)`]{#MetaBool}
: Creates boolean to be used in meta data.
Parameters:
`bool`:
: boolean value
## Blocks
[`Block`]{#Block}
: Block elements
[`BlockQuote (content)`]{#BlockQuote}
: Creates a block quote element
Parameters:
`content`:
: block content
Returns: block quote element
[`BulletList (content)`]{#BulletList}
: Creates a bullet (i.e.
Parameters:
`content`:
: list of items
Returns: block quote element
[`CodeBlock (text[, attr])`]{#CodeBlock}
: Creates a code block element
Parameters:
`text`:
: code string
`attr`:
: element attributes
Returns: code block element
[`DefinitionList (content)`]{#DefinitionList}
: Creates a definition list, containing terms and their
explanation.
Parameters:
`content`:
: list of items
Returns: block quote element
[`Div (content[, attr])`]{#Div}
: Creates a div element
Parameters:
`content`:
: block content
`attr`:
: element attributes
Returns: code block element
[`Header (level, content[, attr])`]{#Header}
: Creates a block quote element.
Parameters:
`level`:
: header level
`content`:
: inline content
`attr`:
: element attributes
Returns: header element
[`HorizontalRule ()`]{#HorizontalRule}
: Creates a horizontal rule.
Returns: horizontal rule
[`LineBlock (content)`]{#LineBlock}
: Creates a line block element.
Parameters:
`content`:
: inline content
Returns: block quote element
[`Null ()`]{#Null}
: Creates a null element.
Returns: null element
[`OrderedList (items[, listAttributes])`]{#OrderedList}
: Creates an ordered list.
Parameters:
`items`:
: list items
`listAttributes`:
: list parameters
Returns:
[`Para (content)`]{#Para}
: Creates a para element.
Parameters:
`content`:
: inline content
Returns: block quote element
[`Plain (content)`]{#Plain}
: Creates a plain element.
Parameters:
`content`:
: inline content
Returns: block quote element
[`RawBlock (format, text)`]{#RawBlock}
: Creates a raw content block of the specified format.
Parameters:
`format`:
: format of content
`text`:
: string content
Returns: block quote element
[`Table (caption, aligns, widths, headers, rows)`]{#Table}
: Creates a table element.
Parameters:
`caption`:
: table caption
`aligns`:
: alignments
`widths`:
: column widths
`headers`:
: header row
`rows`:
: table rows
Returns: block quote element
## Inline
[`Inline`]{#Inline}
: Inline element class
[`Cite (content, citations)`]{#Cite}
: Creates a Cite inline element
Parameters:
`content`:
: List of inlines
`citations`:
: List of citations
Returns: citations element
[`Code (text[, attr])`]{#Code}
: Creates a Code inline element
Parameters:
`text`:
: brief image description
`attr`:
: additional attributes
Returns: code element
[`Emph (content)`]{#Emph}
: Creates an inline element representing emphasised text.
Parameters:
`content`:
: inline content
Returns: emphasis element
[`Image (caption, src[, title[, attr]])`]{#Image}
: Creates a Image inline element
Parameters:
`caption`:
: text used to describe the image
`src`:
: path to the image file
`title`:
: brief image description
`attr`:
: additional attributes
Returns: image element
[`LineBreak ()`]{#LineBreak}
: Create a LineBreak inline element
Returns: linebreak element
[`Link (content, target[, title[, attr]])`]{#Link}
: Creates a link inline element, usually a hyperlink.
Parameters:
`content`:
: text for this link
`target`:
: the link target
`title`:
: brief link description
`attr`:
: additional attributes
Returns: image element
[`Math (mathtype, text)`]{#Math}
: Creates a Math element, either inline or displayed.
Parameters:
`mathtype`:
: rendering specifier
`text`:
: Math content
Returns: Math element
[`DisplayMath (text)`]{#DisplayMath}
: Creates a DisplayMath element (DEPRECATED).
Parameters:
`text`:
: Math content
Returns: Math element
[`InlineMath (text)`]{#InlineMath}
: Creates an InlineMath inline element (DEPRECATED).
Parameters:
`text`:
: Math content
Returns: Math element
[`Note (content)`]{#Note}
: Creates a Note inline element
Parameters:
`content`:
: footnote block content
[`Quoted (quotetype, content)`]{#Quoted}
: Creates a Quoted inline element given the quote type and
quoted content.
Parameters:
`quotetype`:
: type of quotes to be used
`content`:
: inline content
Returns: quoted element
[`SingleQuoted (content)`]{#SingleQuoted}
: Creates a single-quoted inline element (DEPRECATED).
Parameters:
`content`:
: inline content
Returns: quoted element
See also: [Quoted](#Quoted)
[`DoubleQuoted (content)`]{#DoubleQuoted}
: Creates a single-quoted inline element (DEPRECATED).
Parameters:
`content`:
: inline content
Returns: quoted element
See also: [Quoted](#Quoted)
[`RawInline (format, text)`]{#RawInline}
: Creates a RawInline inline element
Parameters:
`format`:
: format of the contents
`text`:
: string content
Returns: raw inline element
[`SmallCaps (content)`]{#SmallCaps}
: Creates text rendered in small caps
Parameters:
`content`:
: inline content
Returns: smallcaps element
[`SoftBreak ()`]{#SoftBreak}
: Creates a SoftBreak inline element.
Returns: softbreak element
[`Space ()`]{#Space}
: Create a Space inline element
Returns: space element
[`Span (content[, attr])`]{#Span}
: Creates a Span inline element
Parameters:
`content`:
: inline content
`attr`:
: additional attributes
Returns: span element
[`Str (text)`]{#Str}
: Creates a Str inline element
Parameters:
`text`:
: content
Returns: string element
[`Strikeout (content)`]{#Strikeout}
: Creates text which is striked out.
Parameters:
`content`:
: inline content
Returns: strikeout element
[`Strong (content)`]{#Strong}
: Creates a Strong element, whose text is usually displayed in
a bold font.
Parameters:
`content`:
: inline content
Returns: strong element
[`Subscript (content)`]{#Subscript}
: Creates a Subscript inline element
Parameters:
`content`:
: inline content
Returns: subscript element
[`Superscript (content)`]{#Superscript}
: Creates a Superscript inline element
Parameters:
`content`:
: inline content
Returns: strong element
## Helpers
[`Attr ([identifier[, classes[, attributes]]])`]{#Attr}
: Create a new set of attributes (Attr).
Parameters:
`identifier`:
: element identifier
`classes`:
: element classes
`attributes`:
: table containing string keys and values
Returns: element attributes
[`Citation (id, mode[, prefix[, suffix[, note_num[, hash]]]])`]{#Citation}
: Creates a single citation.
Parameters:
`id`:
: citation identifier (like a bibtex key)
`mode`:
: citation mode
`prefix`:
: citation prefix
`suffix`:
: citation suffix
`note_num`:
: note number
`hash`:
: hash number
## Constants
[`AuthorInText`]{#AuthorInText}
: Author name is mentioned in the text.
See also: [Citation](#Citation)
[`SuppressAuthor`]{#SuppressAuthor}
: Author name is suppressed.
See also: [Citation](#Citation)
[`NormalCitation`]{#NormalCitation}
: Default citation style is used.
See also: [Citation](#Citation)
[`AlignLeft`]{#AlignLeft}
: Table cells aligned left.
See also: [Table](#Table)
[`AlignRight`]{#AlignRight}
: Table cells right-aligned.
See also: [Table](#Table)
[`AlignCenter`]{#AlignCenter}
: Table cell content is centered.
See also: [Table](#Table)
[`AlignDefault`]{#AlignDefault}
: Table cells are alignment is unaltered.
See also: [Table](#Table)
[`DefaultDelim`]{#DefaultDelim}
: Default list number delimiters are used.
See also: [OrderedList](#OrderedList)
[`Period`]{#Period}
: List numbers are delimited by a period.
See also: [OrderedList](#OrderedList)
[`OneParen`]{#OneParen}
: List numbers are delimited by a single parenthesis.
See also: [OrderedList](#OrderedList)
[`TwoParens`]{#TwoParens}
: List numbers are delimited by a double parentheses.
See also: [OrderedList](#OrderedList)
[`DefaultStyle`]{#DefaultStyle}
: List are numbered in the default style
See also: [OrderedList](#OrderedList)
[`Example`]{#Example}
: List items are numbered as examples.
See also: [OrderedList](#OrderedList)
[`Decimal`]{#Decimal}
: List are numbered using decimal integers.
See also: [OrderedList](#OrderedList)
[`LowerRoman`]{#LowerRoman}
: List are numbered using lower-case roman numerals.
See also: [OrderedList](#OrderedList)
[`UpperRoman`]{#UpperRoman}
: List are numbered using upper-case roman numerals
See also: [OrderedList](#OrderedList)
[`LowerAlpha`]{#LowerAlpha}
: List are numbered using lower-case alphabetic characters.
See also: [OrderedList](#OrderedList)
[`UpperAlpha`]{#UpperAlpha}
: List are numbered using upper-case alphabetic characters.
See also: [OrderedList](#OrderedList)
## Helper Functions
[`read (markup[, format])`]{#read}
: Parse the given string into a Pandoc document.
Parameters:
`markup`:
: the markup to be parsed
`format`:
: format specification, defaults to \"markdown\".
Returns: pandoc document
Usage:
local org_markup = "/emphasis/" -- Input to be read
local document = pandoc.read(org_markup, "org")
-- Get the first block of the document
local block = document.blocks[1]
-- The inline element in that block is an `Emph`
assert(block.content[1].t == "Emph")
[`global_filter ()`]{#global_filter}
: Use functions defined in the global namespace to create a
pandoc filter.
Returns: A list of filter functions
Usage:
-- within a file defining a pandoc filter:
function Str(text)
return pandoc.Str(utf8.upper(text))
end
return {pandoc.global_filter()}
-- the above is equivallent to
-- return {{Str = Str}}

View file

@ -5,7 +5,7 @@ ADD https://raw.githubusercontent.com/mitchty/alpine-ghc/master/mitch.tishmack%4
/etc/apk/keys/mitch.tishmack@gmail.com-55881c97.rsa.pub /etc/apk/keys/mitch.tishmack@gmail.com-55881c97.rsa.pub
RUN apk update RUN apk update
RUN apk add alpine-sdk git ca-certificates ghc cabal stack zlib-dev \ RUN apk add alpine-sdk git ca-certificates ghc cabal stack zlib-dev \
dpkg fakeroot sed gawk grep dpkg fakeroot sed gawk grep bash linux-headers
RUN stack update RUN stack update
RUN stack config set system-ghc --global true RUN stack config set system-ghc --global true
RUN mkdir -p /etc/stack RUN mkdir -p /etc/stack
@ -16,13 +16,15 @@ RUN git clone https://github.com/jgm/pandoc
WORKDIR /usr/src/pandoc WORKDIR /usr/src/pandoc
RUN stack install --stack-yaml stack.pkg.yaml --only-dependencies \ RUN stack install --stack-yaml stack.pkg.yaml --only-dependencies \
--flag 'pandoc:embed_data_files' \ --flag 'pandoc:embed_data_files' \
--test --ghc-options '-O2 -optc-Os -optl-static -fPIC' \ --ghc-options '-O2 -optc-Os -optl=-pthread -optl=-static -fPIC' \
pandoc pandoc-citeproc pandoc pandoc-citeproc
CMD git pull && \ CMD git pull && \
git checkout -b work $TREE && \ git checkout -b work $TREE && \
stack install --stack-yaml stack.pkg.yaml \ stack install --stack-yaml stack.pkg.yaml \
--local-bin-path /artifacts --flag 'pandoc:embed_data_files' \ --flag 'pandoc:static' \
--test --ghc-options '-O2 -optc-Os -optl-static -fPIC' \ --flag 'pandoc:embed_data_files' \
--ghc-options '-O2 -optc-Os -optl=-pthread -optl=-static -fPIC' \
--local-bin-path /artifacts \
pandoc pandoc-citeproc && \ pandoc pandoc-citeproc && \
bash linux/make_deb.sh && \ bash linux/make_deb.sh && \
bash linux/make_tarball.sh bash linux/make_tarball.sh

View file

@ -1,19 +1,19 @@
Name: pandoc name: pandoc
Version: 2.0 version: 2.0
Cabal-Version: >= 1.10 cabal-version: >= 1.10
Build-Type: Custom build-type: Custom
License: GPL license: GPL
License-File: COPYING.md license-file: COPYING.md
Copyright: (c) 2006-2017 John MacFarlane copyright: (c) 2006-2017 John MacFarlane
Author: John MacFarlane <jgm@berkeley.edu> author: John MacFarlane <jgm@berkeley.edu>
Maintainer: John MacFarlane <jgm@berkeley.edu> maintainer: John MacFarlane <jgm@berkeley.edu>
Bug-Reports: https://github.com/jgm/pandoc/issues bug-reports: https://github.com/jgm/pandoc/issues
Stability: alpha stability: alpha
Homepage: http://pandoc.org homepage: http://pandoc.org
Category: Text category: Text
Tested-With: GHC == 7.8.4, GHC == 7.10.3, GHC == 8.0.2 tested-with: GHC == 7.8.4, GHC == 7.10.3, GHC == 8.0.2
Synopsis: Conversion between markup formats synopsis: Conversion between markup formats
Description: Pandoc is a Haskell library for converting from one markup description: Pandoc is a Haskell library for converting from one markup
format to another, and a command-line tool that uses format to another, and a command-line tool that uses
this library. It can read several dialects of Markdown and this library. It can read several dialects of Markdown and
(subsets of) HTML, reStructuredText, LaTeX, DocBook, (subsets of) HTML, reStructuredText, LaTeX, DocBook,
@ -35,7 +35,7 @@ Description: Pandoc is a Haskell library for converting from one markup
which convert this native representation into a target which convert this native representation into a target
format. Thus, adding an input or output format requires format. Thus, adding an input or output format requires
only adding a reader or writer. only adding a reader or writer.
Data-Files: data-files:
-- templates -- templates
data/templates/default.html4 data/templates/default.html4
data/templates/default.html5 data/templates/default.html5
@ -119,7 +119,7 @@ Data-Files:
data/jats.csl data/jats.csl
-- documentation -- documentation
MANUAL.txt, COPYRIGHT MANUAL.txt, COPYRIGHT
Extra-Source-Files: extra-source-files:
-- documentation -- documentation
INSTALL.md, BUGS, README.md, CONTRIBUTING.md, changelog INSTALL.md, BUGS, README.md, CONTRIBUTING.md, changelog
man/pandoc.1 man/pandoc.1
@ -138,6 +138,7 @@ Extra-Source-Files:
test/*.native test/*.native
test/command/*.md test/command/*.md
test/command/3533-rst-csv-tables.csv test/command/3533-rst-csv-tables.csv
test/command/3880.txt
test/command/abbrevs test/command/abbrevs
test/command/SVG_logo-without-xml-declaration.svg test/command/SVG_logo-without-xml-declaration.svg
test/command/SVG_logo.svg test/command/SVG_logo.svg
@ -260,32 +261,39 @@ Extra-Source-Files:
test/odt/markdown/*.md test/odt/markdown/*.md
test/odt/native/*.native test/odt/native/*.native
test/lua/*.lua test/lua/*.lua
Source-repository head source-repository head
type: git type: git
location: git://github.com/jgm/pandoc.git location: git://github.com/jgm/pandoc.git
Flag embed_data_files flag static
Description: Use static linking for pandoc executable.
Default: False
flag embed_data_files
Description: Embed data files in binary for relocatable executable. Description: Embed data files in binary for relocatable executable.
Default: False Default: False
Flag trypandoc flag trypandoc
Description: Build trypandoc cgi executable. Description: Build trypandoc cgi executable.
Default: False Default: False
Flag weigh-pandoc flag weigh-pandoc
Description: Build weigh-pandoc to measure memory usage. Description: Build weigh-pandoc to measure memory usage.
Default: False Default: False
Flag network-uri flag network-uri
Description: Get Network.URI from the network-uri package Description: Get Network.URI from the network-uri package
Default: True Default: True
Flag old-locale flag old-locale
Description: Use old-locale and time < 1.5 Description: Use old-locale and time < 1.5
Default: False Default: False
Library custom-setup
Build-Depends: base >= 4.7 && < 5, setup-depends: base, Cabal
library
build-depends: base >= 4.7 && < 5,
syb >= 0.1 && < 0.8, syb >= 0.1 && < 0.8,
containers >= 0.4.2.1 && < 0.6, containers >= 0.4.2.1 && < 0.6,
unordered-containers >= 0.2 && < 0.3, unordered-containers >= 0.2 && < 0.3,
@ -331,37 +339,37 @@ Library
http-types >= 0.8 && < 0.10, http-types >= 0.8 && < 0.10,
csv-conduit >= 0.6 && < 0.7 csv-conduit >= 0.6 && < 0.7
if os(windows) if os(windows)
Cpp-options: -D_WINDOWS cpp-options: -D_WINDOWS
else else
Build-Depends: unix >= 2.4 && < 2.8 build-depends: unix >= 2.4 && < 2.8
if flag(old-locale) if flag(old-locale)
Build-Depends: old-locale >= 1 && < 1.1, build-depends: old-locale >= 1 && < 1.1,
time >= 1.2 && < 1.5 time >= 1.2 && < 1.5
else else
Build-Depends: time >= 1.5 && < 1.9 build-depends: time >= 1.5 && < 1.9
if flag(network-uri) if flag(network-uri)
Build-Depends: network-uri >= 2.6 && < 2.7, network >= 2.6 build-depends: network-uri >= 2.6 && < 2.7, network >= 2.6
else else
Build-Depends: network >= 2 && < 2.6 build-depends: network >= 2 && < 2.6
if flag(embed_data_files) if flag(embed_data_files)
cpp-options: -DEMBED_DATA_FILES cpp-options: -DEMBED_DATA_FILES
build-depends: file-embed >= 0.0 && < 0.1 build-depends: file-embed >= 0.0 && < 0.1
other-modules: Text.Pandoc.Data other-modules: Text.Pandoc.Data
if os(windows) if os(windows)
Cpp-options: -D_WINDOWS cpp-options: -D_WINDOWS
Ghc-Options: -Wall -fno-warn-unused-do-bind ghc-options: -Wall -fno-warn-unused-do-bind
Ghc-Prof-Options: -fprof-auto-exported ghc-prof-options: -fprof-auto-exported
Default-Language: Haskell98 default-language: Haskell98
Other-Extensions: PatternGuards, OverloadedStrings, other-extensions: PatternGuards, OverloadedStrings,
ScopedTypeVariables, GeneralizedNewtypeDeriving, ScopedTypeVariables, GeneralizedNewtypeDeriving,
RelaxedPolyRec, DeriveDataTypeable, TypeSynonymInstances, RelaxedPolyRec, DeriveDataTypeable, TypeSynonymInstances,
FlexibleInstances FlexibleInstances
Hs-Source-Dirs: src hs-source-dirs: src
if impl(ghc < 7.10) if impl(ghc < 7.10)
Hs-Source-Dirs: prelude hs-source-dirs: prelude
Other-Modules: Prelude other-modules: Prelude
Exposed-Modules: Text.Pandoc, exposed-modules: Text.Pandoc,
Text.Pandoc.App, Text.Pandoc.App,
Text.Pandoc.Options, Text.Pandoc.Options,
Text.Pandoc.Extensions, Text.Pandoc.Extensions,
@ -439,7 +447,7 @@ Library
Text.Pandoc.Emoji, Text.Pandoc.Emoji,
Text.Pandoc.ImageSize, Text.Pandoc.ImageSize,
Text.Pandoc.Class Text.Pandoc.Class
Other-Modules: Text.Pandoc.Readers.Docx.Lists, other-modules: Text.Pandoc.Readers.Docx.Lists,
Text.Pandoc.Readers.Docx.Combine, Text.Pandoc.Readers.Docx.Combine,
Text.Pandoc.Readers.Docx.Parse, Text.Pandoc.Readers.Docx.Parse,
Text.Pandoc.Readers.Docx.Util, Text.Pandoc.Readers.Docx.Util,
@ -476,66 +484,67 @@ Library
Text.Pandoc.Compat.Time, Text.Pandoc.Compat.Time,
Paths_pandoc Paths_pandoc
Buildable: True buildable: True
Executable pandoc executable pandoc
Build-Depends: pandoc, base >= 4.7 && < 5 build-depends: pandoc, base >= 4.7 && < 5
Ghc-Options: -rtsopts -with-rtsopts=-K16m -Wall -fno-warn-unused-do-bind ghc-options: -rtsopts -with-rtsopts=-K16m -Wall -fno-warn-unused-do-bind
Ghc-Prof-Options: -fprof-auto-exported -rtsopts -with-rtsopts=-K16m ghc-prof-options: -fprof-auto-exported -rtsopts -with-rtsopts=-K16m
if flag(static)
Default-Language: Haskell98 ld-options: -static
Other-Extensions: PatternGuards, OverloadedStrings, default-language: Haskell98
other-extensions: PatternGuards, OverloadedStrings,
ScopedTypeVariables, GeneralizedNewtypeDeriving, ScopedTypeVariables, GeneralizedNewtypeDeriving,
RelaxedPolyRec, DeriveDataTypeable, TypeSynonymInstances, RelaxedPolyRec, DeriveDataTypeable, TypeSynonymInstances,
FlexibleInstances FlexibleInstances
Hs-Source-Dirs: . hs-source-dirs: .
if impl(ghc < 7.10) if impl(ghc < 7.10)
Hs-Source-Dirs: prelude hs-source-dirs: prelude
Other-Modules: Prelude other-modules: Prelude
Main-Is: pandoc.hs main-is: pandoc.hs
Buildable: True buildable: True
Other-Modules: Paths_pandoc other-modules: Paths_pandoc
Executable trypandoc executable trypandoc
Main-Is: trypandoc.hs main-is: trypandoc.hs
Hs-Source-Dirs: trypandoc hs-source-dirs: trypandoc
if impl(ghc < 7.10) if impl(ghc < 7.10)
Hs-Source-Dirs: prelude hs-source-dirs: prelude
Other-Modules: Prelude other-modules: Prelude
default-language: Haskell2010 default-language: Haskell2010
if flag(trypandoc) if flag(trypandoc)
Build-Depends: base, aeson, pandoc, build-depends: base, aeson, pandoc,
text, wai-extra, wai >= 0.3, http-types text, wai-extra, wai >= 0.3, http-types
Buildable: True buildable: True
else else
Buildable: False buildable: False
Executable weigh-pandoc executable weigh-pandoc
Main-Is: weigh-pandoc.hs main-is: weigh-pandoc.hs
Hs-Source-Dirs: benchmark hs-source-dirs: benchmark
if impl(ghc < 7.10) if impl(ghc < 7.10)
Hs-Source-Dirs: prelude hs-source-dirs: prelude
Other-Modules: Prelude other-modules: Prelude
if flag(weigh-pandoc) if flag(weigh-pandoc)
Build-Depends: pandoc, build-depends: pandoc,
base >= 4.2 && < 5, base >= 4.2 && < 5,
text, text,
weigh >= 0.0 && < 0.1, weigh >= 0.0 && < 0.1,
mtl >= 2.2 && < 2.3 mtl >= 2.2 && < 2.3
Buildable: True buildable: True
else else
Buildable: False buildable: False
Ghc-Options: -rtsopts -Wall -fno-warn-unused-do-bind ghc-options: -rtsopts -Wall -fno-warn-unused-do-bind
Default-Language: Haskell98 default-language: Haskell98
Test-Suite test-pandoc test-suite test-pandoc
Type: exitcode-stdio-1.0 type: exitcode-stdio-1.0
Main-Is: test-pandoc.hs main-is: test-pandoc.hs
Hs-Source-Dirs: test hs-source-dirs: test
if impl(ghc < 7.10) if impl(ghc < 7.10)
Hs-Source-Dirs: prelude hs-source-dirs: prelude
Other-Modules: Prelude other-modules: Prelude
Build-Depends: base >= 4.2 && < 5, build-depends: base >= 4.2 && < 5,
syb >= 0.1 && < 0.8, syb >= 0.1 && < 0.8,
pandoc, pandoc,
pandoc-types >= 1.17.1 && < 1.18, pandoc-types >= 1.17.1 && < 1.18,
@ -557,7 +566,7 @@ Test-Suite test-pandoc
executable-path >= 0.0 && < 0.1, executable-path >= 0.0 && < 0.1,
zip-archive >= 0.2.3.4 && < 0.4, zip-archive >= 0.2.3.4 && < 0.4,
mtl >= 2.2 && < 2.3 mtl >= 2.2 && < 2.3
Other-Modules: Tests.Old other-modules: Tests.Old
Tests.Command Tests.Command
Tests.Helpers Tests.Helpers
Tests.Lua Tests.Lua
@ -585,21 +594,21 @@ Test-Suite test-pandoc
Tests.Writers.RST Tests.Writers.RST
Tests.Writers.TEI Tests.Writers.TEI
Tests.Writers.Muse Tests.Writers.Muse
Ghc-Options: -rtsopts -Wall -fno-warn-unused-do-bind -threaded ghc-options: -rtsopts -Wall -fno-warn-unused-do-bind -threaded
Default-Language: Haskell98 default-language: Haskell98
benchmark benchmark-pandoc benchmark benchmark-pandoc
Type: exitcode-stdio-1.0 type: exitcode-stdio-1.0
Main-Is: benchmark-pandoc.hs main-is: benchmark-pandoc.hs
Hs-Source-Dirs: benchmark hs-source-dirs: benchmark
if impl(ghc < 7.10) if impl(ghc < 7.10)
Hs-Source-Dirs: prelude hs-source-dirs: prelude
Other-Modules: Prelude other-modules: Prelude
Build-Depends: pandoc, build-depends: pandoc,
time, bytestring, containers, time, bytestring, containers,
base >= 4.2 && < 5, base >= 4.2 && < 5,
text >= 0.11 && < 1.3, text >= 0.11 && < 1.3,
syb >= 0.1 && < 0.8, syb >= 0.1 && < 0.8,
criterion >= 1.0 && < 1.3 criterion >= 1.0 && < 1.3
Ghc-Options: -rtsopts -Wall -fno-warn-unused-do-bind ghc-options: -rtsopts -Wall -fno-warn-unused-do-bind
Default-Language: Haskell98 default-language: Haskell98

View file

@ -838,7 +838,7 @@ blankLineBlockLine = try (char '|' >> blankline)
lineBlockLines :: Monad m => ParserT [Char] st m [String] lineBlockLines :: Monad m => ParserT [Char] st m [String]
lineBlockLines = try $ do lineBlockLines = try $ do
lines' <- many1 (lineBlockLine <|> ((:[]) <$> blankLineBlockLine)) lines' <- many1 (lineBlockLine <|> ((:[]) <$> blankLineBlockLine))
skipMany1 $ blankline <|> blankLineBlockLine skipMany $ blankline
return lines' return lines'
-- | Parse a table using 'headerParser', 'rowParser', -- | Parse a table using 'headerParser', 'rowParser',

View file

@ -58,7 +58,7 @@ import Data.Maybe ( fromMaybe, isJust, isNothing )
import Data.List.Split ( wordsBy ) import Data.List.Split ( wordsBy )
import Data.List ( intercalate, isPrefixOf ) import Data.List ( intercalate, isPrefixOf )
import Data.Char ( isDigit, isLetter, isAlphaNum ) import Data.Char ( isDigit, isLetter, isAlphaNum )
import Control.Monad ( guard, mzero, void, unless, mplus ) import Control.Monad ( guard, mzero, void, unless, mplus, msum )
import Control.Arrow ((***)) import Control.Arrow ((***))
import Control.Applicative ( (<|>) ) import Control.Applicative ( (<|>) )
import Data.Monoid (First (..)) import Data.Monoid (First (..))
@ -576,23 +576,23 @@ pPara = do
return $ B.para contents return $ B.para contents
pFigure :: PandocMonad m => TagParser m Blocks pFigure :: PandocMonad m => TagParser m Blocks
pFigure = do pFigure = try $ do
TagOpen _ _ <- pSatisfy (matchTagOpen "figure" []) TagOpen _ _ <- pSatisfy (matchTagOpen "figure" [])
skipMany pBlank skipMany pBlank
let pImg = pOptInTag "p" pImage <* skipMany pBlank let pImg = (\x -> (Just x, Nothing)) <$>
pCapt = option mempty $ pInTags "figcaption" inline <* skipMany pBlank (pOptInTag "p" pImage <* skipMany pBlank)
pImgCapt = do pCapt = (\x -> (Nothing, Just x)) <$>
img <- pImg (pInTags "figcaption" inline <* skipMany pBlank)
cap <- pCapt pSkip = (Nothing, Nothing) <$ pSatisfy (not . matchTagClose "figure")
return (img, cap) res <- many (pImg <|> pCapt <|> pSkip)
pCaptImg = do let mbimg = msum $ map fst res
cap <- pCapt let mbcap = msum $ map snd res
img <- pImg
return (img, cap)
(imgMany, caption) <- pImgCapt <|> pCaptImg
TagClose _ <- pSatisfy (matchTagClose "figure") TagClose _ <- pSatisfy (matchTagClose "figure")
let (Image attr _ (url, tit)):_ = B.toList imgMany let caption = fromMaybe mempty mbcap
return $ B.para $ B.imageWith attr url ("fig:" ++ tit) caption case B.toList <$> mbimg of
Just [Image attr _ (url, tit)] ->
return $ B.para $ B.imageWith attr url ("fig:" ++ tit) caption
_ -> mzero
pCodeBlock :: PandocMonad m => TagParser m Blocks pCodeBlock :: PandocMonad m => TagParser m Blocks
pCodeBlock = try $ do pCodeBlock = try $ do
@ -961,7 +961,7 @@ blockHtmlTags = Set.fromList
"dir", "div", "dl", "dt", "fieldset", "figcaption", "figure", "dir", "div", "dl", "dt", "fieldset", "figcaption", "figure",
"footer", "form", "h1", "h2", "h3", "h4", "footer", "form", "h1", "h2", "h3", "h4",
"h5", "h6", "head", "header", "hgroup", "hr", "html", "h5", "h6", "head", "header", "hgroup", "hr", "html",
"isindex", "main", "menu", "noframes", "ol", "output", "p", "pre", "isindex", "main", "menu", "meta", "noframes", "ol", "output", "p", "pre",
"section", "table", "tbody", "textarea", "section", "table", "tbody", "textarea",
"thead", "tfoot", "ul", "dd", "thead", "tfoot", "ul", "dd",
"dt", "frameset", "li", "tbody", "td", "tfoot", "dt", "frameset", "li", "tbody", "td", "tfoot",
@ -1048,7 +1048,7 @@ x `closes` "p" | x `elem` ["address", "article", "aside", "blockquote",
"dir", "div", "dl", "fieldset", "footer", "form", "h1", "h2", "h3", "h4", "dir", "div", "dl", "fieldset", "footer", "form", "h1", "h2", "h3", "h4",
"h5", "h6", "header", "hr", "main", "menu", "nav", "ol", "p", "pre", "section", "h5", "h6", "header", "hr", "main", "menu", "nav", "ol", "p", "pre", "section",
"table", "ul"] = True "table", "ul"] = True
"meta" `closes` "meta" = True _ `closes` "meta" = True
"form" `closes` "form" = True "form" `closes` "form" = True
"label" `closes` "label" = True "label" `closes` "label" = True
"map" `closes` "map" = True "map" `closes` "map" = True

View file

@ -770,11 +770,13 @@ keyval = try $ do
keyvals :: PandocMonad m => LP m [(String, String)] keyvals :: PandocMonad m => LP m [(String, String)]
keyvals = try $ symbol '[' >> manyTill keyval (symbol ']') keyvals = try $ symbol '[' >> manyTill keyval (symbol ']')
accent :: (Char -> String) -> Inlines -> LP m Inlines accent :: PandocMonad m => Char -> (Char -> String) -> LP m Inlines
accent f ils = accent c f = try $ do
ils <- tok
case toList ils of case toList ils of
(Str (x:xs) : ys) -> return $ fromList (Str (f x ++ xs) : ys) (Str (x:xs) : ys) -> return $ fromList (Str (f x ++ xs) : ys)
[] -> mzero [Space] -> return $ str [c]
[] -> return $ str [c]
_ -> return ils _ -> return ils
grave :: Char -> String grave :: Char -> String
@ -961,6 +963,19 @@ hacek 'Z' = "Ž"
hacek 'z' = "ž" hacek 'z' = "ž"
hacek c = [c] hacek c = [c]
ogonek :: Char -> String
ogonek 'a' = "ą"
ogonek 'e' = "ę"
ogonek 'o' = "ǫ"
ogonek 'i' = "į"
ogonek 'u' = "ų"
ogonek 'A' = "Ą"
ogonek 'E' = "Ę"
ogonek 'I' = "Į"
ogonek 'O' = "Ǫ"
ogonek 'U' = "Ų"
ogonek c = [c]
breve :: Char -> String breve :: Char -> String
breve 'A' = "Ă" breve 'A' = "Ă"
breve 'a' = "ă" breve 'a' = "ă"
@ -1275,17 +1290,19 @@ inlineCommands = M.fromList $
, ("copyright", lit "©") , ("copyright", lit "©")
, ("textasciicircum", lit "^") , ("textasciicircum", lit "^")
, ("textasciitilde", lit "~") , ("textasciitilde", lit "~")
, ("H", try $ tok >>= accent hungarumlaut) , ("H", accent '\779' hungarumlaut)
, ("`", option (str "`") $ try $ tok >>= accent grave) , ("`", accent '`' grave)
, ("'", option (str "'") $ try $ tok >>= accent acute) , ("'", accent '\'' acute)
, ("^", option (str "^") $ try $ tok >>= accent circ) , ("^", accent '^' circ)
, ("~", option (str "~") $ try $ tok >>= accent tilde) , ("~", accent '~' tilde)
, ("\"", option (str "\"") $ try $ tok >>= accent umlaut) , ("\"", accent '\776' umlaut)
, (".", option (str ".") $ try $ tok >>= accent dot) , (".", accent '\775' dot)
, ("=", option (str "=") $ try $ tok >>= accent macron) , ("=", accent '\772' macron)
, ("c", option (str "c") $ try $ tok >>= accent cedilla) , ("c", accent '\807' cedilla)
, ("v", option (str "v") $ try $ tok >>= accent hacek) , ("v", accent 'ˇ' hacek)
, ("u", option (str "u") $ try $ tok >>= accent breve) , ("u", accent '\774' breve)
, ("k", accent '\808' ogonek)
, ("textogonekcentered", accent '\808' ogonek)
, ("i", lit "i") , ("i", lit "i")
, ("\\", linebreak <$ (do inTableCell <- sInTableCell <$> getState , ("\\", linebreak <$ (do inTableCell <- sInTableCell <$> getState
guard $ not inTableCell guard $ not inTableCell

View file

@ -1,3 +1,4 @@
{-# LANGUAGE FlexibleContexts #-}
{- {-
Copyright (C) 2017 Alexander Krotov <ilabdsf@gmail.com> Copyright (C) 2017 Alexander Krotov <ilabdsf@gmail.com>
@ -32,7 +33,6 @@ TODO:
- {{{ }}} syntax for <example> - {{{ }}} syntax for <example>
- Page breaks (five "*") - Page breaks (five "*")
- Headings with anchors (make it round trip with Muse writer) - Headings with anchors (make it round trip with Muse writer)
- Verse markup (">")
- Org tables - Org tables
- table.el tables - table.el tables
- Images with attributes (floating and width) - Images with attributes (floating and width)
@ -101,6 +101,9 @@ parseBlocks = do
-- utility functions -- utility functions
-- --
eol :: Stream s m Char => ParserT s st m ()
eol = void newline <|> eof
nested :: PandocMonad m => MuseParser m a -> MuseParser m a nested :: PandocMonad m => MuseParser m a -> MuseParser m a
nested p = do nested p = do
nestlevel <- stateMaxNestingLevel <$> getState nestlevel <- stateMaxNestingLevel <$> getState
@ -180,7 +183,9 @@ blockElements = choice [ comment
, centerTag , centerTag
, rightTag , rightTag
, quoteTag , quoteTag
, divTag
, verseTag , verseTag
, lineBlock
, bulletList , bulletList
, orderedList , orderedList
, definitionList , definitionList
@ -194,7 +199,7 @@ comment = try $ do
char ';' char ';'
space space
many $ noneOf "\n" many $ noneOf "\n"
void newline <|> eof eol
return mempty return mempty
separator :: PandocMonad m => MuseParser m (F Blocks) separator :: PandocMonad m => MuseParser m (F Blocks)
@ -202,7 +207,7 @@ separator = try $ do
string "----" string "----"
many $ char '-' many $ char '-'
many spaceChar many spaceChar
void newline <|> eof eol
return $ return B.horizontalRule return $ return B.horizontalRule
header :: PandocMonad m => MuseParser m (F Blocks) header :: PandocMonad m => MuseParser m (F Blocks)
@ -212,8 +217,8 @@ header = try $ do
getPosition >>= \pos -> guard (st == NullState && q == NoQuote && sourceColumn pos == 1) getPosition >>= \pos -> guard (st == NullState && q == NoQuote && sourceColumn pos == 1)
level <- liftM length $ many1 $ char '*' level <- liftM length $ many1 $ char '*'
guard $ level <= 5 guard $ level <= 5
skipSpaces spaceChar
content <- trimInlinesF . mconcat <$> manyTill inline newline content <- trimInlinesF . mconcat <$> manyTill inline eol
attr <- registerHeader ("", [], []) (runF content defaultParserState) attr <- registerHeader ("", [], []) (runF content defaultParserState)
return $ B.headerWith attr level <$> content return $ B.headerWith attr level <$> content
@ -245,6 +250,12 @@ rightTag = blockTag id "right"
quoteTag :: PandocMonad m => MuseParser m (F Blocks) quoteTag :: PandocMonad m => MuseParser m (F Blocks)
quoteTag = withQuoteContext InDoubleQuote $ blockTag B.blockQuote "quote" quoteTag = withQuoteContext InDoubleQuote $ blockTag B.blockQuote "quote"
-- <div> tag is supported by Emacs Muse, but not Amusewiki 2.025
divTag :: PandocMonad m => MuseParser m (F Blocks)
divTag = do
(attrs, content) <- parseHtmlContentWithAttrs "div" block
return $ (B.divWith attrs) <$> mconcat content
verseLine :: PandocMonad m => MuseParser m String verseLine :: PandocMonad m => MuseParser m String
verseLine = do verseLine = do
line <- anyLine <|> many1Till anyChar eof line <- anyLine <|> many1Till anyChar eof
@ -261,8 +272,7 @@ verseLines = do
verseTag :: PandocMonad m => MuseParser m (F Blocks) verseTag :: PandocMonad m => MuseParser m (F Blocks)
verseTag = do verseTag = do
(_, content) <- htmlElement "verse" (_, content) <- htmlElement "verse"
parsedContent <- parseFromString verseLines content parseFromString verseLines content
return parsedContent
commentTag :: PandocMonad m => MuseParser m (F Blocks) commentTag :: PandocMonad m => MuseParser m (F Blocks)
commentTag = parseHtmlContent "comment" anyChar >> return mempty commentTag = parseHtmlContent "comment" anyChar >> return mempty
@ -299,6 +309,26 @@ noteBlock = try $ do
blocksTillNote = blocksTillNote =
many1Till block (eof <|> () <$ lookAhead noteMarker) many1Till block (eof <|> () <$ lookAhead noteMarker)
--
-- Verse markup
--
lineVerseLine :: PandocMonad m => MuseParser m String
lineVerseLine = try $ do
char '>'
white <- many1 (char ' ' >> pure '\160')
rest <- anyLine
return $ tail white ++ rest
blanklineVerseLine :: PandocMonad m => MuseParser m Char
blanklineVerseLine = try $ char '>' >> blankline
lineBlock :: PandocMonad m => MuseParser m (F Blocks)
lineBlock = try $ do
lns <- many1 (pure <$> blanklineVerseLine <|> lineVerseLine)
lns' <- mapM (parseFromString' (trimInlinesF . mconcat <$> many inline)) lns
return $ B.lineBlock <$> sequence lns'
-- --
-- lists -- lists
-- --
@ -379,8 +409,8 @@ definitionListItem = try $ do
pure $ do lineContent' <- lineContent pure $ do lineContent' <- lineContent
pure (B.text term, [lineContent']) pure (B.text term, [lineContent'])
where where
termParser = (many1 spaceChar) >> -- Initial space as required by Amusewiki, but not Emacs Muse termParser = many1 spaceChar >> -- Initial space as required by Amusewiki, but not Emacs Muse
(many1Till anyChar $ lookAhead (void (try (spaceChar >> string "::")) <|> void newline)) many1Till anyChar (lookAhead (void (try (spaceChar >> string "::")) <|> void newline))
endOfInput = try $ skipMany blankline >> skipSpaces >> eof endOfInput = try $ skipMany blankline >> skipSpaces >> eof
twoBlankLines = try $ blankline >> skipMany1 blankline twoBlankLines = try $ blankline >> skipMany1 blankline
newDefinitionListItem = try $ void termParser newDefinitionListItem = try $ void termParser
@ -438,10 +468,10 @@ museAppendElement tbl element =
tableCell :: PandocMonad m => MuseParser m (F Blocks) tableCell :: PandocMonad m => MuseParser m (F Blocks)
tableCell = try $ liftM B.plain . trimInlinesF . mconcat <$> manyTill inline (lookAhead cellEnd) tableCell = try $ liftM B.plain . trimInlinesF . mconcat <$> manyTill inline (lookAhead cellEnd)
where cellEnd = try $ void (many1 spaceChar >> char '|') <|> void newline <|> eof where cellEnd = try $ void (many1 spaceChar >> char '|') <|> eol
tableElements :: PandocMonad m => MuseParser m [MuseTableElement] tableElements :: PandocMonad m => MuseParser m [MuseTableElement]
tableElements = tableParseElement `sepEndBy1` (void newline <|> eof) tableElements = tableParseElement `sepEndBy1` eol
elementsToTable :: [MuseTableElement] -> F MuseTable elementsToTable :: [MuseTableElement] -> F MuseTable
elementsToTable = foldM museAppendElement emptyTable elementsToTable = foldM museAppendElement emptyTable

View file

@ -219,7 +219,6 @@ block = choice [ codeBlock
, directive , directive
, anchor , anchor
, comment , comment
, include
, header , header
, hrule , hrule
, lineBlock -- must go before definitionList , lineBlock -- must go before definitionList
@ -460,16 +459,16 @@ tab-width
encoding encoding
-} -}
include :: PandocMonad m => RSTParser m Blocks includeDirective :: PandocMonad m
include = try $ do => String -> [(String, String)] -> String
string ".. include::" -> RSTParser m Blocks
skipMany spaceChar includeDirective top fields body = do
f <- trim <$> anyLine let f = trim top
fields <- many $ rawFieldListItem 3 guard $ not (null f)
guard $ null (trim body)
-- options -- options
let (startLine :: Maybe Int) = lookup "start-line" fields >>= safeRead let (startLine :: Maybe Int) = lookup "start-line" fields >>= safeRead
let (endLine :: Maybe Int) = lookup "end-line" fields >>= safeRead let (endLine :: Maybe Int) = lookup "end-line" fields >>= safeRead
guard $ not (null f)
oldPos <- getPosition oldPos <- getPosition
oldInput <- getInput oldInput <- getInput
containers <- stateContainers <$> getState containers <- stateContainers <$> getState
@ -501,7 +500,7 @@ include = try $ do
Just patt -> drop 1 . Just patt -> drop 1 .
dropWhile (not . (patt `isInfixOf`)) dropWhile (not . (patt `isInfixOf`))
Nothing -> id) $ contentLines' Nothing -> id) $ contentLines'
let contents' = unlines contentLines'' let contents' = unlines contentLines'' ++ "\n"
case lookup "code" fields of case lookup "code" fields of
Just lang -> do Just lang -> do
let numberLines = lookup "number-lines" fields let numberLines = lookup "number-lines" fields
@ -687,6 +686,7 @@ directive' = do
$ lookup "height" fields >>= $ lookup "height" fields >>=
(lengthToDim . filter (not . isSpace)) (lengthToDim . filter (not . isSpace))
case label of case label of
"include" -> includeDirective top fields body'
"table" -> tableDirective top fields body' "table" -> tableDirective top fields body'
"list-table" -> listTableDirective top fields body' "list-table" -> listTableDirective top fields body'
"csv-table" -> csvTableDirective top fields body' "csv-table" -> csvTableDirective top fields body'

View file

@ -47,7 +47,7 @@ import Control.Monad.State.Strict
import Data.Char (ord, toLower) import Data.Char (ord, toLower)
import Data.Text (Text) import Data.Text (Text)
import qualified Data.Text.Lazy as TL import qualified Data.Text.Lazy as TL
import Data.List (intersperse, isPrefixOf) import Data.List (intersperse, isPrefixOf, partition, intercalate)
import Data.Maybe (catMaybes, fromMaybe, isJust, isNothing) import Data.Maybe (catMaybes, fromMaybe, isJust, isNothing)
import Data.Monoid ((<>)) import Data.Monoid ((<>))
import qualified Data.Set as Set import qualified Data.Set as Set
@ -569,8 +569,15 @@ imgAttrsToHtml opts attr = do
isNotDim _ = True isNotDim _ = True
dimensionsToAttrList :: Attr -> [(String, String)] dimensionsToAttrList :: Attr -> [(String, String)]
dimensionsToAttrList attr = (go Width) ++ (go Height) dimensionsToAttrList attr = consolidateStyles $ go Width ++ go Height
where where
consolidateStyles :: [(String, String)] -> [(String, String)]
consolidateStyles xs =
case partition isStyle xs of
([], _) -> xs
(ss, rest) -> ("style", intercalate ";" $ map snd ss) : rest
isStyle ("style", _) = True
isStyle _ = False
go dir = case (dimension dir attr) of go dir = case (dimension dir attr) of
(Just (Pixel a)) -> [(show dir, show a)] (Just (Pixel a)) -> [(show dir, show a)]
(Just x) -> [("style", show dir ++ ":" ++ show x)] (Just x) -> [("style", show dir ++ ":" ++ show x)]

View file

@ -628,6 +628,7 @@ blockToLaTeX (OrderedList (start, numstyle, numdelim) lst) = do
put $ st {stOLLevel = oldlevel + 1} put $ st {stOLLevel = oldlevel + 1}
items <- mapM listItemToLaTeX lst items <- mapM listItemToLaTeX lst
modify (\s -> s {stOLLevel = oldlevel}) modify (\s -> s {stOLLevel = oldlevel})
let beamer = stBeamer st
let tostyle x = case numstyle of let tostyle x = case numstyle of
Decimal -> "\\arabic" <> braces x Decimal -> "\\arabic" <> braces x
UpperRoman -> "\\Roman" <> braces x UpperRoman -> "\\Roman" <> braces x
@ -641,11 +642,21 @@ blockToLaTeX (OrderedList (start, numstyle, numdelim) lst) = do
TwoParens -> parens x TwoParens -> parens x
Period -> x <> "." Period -> x <> "."
_ -> x <> "." _ -> x <> "."
let exemplar = case numstyle of
Decimal -> "1"
UpperRoman -> "I"
LowerRoman -> "i"
UpperAlpha -> "A"
LowerAlpha -> "a"
Example -> "1"
DefaultStyle -> "1"
let enum = text $ "enum" ++ map toLower (toRomanNumeral oldlevel) let enum = text $ "enum" ++ map toLower (toRomanNumeral oldlevel)
let stylecommand = if numstyle == DefaultStyle && numdelim == DefaultDelim let stylecommand = if numstyle == DefaultStyle && numdelim == DefaultDelim
then empty then empty
else "\\def" <> "\\label" <> enum <> else if beamer
braces (todelim $ tostyle enum) then brackets (todelim exemplar)
else "\\def" <> "\\label" <> enum <>
braces (todelim $ tostyle enum)
let resetcounter = if start == 1 || oldlevel > 4 let resetcounter = if start == 1 || oldlevel > 4
then empty then empty
else "\\setcounter" <> braces enum <> else "\\setcounter" <> braces enum <>

View file

@ -288,6 +288,7 @@ escapeString opts (c:cs) =
| otherwise -> "&gt;" ++ escapeString opts cs | otherwise -> "&gt;" ++ escapeString opts cs
_ | c `elem` ['\\','`','*','_','[',']','#'] -> _ | c `elem` ['\\','`','*','_','[',']','#'] ->
'\\':c:escapeString opts cs '\\':c:escapeString opts cs
'|' | isEnabled Ext_pipe_tables opts -> '\\':'|':escapeString opts cs
'^' | isEnabled Ext_superscript opts -> '\\':'^':escapeString opts cs '^' | isEnabled Ext_superscript opts -> '\\':'^':escapeString opts cs
'~' | isEnabled Ext_subscript opts -> '\\':'~':escapeString opts cs '~' | isEnabled Ext_subscript opts -> '\\':'~':escapeString opts cs
'$' | isEnabled Ext_tex_math_dollars opts -> '\\':'$':escapeString opts cs '$' | isEnabled Ext_tex_math_dollars opts -> '\\':'$':escapeString opts cs
@ -787,6 +788,7 @@ blockListToMarkdown :: PandocMonad m
-> MD m Doc -> MD m Doc
blockListToMarkdown opts blocks = do blockListToMarkdown opts blocks = do
inlist <- asks envInList inlist <- asks envInList
isPlain <- asks envPlain
-- a) insert comment between list and indented code block, or the -- a) insert comment between list and indented code block, or the
-- code block will be treated as a list continuation paragraph -- code block will be treated as a list continuation paragraph
-- b) change Plain to Para unless it's followed by a RawBlock -- b) change Plain to Para unless it's followed by a RawBlock
@ -813,9 +815,11 @@ blockListToMarkdown opts blocks = do
isListBlock (OrderedList _ _) = True isListBlock (OrderedList _ _) = True
isListBlock (DefinitionList _) = True isListBlock (DefinitionList _) = True
isListBlock _ = False isListBlock _ = False
commentSep = if isEnabled Ext_raw_html opts commentSep = if isPlain
then RawBlock "html" "<!-- -->\n" then Null
else RawBlock "markdown" "&nbsp;\n" else if isEnabled Ext_raw_html opts
then RawBlock "html" "<!-- -->\n"
else RawBlock "markdown" "&nbsp;\n"
mapM (blockToMarkdown opts) (fixBlocks blocks) >>= return . cat mapM (blockToMarkdown opts) (fixBlocks blocks) >>= return . cat
getKey :: Doc -> Key getKey :: Doc -> Key
@ -931,7 +935,7 @@ avoidBadWrapsInList (s:Str cs:[])
avoidBadWrapsInList (x:xs) = x : avoidBadWrapsInList xs avoidBadWrapsInList (x:xs) = x : avoidBadWrapsInList xs
isOrderedListMarker :: String -> Bool isOrderedListMarker :: String -> Bool
isOrderedListMarker xs = (last xs `elem` ['.',')']) && isOrderedListMarker xs = not (null xs) && (last xs `elem` ['.',')']) &&
isRight (runParser (anyOrderedListMarker >> eof) isRight (runParser (anyOrderedListMarker >> eof)
defaultParserState "" xs) defaultParserState "" xs)
@ -946,11 +950,10 @@ inlineToMarkdown opts (Span attrs ils) = do
contents <- inlineListToMarkdown opts ils contents <- inlineListToMarkdown opts ils
return $ case plain of return $ case plain of
True -> contents True -> contents
False | isEnabled Ext_bracketed_spans opts -> False | attrs == nullAttr -> contents
| isEnabled Ext_bracketed_spans opts ->
"[" <> contents <> "]" <> "[" <> contents <> "]" <>
if attrs == nullAttr linkAttributes opts attrs
then "{}"
else linkAttributes opts attrs
| isEnabled Ext_raw_html opts || | isEnabled Ext_raw_html opts ||
isEnabled Ext_native_spans opts -> isEnabled Ext_native_spans opts ->
tagWithAttrs "span" attrs <> contents <> text "</span>" tagWithAttrs "span" attrs <> contents <> text "</span>"

View file

@ -129,36 +129,25 @@ blockToOrg (Div (_,classes@(cls:_),kvs) bs) | "drawer" `elem` classes = do
blankline $$ contents $$ blankline $$ contents $$
blankline $$ drawerEndTag $$ blankline $$ drawerEndTag $$
blankline blankline
blockToOrg (Div attrs bs) = do blockToOrg (Div (ident, classes, kv) bs) = do
contents <- blockListToOrg bs contents <- blockListToOrg bs
-- if one class looks like the name of a greater block then output as such:
-- The ID, if present, is added via the #+NAME keyword; other classes and
-- key-value pairs are kept as #+ATTR_HTML attributes.
let isGreaterBlockClass = (`elem` ["center", "quote"]) . map toLower let isGreaterBlockClass = (`elem` ["center", "quote"]) . map toLower
return $ case attrs of (blockTypeCand, classes') = partition isGreaterBlockClass classes
("", [], []) -> return $ case blockTypeCand of
-- nullAttr, treat contents as if it wasn't wrapped (blockType:classes'') ->
blankline $$ contents $$ blankline blankline $$ attrHtml (ident, classes'' <> classes', kv) $$
(ident, [], []) -> "#+BEGIN_" <> text blockType $$ contents $$
-- only an id: add id as an anchor, unwrap the rest "#+END_" <> text blockType $$ blankline
blankline $$ "<<" <> text ident <> ">>" $$ contents $$ blankline _ ->
(ident, classes, kv) -> -- fallback with id: add id as an anchor if present, discard classes and
-- if one class looks like the name of a greater block then output as -- key-value pairs, unwrap the content.
-- such: The ID, if present, is added via the #+NAME keyword; other let contents' = if not (null ident)
-- classes and key-value pairs are kept as #+ATTR_HTML attributes. then "<<" <> text ident <> ">>" $$ contents
let else contents
(blockTypeCand, classes') = partition isGreaterBlockClass classes in blankline $$ contents' $$ blankline
in case blockTypeCand of
(blockType:classes'') ->
blankline $$ attrHtml (ident, classes'' <> classes', kv) $$
"#+BEGIN_" <> text blockType $$ contents $$
"#+END_" <> text blockType $$ blankline
_ ->
-- fallback: wrap in div tags
let
startTag = tagWithAttrs "div" attrs
endTag = text "</div>"
in blankline $$ "#+BEGIN_HTML" $$
nest 2 startTag $$ "#+END_HTML" $$ blankline $$
contents $$ blankline $$ "#+BEGIN_HTML" $$
nest 2 endTag $$ "#+END_HTML" $$ blankline
blockToOrg (Plain inlines) = inlineListToOrg inlines blockToOrg (Plain inlines) = inlineListToOrg inlines
-- title beginning with fig: indicates that the image is a figure -- title beginning with fig: indicates that the image is a figure
blockToOrg (Para [Image attr txt (src,'f':'i':'g':':':tit)]) = do blockToOrg (Para [Image attr txt (src,'f':'i':'g':':':tit)]) = do
@ -173,7 +162,7 @@ blockToOrg (Para inlines) = do
blockToOrg (LineBlock lns) = do blockToOrg (LineBlock lns) = do
let splitStanza [] = [] let splitStanza [] = []
splitStanza xs = case break (== mempty) xs of splitStanza xs = case break (== mempty) xs of
(l, []) -> l : [] (l, []) -> [l]
(l, _:r) -> l : splitStanza r (l, _:r) -> l : splitStanza r
let joinWithLinefeeds = nowrap . mconcat . intersperse cr let joinWithLinefeeds = nowrap . mconcat . intersperse cr
let joinWithBlankLines = mconcat . intersperse blankline let joinWithBlankLines = mconcat . intersperse blankline
@ -213,7 +202,7 @@ blockToOrg (Table caption' _ _ headers rows) = do
caption'' <- inlineListToOrg caption' caption'' <- inlineListToOrg caption'
let caption = if null caption' let caption = if null caption'
then empty then empty
else ("#+CAPTION: " <> caption'') else "#+CAPTION: " <> caption''
headers' <- mapM blockListToOrg headers headers' <- mapM blockListToOrg headers
rawRows <- mapM (mapM blockListToOrg) rows rawRows <- mapM (mapM blockListToOrg) rows
let numChars = maximum . map offset let numChars = maximum . map offset
@ -289,8 +278,8 @@ propertiesDrawer (ident, classes, kv) =
let let
drawerStart = text ":PROPERTIES:" drawerStart = text ":PROPERTIES:"
drawerEnd = text ":END:" drawerEnd = text ":END:"
kv' = if (classes == mempty) then kv else ("CLASS", unwords classes):kv kv' = if classes == mempty then kv else ("CLASS", unwords classes):kv
kv'' = if (ident == mempty) then kv' else ("CUSTOM_ID", ident):kv' kv'' = if ident == mempty then kv' else ("CUSTOM_ID", ident):kv'
properties = vcat $ map kvToOrgProperty kv'' properties = vcat $ map kvToOrgProperty kv''
in in
drawerStart <> cr <> properties <> cr <> drawerEnd drawerStart <> cr <> properties <> cr <> drawerEnd
@ -303,7 +292,7 @@ attrHtml :: Attr -> Doc
attrHtml ("" , [] , []) = mempty attrHtml ("" , [] , []) = mempty
attrHtml (ident, classes, kvs) = attrHtml (ident, classes, kvs) =
let let
name = if (null ident) then mempty else "#+NAME: " <> text ident <> cr name = if null ident then mempty else "#+NAME: " <> text ident <> cr
keyword = "#+ATTR_HTML" keyword = "#+ATTR_HTML"
classKv = ("class", unwords classes) classKv = ("class", unwords classes)
kvStrings = map (\(k,v) -> ":" <> k <> " " <> v) (classKv:kvs) kvStrings = map (\(k,v) -> ":" <> k <> " " <> v) (classKv:kvs)
@ -370,19 +359,19 @@ inlineToOrg SoftBreak = do
WrapPreserve -> return cr WrapPreserve -> return cr
WrapAuto -> return space WrapAuto -> return space
WrapNone -> return space WrapNone -> return space
inlineToOrg (Link _ txt (src, _)) = do inlineToOrg (Link _ txt (src, _)) =
case txt of case txt of
[Str x] | escapeURI x == src -> -- autolink [Str x] | escapeURI x == src -> -- autolink
do return $ "[[" <> text (orgPath x) <> "]]" return $ "[[" <> text (orgPath x) <> "]]"
_ -> do contents <- inlineListToOrg txt _ -> do contents <- inlineListToOrg txt
return $ "[[" <> text (orgPath src) <> "][" <> contents <> "]]" return $ "[[" <> text (orgPath src) <> "][" <> contents <> "]]"
inlineToOrg (Image _ _ (source, _)) = do inlineToOrg (Image _ _ (source, _)) =
return $ "[[" <> text (orgPath source) <> "]]" return $ "[[" <> text (orgPath source) <> "]]"
inlineToOrg (Note contents) = do inlineToOrg (Note contents) = do
-- add to notes in state -- add to notes in state
notes <- gets stNotes notes <- gets stNotes
modify $ \st -> st { stNotes = contents:notes } modify $ \st -> st { stNotes = contents:notes }
let ref = show $ (length notes) + 1 let ref = show $ length notes + 1
return $ "[fn:" <> text ref <> "]" return $ "[fn:" <> text ref <> "]"
orgPath :: String -> String orgPath :: String -> String

View file

@ -14,7 +14,7 @@ packages:
- '.' - '.'
- location: - location:
git: https://github.com/jgm/pandoc-citeproc.git git: https://github.com/jgm/pandoc-citeproc.git
commit: 71ca48b6e0044ea959d8e7882b03cceba9c7960c commit: 5a7f26b61c8577916093851cdeb31fa9a198edcb
extra-dep: false extra-dep: false
extra-deps: extra-deps:
- hslua-0.8.0 - hslua-0.8.0

View file

@ -145,6 +145,38 @@ tests =
, " with a continuation" , " with a continuation"
] =?> ] =?>
blockQuote (para "This is a quotation with a continuation") blockQuote (para "This is a quotation with a continuation")
, testGroup "Div"
[ "Div without id" =:
"<div>Foo bar</div>" =?>
divWith nullAttr (para "Foo bar")
, "Div with id" =:
"<div id=\"foo\">Foo bar</div>" =?>
divWith ("foo", [], []) (para "Foo bar")
]
, "Verse" =:
T.unlines [ "> This is"
, "> First stanza"
, ">" -- Emacs produces verbatim ">" here, we follow Amusewiki
, "> And this is"
, "> Second stanza"
, ">"
, ""
, ">"
, ""
, "> Another verse"
, "> is here"
] =?>
lineBlock [ "This is"
, "First stanza"
, ""
, "And this is"
, "\160\160Second stanza"
, ""
] <>
lineBlock [ "" ] <>
lineBlock [ "Another verse"
, "\160\160\160is here"
]
] ]
, "Quote tag" =: "<quote>Hello, world</quote>" =?> blockQuote (para $ text "Hello, world") , "Quote tag" =: "<quote>Hello, world</quote>" =?> blockQuote (para $ text "Hello, world")
, "Verse tag" =: , "Verse tag" =:
@ -178,20 +210,21 @@ tests =
] ]
, testGroup "Headers" , testGroup "Headers"
[ "Part" =: [ "Part" =:
"* First level\n" =?> "* First level" =?>
header 1 "First level" header 1 "First level"
, "Chapter" =: , "Chapter" =:
"** Second level\n" =?> "** Second level" =?>
header 2 "Second level" header 2 "Second level"
, "Section" =: , "Section" =:
"*** Third level\n" =?> "*** Third level" =?>
header 3 "Third level" header 3 "Third level"
, "Subsection" =: , "Subsection" =:
"**** Fourth level\n" =?> "**** Fourth level" =?>
header 4 "Fourth level" header 4 "Fourth level"
, "Subsubsection" =: , "Subsubsection" =:
"***** Fifth level\n" =?> "***** Fifth level" =?>
header 5 "Fifth level" header 5 "Fifth level"
, "Whitespace is required after *" =: "**Not a header" =?> para "**Not a header"
, "No headers in footnotes" =: , "No headers in footnotes" =:
T.unlines [ "Foo[1]" T.unlines [ "Foo[1]"
, "[1] * Bar" , "[1] * Bar"

View file

@ -136,6 +136,19 @@ tests = [ "line block with blank line" =:
para "but must stop here") para "but must stop here")
, "line block with 3 lines" =: "| a\n| b\n| c" , "line block with 3 lines" =: "| a\n| b\n| c"
=?> lineBlock ["a", "b", "c"] =?> lineBlock ["a", "b", "c"]
, "line blocks with blank lines" =: T.unlines
[ "|"
, ""
, "|"
, "| a"
, "| b"
, "|"
, ""
, "|"
] =?>
lineBlock [""] <>
lineBlock ["", "a", "b", ""] <>
lineBlock [""]
, "quoted literal block using >" =: "::\n\n> quoted\n> block\n\nOrdinary paragraph" , "quoted literal block using >" =: "::\n\n> quoted\n> block\n\nOrdinary paragraph"
=?> codeBlock "> quoted\n> block" <> para "Ordinary paragraph" =?> codeBlock "> quoted\n> block" <> para "Ordinary paragraph"
, "quoted literal block using | (not a line block)" =: "::\n\n| quoted\n| block\n\nOrdinary paragraph" , "quoted literal block using | (not a line block)" =: "::\n\n| quoted\n| block\n\nOrdinary paragraph"

View file

@ -46,6 +46,6 @@ Also escape things that might become line blocks or tables:
% pandoc -t markdown % pandoc -t markdown
\| hi \| \| hi \|
^D ^D
\| hi | \| hi \|
``` ```

14
test/command/3771.md Normal file
View file

@ -0,0 +1,14 @@
```
% pandoc -f html -t org
<div class="Section1">
Today is a nice day.
</div>
<div id="forecast">
Tomorrow will be rainy.
</div>
^D
Today is a nice day.
<<forecast>>
Tomorrow will be rainy.
```

6
test/command/3880.md Normal file
View file

@ -0,0 +1,6 @@
```
pandoc -f rst -t native
.. include:: command/3880.txt
^D
[Para [Str "hi"]]
```

1
test/command/3880.txt Normal file
View file

@ -0,0 +1 @@
hi

View file

@ -44,6 +44,12 @@
\let\oldsubparagraph\subparagraph \let\oldsubparagraph\subparagraph
\renewcommand{\subparagraph}[1]{\oldsubparagraph{#1}\mbox{}} \renewcommand{\subparagraph}[1]{\oldsubparagraph{#1}\mbox{}}
\fi \fi
% set default figure placement to htbp
\makeatletter
\def\fps@figure{htbp}
\makeatother
\ifnum 0\ifxetex 1\fi\ifluatex 1\fi=0 % if pdftex \ifnum 0\ifxetex 1\fi\ifluatex 1\fi=0 % if pdftex
\usepackage[shorthands=off,ngerman,british,nswissgerman,spanish,french,main=english]{babel} \usepackage[shorthands=off,ngerman,british,nswissgerman,spanish,french,main=english]{babel}
\newcommand{\textgerman}[2][]{\foreignlanguage{ngerman}{#2}} \newcommand{\textgerman}[2][]{\foreignlanguage{ngerman}{#2}}
@ -77,12 +83,6 @@
\newenvironment{LTR}{\beginL}{\endL} \newenvironment{LTR}{\beginL}{\endL}
\fi \fi
% set default figure placement to htbp
\makeatletter
\def\fps@figure{htbp}
\makeatother
\date{} \date{}
\begin{document} \begin{document}

View file

@ -0,0 +1,58 @@
;;; pandoc-template-mode.el --- Pandoc-Template major mode
;; Copyright (C) 2017
;; Author: Václav Haisman
;; Keywords: extensions
;; This file is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 2, or (at your option)
;; any later version.
;; This file is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs; see the file COPYING. If not, write to
;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
;; Boston, MA 02111-1307, USA.
;;; Commentary:
;;
;;; Code:
(defvar pandoc-template-font-lock-keywords
'(("\\(\\$\\)\\(if\\|for\\)(\\([^)]+\\))\\(\\$\\)"
(1 font-lock-preprocessor-face)
(2 font-lock-keyword-face)
(3 font-lock-variable-name-face)
(4 font-lock-preprocessor-face))
("\\(\\$\\)\\(endif\\|endfor\\|else\\)\\(\\$\\)"
(1 font-lock-preprocessor-face)
(2 font-lock-keyword-face)
(3 font-lock-preprocessor-face))
("\\(\\$\\)\\(sep\\)\\(\\$\\)"
(1 font-lock-preprocessor-face)
(2 font-lock-builtin-face)
(3 font-lock-preprocessor-face))
("\\(\\$\\)\\([^$]+\\)\\(\\$\\)"
(1 font-lock-preprocessor-face)
(2 font-lock-variable-name-face)
(3 font-lock-preprocessor-face))
)
"Keyword highlighting specification for `pandoc-template-mode'.")
;;;###autoload
(define-derived-mode pandoc-template-mode fundamental-mode "Pandoc-Template"
"A major mode for editing Pandoc-Template files."
:syntax-table nil
(setq-local font-lock-defaults
'(pandoc-template-font-lock-keywords)))
(provide 'pandoc-template-mode)
;;; pandoc-template.el ends here