Pandoc Lua 过滤器
Pandoc Lua Filters

原始链接: https://pandoc.org/lua-filters.html

Pandoc 过滤器允许在解析阶段和写入阶段之间对文档的抽象语法树(AST)进行操作。传统的基于 JSON 的过滤器虽然可以使用任何语言编写,但由于数据序列化的开销,其性能损耗显著。 自 2.0 版本引入以来,**Lua 过滤器**已成为推荐方案。它们直接内置于 Pandoc 可执行文件中,消除了外部依赖,并避免了 JSON 管道传输的开销。Lua 过滤器通过定义与 AST 元素类型(如 `Strong`、`Para`)匹配的函数来工作,当 Pandoc 遍历文档时会调用这些函数。 主要特性包括: * **高效性:** 无需标准输入输出开销,可直接访问数据。 * **可控性:** 支持顺序遍历(自顶向下或按类型)、基于输出格式的条件逻辑(通过 `FORMAT` 变量),以及使用内置模块(如 `pandoc.text`、`pandoc.utils`)进行高级转换。 * **灵活性:** 过滤器可以修改、替换或删除元素。它们还可以访问元数据、执行文件系统操作,并通过 `mediabag` 处理参考文献或图像转换等复杂任务。 Lua 过滤器通过 `--lua-filter` 命令行参数调用,使其成为自定义 Pandoc 文档转换功能强大、便携且高效的工具。

抱歉。
相关文章

原文

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.4) 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:

walk method was made available, this was the only way to run multiple filters from one Lua file. However, returning a list of filters is now discouraged in favor of using the walk method, and this functionality may be removed at some point.

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:

  • nil: this means that the object should remain unchanged.
  • a pandoc object: this must be of the same type as the input and will replace the original object.
  • a list of pandoc objects: these will replace the original object; the list is merged with the neighbors of the original objects (spliced into the list the original object belongs to); returning an empty list deletes the object.

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.

Para (paragraph) block, or the description of an Image. The inlines argument passed to the function will be a List of Inline elements for each call.
Blocks (blocks)
If present in a filter, this function will be called on all lists of block elements, like the content of a MetaBlocks meta element block, on each item of a list, and the main content of the Pandoc document. The 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.

  1. Inline elements,
  2. the Inlines filter function,
  3. functions for Block elements ,
  4. the Blocks filter function,
  5. the Meta filter function, and last
  6. the Pandoc filter function.

It is still possible to force a different order by manually running the filters using the walk method. For example, if the filter for Meta is to be run before that for Str, one can write

ReaderOptions)
PANDOC_WRITER_OPTIONS
Table 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) Accessing this variable in custom writers is deprecated. Starting with pandoc 3.0, it is set to a placeholder value (the default options) in custom writers. Access to the actual writer options is provided via the Writer or ByteStringWriter function, to which the options are passed as the second function argument. Since: pandoc 2.17
PANDOC_VERSION
Contains the pandoc version as a Version object which behaves like a numerically indexed table, most significant number first. E.g., for pandoc 2.7.3, the value of the variable is equivalent to a table {2, 7, 3}. Use tostring(PANDOC_VERSION) to produce a version string. This variable is also set in custom writers.
PANDOC_API_VERSION
Contains the version of the pandoc-types API against which pandoc was compiled. It is given as a numerically indexed table, most significant number first. E.g., if pandoc was compiled against pandoc-types 1.17.3, then the value of the variable will behave like the table {1, 17, 3}. Use tostring(PANDOC_API_VERSION) to produce a version string. This variable is also set in custom writers.
PANDOC_SCRIPT_FILE
The name used to involve the filter. This value can be used to find files relative to the script file. This variable is also set in custom writers.
PANDOC_STATE
The state shared by all readers and writers. It is used by pandoc to collect and pass information. The value of this variable is of type CommonState and is read-only.
pandoc
The pandoc module, described in the next section, is available through the global pandoc. The other modules described herein are loaded as subfields under their respective name.
lpeg
This 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.
re
Contains 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.

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.

  • 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;
  • the pandoc.mediabag module allows access to the “mediabag,” which stores binary content such as images that may be included in the final document;
  • the 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_.

luacheck may be used for this purpose. A Luacheck configuration file for pandoc filters is available at https://github.com/rnwst/pandoc-luacheckrc.

William Lupton has written a Lua module with some handy functions for debugging Lua filters, including functions that can pretty-print the Pandoc AST elements manipulated by the filters: it is available at https://github.com/wlupton/pandoc-lua-logging.

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 Studio. ZeroBrane offers a REPL console and UI to step-through and view all variables and state.

ZeroBrane doesn’t come with Lua 5.4 bundled, but it can debug it, so you should install Lua 5.4, and then add mobdebug and its dependency luasocket using luarocks. ZeroBrane can use your Lua 5.4 install by adding path.lua = "/path/to/your/lua" in your ZeroBrane settings file. Next, open your Lua filter in ZeroBrane, and add require('mobdebug').start() at the line where you want your breakpoint. Then make sure the Project > Lua Interpreter is set to the “Lua” you added in settings and enable “Start Debugger Server” see detailed instructions here. Run Pandoc as you normally would, and ZeroBrane should break at the correct line.

pandoc.text module for Unicode-aware transformation, and consider using using the lpeg or re library for pattern matching.

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.

walk to transform inline elements inside headers), removes footnotes, and replaces links with regular text.

pandoc.Table constructor.

This is my table caption.
This is my table header
Cell 1 Cell 2 Cell 3
Cell 4 Cell 5 Cell 6
This is my table footer.

Note that:

  • The number of columns in the resulting Table element is equal to the number of entries in the colspecs parameter.

  • A ColSpec object must contain the cell alignment, but the column width is optional.

  • A TableBody object is specified using a Lua table in the bodies parameter because there is no pandoc.TableBody constructor.

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 --embed-resources.

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.)

pandoc module for functions to create these objects.

pandoc.Pandoc constructor. Pandoc values are equal in Lua if and only if they are equal in Haskell.

blocks
document content (Blocks)
meta
document meta information (Meta object)

Pandoc)

Results:

  • cloned and normalized document. (Pandoc)

traversal order. Returns a (deep) copy on which the filter has been applied: the original element is left untouched.

Parameters:

self
the element (Pandoc)
lua_filter
map of filter functions (table)

Result:

Usage:

-- returns `pandoc.Pandoc{pandoc.Para{pandoc.Str 'Bye'}}`
return pandoc.Pandoc{pandoc.Para('Hi')}:walk {
  Str = function (_) return 'Bye' end,
}

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.

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.

traversal order. Returns a (deep) copy on which the filter has been applied: the original element is left untouched.

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:

self
the element (Block)
lua_filter
map of filter functions (table)

Result:

Usage:

-- returns `pandoc.Para{pandoc.Str 'Bye'}`
return pandoc.Para('Hi'):walk {
  Str = function (_) return 'Bye' end,
}

pandoc.BlockQuote constructor.

Fields:

content
block content (Blocks)
tag, t
the literal BlockQuote (string)

pandoc.BulletList constructor.

Fields:

content
list items (List of items, i.e., List of Blocks)
tag, t
the literal BulletList (string)

pandoc.CodeBlock constructor.

Fields:

text
code string (string)
attr
element attributes (Attr)
identifier
alias for attr.identifier (string)
classes
alias for attr.classes (List of strings)
attributes
alias for attr.attributes (Attributes)
tag, t
the literal CodeBlock (string)

pandoc.DefinitionList constructor.

Fields:

content
list of items
tag, t
the literal DefinitionList (string)

pandoc.Div constructor.

Fields:

content
block content (Blocks)
attr
element attributes (Attr)
identifier
alias for attr.identifier (string)
classes
alias for attr.classes (List of strings)
attributes
alias for attr.attributes (Attributes)
tag, t
the literal Div (string)

pandoc.Figure constructor.

Fields:

content
block content (Blocks)
caption
figure caption (Caption)
attr
element attributes (Attr)
identifier
alias for attr.identifier (string)
classes
alias for attr.classes (List of strings)
attributes
alias for attr.attributes (Attributes)
tag, t
the literal Figure (string)

pandoc.HorizontalRule constructor.

Fields:

tag, t
the literal HorizontalRule (string)

pandoc.LineBlock constructor.

Fields:

content
inline content (List of lines, i.e. List of Inlines)
tag, t
the literal LineBlock (string)

pandoc.OrderedList constructor.

Fields:

content
list items (List of items, i.e., List of Blocks)
listAttributes
list parameters (ListAttributes)
start
alias for listAttributes.start (integer)
style
alias for listAttributes.style (string)
delimiter
alias for listAttributes.delimiter (string)
tag, t
the literal OrderedList (string)

pandoc.Para constructor.

Fields:

content
inline content (Inlines)
tag, t
the literal Para (string)

pandoc.Plain constructor.

Fields:

content
inline content (Inlines)
tag, t
the literal Plain (string)

pandoc.RawBlock constructor.

Fields:

format
format of content (string)
text
raw content (string)
tag, t
the literal RawBlock (string)

pandoc.Table constructor.

Fields:

attr
table attributes (Attr)
caption
table caption (Caption)
colspecs
column specifications, i.e., alignments and widths (List of ColSpecs)
head
table head (TableHead)
bodies
table bodies (List of TableBodys)
foot
table foot (TableFoot)
identifier
alias for attr.identifier (string)
classes
alias for attr.classes (List of strings)
attributes
alias for attr.attributes (Attributes)
tag, t
the literal Table (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).

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:

  • a list of Block (or Block-like) values is used directly;
  • a single Inlines value is wrapped into a Plain element;
  • string values are turned into an Inlines value by splitting the string into words (see Inlines), and then wrapping the result into a Plain singleton.

pandoc.List module.

Additionally, the following methods are available on Blocks values:

traversal order. Returns a (deep) copy on which the filter has been applied: the original list is left untouched.

Parameters:

self
the list (Blocks)
lua_filter
map of filter functions (table)

Result:

Usage:

-- returns `pandoc.Blocks{pandoc.Para('Salve!')}`
return pandoc.Blocks{pandoc.Plain('Salve!)}:walk {
  Plain = function (p) return pandoc.Para(p.content) end,
}

traversal order. Returns a (deep) copy on which the filter has been applied: the original element is left untouched.

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:

self
the element (Inline)
lua_filter
map of filter functions (table)

Result:

  • filtered inline element (Inline)

Usage:

-- returns `pandoc.SmallCaps('SPQR)`
return pandoc.SmallCaps('spqr'):walk {
  Str = function (s) return string.upper(s.text) end,
}

pandoc.Cite constructor.

Fields:

content
(Inlines)
citations
citation entries (List of Citations)
tag, t
the literal Cite (string)

pandoc.Code constructor.

Fields:

text
code string (string)
attr
attributes (Attr)
identifier
alias for attr.identifier (string)
classes
alias for attr.classes (List of strings)
attributes
alias for attr.attributes (Attributes)
tag, t
the literal Code (string)

pandoc.Emph constructor.

Fields:

content
inline content (Inlines)
tag, t
the literal Emph (string)

pandoc.Image constructor.

Fields:

caption
text used to describe the image (Inlines)
src
path to the image file (string)
title
brief image description (string)
attr
attributes (Attr)
identifier
alias for attr.identifier (string)
classes
alias for attr.classes (List of strings)
attributes
alias for attr.attributes (Attributes)
tag, t
the literal Image (string)

pandoc.LineBreak constructor.

Fields:

tag, t
the literal LineBreak (string)

pandoc.Math constructor.

Fields:

mathtype
specifier determining whether the math content should be shown inline (InlineMath) or on a separate line (DisplayMath) (string)
text
math content (string)
tag, t
the literal Math (string)

pandoc.Note constructor.

Fields:

content
(Blocks)
tag, t
the literal Note (string)

pandoc.Quoted constructor.

Fields:

quotetype
type of quotes to be used; one of SingleQuote or DoubleQuote (string)
content
quoted text (Inlines)
tag, t
the literal Quoted (string)

pandoc.RawInline constructor.

Fields:

format
the format of the content (string)
text
raw content (string)
tag, t
the literal RawInline (string)

pandoc.SmallCaps constructor.

Fields:

content
(Inlines)
tag, t
the literal SmallCaps (string)

pandoc.SoftBreak constructor.

Fields:

tag, t
the literal SoftBreak (string)

pandoc.Space constructor.

Fields:

tag, t
the literal Space (string)

pandoc.Span constructor.

Fields:

attr
attributes (Attr)
content
wrapped content (Inlines)
identifier
alias for attr.identifier (string)
classes
alias for attr.classes (List of strings)
attributes
alias for attr.attributes (Attributes)
tag, t
the literal Span (string)

pandoc.Str constructor.

Fields:

text
content (string)
tag, t
the literal Str (string)

pandoc.Strikeout constructor.

Fields:

content
inline content (Inlines)
tag, t
the literal Strikeout (string)

pandoc.Strong constructor.

Fields:

content
inline content (Inlines)
tag, t
the literal Strong (string)

pandoc.Subscript constructor.

Fields:

content
inline content (Inlines)
tag, t
the literal Subscript (string)

pandoc.Superscript constructor.

Fields:

content
inline content (Inlines)
tag, t
the literal Superscript (string)

pandoc.Underline constructor.

Fields:

content
inline content (Inlines)
tag, t
the literal Underline (string)

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 Inlines wherever a value of this type is expected:

  • lists of Inline (or Inline-like) values are used directly;
  • single Inline values are converted into a list containing just that element;
  • String values are split into words, converting line breaks into SoftBreak elements, and other whitespace characters into Spaces.

pandoc.List module.

Additionally, the following methods are available on Inlines values:

Inlines)
lua_filter
map of filter functions (table)

Result:

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,
}

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:

identifier
element identifier (string)
classes
element classes (List of strings)
attributes
collection of key/value pairs (Attributes)

Blocks)
short
short caption (Inlines)

Alignment).
contents
cell contents (Blocks).
col_span
number of columns spanned by the cell; the width of the cell in columns (integer).
row_span
number of rows spanned by the cell; the height of the cell in rows (integer).
identifier
alias for attr.identifier (string)
classes
alias for attr.classes (List of strings)
attributes
alias for attr.attributes (Attributes)

pandoc.Citation constructor.

Citation values are equal in Lua if and only if they are equal in Haskell.

Fields:

id
citation identifier, e.g., a bibtex key (string)
mode
citation mode, one of AuthorInText, SuppressAuthor, or NormalCitation (string)
prefix
citation prefix (Inlines)
suffix
citation suffix (Inlines)
note_num
note number (integer)
hash
hash (integer)

  1. Alignment).
  2. table column width, as a fraction of the page width (number).

pandoc.ListAttributes constructor.

Fields:

start
number of the first list item (integer)
style
style used for list numbers; possible values are DefaultStyle, Example, Decimal, LowerRoman, UpperRoman, LowerAlpha, and UpperAlpha (string)
delimiter
delimiter of list numbers; one of DefaultDelim, Period, OneParen, and TwoParens (string)

Attr)
cells
list of table cells (List of Cells)

Attr)
body
table body rows (List of Rows)
head
intermediate head (List of Rows)
row_head_columns
number of columns taken up by the row head of each row of a TableBody. The row body takes up the remaining columns.

Attr)
rows
list of rows (List of Rows)
identifier
alias for attr.identifier (string)
classes
alias for attr.classes (List of strings)
attributes
alias for attr.attributes (Attributes)

Template|nil)
toc_depth
Number of levels to include in TOC (integer)
top_level_division
Type of top-level divisions; one of ‘top-level-part’, ‘top-level-chapter’, ‘top-level-section’, or ‘top-level-default’. The prefix top-level may be omitted when setting this value. (string)
variables
Variables to set in template; string-indexed table (table)
wrap_text
Option for wrapping text; one of ‘wrap-auto’, ‘wrap-none’, or ‘wrap-preserve’. The wrap- prefix may be omitted when setting this value. (string)

List of strings)
output_file
Output file from command line (string or nil)
log
A list of log messages (List of LogMessages)
request_headers
Headers to add for HTTP requests; table with header names as keys and header contents as value (table)
resource_path
Path to search for resources like included images (List of strings)
source_url
Absolute URL or directory of first source file (string or nil)
user_data_dir
Directory to search for data files (string or nil)
trace
Whether tracing messages are issued (boolean)
verbosity
Verbosity level; one of INFO, WARNING, ERROR (string)

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:

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.

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:

caption
Inlines
aligns
column alignments (List of Alignments)
widths
column widths; a (List of numbers)
headers
table header row (List of simple cells, i.e., List of Blocks)
rows
table rows (List of rows, where a row is a list of simple cells, i.e., List of Blocks)

pandoc.types.Version constructor.

Version)
expected
minimum expected version (Version)
error_message
optional error message template. The string is used as format string, with the expected and actual versions as arguments. Defaults to "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'
)

Inlines)
id
identifier (string)
level
level of topmost heading in chunk (integer)
number
chunk number (integer)
section_number
hierarchical section number (string)
path
target filepath for this chunk (string)
up
link to the enclosing section, if any (Chunk|nil)
prev
link to the previous section, if any (Chunk|nil)
next
link to the next section, if any (Chunk|nil)
unlisted
whether the section in this chunk should be listed in the TOC even if the chunk has no section number. (boolean)
contents
the chunk’s block contents (Blocks)

Inlines), number (string|nil), id (string), path (string), and level (integer).

Fields:

chunks
list of chunks that make up the document (list of Chunks).
meta
the document’s metadata (Meta)
toc
table of contents information (table)

Fields and 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.

Blocks)
meta
document metadata (Meta)

Returns:

Blocks)

Returns:

  • list of Block elements (Blocks)

Inlines)

Returns:

MetaValue|{MetaValue,...})

Returns:

  • list of meta values (List)

Blocks)

Returns:

  • BlockQuote element (Block)

Blocks,...})

Returns:

  • BulletList element (Block)

Attr)

Returns:

  • CodeBlock element (Block)

Blocks)
attr
element attributes (Attr)

Returns:

Figure element.

Parameters:

content
figure block content (Blocks)
caption
figure caption (Caption)
attr
element attributes (Attr)

Returns:

Inlines)
attr
element attributes (Attr)

Returns:

Inlines,...})

Returns:

  • LineBlock element (Block)

Blocks,...})
listAttributes
list parameters (ListAttributes)

Returns:

  • OrderedList element (Block)

Inlines)

Returns:

Inlines)

Returns:

Caption)
colspecs
column alignments and widths ({ColSpec,...})
head
table head (TableHead)
bodies
table bodies ({TableBody,...})
foot
table foot (TableFoot)
attr
element attributes (Attr)

Returns:

Blocks list.

Parameters:

block_like_elements
List where each element can be treated as a Block value, or a single such value. (Blocks)

Returns:

  • list of block elements (Blocks)

Inlines)
citations
List of Citations ({Citation,...})

Returns:

Attr)

Returns:

Inlines)

Returns:

Inlines)
src
path to the image file (string)
title
brief image description (string)
attr
image attributes (Attr)

Returns:

Blocks)

Returns:

Inlines)

Returns:

Inlines)

Returns:

Inlines)
attr
additional attributes (Attr)

Returns:

Inlines)

Returns:

Inlines)

Returns:

Inlines)

Returns:

Inlines)

Returns:

Inlines)

Returns:

Inlines list:

  • copies a list of Inline elements into a fresh list; any string s within the list is treated as pandoc.Str(s);
  • turns a single Inline into a singleton list;
  • splits a string into Str-wrapped words, treating interword spaces as Spaces or SoftBreaks.

Parameters:

inline_like_elements
List where each element can be treated as an Inline value, or just a single such value. (Inlines)

Returns:

Attr)
classes
element classes ({string,...})
attributes
table containing string keys and values (table|AttributeList)

Returns:

Blocks)
short
short summary caption (Inlines)

Returns:

Since: 3.6.1

Blocks)
align
text alignment; defaults to AlignDefault (Alignment)
rowspan
number of rows occupied by the cell; defaults to 1 (integer)
colspan
number of columns occupied by the cell; defaults to 1 (integer)
attr
cell attributes (Attr)

Returns:

AttributeList)

Returns:

Inlines)
suffix
(Inlines)
note_num
note number (integer)
hash
hash number (integer)

Returns:

  • new citation object (Citation)

Cell,...})
attr
row attributes (Attr)

Returns:

Row,...})
head
intermediate head ({Row,...})
row_head_columns
number of columns taken up by the row head of each row of the TableBody (integer)
attr
table body attributes (Attr)

Returns:

Row,...})
attr
table foot attributes (Attr)

Returns:

Row,...})
attr
table head attributes (Attr)

Returns:

Inlines)
align
column alignments ({Alignment,...})
widths
relative column widths ({number,...})
header
table header row ({Blocks,...})
rows
table rows ({{Blocks,...},...})

Returns:

Citation

SuppressAuthor

Author name is suppressed.

See also: Citation

NormalCitation

Default citation style is used.

See also: Citation

DisplayMath

Math style identifier, marking that the formula should be show in “display” style, i.e., on a separate line.

See also: Math

InlineMath

Math style identifier, marking that the formula should be show inline.

See also: Math

SingleQuote

Quote type used with Quoted, indicating that the string is enclosed in single quotes.

See also: Quoted

DoubleQuote

Quote type used with Quoted, indicating that the string is enclosed in double quotes.

See also: Quoted

AlignLeft

Table cells aligned left.

See also: Table

AlignRight

Table cells right-aligned.

See also: Table

AlignCenter

Table cell content is centered.

See also: Table

AlignDefault

Table cells are alignment is unaltered.

See also: Table

DefaultDelim

Default list number delimiters are used.

See also: ListAttributes

Period

List numbers are delimited by a period.

See also: ListAttributes

OneParen

List numbers are delimited by a single parenthesis.

See also: ListAttributes

TwoParens

List numbers are delimited by a double parentheses.

See also: ListAttributes

DefaultStyle

List are numbered in the default style

See also: ListAttributes

Example

List items are numbered as examples.

See also: ListAttributes

Decimal

List are numbered using decimal integers.

See also: ListAttributes

LowerRoman

List are numbered using lower-case roman numerals.

See also: ListAttributes

UpperRoman

List are numbered using upper-case roman numerals

See also: ListAttributes

LowerAlpha

List are numbered using lower-case alphabetic characters.

See also: ListAttributes

UpperAlpha

List are numbered using upper-case alphabetic characters.

See also: ListAttributes

sha1

Alias for pandoc.utils.sha1 (DEPRECATED, use pandoc.utils.sha1 instead).

ReaderOptions value.

Parameters

opts
Either a table with a subset of the properties of a ReaderOptions object, or another ReaderOptions object. Uses the defaults specified in the manual for all properties that are not explicitly specified. Throws an error if a table contains properties which are not present in a ReaderOptions object. (ReaderOptions|table)

Returns: 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 value.

Parameters

opts
Either a table with a subset of the properties of a WriterOptions object, or another WriterOptions object. Uses the defaults specified in the manual for all properties that are not explicitly specified. Throws an error if a table contains properties which are not present in a WriterOptions object. (WriterOptions|table)

Returns: 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}

ReaderOptions|table)
read_env
If the value is not given or nil, then the global environment is used. Passing a list of filenames causes the reader to be run in a sandbox. The given files are read from the file system and provided to the sandbox via an ersatz file system. The table can also contain mappings from filenames to contents, which will be used to populate the ersatz file system.

Returns: 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")

Pandoc)
format
format specification; defaults to "html". See the documentation of pandoc.read for a complete description of this parameter. (string|table)
writer_options
options passed to the writer; may be a WriterOptions object or a table with a subset of the keys and values of a WriterOptions object; defaults to the default values documented in the manual. (WriterOptions|table)

Returns: - converted document (string)

Usage:

local doc = pandoc.Pandoc(
  {pandoc.Para {pandoc.Strong 'Tea'}}
)
local html = pandoc.write(doc, 'html')
assert(html == "<p><strong>Tea</strong></p>")

Pandoc)
writer_options
options passed to the writer; may be a WriterOptions object or a table with a subset of the keys and values of a WriterOptions object; defaults to the default values documented in the manual. (WriterOptions|table)

Returns: - converted document (string)

Usage:

-- Adding this function converts a classic writer into a
-- new-style custom writer.
function Writer (doc, opts)
  PANDOC_DOCUMENT = doc
  PANDOC_WRITER_OPTIONS = opts
  loadfile(PANDOC_SCRIPT_FILE)()
  return pandoc.write_classic(doc, opts)
end

Command line options and argument parsing.

Block elements to be flattened. (Blocks)
sep
List of Inline elements inserted as separator between two consecutive blocks; defaults to {pandoc.LineBreak()}. (Inlines)

Returns:

Since: 2.2.3

Pandoc)

Returns:

Since: 2.19.1

Blocks.

Parameters:

object
Retrieve documentation for this object (any)
format
result format; defaults to 'ansi' (string|table)

Returns:

  • rendered documentation (string|Blocks)

Since: 3.8.4

Table block element from a SimpleTable. This is useful for dealing with legacy code which was written for pandoc versions older than 2.10.

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)

Parameters:

simple_tbl
(SimpleTable)

Returns:

  • table block element (Block)

Since: 2.11

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_sections
whether section divs should get an additional number attribute containing the section number. (boolean)
baselevel
shift top-level headings to this level (integer|nil)
blocks
list of blocks to process (Blocks)

Returns:

Since: 2.8

Pandoc)

Returns:

  • lift of references. (table)

Since: 2.17

Pandoc)
filter
filter to run (string)
args
list of arguments passed to the filter. Defaults to {FORMAT}. ({string,...})

Returns:

Since: 2.1.1

Pandoc)
filter
filepath of the filter to run (string)
env
environment to load and run the filter in (table)

Returns:

Since: 3.2.1

Pandoc|Block|Inline|Caption|Cell|MetaValue)

Returns:

  • A plain string representation of the given element. (string)

Since: 2.0.6

Block)

Returns:

Since: 2.11

Version|string|{integer,...}|number)

Returns:

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) --embed-resources 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'

Pandoc)

Returns:

Since: 2.19

list should be preferred.

Usage:

for fp, mt, contents in pandoc.mediabag.items() do
  -- print(fp, mt, contents)
end

Returns:

Iterator triple:

  • The iterator function; must be called with the iterator state and the current iterator value.
  • Iterator state – an opaque value to be passed to the iterator function.
  • Initial iterator value.

Since: 2.7.3

pandoc.List:new([table]).

table.insert.

Parameters:

pos
index of the new value; defaults to length of the list + 1
value
value to insert into the list

table.remove.

Parameters:

pos
position of the list value that will be removed; defaults to the index of the last element

Returns: the removed element

table.sort.

Parameters:

comp
Comparison function as described above.

Information about the formats supported by pandoc.

WriterOptions|table)

Returns:

  • image size information or error message (table)

Since: 3.1.13

Inline, Block, Pandoc, Inlines, or Blocks element the function will return an object of the appropriate type. Otherwise, if the input does not represent any of the AST types, the default decoding is applied: Objects and arrays are represented as tables, the JSON null value becomes null, and JSON booleans, strings, and numbers are converted using the Lua types of the same name.

The special handling of AST elements can be disabled by setting pandoc_types to false.

Parameters:

str
JSON string (string)
pandoc_types
whether to use pandoc types when possible. (boolean)

Returns:

Since: 3.1.1

this blog post.

Parameters:

path
path to be made relative (string)
root
root path (string)
unsafe
whether to allow .. in the result. (boolean)

Returns:

  • contracted filename (string)

Since: 2.12

Blocks into a hierarchical structure: a list of sections (each a Div with class “section” and first element a Header).

The optional opts argument can be a table; two settings are recognized: If number_sections is true, a number attribute containing the section number will be added to each Header. If base_level is an integer, then Header levels will be reorganized so that there are no gaps, with numbering levels shifted by the given value. Finally, an integer slide_level value triggers the creation of slides at that heading level.

Note that a WriterOptions object can be passed as the opts table; this will set the number_section and slide_level values to those defined on the command line.

Usage:

local blocks = {
  pandoc.Header(2, pandoc.Str 'first'),
  pandoc.Header(2, pandoc.Str 'second'),
}
local opts = PANDOC_WRITER_OPTIONS
local newblocks = pandoc.structure.make_sections(blocks, opts)

Parameters:

blocks
document blocks to process (Blocks|Pandoc)
opts
options (table)

Returns:

Since: 3.0

Blocks|Pandoc)

Returns:

Since: 3.0

Pandoc document into a ChunkedDoc.

Parameters:

doc
document to split (Pandoc)
opts

Splitting options.

The following options are supported:

`path_template`
:   template used to generate the chunks' filepaths
    `%n` will be replaced with the chunk number (padded with
    leading 0s to 3 digits), `%s` with the section number of
    the heading, `%h` with the (stringified) heading text,
    `%i` with the section identifier. For example,
    `"section-%s-%i.html"` might be resolved to
    `"section-1.2-introduction.html"`.

    Default is `"chunk-%n"` (string)

`number_sections`
:   whether sections should be numbered; default is `false`
    (boolean)

`chunk_level`
:   The heading level the document should be split into
    chunks. The default is to split at the top-level, i.e.,
    `1`. (integer)

`base_heading_level`
:   The base level to be used for numbering. Default is `nil`
    (integer|nil)

(table)

Returns:

Since: 3.0

Blocks|Pandoc|ChunkedDoc)
opts
options (WriterOptions)

Returns:

  • Table of contents as a BulletList object (Block)

Since: 3.0

Inlines)
used
set of identifiers (string keys, boolean values) that have already been used. (table)
exts
list of format extensions ({string,...})

Returns:

  • unique identifier (string)

Since: 3.8

Access to the system’s information and file functionality.

XDG Base Directory Specification.

Parameters:

xdg_directory_type

The type of the XDG directory or search path. Must be one of config, data, cache, state, datadirs, or configdirs.

Matching is case-insensitive, and underscores and XDG prefixes are ignored, so a value like XDG_DATA_DIRS is also acceptable.

The state directory might not be available, depending on the version of the underlying Haskell library. (string)

filepath
relative path that is appended to the path; ignored if the result is a list of search paths. (string)

Returns:

  • Either a single file path, or a list of search paths. (string|{string,...})

Since: 3.7.1

Plain-text document layouting.

Doc)

Doc)

Doc)

Doc)

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:

text
content to include when placed after a break (string)

Returns:

Since: 2.18

Doc)

Returns:

Since: 2.18

Since: 2.18

Doc)

Returns:

  • doc enclosed by {}. (Doc)

Since: 2.18

Doc)

Returns:

  • doc enclosed by []. (Doc)

Since: 2.18

Doc)
width
block width in chars (integer)

Returns:

  • doc, aligned centered in a block with max width chars per line. (Doc)

Since: 2.18

Doc)

Returns:

  • doc without trailing blanks (Doc)

Since: 2.18

Doc)

Returns:

Since: 2.18

Doc)

Returns:

  • doc enclosed by " chars (Doc)

Since: 2.18

Doc)

Returns:

Since: 2.18

Doc)
ind
indentation width (integer)
start
document (Doc)

Returns:

  • doc prefixed by start on the first line, subsequent lines indented by ind spaces. (Doc)

Since: 2.18

Doc inside a start and end Doc.

Parameters:

contents
document (Doc)
start
document (Doc)
end
document (Doc)

Returns:

Since: 2.18

Doc)
width
block width in chars (integer)

Returns:

  • doc put into block with max width chars per line. (Doc)

Since: 2.18

Since: 2.18

Doc)
ind
indentation size (integer)

Returns:

  • doc indented by ind spaces (Doc)

Since: 2.18

Doc)

Returns:

  • doc with leading blanks removed (Doc)

Since: 2.18

Doc)

Returns:

  • same as input, but non-reflowable (Doc)

Since: 2.18

Doc)

Returns:

  • doc enclosed by (). (Doc)

Since: 2.18

Doc)
prefix
prefix for each line (string)

Returns:

Since: 2.18

Doc)

Returns:

Since: 2.18

Doc)
width
block width in chars (integer)

Returns:

  • doc, right aligned in a block with max width chars per line. (Doc)

Since: 2.18

Since: 2.18

Doc. The text is reflowed on breakable spaces to match the given line length. Text is not reflowed if the line length parameter is omitted or nil.

Parameters:

doc
document (Doc)
colwidth
Maximum number of characters per line. A value of nil, the default, means that the text is not reflown. (integer)
style
Whether to generate plain text or ANSI terminal output. Must be either 'plain' or 'ansi'. Defaults to 'plain'. (string)

Returns:

Since: 2.18

Doc)

Returns:

  • true iff doc is the empty document, false otherwise. (boolean)

Since: 2.18

Doc)

Returns:

  • doc height (integer|string)

Since: 2.18

Doc when reflowed at breakable spaces.

Parameters:

doc
document (Doc)

Returns:

  • minimal possible width (integer|string)

Since: 2.18

Doc as number of characters.

Parameters:

doc
document (Doc)

Returns:

  • doc width (integer|string)

Since: 2.18

Doc)
i
start column (integer)

Returns:

  • column number (integer|string)

Since: 2.18

Doc in boldface.

Parameters:

doc
document (Doc)

Returns:

Since: 3.4.1

Doc in italics.

Parameters:

doc
document (Doc)

Returns:

Since: 3.4.1

Doc.

Parameters:

doc
document (Doc)

Returns:

Since: 3.4.1

Doc.

Parameters:

doc
document (Doc)

Returns:

Since: 3.4.1

Doc)
color
One of ‘black’, ‘red’, ‘green’, ‘yellow’, ‘blue’, ‘magenta’ ‘cyan’, or ‘white’. (string)

Returns:

Since: 3.4.1

Doc)
color
One of ‘black’, ‘red’, ‘green’, ‘yellow’, ‘blue’, ‘magenta’ ‘cyan’, or ‘white’. (string)

Returns:

Since: 3.4.1

above.

Scaffolding for custom writers.

Doc, string, boolean, or table as values, where the table can be either be a list of the aforementioned types, or a nested context.

Parameters:

template
template to apply (Template)
context
variable values (table)

Returns:

Since: 3.0

Template object usable by pandoc.

If the templates_path parameter is specified, then it 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:

template
template string (string)
templates_path
parameter to determine a default path and extension for partials; uses the data files templates path by default. (string)

Returns:

Since: 2.17

Meta data, using the given functions to convert Blocks and Inlines to Doc values.

Parameters:

meta
document metadata (Meta)
blocks_writer
converter from Blocks to Doc values (function)
inlines_writer
converter from Inlines to Doc values (function)

Returns:

Since: 3.0

Version)

Returns:

Since: 2.7.3

Source items.

Pandoc’s text readers expect the input text to be paired with information on where the text originated, e.g., a file name. This abstraction is provided via the Sources type.

Pandoc accepts a range of objects wherever a Sources list is expected:

  • a list of Source items;
  • a simple string, which becomes an unnamed source;
  • a list of table objects, where each table contains the fields name (the filepath) and text (the file contents)

A Sources list can be converted to a string via the default tostring Lua function. This will concatenate all source items.

Parameters:

srcs
sources (string|{string,...}|table)

Returns:

  • new Sources object ({Source,...})

Since: 3.9.1

Version)
reference
minimum version (Version)
msg
alternative message (string)

Returns:

Returns no result, and throws an error if this version is older than reference.

Functions to create, modify, and extract files from zip archives.

The module can be called as a function, in which case it behaves like the zip function described below.

Zip options are optional; when defined, they must be a table with any of the following keys:

  • recursive: recurse directories when set to true;
  • verbose: print info messages to stdout;
  • destination: the value specifies the directory in which to extract;
  • location: value is used as path name, defining where files are placed.
  • preserve_symlinks: Boolean value, controlling whether symbolic links are preserved as such. This option is ignored on Windows.

zip.Entry,...})

Returns:

Since: 3.0

zip.Entry,...})

zip.Archive)

Returns:

  • bytes of the archive (string)
zip.Archive)
opts
zip options (table)

zip.Entry)

zip.Entry)
password
password for entry (string)

Returns:

联系我们 contact @ memedata.com