LEFT TEXT
2020-01-10 :: Pandoc Lua Filters… – Albert Krewinkel; John MacFarlane
Title: Pandoc Lua Filters
Date: 2020-01-10
Authors: Albert Krewinkel, John MacFarlane
Tags: (no tags)
Reading time: 13425 words, 61 minutes
<!-- composer >> metainfo box-begin 0 -->
#WORK
<!-- composer >> box-end -->
Pandoc has long supported filters, which allow the pandoc abstract syntax tree (AST) to be manipulated between the parsing and the writing phase. Traditional pandoc filters accept a JSON representation of the pandoc AST and produce an altered JSON representation of the AST. They may be written in any programming language, and invoked from pandoc using the --filter option.
Although traditional filters are very flexible, they have a couple of disadvantages. First, there is some overhead in writing JSON to stdout and reading it from stdin (twice, once on each side of the filter). Second, whether a filter will work will depend on details of the user’s environment. A filter may require an interpreter for a certain programming language to be available, as well as a library for manipulating the pandoc AST in JSON form. One cannot simply provide a filter that can be used by anyone who has a certain version of the pandoc executable.
Starting with version 2.0, pandoc makes it possible to write filters in Lua without any external dependencies at all. A Lua interpreter (version 5.3) and a Lua library for creating pandoc filters is built into the pandoc executable. Pandoc data types are marshaled to Lua directly, avoiding the overhead of writing JSON to stdout and reading it from stdin.
Here is an example of a Lua filter that converts strong emphasis to small caps:
or equivalently,
This says: walk the AST, and when you find a Strong element, replace it with a SmallCaps element with the same content.
To run it, save it in a file, say smallcaps.lua, and invoke pandoc with --lua-filter=smallcaps.lua.
Here’s a quick performance comparison, converting the pandoc manual (MANUAL.txt) to HTML, with versions of the same JSON filter written in compiled Haskell (smallcaps) and interpreted Python (smallcaps.py):
| Command | Time |
|---|---|
pandoc |
1.01s |
pandoc --filter ./smallcaps |
1.36s |
pandoc --filter ./smallcaps.py |
1.40s |
pandoc --lua-filter ./smallcaps.lua |
1.03s |
As you can see, the Lua filter avoids the substantial overhead associated with marshaling to and from JSON over a pipe.
Lua filters are tables with element names as keys and values consisting of functions acting on those elements.
Filters are expected to be put into separate files and are passed via the --lua-filter command-line argument. For example, if a filter is defined in a file current-date.lua, then it would be applied like this:
pandoc --lua-filter=current-date.lua -f markdown MANUAL.txt
The --lua-filter option may be supplied multiple times. Pandoc applies all filters (including JSON filters specified via --filter and Lua filters specified via --lua-filter) in the order they appear on the command line.
Pandoc expects each Lua file to return a list of filters. The filters in that list are called sequentially, each on the result of the previous filter. If there is no value returned by the filter script, then pandoc will try to generate a single filter by collecting all top-level functions whose names correspond to those of pandoc elements (e.g., Str, Para, Meta, or Pandoc). (That is why the two examples above are equivalent.)
For each filter, the document is traversed and each element subjected to the filter. Elements for which the filter contains an entry (i.e. a function of the same name) are passed to Lua element filtering function. In other words, filter entries will be called for each corresponding element in the document, getting the respective element as input.
The return value of a filter function must be one of the following:
The function’s output must result in an element of the same type as the input. This means a filter function acting on an inline element must return either nil, an inline, or a list of inlines, and a function filtering a block element must return one of nil, a block, or a list of block elements. Pandoc will 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.
See module documentation for a list of pandoc elements.
For some filtering tasks, it is necessary to know the order in which elements occur in the document. It is not enough then to inspect a single element at a time.
There are two special function names, which can be used to define filters on lists of blocks or lists of inlines.
Inlines (inlines)inlines argument passed to the function will be a List of Inline elements for each call.
Blocks (blocks)blocks argument passed to the function will be a List of Block elements for each call.
These filter functions are special in that the result must either be nil, in which case the list is left unchanged, or must be a list of the correct type, i.e., the same type as the input argument. Single elements are not allowed as return values, as a single element in this context usually hints at a bug.
See “Remove spaces before normal citations” for an example.
This functionality has been added in pandoc 2.9.2.
The traversal order of filters can be selected by setting the key traverse to either 'topdown' or 'typewise'; the default is 'typewise'.
Example:
Support for this was added in pandoc 2.17; previous versions ignore the traverse setting.
Element filter functions within a filter set are called in a fixed order, skipping any which are not present:
Inlines filter function,Blocks filter function,Meta filter function, and lastPandoc filter function.It is still possible to force a different order by explicitly returning multiple filter sets. For example, if the filter for Meta is to be run before that for Str, one can write
Filter sets are applied in the order in which they are returned. All functions in set (1) are thus run before those in (2), causing the filter function for Meta to be run before the filtering of Str elements is started.
It is sometimes more natural to traverse the document tree depth-first from the root towards the leaves, and all in a single run.
For example, a block list [Plain [Str "a"], Para [Str "b"]] will try the following filter functions, in order: Blocks, Plain, Inlines, Str, Para, Inlines, Str.
Topdown traversals can be cut short by returning false as a second value from the filter function. No child-element of the returned element is processed in that case.
For example, to exclude the contents of a footnote from being processed, one might write
Pandoc passes additional data to Lua filters by setting global variables.
FORMATFORMAT is set to the format of the pandoc writer being used (html5, latex, etc.), so the behavior of a filter can be made conditional on the eventual output format.
PANDOC_READER_OPTIONSPANDOC_WRITER_OPTIONSTable of the options that will be passed to the writer. While the object can be modified, the changes will not be picked up by pandoc. (WriterOptions)
This variable is also set in custom writers.
Since: pandoc 2.17
PANDOC_VERSION{2, 7, 3}. Use tostring(PANDOC_VERSION) to produce a version string. This variable is also set in custom writers.
PANDOC_API_VERSION{1, 17, 3}. Use tostring(PANDOC_API_VERSION) to produce a version string. This variable is also set in custom writers.
PANDOC_SCRIPT_FILEPANDOC_STATEpandocpandoc. The other modules described herein are loaded as subfields under their respective name.
lpegThis variable holds the lpeg module, a package based on Parsing Expression Grammars (PEG). It provides excellent parsing utilities and is documented on the official LPeg homepage. Pandoc uses a built-in version of the library, unless it has been configured by the package maintainer to rely on a system-wide installation.
Note that the result of require 'lpeg' is not necessarily equal to this value; the require mechanism prefers the system’s lpeg library over the built-in version.
reContains the LPeg.re module, which is built on top of LPeg and offers an implementation of a regex engine. Pandoc uses a built-in version of the library, unless it has been configured by the package maintainer to rely on a system-wide installation.
Note that the result of require 're is not necessarily equal to this value; the require mechanism prefers the system’s lpeg library over the built-in version.
The pandoc Lua module is loaded into the filter’s Lua environment and provides a set of functions and constants to make creation and manipulation of elements easier. The global variable pandoc is bound to the module and should generally not be overwritten for this reason.
Two major functionalities are provided by the module: element creator functions and access to some of pandoc’s main functionalities.
Element creator functions like Str, Para, and Pandoc are designed to allow easy creation of new elements that are simple to use and can be read back from the Lua environment. Internally, pandoc uses these functions to create the Lua objects which are passed to element filter functions. This means that elements created via this module will behave exactly as those elements accessible through the filter function parameter.
Some pandoc functions have been made available in Lua:
walk_block and walk_inline allow filters to be applied inside specific block or inline elements;read allows filters to parse strings into pandoc documents;pipe runs an external command with input from and output to strings;pandoc.mediabag module allows access to the “mediabag,” which stores binary content such as images that may be included in the final document;pandoc.utils module contains various utility functions.Initialization of pandoc’s Lua interpreter can be controlled by placing a file init.lua in pandoc’s data directory. A common use-case would be to load additional modules, or even to alter default modules.
The following snippet is an example of code that might be useful when added to init.lua. The snippet adds all Unicode-aware functions defined in the text module to the default string module, prefixed with the string uc_.
This makes it possible to apply these functions on strings using colon syntax (mystring:uc_upper()).
It is possible to use a debugging interface to halt execution and step through a Lua filter line by line as it is run inside Pandoc. This is accomplished using the remote-debugging interface of the package mobdebug. Although mobdebug can be run from the terminal, it is more useful run within the donation-ware Lua editor and IDE, ZeroBrane. ZeroBrane offers a REPL console and UI to step-through and view all variables and state.
If you already have Lua 5.3 installed, you can add mobdebug and its dependency luasocket using luarocks, which should then be available on the path. ZeroBrane also includes both of these in its package, so if you don’t want to install Lua separately, you should add/modify your LUA_PATH and LUA_CPATH to include the correct locations; see detailed instructions here.
The following filters are presented as examples. A repository of useful Lua filters (which may also serve as good examples) is available at https://github.com/pandoc/lua-filters.
The following filter converts the string {{helloworld}} into emphasized text “Hello, World”.
For LaTeX, wrap an image in LaTeX snippets which cause the image to be centered horizontally. In HTML, the image element’s style attribute is used to achieve centering.
-- Filter images with this function if the target format is LaTeX.
if FORMAT:match 'latex' then
function Image (elem)
-- Surround all images with image-centering raw LaTeX.
return {
pandoc.RawInline('latex', '\\hfill\\break{\\centering'),
elem,
pandoc.RawInline('latex', '\\par}')
}
end
end
-- Filter images with this function if the target format is HTML
if FORMAT:match 'html' then
function Image (elem)
-- Use CSS style to center image
elem.attributes.style = 'margin:auto; display: block;'
return elem
end
endThis filter sets the date in the document’s metadata to the current date, if a date isn’t already set:
This filter removes all spaces preceding an “author-in-text” citation. In Markdown, author-in-text citations (e.g., @citekey), must be preceded by a space. If these spaces are undesired, they must be removed with a filter.
local function is_space_before_author_in_text(spc, cite)
return spc and spc.t == 'Space'
and cite and cite.t == 'Cite'
-- there must be only a single citation, and it must have
-- mode 'AuthorInText'
and #cite.citations == 1
and cite.citations[1].mode == 'AuthorInText'
end
function Inlines (inlines)
-- Go from end to start to avoid problems with shifting indices.
for i = #inlines-1, 1, -1 do
if is_space_before_author_in_text(inlines[i], inlines[i+1]) then
inlines:remove(i)
end
end
return inlines
endLua filter functions are run in the order
Inlines → Blocks → Meta → Pandoc.
Passing information from a higher level (e.g., metadata) to a lower level (e.g., inlines) is still possible by using two filters living in the same file:
local vars = {}
function get_vars (meta)
for k, v in pairs(meta) do
if pandoc.utils.type(v) == 'Inlines' then
vars["%" .. k .. "%"] = {table.unpack(v)}
end
end
end
function replace (el)
if vars[el.text] then
return pandoc.Span(vars[el.text])
else
return el
end
end
return {{Meta = get_vars}, {Str = replace}}If the contents of file occupations.md is
---
name: Samuel Q. Smith
occupation: Professor of Phrenology
---
Name
: %name%
Occupation
: %occupation%then running pandoc --lua-filter=meta-vars.lua occupations.md will output:
MANUAL.txt for man pagesThis is the filter we use when converting MANUAL.txt to man pages. It converts level-1 headers to uppercase (using walk to transform inline elements inside headers), removes footnotes, and replaces links with regular text.
This filter extracts all the numbered examples, section headers, block quotes, and figures from a document, in addition to any divs with class handout. (Note that only blocks at the “outer level” are included; this ignores blocks inside nested constructs, like list items.)
-- creates a handout from an article, using its headings,
-- blockquotes, numbered examples, figures, and any
-- Divs with class "handout"
function Pandoc(doc)
local hblocks = {}
for i,el in pairs(doc.blocks) do
if (el.t == "Div" and el.classes[1] == "handout") or
(el.t == "BlockQuote") or
(el.t == "OrderedList" and el.style == "Example") or
(el.t == "Para" and #el.c == 1 and el.c[1].t == "Image") or
(el.t == "Header") then
table.insert(hblocks, el)
end
end
return pandoc.Pandoc(hblocks, doc.meta)
endThis filter counts the words in the body of a document (omitting metadata like titles and abstracts), including words in code. It should be more accurate than wc -w run directly on a Markdown document, since the latter will count markup characters, like the # in front of an ATX header, or tags in HTML documents, as words. To run it, pandoc --lua-filter wordcount.lua myfile.md.
-- counts words in a document
words = 0
wordcount = {
Str = function(el)
-- we don't count a word if it's entirely punctuation:
if el.text:match("%P") then
words = words + 1
end
end,
Code = function(el)
_,n = el.text:gsub("%S+","")
words = words + n
end,
CodeBlock = function(el)
_,n = el.text:gsub("%S+","")
words = words + n
end
}
function Pandoc(el)
-- skip metadata, just count body:
el.blocks:walk(wordcount)
print(words .. " words in body")
os.exit(0)
endThis filter replaces code blocks with class abc with images created by running their contents through abcm2ps and ImageMagick’s convert. (For more on ABC notation, see https://abcnotation.com.)
Images are added to the mediabag. For output to binary formats, pandoc will use images in the mediabag. For textual formats, use --extract-media to specify a directory where the files in the mediabag will be written, or (for HTML only) use --self-contained.
-- Pandoc filter to process code blocks with class "abc" containing
-- ABC notation into images.
--
-- * Assumes that abcm2ps and ImageMagick's convert are in the path.
-- * For textual output formats, use --extract-media=abc-images
-- * For HTML formats, you may alternatively use --self-contained
local filetypes = { html = {"png", "image/png"}
, latex = {"pdf", "application/pdf"}
}
local filetype = filetypes[FORMAT][1] or "png"
local mimetype = filetypes[FORMAT][2] or "image/png"
local function abc2eps(abc, filetype)
local eps = pandoc.pipe("abcm2ps", {"-q", "-O", "-", "-"}, abc)
local final = pandoc.pipe("convert", {"-", filetype .. ":-"}, eps)
return final
end
function CodeBlock(block)
if block.classes[1] == "abc" then
local img = abc2eps(block.text, filetype)
local fname = pandoc.sha1(img) .. "." .. filetype
pandoc.mediabag.insert(fname, mimetype, img)
return pandoc.Para{ pandoc.Image({pandoc.Str("abc tune")}, fname) }
end
endThis filter converts raw LaTeX TikZ environments into images. It works with both PDF and HTML output. The TikZ code is compiled to an image using pdflatex, and the image is converted from pdf to svg format using pdf2svg, so both of these must be in the system path. Converted images are cached in the working directory and given filenames based on a hash of the source, so that they need not be regenerated each time the document is built. (A more sophisticated version of this might put these in a special cache directory.)
local system = require 'pandoc.system'
local tikz_doc_template = [[
\documentclass{standalone}
\usepackage{xcolor}
\usepackage{tikz}
\begin{document}
\nopagecolor
%s
\end{document}
]]
local function tikz2image(src, filetype, outfile)
system.with_temporary_directory('tikz2image', function (tmpdir)
system.with_working_directory(tmpdir, function()
local f = io.open('tikz.tex', 'w')
f:write(tikz_doc_template:format(src))
f:close()
os.execute('pdflatex tikz.tex')
if filetype == 'pdf' then
os.rename('tikz.pdf', outfile)
else
os.execute('pdf2svg tikz.pdf ' .. outfile)
end
end)
end)
end
extension_for = {
html = 'svg',
html4 = 'svg',
html5 = 'svg',
latex = 'pdf',
beamer = 'pdf' }
local function file_exists(name)
local f = io.open(name, 'r')
if f ~= nil then
io.close(f)
return true
else
return false
end
end
local function starts_with(start, str)
return str:sub(1, #start) == start
end
function RawBlock(el)
if starts_with('\\begin{tikzpicture}', el.text) then
local filetype = extension_for[FORMAT] or 'svg'
local fbasename = pandoc.sha1(el.text) .. '.' .. filetype
local fname = system.get_working_directory() .. '/' .. fbasename
if not file_exists(fname) then
tikz2image(el.text, filetype, fname)
end
return pandoc.Para({pandoc.Image({}, fbasename)})
else
return el
end
endExample of use:
pandoc --lua-filter tikz.lua -s -o cycle.html <<EOF
Here is a diagram of the cycle:
\begin{tikzpicture}
\def \n {5}
\def \radius {3cm}
\def \margin {8} % margin in angles, depends on the radius
\foreach \s in {1,...,\n}
{
\node[draw, circle] at ({360/\n * (\s - 1)}:\radius) {$\s$};
\draw[->, >=latex] ({360/\n * (\s - 1)+\margin}:\radius)
arc ({360/\n * (\s - 1)+\margin}:{360/\n * (\s)-\margin}:\radius);
}
\end{tikzpicture}
EOF
This section describes the types of objects available to Lua filters. See the pandoc module for functions to create these objects.
cloneclone ()
All instances of the types listed here, with the exception of read-only objects, can be cloned via the clone() method.
Usage:
local emph = pandoc.Emph {pandoc.Str 'important'}
local cloned_emph = emph:clone() -- note the colon
Pandoc document
Values of this type can be created with the pandoc.Pandoc constructor. Pandoc values are equal in Lua if and only if they are equal in Haskell.
walk(self, lua_filter)
Applies a Lua filter to the Pandoc element. Just as for full-document filters, the order in which elements are traversed can be controlled by setting the traverse field of the filter; see the section on traversal order.
Parameters:
selflua_filterResult:
Usage:
-- returns `pandoc.Pandoc{pandoc.Para{pandoc.Str 'Bye'}}`
return pandoc.Pandoc{pandoc.Para('Hi')}:walk {
Str = function (_) return 'Bye' end,
}
Meta information on a document; string-indexed collection of MetaValues.
Values of this type can be created with the pandoc.Meta constructor. Meta values are equal in Lua if and only if they are equal in Haskell.
Document meta information items. This is not a separate type, but describes a set of types that can be used in places were a MetaValue is expected. The types correspond to the following Haskell type constructors:
The corresponding constructors pandoc.MetaBool, pandoc.MetaString, pandoc.MetaInlines, pandoc.MetaBlocks, pandoc.MetaList, and pandoc.MetaMap can be used to ensure that a value is treated in the intended way. E.g., an empty table is normally treated as a MetaMap, but can be made into an empty MetaList by calling pandoc.MetaList{}. However, the same can be accomplished by using the generic functions like pandoc.List, pandoc.Inlines, or pandoc.Blocks.
Use the function pandoc.utils.type to get the type of a metadata value.
Block values are equal in Lua if and only if they are equal in Haskell.
walk(self, lua_filter)
Applies a Lua filter to the block element. Just as for full-document filters, the order in which elements are traversed can be controlled by setting the traverse field of the filter; see the section on traversal order.
Note that the filter is applied to the subtree, but not to the self block element. The rationale is that otherwise the element could be deleted by the filter, or replaced with multiple block elements, which might lead to possibly unexpected results.
Parameters:
selflua_filterResult:
Usage:
-- returns `pandoc.Para{pandoc.Str 'Bye'}`
return pandoc.Para('Hi'):walk {
Str = function (_) return 'Bye' end,
}
A block quote element.
Values of this type can be created with the pandoc.BlockQuote constructor.
Fields:
contenttag, tBlockQuote (string)
A bullet list.
Values of this type can be created with the pandoc.BulletList constructor.
Fields:
Block of code.
Values of this type can be created with the pandoc.CodeBlock constructor.
Fields:
textattridentifierattr.identifier (string)
classesattr.classes (List of strings)
attributesattr.attributes (Attributes)
tag, tCodeBlock (string)
Definition list, containing terms and their explanation.
Values of this type can be created with the pandoc.DefinitionList constructor.
Fields:
contenttag, tDefinitionList (string)
Generic block container with attributes.
Values of this type can be created with the pandoc.Div constructor.
Fields:
contentattridentifierattr.identifier (string)
classesattr.classes (List of strings)
attributesattr.attributes (Attributes)
tag, tDiv (string)
Creates a header element.
Values of this type can be created with the pandoc.Header constructor.
Fields:
levelcontentattridentifierattr.identifier (string)
classesattr.classes (List of strings)
attributesattr.attributes (Attributes)
tag, tHeader (string)
A horizontal rule.
Values of this type can be created with the pandoc.HorizontalRule constructor.
Fields:
tag, tHorizontalRule (string)
A line block, i.e. a list of lines, each separated from the next by a newline.
Values of this type can be created with the pandoc.LineBlock constructor.
Fields:
A null element; this element never produces any output in the target format.
Values of this type can be created with the pandoc.Null constructor.
tag, tNull (string)
An ordered list.
Values of this type can be created with the pandoc.OrderedList constructor.
Fields:
contentlistAttributesstartlistAttributes.start (integer)
stylelistAttributes.style (string)
delimiterlistAttributes.delimiter (string)
tag, tOrderedList (string)
A paragraph.
Values of this type can be created with the pandoc.Para constructor.
Fields:
contenttag, tPara (string)
Plain text, not a paragraph.
Values of this type can be created with the pandoc.Plain constructor.
Fields:
contenttag, tPlain (string)
Raw content of a specified format.
Values of this type can be created with the pandoc.RawBlock constructor.
Fields:
formattexttag, tRawBlock (string)
A table.
Values of this type can be created with the pandoc.Table constructor.
Fields:
attrcaptioncolspecsheadbodiesfootidentifierattr.identifier (string)
classesattr.classes (List of strings)
attributesattr.attributes (Attributes)
tag, tTable (string)
A table cell is a list of blocks.
Alignment is a string value indicating the horizontal alignment of a table column. AlignLeft, AlignRight, and AlignCenter leads cell content to be left-aligned, right-aligned, and centered, respectively. The default alignment is AlignDefault (often equivalent to centered).
List of Block elements, with the same methods as a generic List. It is usually not necessary to create values of this type in user scripts, as pandoc can convert other types into Blocks wherever a value of this type is expected:
Lists of type Blocks share all methods available in generic lists, see the pandoc.List module.
Additionally, the following methods are available on Blocks values:
walk(self, lua_filter)
Applies a Lua filter to the Blocks list. Just as for full-document filters, the order in which elements are traversed can be controlled by setting the traverse field of the filter; see the section on traversal order.
Parameters:
selflua_filterResult:
Usage:
-- returns `pandoc.Blocks{pandoc.Para('Salve!')}`
return pandoc.Blocks{pandoc.Plain('Salve!)}:walk {
Plain = function (p) return pandoc.Para(p.content) end,
}
Inline values are equal in Lua if and only if they are equal in Haskell.
walk(self, lua_filter)
Applies a Lua filter to the Inline element. Just as for full-document filters, the order in which elements are traversed can be controlled by setting the traverse field of the filter; see the section on traversal order.
Note that the filter is applied to the subtree, but not to the self inline element. The rationale is that otherwise the element could be deleted by the filter, or replaced with multiple inline elements, which might lead to possibly unexpected results.
Parameters:
selflua_filterResult:
Usage:
-- returns `pandoc.SmallCaps('SPQR)`
return pandoc.SmallCaps('spqr'):walk {
Str = function (s) return string.upper(s.text) end,
}
Citation.
Values of this type can be created with the pandoc.Cite constructor.
Fields:
Inline code
Values of this type can be created with the pandoc.Code constructor.
Fields:
textattridentifierattr.identifier (string)
classesattr.classes (List of strings)
attributesattr.attributes (Attributes)
tag, tCode (string)
Emphasized text
Values of this type can be created with the pandoc.Emph constructor.
Fields:
contenttag, tEmph (string)
Image: alt text (list of inlines), target
Values of this type can be created with the pandoc.Image constructor.
Fields:
captionsrctitleattridentifierattr.identifier (string)
classesattr.classes (List of strings)
attributesattr.attributes (Attributes)
tag, tImage (string)
Hard line break
Values of this type can be created with the pandoc.LineBreak constructor.
Fields:
tag, tLineBreak (string)
Hyperlink: alt text (list of inlines), target
Values of this type can be created with the pandoc.Link constructor.
Fields:
attrcontenttargettitleidentifierattr.identifier (string)
classesattr.classes (List of strings)
attributesattr.attributes (Attributes)
tag, tLink (string)
TeX math (literal)
Values of this type can be created with the pandoc.Math constructor.
Fields:
mathtypeInlineMath) or on a separate line (DisplayMath) (string)
texttag, tMath (string)
Footnote or endnote
Values of this type can be created with the pandoc.Note constructor.
Fields:
contenttag, tNote (string)
Quoted text
Values of this type can be created with the pandoc.Quoted constructor.
Fields:
quotetypeSingleQuote or DoubleQuote (string)
contenttag, tQuoted (string)
Raw inline
Values of this type can be created with the pandoc.RawInline constructor.
Fields:
formattexttag, tRawInline (string)
Small caps text
Values of this type can be created with the pandoc.SmallCaps constructor.
Fields:
contenttag, tSmallCaps (string)
Soft line break
Values of this type can be created with the pandoc.SoftBreak constructor.
Fields:
tag, tSoftBreak (string)
Inter-word space
Values of this type can be created with the pandoc.Space constructor.
Fields:
tag, tSpace (string)
Generic inline container with attributes
Values of this type can be created with the pandoc.Span constructor.
Fields:
attrcontentidentifierattr.identifier (string)
classesattr.classes (List of strings)
attributesattr.attributes (Attributes)
tag, tSpan (string)
Text
Values of this type can be created with the pandoc.Str constructor.
Fields:
texttag, tStr (string)
Strikeout text
Values of this type can be created with the pandoc.Strikeout constructor.
Fields:
contenttag, tStrikeout (string)
Strongly emphasized text
Values of this type can be created with the pandoc.Strong constructor.
Fields:
contenttag, tStrong (string)
Subscripted text
Values of this type can be created with the pandoc.Subscript constructor.
Fields:
contenttag, tSubscript (string)
Superscripted text
Values of this type can be created with the pandoc.Superscript constructor.
Fields:
contenttag, tSuperscript (string)
Underlined text
Values of this type can be created with the pandoc.Underline constructor.
Fields:
contenttag, tUnderline (string)
List of Inline elements, with the same methods as a generic List. It is usually not necessary to create values of this type in user scripts, as pandoc can convert other types into Blocks wherever a value of this type is expected:
Lists of type Inlines share all methods available in generic lists, see the pandoc.List module.
Additionally, the following methods are available on Inlines values:
walk(self, lua_filter)
Applies a Lua filter to the Inlines list. Just as for full-document filters, the order in which elements are handled are are Inline → Inlines → Block → Blocks. The filter is applied to all list items and to the list itself.
Parameters:
selflua_filterResult:
Usage:
-- returns `pandoc.Inlines{pandoc.SmallCaps('SPQR')}`
return pandoc.Inlines{pandoc.Emph('spqr')}:walk {
Str = function (s) return string.upper(s.text) end,
Emph = function (e) return pandoc.SmallCaps(e.content) end,
}
A set of element attributes. Values of this type can be created with the pandoc.Attr constructor. For convenience, it is usually not necessary to construct the value directly if it is part of an element, and it is sufficient to pass an HTML-like table. E.g., to create a span with identifier “text” and classes “a” and “b”, one can write:
local span = pandoc.Span('text', {id = 'text', class = 'a b'})
This also works when using the attr setter:
local span = pandoc.Span 'text'
span.attr = {id = 'text', class = 'a b', other_attribute = '1'}
Attr values are equal in Lua if and only if they are equal in Haskell.
Fields:
identifierclassesattributesList of key/value pairs. Values can be accessed by using keys as indices to the list table.
Attributes values are equal in Lua if and only if they are equal in Haskell.
The caption of a table, with an optional short caption.
Fields:
A table cell.
Fields:
attralignmentcontentscol_spanrow_spanidentifierattr.identifier (string)
classesattr.classes (List of strings)
attributesattr.attributes (Attributes)
Single citation entry
Values of this type can be created with the pandoc.Citation constructor.
Citation values are equal in Lua if and only if they are equal in Haskell.
Fields:
Column alignment and width specification for a single table column.
This is a pair, i.e., a plain table, with the following components:
List attributes
Values of this type can be created with the pandoc.ListAttributes constructor.
Fields:
startstyleDefaultStyle, Example, Decimal, LowerRoman, UpperRoman, LowerAlpha, and UpperAlpha (string)
delimiterDefaultDelim, Period, OneParen, and TwoParens (string)
A table row.
Fields:
A body of a table, with an intermediate head and the specified number of row header columns.
Fields:
The foot of a table.
Fields:
attrrowsidentifierattr.identifier (string)
classesattr.classes (List of strings)
attributesattr.attributes (Attributes)
The head of a table.
Fields:
attrrowsidentifierattr.identifier (string)
classesattr.classes (List of strings)
attributesattr.attributes (Attributes)
Pandoc reader options
Fields:
abbreviationscolumnsdefault_image_extensionextensionsindented_code_classesstandalonestrip_commentstab_stoptrack_changesaccept-changes, reject-changes, and all-changes (string)
Pandoc writer options
Fields:
cite_methodcolumnsdpiemail_obfuscationepub_chapter_levelepub_fontsepub_metadataepub_subdirectoryextensionshighlight_stylepandoc --print-highlight-style=... for an example structure. The value nil means that no highlighting is used. (table|nil)
html_math_methodmethod and url. (string|table)
html_q_tags<q> tags for quotes in HTML (boolean)
identifier_prefixincrementallistingsnumber_offsetnumber_sectionsprefer_asciireference_docreference_linksreference_locationsection_divssetext_headersslide_leveltab_stoptable_of_contentstemplatetoc_depthtop_level_divisiontop-level may be omitted when setting this value. (string)
variableswrap_textwrap- prefix may be omitted when setting this value. (string)
The state used by pandoc to collect information and make it available to readers and writers.
Fields:
input_filesoutput_filelogrequest_headersresource_pathsource_urluser_data_dirtraceverbosityINFO, WARNING, ERROR (string)
Reflowable plain-text document. A Doc value can be rendered and reflown to fit a given column width.
The pandoc.layout module can be used to create and modify Doc values. All functions in that module that take a Doc value as their first argument are also available as Doc methods. E.g., (pandoc.layout.literal 'text'):render().
If a string is passed to a function expecting a Doc, then the string is treated as a literal value. I.e., the following two lines are equivalent:
A list is any Lua table with integer indices. Indices start at one, so if alist = {'value'} then alist[1] == 'value'.
Lists, when part of an element, or when generated during marshaling, are made instances of the pandoc.List type for convenience. The pandoc.List type is defined in the pandoc.List module. See there for available methods.
Values of this type can be created with the pandoc.List constructor, turning a normal Lua table into a List.
A pandoc log message. Objects have no fields, but can be converted to a string via tostring.
A simple table is a table structure which resembles the old (pre pandoc 2.10) Table type. Bi-directional conversion from and to Tables is possible with the pandoc.utils.to_simple_table and pandoc.utils.from_simple_table function, respectively. Instances of this type can also be created directly with the pandoc.SimpleTable constructor.
Fields:
Opaque type holding a compiled template.
A version object. This represents a software version like “2.7.3”. The object behaves like a numerically indexed table, i.e., if version represents the version 2.7.3, then
version[1] == 2
version[2] == 7
version[3] == 3
#version == 3 -- length
Comparisons are performed element-wise, i.e.
Version '1.12' > Version '1.9'
Values of this type can be created with the pandoc.types.Version constructor.
must_be_at_leastmust_be_at_least(actual, expected [, error_message])
Raise an error message if the actual version is older than the expected version; does nothing if actual is equal to or newer than the expected version.
Parameters:
actualexpectederror_message"expected version %s or newer, got %s".
Usage:
PANDOC_VERSION:must_be_at_least '2.7.3'
PANDOC_API_VERSION:must_be_at_least(
'1.17.4',
'pandoc-types is too old: expected version %s, got %s'
)
UTF-8 aware text manipulation functions, implemented in Haskell. The module is made available as part of the pandoc module via pandoc.text. The text module can also be loaded explicitly:
-- uppercase all regular text in a document:
text = require 'text'
function Str (s)
s.text = text.upper(s.text)
return s
endlower (s)
Returns a copy of a UTF-8 string, converted to lowercase.
upper (s)
Returns a copy of a UTF-8 string, converted to uppercase.
reverse (s)
Returns a copy of a UTF-8 string, with characters reversed.
len (s)
Returns the length of a UTF-8 string.
sub (s)
Returns a substring of a UTF-8 string, using Lua’s string indexing rules.
Lua functions for pandoc scripts; includes constructors for document tree elements, functions to parse text in a given format, and functions to filter and modify a subtree.
Pandoc (blocks[, meta])A complete pandoc document
Parameters:
blocksmetaReturns: Pandoc object
Meta (table)Create a new Meta object.
Parameters:
tableReturns: Meta object
MetaBlocks (blocks)Creates a value to be used as a MetaBlocks value in meta data; creates a copy of the input list via pandoc.Blocks, discarding all non-list keys.
Parameters:
blocksReturns: Blocks
MetaInlines (inlines)Creates a value to be used as a MetaInlines value in meta data; creates a copy of the input list via pandoc.Inlines, discarding all non-list keys.
Parameters:
inlinesReturns: Inlines
MetaList (meta_values)Creates a value to be used as a MetaList in meta data; creates a copy of the input list via pandoc.List, discarding all non-list keys.
Parameters:
meta_valuesReturns: List
MetaMap (key_value_map)Creates a value to be used as a MetaMap in meta data; creates a copy of the input table, keeping only pairs with string keys and discards all other keys.
Parameters:
key_value_mapReturns: table
MetaString (str)Creates a value to be used as a MetaString in meta data; this is the identity function for boolean values and exists only for completeness.
Parameters:
strReturns: string
MetaBool (bool)Creates a value to be used as MetaBool in meta data; this is the identity function for boolean values and exists only for completeness.
Parameters:
boolReturns: boolean
BlockQuote (content)Creates a block quote element
Parameters:
contentReturns: BlockQuote object
BulletList (items)Creates a bullet list.
Parameters:
itemsReturns: BulletList object
CodeBlock (text[, attr])Creates a code block element
Parameters:
textattrReturns: CodeBlock object
DefinitionList (content)Creates a definition list, containing terms and their explanation.
Parameters:
contentReturns: DefinitionList object
Div (content[, attr])Creates a div element
Parameters:
contentattrReturns: Div object
Header (level, content[, attr])Creates a header element.
Parameters:
levelcontentattrReturns: Header object
HorizontalRule ()Creates a horizontal rule.
Returns: HorizontalRule object
LineBlock (content)Creates a line block element.
Parameters:
contentReturns: LineBlock object
Null ()Creates a null element.
Returns: Null object
OrderedList (items[, listAttributes])Creates an ordered list.
Parameters:
itemslistAttributesReturns: OrderedList object
Para (content)Creates a para element.
Parameters:
contentReturns: Para object
Plain (content)Creates a plain element.
Parameters:
contentReturns: Plain object
RawBlock (format, text)Creates a raw content block of the specified format.
Parameters:
formattextReturns: RawBlock object
Table (caption, colspecs, head, bodies, foot[, attr])Creates a table element.
Parameters:
captioncolspecsheadbodiesfootattrReturns: Table object
Blocks (block_like_elements)Creates a Blocks list.
Parameters:
block_like_elementsReturns: Blocks
Cite (content, citations)Creates a Cite inline element
Parameters:
contentcitationsReturns: Cite object
Code (text[, attr])Creates a Code inline element
Parameters:
textattrReturns: Code object
Emph (content)Creates an inline element representing emphasized text.
Parameters:
contentReturns: Emph object
Image (caption, src[, title[, attr]])Creates a Image inline element
Parameters:
captionsrctitleattrReturns: Image object
LineBreak ()Create a LineBreak inline element
Returns: LineBreak object
Link (content, target[, title[, attr]])Creates a link inline element, usually a hyperlink.
Parameters:
contenttargettitleattrReturns: Link object
Math (mathtype, text)Creates a Math element, either inline or displayed.
Parameters:
mathtypetextReturns: Math object
DisplayMath (text)Creates a math element of type “DisplayMath” (DEPRECATED).
Parameters:
textReturns: Math object
InlineMath (text)Creates a math element of type “InlineMath” (DEPRECATED).
Parameters:
textReturns: Math object
Note (content)Creates a Note inline element
Parameters:
contentReturns: Note object
Quoted (quotetype, content)Creates a Quoted inline element given the quote type and quoted content.
Parameters:
quotetypecontentReturns: Quoted object
SingleQuoted (content)Creates a single-quoted inline element (DEPRECATED).
Parameters:
contentReturns: Quoted
DoubleQuoted (content)Creates a single-quoted inline element (DEPRECATED).
Parameters:
contentReturns: Quoted
RawInline (format, text)Creates a raw inline element
Parameters:
formattextReturns: RawInline object
SmallCaps (content)Creates text rendered in small caps
Parameters:
contentReturns: SmallCaps object
SoftBreak ()Creates a SoftBreak inline element.
Returns: SoftBreak object
Space ()Create a Space inline element
Returns: Space object
Span (content[, attr])Creates a Span inline element
Parameters:
contentattrReturns: Span object
Str (text)Creates a Str inline element
Parameters:
textReturns: Str object
Strikeout (content)Creates text which is struck out.
Parameters:
contentReturns: Strikeout object
Strong (content)Creates a Strong element, whose text is usually displayed in a bold font.
Parameters:
contentReturns: Strong object
Subscript (content)Creates a Subscript inline element
Parameters:
contentReturns: Subscript object
Superscript (content)Creates a Superscript inline element
Parameters:
contentReturns: Superscript object
Underline (content)Creates an Underline inline element
Parameters:
contentReturns: Underline object
Inlines (inline_like_elements)Converts its argument into an Inlines list:
s within the list is treated as pandoc.Str(s);Str-wrapped words, treating interword spaces as Spaces or SoftBreaks.Parameters:
inline_like_elementsReturns: Inlines list
Attr ([identifier[, classes[, attributes]]])Create a new set of attributes (Attr).
Parameters:
identifierclassesattributesReturns: Attr object
Cell (blocks[, align[, rowspan[, colspan[, attr]]]])Create a new table cell.
Parameters:
blocksalignAlignDefault (Alignment)
rowspan1 (integer)
colspan1 (integer)
attrReturns:
Citation (id, mode[, prefix[, suffix[, note_num[, hash]]]])Creates a single citation.
Parameters:
idmodeprefixsuffixnote_numhashReturns: Citation object
ListAttributes ([start[, style[, delimiter]]])Creates a set of list attributes.
Parameters:
startstyledelimiterReturns: ListAttributes object
Row ([cells[, attr]])Creates a table row.
Parameters:
cellsattrTableFoot ([rows[, attr]])Creates a table foot.
Parameters:
rowsattrTableHead ([rows[, attr]])Creates a table head.
Parameters:
rowsattrSimpleTable (caption, aligns, widths, headers, rows)Creates a simple table resembling the old (pre pandoc 2.10) table type.
Parameters:
captionalignswidthsheadersrowsReturns: SimpleTable object
Usage:
local caption = "Overview"
local aligns = {pandoc.AlignDefault, pandoc.AlignDefault}
local widths = {0, 0} -- let pandoc determine col widths
local headers = {{pandoc.Plain({pandoc.Str "Language"})},
{pandoc.Plain({pandoc.Str "Typing"})}}
local rows = {
{{pandoc.Plain "Haskell"}, {pandoc.Plain "static"}},
{{pandoc.Plain "Lua"}, {pandoc.Plain "Dynamic"}},
}
simple_table = pandoc.SimpleTable(
caption,
aligns,
widths,
headers,
rows
)
AuthorInTextAuthor name is mentioned in the text.
See also: Citation
SuppressAuthorAuthor name is suppressed.
See also: Citation
NormalCitationDefault citation style is used.
See also: Citation
AlignLeftTable cells aligned left.
See also: Table
AlignRightTable cells right-aligned.
See also: Table
AlignCenterTable cell content is centered.
See also: Table
AlignDefaultTable cells are alignment is unaltered.
See also: Table
DefaultDelimDefault list number delimiters are used.
See also: ListAttributes
PeriodList numbers are delimited by a period.
See also: ListAttributes
OneParenList numbers are delimited by a single parenthesis.
See also: ListAttributes
TwoParensList numbers are delimited by a double parentheses.
See also: ListAttributes
DefaultStyleList are numbered in the default style
See also: ListAttributes
ExampleList items are numbered as examples.
See also: ListAttributes
DecimalList are numbered using decimal integers.
See also: ListAttributes
LowerRomanList are numbered using lower-case roman numerals.
See also: ListAttributes
UpperRomanList are numbered using upper-case roman numerals
See also: ListAttributes
LowerAlphaList are numbered using lower-case alphabetic characters.
See also: ListAttributes
UpperAlphaList are numbered using upper-case alphabetic characters.
See also: ListAttributes
sha1Alias for pandoc.utils.sha1 (DEPRECATED, use pandoc.utils.sha1 instead).
ReaderOptions (opts)Creates a new ReaderOptions value.
Parameters
optsReturns: new ReaderOptions object
Usage:
-- copy of the reader options that were defined on the command line.
local cli_opts = pandoc.ReaderOptions(PANDOC_READER_OPTIONS)
-- default reader options, but columns set to 66.
local short_colums_opts = pandoc.ReaderOptions {columns = 66}
WriterOptions (opts)Creates a new WriterOptions value.
Parameters
optsReturns: new WriterOptions object
Usage:
-- copy of the writer options that were defined on the command line.
local cli_opts = pandoc.WriterOptions(PANDOC_WRITER_OPTIONS)
-- default writer options, but DPI set to 300.
local short_colums_opts = pandoc.WriterOptions {dpi = 300}
pipe (command, args, input)Runs command with arguments, passing it some input, and returns the output.
Parameters:
commandargsinputReturns:
Raises:
command, error_code, and output is thrown if the command exits with a non-zero error code.Usage:
local output = pandoc.pipe("sed", {"-e","s/a/b/"}, "abc")
walk_block (element, filter)Apply a filter inside a block element, walking its contents.
Parameters:
elementfilterReturns: the transformed block element
walk_inline (element, filter)Apply a filter inside an inline element, walking its contents.
Parameters:
elementfilterReturns: the transformed inline element
read (markup[, format[, reader_options]])Parse the given string into a Pandoc document.
The parser is run in the same environment that was used to read the main input files; it has full access to the file-system and the mediabag. This means that if the document specifies files to be included, as is possible in formats like LaTeX, reStructuredText, and Org, then these will be included in the resulting document. Any media elements are added to those retrieved from the other parsed input files.
Parameters:
markupformat"markdown" (string)
reader_optionsReturns: pandoc document (Pandoc)
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")
write (doc[, format[, writer_options]])Converts a document to the given target format.
Parameters:
docformat'html' (string)
writer_optionsReturns:
Usage:
local doc = pandoc.Pandoc(
{pandoc.Para {pandoc.Strong 'Tea'}}
)
local html = pandoc.write(doc, 'html')
assert(html == "<p><strong>Tea</strong></p>")
This module exposes internal pandoc functions and utility functions.
The module is loaded as part of the pandoc module and available as pandoc.utils. In versions up-to and including pandoc 2.6, this module had to be loaded explicitly. Example:
pandoc.utils = require 'pandoc.utils'
Use the above for backwards compatibility.
blocks_to_inlines (blocks[, sep])Squash a list of blocks into a list of inlines.
Parameters:
blockssep{ pandoc.Space(), pandoc.Str'¶', pandoc.Space()}.
Returns:
Usage:
local blocks = {
pandoc.Para{ pandoc.Str 'Paragraph1' },
pandoc.Para{ pandoc.Emph 'Paragraph2' }
}
local inlines = pandoc.utils.blocks_to_inlines(blocks)
-- inlines = {
-- pandoc.Str 'Paragraph1',
-- pandoc.Space(), pandoc.Str'¶', pandoc.Space(),
-- pandoc.Emph{ pandoc.Str 'Paragraph2' }
-- }
equals (element1, element2)Test equality of AST elements. Elements in Lua are considered equal if and only if the objects obtained by unmarshaling are equal.
This function is deprecated. Use the normal Lua == equality operator instead.
Parameters:
element1, element2Returns:
from_simple_table (table)Creates a Table block element from a SimpleTable. This is useful for dealing with legacy code which was written for pandoc versions older than 2.10.
Returns:
Usage:
local simple = pandoc.SimpleTable(table)
-- modify, using pre pandoc 2.10 methods
simple.caption = pandoc.SmallCaps(simple.caption)
-- create normal table block again
table = pandoc.utils.from_simple_table(simple)
make_sections (number_sections, base_level, blocks)Converts list of Block elements into sections. Divs will be created beginning at each Header and containing following content until the next Header of comparable level. If number_sections is true, a number attribute will be added to each Header containing the section number. If base_level is non-null, Header levels will be reorganized so that there are no gaps, and so that the base level is the level specified.
Parameters:
number_sectionsnumber attribute containing the section number. (boolean)
base_levelblocksReturns:
Usage:
local blocks = {
pandoc.Header(2, pandoc.Str 'first'),
pandoc.Header(2, pandoc.Str 'second'),
}
local newblocks = pandoc.utils.make_sections(true, 1, blocks)
references (doc)
Get references defined inline in the metadata and via an external bibliography. Only references that are actually cited in the document (either with a genuine citation or with nocite) are returned. URL variables are converted to links.
The structure used represent reference values corresponds to that used in CSL JSON; the return value can be use as references metadata, which is one of the values used by pandoc and citeproc when generating bibliographies.
Parameters:
docReturns:
Usage:
-- Include all cited references in document
function Pandoc (doc)
doc.meta.references = pandoc.utils.references(doc)
doc.meta.bibliography = nil
return doc
end
run_json_filter (doc, filter[, args])
Filter the given doc by passing it through the a JSON filter.
Parameters:
docfilterargs{FORMAT}.
Returns:
Usage:
-- Assumes `some_blocks` contains blocks for which a
-- separate literature section is required.
local sub_doc = pandoc.Pandoc(some_blocks, metadata)
sub_doc_with_bib = pandoc.utils.run_json_filter(
sub_doc,
'pandoc-citeproc'
)
some_blocks = sub_doc.blocks -- some blocks with bib
normalize_date (date_string)
Parse a date and convert (if possible) to “YYYY-MM-DD” format. We limit years to the range 1601-9999 (ISO 8601 accepts greater than or equal to 1583, but MS Word only accepts dates starting 1601).
Returns:
sha1 (contents)
Returns the SHA1 has of the contents.
Returns:
Usage:
local fp = pandoc.utils.sha1("foobar")
stringify (element)
Converts the given element (Pandoc, Meta, Block, or Inline) into a string with all formatting removed.
Returns:
Usage:
local inline = pandoc.Emph{pandoc.Str 'Moin'}
-- outputs "Moin"
print(pandoc.utils.stringify(inline))
to_roman_numeral (integer)
Converts an integer < 4000 to uppercase roman numeral.
Returns:
Usage:
local to_roman_numeral = pandoc.utils.to_roman_numeral
local pandoc_birth_year = to_roman_numeral(2006)
-- pandoc_birth_year == 'MMVI'
to_simple_table (table)
Creates a SimpleTable out of a Table block.
Returns:
Usage:
local simple = pandoc.utils.to_simple_table(table)
-- modify, using pre pandoc 2.10 methods
simple.caption = pandoc.SmallCaps(simple.caption)
-- create normal table block again
table = pandoc.utils.from_simple_table(simple)
type (value)
Pandoc-friendly version of Lua’s default type function, returning the type of a value. This function works with all types listed in section Lua type reference, except if noted otherwise.
The function works by checking the metafield __name. If the argument has a string-valued metafield __name, then it returns that string. Otherwise it behaves just like the normal type function.
Parameters:
valueReturns:
Usage:
-- Prints one of 'string', 'boolean', 'Inlines', 'Blocks',
-- 'table', and 'nil', corresponding to the Haskell constructors
-- MetaString, MetaBool, MetaInlines, MetaBlocks, MetaMap,
-- and an unset value, respectively.
function Meta (meta)
print('type of metavalue `author`:', pandoc.utils.type(meta.author))
end
The pandoc.mediabag module allows accessing pandoc’s media storage. The “media bag” is used when pandoc is called with the --extract-media or (for HTML only) --self-contained option.
The module is loaded as part of module pandoc and can either be accessed via the pandoc.mediabag field, or explicitly required, e.g.:
local mb = require 'pandoc.mediabag'
delete (filepath)
Removes a single entry from the media bag.
Parameters:
filepathempty ()
Clear-out the media bag, deleting all items.
insert (filepath, mime_type, contents)
Adds a new entry to pandoc’s media bag. Replaces any existing mediabag entry with the same filepath.
Parameters:
filepathmime_typenil if unknown or unavailable.
contentsUsage:
local fp = "media/hello.txt"
local mt = "text/plain"
local contents = "Hello, World!"
pandoc.mediabag.insert(fp, mt, contents)
items ()
Returns an iterator triple to be used with Lua’s generic for statement. The iterator returns the filepath, MIME type, and content of a media bag item on each invocation. Items are processed one-by-one to avoid excessive memory use.
This function should be used only when full access to all items, including their contents, is required. For all other cases, list should be preferred.
Returns:
Usage:
for fp, mt, contents in pandoc.mediabag.items() do
-- print(fp, mt, contents)
end
list ()
Get a summary of the current media bag contents.
Returns: A list of elements summarizing each entry in the media bag. The summary item contains the keys path, type, and length, giving the filepath, MIME type, and length of contents in bytes, respectively.
Usage:
-- calculate the size of the media bag.
local mb_items = pandoc.mediabag.list()
local sum = 0
for i = 1, #mb_items do
sum = sum + mb_items[i].length
end
print(sum)
lookup (filepath)
Lookup a media item in the media bag, and return its MIME type and contents.
Parameters:
filepathReturns:
Usage:
local filename = "media/diagram.png"
local mt, contents = pandoc.mediabag.lookup(filename)
fetch (source)
Fetches the given source from a URL or local file. Returns two values: the contents of the file and the MIME type (or an empty string).
The function will first try to retrieve source from the mediabag; if that fails, it will try to download it or read it from the local file system while respecting pandoc’s “resource path” setting.
Parameters:
sourceReturns:
Usage:
local diagram_url = "https://pandoc.org/diagram.jpg"
local mt, contents = pandoc.mediabag.fetch(diagram_url)
This module defines pandoc’s list type. It comes with useful methods and convenience functions.
pandoc.List([table])Create a new List. If the optional argument table is given, set the metatable of that value to pandoc.List. This is an alias for pandoc.List:new([table]).
pandoc.List:__concat (list)Concatenates two lists.
Parameters:
listReturns: a new list containing all elements from list1 and list2
pandoc.List:__eq (a, b)Compares two lists for equality. The lists are taken as equal if and only if they are of the same type (i.e., have the same non-nil metatable), have the same length, and if all elements are equal.
Parameters:
a, bReturns:
true if the two lists are equal, false otherwise.pandoc.List:clone ()Returns a (shallow) copy of the list.
pandoc.List:extend (list)Adds the given list to the end of this list.
Parameters:
listpandoc.List:find (needle, init)Returns the value and index of the first occurrence of the given item.
Parameters:
needleinitReturns: first item equal to the needle, or nil if no such item exists.
pandoc.List:find_if (pred, init)Returns the value and index of the first element for which the predicate holds true.
Parameters:
predinitReturns: first item for which `test` succeeds, or nil if no such item exists.
pandoc.List:filter (pred)Returns a new list containing all items satisfying a given condition.
Parameters:
predReturns: a new list containing all items for which `test` was true.
pandoc.List:includes (needle, init)Checks if the list has an item equal to the given needle.
Parameters:
needleinitReturns: true if a list item is equal to the needle, false otherwise
pandoc.List:insert ([pos], value)Inserts element value at position pos in list, shifting elements to the next-greater index if necessary.
This function is identical to table.insert.
Parameters:
posvaluepandoc.List:map (fn)Returns a copy of the current list by applying the given function to all elements.
Parameters:
fnpandoc.List:new([table])Create a new List. If the optional argument table is given, set the metatable of that value to pandoc.List.
Parameters:
tableReturns: the updated input value
pandoc.List:remove ([pos])Removes the element at position pos, returning the value of the removed element.
This function is identical to table.remove.
Parameters:
posReturns: the removed element
pandoc.List:sort ([comp])Sorts list elements in a given order, in-place. If comp is given, then it must be a function that receives two list elements and returns true when the first element must come before the second in the final order (so that, after the sort, i < j implies not comp(list[j],list[i])). If comp is not given, then the standard Lua operator < is used instead.
Note that the comp function must define a strict partial order over the elements in the list; that is, it must be asymmetric and transitive. Otherwise, no valid sort may be possible.
The sort algorithm is not stable: elements considered equal by the given order may have their relative positions changed by the sort.
This function is identical to table.sort.
Parameters:
compModule for file path manipulations.
The character that separates directories.
The character that is used to separate the entries in the PATH environment variable.
Gets the directory name, i.e., removes the last directory separator and everything after from the given path.
Parameters:
filepathReturns:
Get the file name.
Parameters:
filepathReturns:
Checks whether a path is absolute, i.e. not fixed to a root.
Parameters:
filepathReturns:
true if filepath is an absolute path, false otherwise. (boolean)Checks whether a path is relative or fixed to a root.
Parameters:
filepathReturns:
true if filepath is a relative path, false otherwise. (boolean)Join path elements back together by the directory separator.
Parameters:
filepathsReturns:
Contract a filename, based on a relative path. Note that the resulting path will usually not introduce .. paths, as the presence of symlinks means ../b may not reach a/b if it starts from a/c. For a worked example see this blog post.
Set unsafe to a truthy value to a allow .. in paths.
Parameters:
pathrootunsafe.. in the result. (boolean)
Returns:
Normalizes a path.
// makes sense only as part of a (Windows) network drive; elsewhere, multiple slashes are reduced to a single path.separator (platform dependent)./ becomes path.separator (platform dependent)./ -> ’’.Parameters:
filepathReturns:
Splits a path by the directory separator.
Parameters:
filepathReturns:
Splits the last extension from a file path and returns the parts. The extension, if present, includes the leading separator; if the path has no extension, then the empty string is returned as the extension.
Parameters:
filepathReturns:
filepath without extension (string)
extension or empty string (string)
Takes a string and splits it on the search_path_separator character. Blank items are ignored on Windows, and converted to . on Posix. On Windows path elements are stripped of quotes.
Parameters:
search_pathReturns:
Access to system information and functionality.
The machine architecture on which the program is running.
The operating system on which the program is running.
environment ()
Retrieve the entire environment as a string-indexed table.
Returns:
get_working_directory ()
Obtain the current working directory as an absolute path.
Returns:
with_environment (environment, callback)
Run an action within a custom environment. Only the environment variables given by environment will be set, when callback is called. The original environment is restored after this function finishes, even if an error occurs while running the callback action.
Parameters:
environmentcallback. (table with string keys and string values)
callbackReturns:
callbackwith_temporary_directory ([parent_dir,] templ, callback)
Create and use a temporary directory inside the given directory. The directory is deleted after the callback returns.
Parameters:
parent_dirtemplcallbackReturns:
callback.with_working_directory (directory, callback)
Run an action within a different directory. This function will change the working directory to directory, execute callback, then switch back to the original working directory, even if an error occurs while running the callback action.
Parameters:
directorycallback should be executed (string)
callbackReturns:
callbackPlain-text document layouting.
Inserts a blank line unless one exists already.
A carriage return. Does nothing if we're at the beginning of a line; otherwise inserts a newline.
The empty document.
A breaking (reflowable) space.
after_break (text)
Creates a Doc which is conditionally included only if it comes at the beginning of a line.
An example where this is useful is for escaping line-initial . in roff man.
Parameters
textcontent to include when placed after a break (string)
Returns
before_non_blank (doc)
Conditionally includes the given doc unless it is followed by a blank space.
Parameters
docdocument (Doc)
Returns
blanklines (n)
Inserts blank lines unless they exist already.
Parameters
nnumber of blank lines (integer)
Returns
braces (doc)
Puts the doc in curly braces.
Parameters
docdocument (Doc)
Returns
brackets (doc)
Puts the doc in square brackets
Parameters
docdocument (Doc)
Returns
cblock (doc, width)
Creates a block with the given width and content, aligned centered.
Parameters
docdocument (Doc)
widthblock width in chars (integer)
Returns
width chars per line. (Doc)chomp (doc)
Chomps trailing blank space off of the doc.
Parameters
docdocument (Doc)
Returns
doc without trailing blanks (Doc)concat (docs[, sep])
Concatenates a list of Docs.
Parameters
docslist of Docs ({Doc,...})
sepseparator (default: none) (Doc)
Returns
double_quotes (doc)
Wraps a Doc in double quotes.
Parameters
docdocument (Doc)
Returns
doc enclosed by " chars (Doc)flush (doc)
Makes a Doc flush against the left margin.
Parameters
docdocument (Doc)
Returns
doc (Doc)hang (doc, ind, start)
Creates a hanging indent.
Parameters
Returns
doc prefixed by start on the first line, subsequent lines indented by ind spaces. (Doc)inside (contents, start, end)
Encloses a Doc inside a start and end Doc.
Parameters
Returns
lblock (doc, width)
Creates a block with the given width and content, aligned to the left.
Parameters
docdocument (Doc)
widthblock width in chars (integer)
Returns
width chars per line. (Doc)literal (text)
Creates a Doc from a string.
Parameters
textliteral value (string)
Returns
nest (doc, ind)
Indents a Doc by the specified number of spaces.
Parameters
docdocument (Doc)
indindentation size (integer)
Returns
doc indented by ind spaces (Doc)nestle (doc)
Removes leading blank lines from a Doc.
Parameters
docdocument (Doc)
Returns
doc with leading blanks removed (Doc)nowrap (doc)
Makes a Doc non-reflowable.
Parameters
docdocument (Doc)
Returns
parens (doc)
Puts the doc in parentheses.
Parameters
docdocument (Doc)
Returns
prefixed (doc, prefix)
Uses the specified string as a prefix for every line of the inside document (except the first, if not at the beginning of the line).
Parameters
docdocument (Doc)
prefixprefix for each line (string)
Returns
doc (Doc)quotes (doc)
Wraps a Doc in single quotes.
Parameters
docdocument (Doc)
Returns
'. (Doc)rblock (doc, width)
Creates a block with the given width and content, aligned to the right.
Parameters
docdocument (Doc)
widthblock width in chars (integer)
Returns
width chars per line. (Doc)vfill (border)
An expandable border that, when placed next to a box, expands to the height of the box. Strings cycle through the list provided.
Parameters
bordervertically expanded characters (string)
Returns
render (doc[, colwidth])
Render a @'Doc'@. The text is reflowed on breakable spacesto match the given line length. Text is not reflowed if theline length parameter is omitted or nil.
Parameters
docdocument (Doc)
colwidthplanned maximum line length (integer)
Returns
is_empty (doc)
Checks whether a doc is empty.
Parameters
docdocument (Doc)
Returns
true iff doc is the empty document, false otherwise. (boolean)height (doc)
Returns the height of a block or other Doc.
Parameters
docdocument (Doc)
Returns
min_offset (doc)
Returns the minimal width of a Doc when reflowed at breakable spaces.
Parameters
docdocument (Doc)
Returns
offset (doc)
Returns the width of a Doc as number of characters.
Parameters
docdocument (Doc)
Returns
real_length (str)
Returns the real length of a string in a monospace font: 0 for a combining chaeracter, 1 for a regular character, 2 for an East Asian wide character.
Parameters
strUTF-8 string to measure (string)
Returns
update_column (doc, i)
Returns the column that would be occupied by the last laid out character.
Parameters
docdocument (Doc)
istart column (integer)
Returns
Handle pandoc templates.
compile (template[, templates_path])
Compiles a template string into a Template object usable by pandoc.
If the templates_path parameter is specified, should be the file path associated with the template. It is used when checking for partials. Partials will be taken only from the default data files if this parameter is omitted.
An error is raised if compilation fails.
Parameters:
templatetemplates_pathReturns:
default ([writer])
Returns the default template for a given writer as a string. An error if no such template can be found.
Parameters:
writerFORMAT.
Returns:
Constructors for types which are not part of the pandoc AST.
Version (version_specifier)
Creates a Version object.
Parameters:
version_specifier'2.7.3', a list of integers like {2, 7, 3}, a single integer, or a Version.
Returns: