Script pandoc-zotxt.lua

SYNOPSIS

pandoc -L pandoc-zotxt.lua -C

DESCRIPTION

pandoc-zotxt.lua is a Lua filter for Pandoc that looks up bibliographic data for citations in Zotero and adds that data to the “references” metadata field or to a bibliography file, where Pandoc can pick it up.

You cite your sources using so-called “Better BibTeX citation keys” (provided by Better BibTeX for Zotero) or “Easy Citekeys” (provided by zotxt) and then tell pandoc to filter your document through pandoc-zotxt.lua before processing citations. That’s all there is to it.

For example:

pandoc -L pandoc-zotxt.lua -C <<EOF
See @DoeTitle2020 for details.
EOF

If the “references” metadata field or a bibliography file already contains bibliographic data for a citation, that citation will not be looked up.

CONNECTING TO ZOTERO

Desktop client

By default, bibliographic data is fetched from the Zotero desktop client, which must be running when you invoke pandoc. This is faster, easier, and less error-prone than using Zotero’s Web API. But it requires the zotxt and BetterBibTeX for Zotero add-ons.

Web API

Bibliographic data can also be fetched from the Zotero Web API.

To fetch data from your personal library, create a Zotero API key and set the “zotero-api-key” metadata field to that key:

pandoc -L pandoc-zotxt.lua -C <<EOF
---
zotero-connectors: zoteroweb
zotero-api-key: MO2GHxbkLnWgCqPtpoewgwIl
...
Look up @DoeTitle2020 via the Zotero Web API.
EOF

You can also fetch bibliographic data from public Zotero groups. To do so, list the IDs of those groups in the metadata field “zotero-public-groups”; fetching data from public groups does not require an API key.

pandoc -L pandoc-zotxt.lua -C <<EOF
---
zotero-connectors: zoteroweb
zotero-public-groups:
    - 199
    - 4532986
...
Look up @DoeTitle2020 in the Zotero groupsma 199 and 4532986.
EOF

The Zotero Web API does not allow to search for citation keys other than Zotero item IDs. Therefore, BetterBibTeX citation keys and Easy Citekeys have to be translated into author names, title keywords, and publication years. Better BibTeX citation keys are split up at uppercase letters and the first as well as the last of each series of digits (“DoeTitle2020” becomes “Doe”, “Title”, “2020”). Easy Citekeys are split up at the first colon and the last digit (“doe:2020title” becomes “doe”, “2020”, “title”). Citation keys that cannot be translated into at least two search terms are ignored.

If a search yields two or more items, you need to disambiguate them. If you use BetterBibTeX, you may want to set its citation key format to something along the lines of “[auth][year][shorttitle3_3]” to make collisions less likely. Alternatively, you can add an item’s citation key to its “extra” field in Zotero. Zotero’s “extra” field is a list of CSL key-value pairs; keys and values are separated by colons (“:”), key-value pairs by linefeeds. Use either the key “Citation key” or the key “Citekey” to add a citation key (e.g., “Citation key: DoeTitle2020”); case is insignificant. If you use Better BibTeX for Zotero, you can add the citation key it has generated by ‘pinning’ it.

Support for accessing group libraries via the Zotero Web API is limited. They are only searched if no item in your personal library matches. Morever, the “extra” field of items in group libraries is ignored.

CACHING SOURCES WITH A BIBLIOGRAPHY FILE

Bibliographic data can be added to a bibliography file, rather than to the “references” metadata field. This speeds up subsequent processing, because data that has already been fetched from Zotero need not be fetched again.

To use such a bibliography file, set the “zotero-bibliography” metadata field to a filename. If that filename is relative, it is interpreted as relative to the directory of the first input file or, if no input files were given, the current working directory.

The filename may contain environment variables. Variable names must be enclosed in ${...}. They are replaced with the value of that variable (e.g., ${HOME} will be replaced with your home directory). Moreover, any series of n dollar signs is replaced with n – 1 dollar signs, so that you can escape them if they occur in the filename.

The format of the file is determined by its filename ending.

Ending Format
.bib BibLaTeX
.bibtex BibTeX
.json CSL JSON
.yaml CSL YAML

Support for BibLaTeX and BibTeX files requires Pandoc v2.17 or later. CSL is preferable to BibLaTeX and BibTeX.

The bibliography file is added to the “bibliography” metadata field automatically; if that field already contains bibliography files, they take priority.

Data is only ever added to the bibliography file, never updated or deleted. However, if you delete the file, it will be regenerated from scratch.

For example:

pandoc -L pandoc-zotxt.lua -C <<EOF
---
zotero-bibliography: ${HOME}/foo/bibliography.json
...
See @DoeTitle2020 for details.
EOF

CITATION KEY TYPES

You can use citation keys of multitple types:

Name Type Example
betterbibtexkey Better BibTeX key DoeTitle2020
easykey Easy Citekey doe:2020title
key Zotero item ID A1BC23D4

You can force citation keys to only be interpreted as being of one of a list of particular types by setting the “zotero-citekey-types” metadata field:

pandoc -L pandoc-zotxt.lua -C <<EOF
---
zotero-citekey-types: betterbibtexkey
...
Force @DoeTitle to be treated as BetterBibTeX key.
EOF

This is useful if a Better BibTeX key is misinterpreted as Easy Citekey, or vica vera.

CONFIGURATION

You can configure how bibligraphic data is fetched by setting the following metadata fields:

  • zotero-api-key: A Zotero API key. Only applies to the ‘Web API’.

  • zotero-bibliography: A bibliography filename. See ‘Caching sources with a bibliography file’ above.

  • zotero-citekey-types: A list of citation key types. Citation keys are interpreted to be of the listed types only. See ‘Citation key types’ above.

  • zotero-connectors: One or more ways to connect to Zotero:

    Key Fetch data from
    zotxt Zotero desktop client
    zoteroweb Zotero Web API

    Data is fetched via the given connectors in the order in which they are given. If bibliographic data for a source can be fetched via an earlier connector, it is not searched for via later ones. By default, data is first searched for using zotxt and then using the Web API.

  • zotero-groups: A list of Zotero group IDs. Only the given groups are searched. By default, all groups you are a member of are searched. Only applies to the ‘Web API’.

  • zotero-public-groups: A list of Zotero group IDs. The given groups are searched in addition to non-public groups. Only applies to the ‘Web API’.

  • zotero-user-id: A Zotero user ID. Looked up automatically if not given. Only applies to the ‘Web API’.

If a metadata field expects a list of values, giving a single item is the same as giving a single-item list. For example:

pandoc -L pandoc-zotxt.lua -C <<EOF
---
zotero-public-groups: 4532986
...
See @DoeTitle2020 for details.
EOF

KNOWN ISSUES

pandoc-zotxt.lua creates a temporary file when it adds bibliographic data to a bibliography file. If Pandoc exits because it catches a signal (e.g., because you press Ctrl-c), this file will not be deleted. This is a bug in Pandoc (issue #7355) and in the process of being fixed. Moreover, if you are using Pandoc up to v2.7, another process may, mistakenly, use the same temporary file at the same time, though this is highly unlikely.

A citation key may pick out the wrong item if it picks out a different items depending on whether it is interpreted as a Better BibTeX key or as an Easy Citekey. Set the ‘zotero-citekey-types’ metadata field to fix this (see ‘Citation key types’ above for details).

Zotero v5.0.71 and v5.0.72 fail to handle HTTP requests from user agents that do not set the “User Agent” HTTP header. And pandoc does not. As a consequence, pandoc-zotxt.lua cannot retrieve data from these versions of Zotero unless you tell pandoc to set that header.

SECURITY

If you are using Pandoc up to v2.7 and place the auto-generated bibliography file in a directory that other users have write access to, those users can read and change the content of that file, regardless of whether they have permission to read or write the file itself.

SEE ALSO

pandoc(1)

Info:

  • Copyright: 2018, 2019, 2020, 2021, 2022 Odin Kroeger
  • Release: 1.2.0
  • License: MIT
  • Author: Odin Kroeger

Metadata

NAME The name of this script.
VERSION The version of this script.

System

PATH_SEP The path segment separator used by the operating system.
EOL The end of line sequence typically used on the given operating system.

Types

type_match (val, decl) Check whether a value is of a type.
type_check (...) Type-check function arguments in debugging mode.

Errors

asserter (fin, msgh) Create an assertion function.
protect (func) Create a function that runs in protected mode.

Variables

vars_get ([level=2]) Get a copy of the variables of a function.

Tables

Set A set representation.
ignore_case Metatable to make index lookups case-insensitive.
ignore_case.__index (tab, key) Look up an item.
ignore_case.__newindex (tab, key, val) Store a new item.
sort_pairs Metatable to sort key-value pairs automatically.
sort_pairs.__pairs (tab) Iterate over the key-value pairs of a table in a given order.
keys (tab) Get the indices and number of items in a table.
order (values) Define a sorting function from an ordered list of values.
sorted (tab[, func[, raw=false]]) Iterate over the key-value pairs of a table in a given order.
tabulate (iter[, tab[, key]]) Tabulate the values an iterator returns.
update (tab, ...) Merge tables.
walk (val, func) Walk a tree and apply a function to every node.

Strings

split (str, pattern[, max[, include]]) Iterate over substrings of a string.
trim (str) Remove leading and trailing whitespace.
vars_sub (str, mapping) Substitute variables in strings.

Prototypes

Object Base prototype.
Object:clone ([tab[, mt]]) Delegate to an object.
Object:new (...) Create and initialise a table that delegates to the object.
Object.mt Metatable for prototypes.
Object.mt.__call (...) Shorthand for Object:new.
Values A simple list.
Values.mt Metatable for values.
Values.mt.__len (obj) Get the size of the list.
Values.mt.__newindex (obj, key, val) Add items to the list.
Values.mt.__pairs (obj) Iterate over list items.
Values.n The number of items in the list.
Values:new (...) Create a new list.
Values:add (...) Add items to the list.
getterify (tab) Add getters to a table.

Warnings

xwarn (...) Print a message to STDERR.

File I/O

path_normalise (path) Normalise a path.
path_split (path) Split a path into a directory and a filename.
path_join (...) Join multiple path segments.
path_is_abs (path) Check whether a path is absolute.
path_make_abs (path) Make a path absolute.
path_prettify (path) Prettify paths.
project_dir () Guess the project directory.
file_exists (fname) Check whether a file exists.
file_locate (fname) Locate a file in Pandoc’s resource path.
file_read (fname) Read a file.
file_write (fname, ...) Write data to a file.
tmp_fname ([dir[, templ='pdz-XXXXXX']]) Generate a name for a temporary file.
with_tmp_file (func[, dir[, templ]]) Run a function with a temporary file.

Networking

http_get (url) Retrieve data from a URL via an HTTP GET request.

Markup converters

escape_markdown (str) Escape Markdown syntax.
markdownify (elem) Convert a Pandoc element to Markdown text.
yamlify (val[, ind=4]) Generate a YAML representation of a value.
zotero_to_html (pseudo) Convert Zotero pseudo-HTML to proper HTML.
zotero_to_markdown (pseudo) Convert Zotero pseudo-HTML to Markdown.

CSL items

CSL_VARS_ORDER Preferred order of CSL variables.
csl_item_extras (item) Iterate over every key-value pair in the “note” field of a CSL item.
csl_item_add_extras (item) Add CSL variables from the “note” field to the item proper.
csl_item_to_meta (item) Convert a CSL item to a Pandoc metadata value.
csl_items_filter_by_ckey (items, ckey) Filter CSL items by their citation key.
csl_items_ids (items) Pick the IDs of CSL items out of a list of CSL items.
csl_items_sort (a, b) Sort CSL items by their ID.
csl_varname_normalise (var) Normalise a CSL variable name.
csl_vars_sort (a, b) Sort CSL variables.

Citation keys

CITEKEY_PARSERS A mapping of citation key types to citation key parsers.
CITEKEY_PARSERS.betterbibtexkey (ckey) Guess search terms from a BetterBibTeX citation key.
CITEKEY_PARSERS.easykey (ckey) Guess search terms from an Easy Citekey.
CITEKEY_TYPIFIERS A mapping of citation key type names to type guessing functions.
CITEKEY_TYPIFIERS.betterbibtexkey (ckey) Check if a citation key could be a Better BibTeX citation key.
CITEKEY_TYPIFIERS.key (ckey) Check if a citation key is a Zotero item ID.
citekey_terms (ckey, types) Guess search terms from a citation key.
citekey_types (ckey, types) Check whether a citation key could be of a type.

Bibliography files

BIBLIO_DECODERS A case-insensitive mapping of filename suffices to decoders.
BIBLIO_DECODERS.bib (str) Parse the contents of a BibLaTeX file.
BIBLIO_DECODERS.bibtex (str) Parse the contents of a BibTeX file.
BIBLIO_DECODERS.json (str) Parse a CSL JSON string.
BIBLIO_DECODERS.yaml (str) Parse a CSL YAML string.
BIBLIO_DECODERS.yml Alternative suffix for YAML files.
BIBLIO_ENCODERS A case-insensitive mapping of filename suffices to encoders.
BIBLIO_ENCODERS.bib (items) Serialise a list of CSL items to a BibLaTeX string.
BIBLIO_ENCODERS.bibtex (items) Serialise a list of CSL items to a BibTeX string.
BIBLIO_ENCODERS.json (items) Serialise a list of CSL items to a JSON string.
BIBLIO_ENCODERS.yaml (items) Serialise a list of CSL items to a YAML string.
BIBLIO_ENCODERS.yml Alternative suffix for YAML files.
biblio_read (fname) Read a bibliography file.
biblio_write (fname[, items]) Write bibliographic data to a bibliography file.
biblio_update (handle, fname, ckeys) Add new items from Zotero to a bibliography file.

Document parsing

elem_clone (elem) Make a shallow copy of a Pandoc AST element.
elem_type (elem) Get the type of a Pandoc AST element.
elem_walk (elem, filter) Walk an AST and apply a filter to matching elements.
doc_srcs (doc) Collect bibliographic data.
doc_ckeys (doc[, undef]) Collect the citation keys used in a document.

Option parsing

Option An option definition
Options An option parser.
Options:new (...) Create a new option parser.
Options:add (...) Add an option to the parser.
Options:parse (meta) Read configuration options from a metadata block.
opts_parse (meta, ...) Read configuration options from a metadata block.

Zotero connectors

connectors A case-insensitive namespace for connector prototypes.
connectors.Zotxt Interface to zotxt.
connectors.Zotxt.options Zotero options.
connectors.Zotxt.citekey_types Types of citation keys to expect.
connectors.Zotxt:fetch (ckey) Fetch a CSL item via zotxt.
connectors.ZoteroWeb Interface to Zotero’s Web API
connectors.ZoteroWeb.citekey_types Types of citation keys to expect.
connectors.ZoteroWeb.options Zotero Web API options.
connectors.ZoteroWeb.mt Metatable for Zotero Web API connectors.
connectors.ZoteroWeb.mt.getters Getters for Zotero Web API connectors.
connectors.ZoteroWeb.mt.getters.user_id (obj) Get the user ID for the given API key.
connectors.ZoteroWeb.mt.getters.groups (obj) Get the groups the user is a member of.
connectors.ZoteroWeb.clone () Delegate to the Zotero Web API interface.
connectors.ZoteroWeb.new Create a new Zotero Web API handle.
connectors.ZoteroWeb.query (ep, params) Retrieve data from the Zotero Web API.
connectors.ZoteroWeb:endpoints ([id]) Iterate over item endpoint URLs.
connectors.ZoteroWeb:search (...) Search items by their author, publication year, and title.
connectors.ZoteroWeb:lookup (id) Look up a CSL item by its Zotero ID.
connectors.ZoteroWeb:fetch (ckey) Fetch a CSL item from the Zotero Web API.

Main

add_biblio (fname, handle, doc) Add bibliographic data to a bibliography file.
add_refs (handle, doc) Add bibliographic data to the references metadata field.
main Collect citations and add bibliographic data to the document.


Metadata

NAME
The name of this script.
VERSION
The version of this script.

System

PATH_SEP
The path segment separator used by the operating system.
EOL
The end of line sequence typically used on the given operating system.

Types

type_match (val, decl)

Check whether a value is of a type.

Type declaration grammar:

Declare one or more Lua type names separated by ‘|’ to require that the given value is of one of the given types (e.g., ‘string|table’ requires the value to be a string or a table). ‘*’ is short for the list of all types but nil. ‘?T’ is short for ’T|nil' (e.g., ‘?table’ is short for ‘table|nil’).

Extended Backus-Naur Form:

Type = ‘boolean’ | ‘function’ | ‘nil’ | ‘number’ | ‘string’ | ‘table’ | ‘thread’ | ‘userdata’

Type list = [ ‘?’ ], type, { ‘|’, type }

Wildcard = [ ‘?’ ], ‘*’

Type declaration = type list | wildcard

Complex types:

You can check types of table or userdata fields by declarding a table that maps indices to declarations.

> type_check({1, '2'}, {'number', 'number'})
nil    index 2: expected number, got string.
> type_check({foo = 'bar'}, {foo = '?table'})
nil    index foo: expected table or nil, got string.
> type_check('foo', {foo = '?table'})
nil    expected table or userdata, got string.

Caveats:

    Wrong type names (e.g., ‘int’) do not throw an error.

Parameters:

  • val A value.
  • decl string or table A type declaration.

Returns:

    bool true if the value matches the declaration.

Or

  1. nil nil otherwise.
  2. string An error message.
type_check (...)
Type-check function arguments in debugging mode.

Type declaration grammar:

The type declaration syntax is that of type_match, save for that you can use ‘…’ to declare that the remaining arguments are of the same type as the previous one.

Caveats:

    • Wrong type names (e.g., ‘int’) do not throw an error.
    • Sometimes the strack trace is wrong.
    • Returns a pass-through function unless DEBUG is true.

Tip:

    Obscure Lua errors may indicate that forgot the quotes around ‘…’.

Parameters:

Returns:

    func A function that adds type checks to a function.

Usage:

    store = type_check('?*', 'table', '?number', '...')(
        function (val, tab, ...)
             local indices = table.pack(...)
             for i = 1, n do tab[indices[i]] = val end
        end
    )

Errors

asserter (fin, msgh)
Create an assertion function.

See http://lua-users.org/wiki/FinalizedExceptions.

Parameters:

  • fin func A finaliser.
  • msgh func A message handler.

Returns:

    func An assertion functin.
protect (func)
Create a function that runs in protected mode.

If an error occurs while running the function, it returns nil and an error message.

See http://lua-users.org/wiki/FinalizedExceptions.

Parameters:

  • func func A function.

Returns:

    func A function that runs in protected mode.

Variables

vars_get ([level=2])
Get a copy of the variables of a function.

Caveats:

    If a global variable is shadowed by a variable that is neither one of the function’s local variables nor one of its upvalues, then the value from _ENV is returned, not the value of the shadowing variable.

Parameters:

  • level int

    A stack level, where

    • 1 = vars_get,
    • 2 = the function calling vars_get,
    • n = the function calling the function at level n – 1.
    (default 2)

Returns:

    table A mapping of variable names to values.

Usage:

    > function bar ()
    >     print(vars_get(3).foo)
    > end
    > function foo ()
    >     foo = 'foo'
    >     bar()
    > end
    > foo()
    foo

Tables

Set
A set representation.

Sets are represented as tables, so that a value v is a member of a set S if and only if S[v] is truthy. See Progamming in Lua (chap. 11.5) for details.

Caveats:

    This table exists in documentation only.
ignore_case
Metatable to make index lookups case-insensitive.

Usage:

    > tab = setmetatable({}, ignore_case)
    > tab.FOO = 'bar'
    > tab.foo
    bar
ignore_case.__index (tab, key)
Look up an item.

Parameters:

  • tab tab A table.
  • key A key.

Returns:

    The item.
ignore_case.__newindex (tab, key, val)
Store a new item.

Parameters:

  • tab tab A table.
  • key A key.
  • val A value.
sort_pairs
Metatable to sort key-value pairs automatically.

Usage:

    > tab = setmetatable({c = 3, b = 2, a = 1}, sort_pairs)
    > for k, v in pairs(tab) do
    >     print(k, v)
    > end
    a    1
    b    2
    c    3
sort_pairs.__pairs (tab)
Iterate over the key-value pairs of a table in a given order.

What order pairs are iterated over is defined by the sort metamethod. Defaults to lexical order if sort is unset. See sorted for details.

Parameters:

  • tab tab A table.

Returns:

    func A stateful iterator.

Usage:

    > sort = order{'c', 'b', 'a'}
    > mt = update({sort = sort}, sort_pairs)
    > tab = setmetatable({a = 1, b = 2, c = 3}, mt)
    > for k, v in pairs(tab) do
    >     print(k, v)
    > end
    c    3
    b    2
    a    1
keys (tab)
Get the indices and number of items in a table.

Parameters:

  • tab tab A table.

Returns:

  1. tab The indices.
  2. int The number of items.
order (values)
Define a sorting function from an ordered list of values.

Parameters:

  • values tab Values.

Returns:

    func A sorting function.

Usage:

    > tab = {a = 3, b = 4, c = 2, d = 1}
    > for k, v in sorted(tab, order{'d', 'c'}) do
    >     print(k, v)
    > end
    d    1
    c    2
    a    3
    b    4
sorted (tab[, func[, raw=false]])
Iterate over the key-value pairs of a table in a given order.

Parameters:

  • tab tab A table.
  • func func A sorting function. If no function is given, sorts lexically. (optional)
  • raw bool Bypass __pairs metamethod? (default false)

Returns:

    func A stateful iterator.

Usage:

    > for k, v in sorted{c = 3, b = 2, a = 1} do
    >     print(k, v)
    > end
    a    1
    b    2
    c    3
tabulate (iter[, tab[, key]])
Tabulate the values an iterator returns.

The iterator must accept, if not honour, the same arguments as next.

Parameters:

  • iter func An iterator.
  • tab A table to iterate over. (optional)
  • key The index to start iterating at. (optional)

Returns:

    The values returned by the iterator.

Usage:

    > str = 'key: value'
    > k, v = tabulate(split(str, '%s*:%s*', 2))
    > print(k, v)
    key    value
update (tab, ...)
Merge tables.

Caveats:

    The table is updated in-place.

Parameters:

  • tab tab A table.
  • ... tab or userdata Mappings to merge into the table.

Returns:

    tab The table.
walk (val, func)
Walk a tree and apply a function to every node.

Nodes are only changed if the function returns a value other than nil.

Parameters:

  • val A value.
  • func func A function.

Returns:

    A changed value.

Strings

split (str, pattern[, max[, include]])
Iterate over substrings of a string.

Caveats:

    Neither supports multi-byte characters nor frontier patterns.

Parameters:

  • str string A string.
  • pattern string Where to split the string.
  • max int Split the string into at most that many substrings. (optional)
  • include string Include separators in substrings?

    • ‘l’ includes them on the left,
    • ‘r’ on the right.

    By default, separators are not included. (optional)

Returns:

    func A stateful iterator.

Usage:

    > for s in split('CamelCase', '%u', nil, 'l') do
    >     print(string.format("%s", s))
    > end
    ""
    "Camel"
    "Case"
trim (str)
Remove leading and trailing whitespace.

Parameters:

Returns:

    string A trimmed string.
vars_sub (str, mapping)

Substitute variables in strings.

If a string of characters is placed within braces (‘{…}’) and the opening brace (‘{’) immediately follows a single dollar (‘$’) sign, then that string names a variable and the whole expression is replaced with the value of that variable.

> vars_sub(
>     '${v1} is ${v2}.',
>     {v1 = 'foo', v2 = 'bar'}
> )
foo is bar.

If a braced string is preceded by two or more dollar signs, it is not a variable name and the expression, therefore, not replaced. Moreover, any series of n dollar signs is replaced with n – 1 dollar signs.

> vars_sub(
>     '$${var} costs $$1.',
>     {var = 'foo'}
> )
${var} costs $1.

You can lookup values in tables by joining the name of the variable and that of the table index with a dot (‘.’). Neither variable nor function names can contain dots.

> vars_sub(
>     '${foo.bar} is baz.', {
>         foo = { bar = 'baz' }
>     }
> )
baz is baz.

If a name is followed by a pipe symbol (‘|’), then the string between that pipe symbol and the next pipe symbol/the closing brace (‘}’) names a function; the value is then passed to that function, and the whole expression replaced with the first value that the function returns. Neither variable nor function names may contain pipe symbols.

> vars_sub(
>     '${var|barify} is bar!', {
>         var = 'foo',
>         barify = function (s)
>             return s:gsub('foo', 'bar')
>         end
>     }
> )
bar is bar!

Variables are substituted recursively.

> vars_sub(
>     '${foo|barify} is bar.', {
>         foo = '${bar}',
>         bar = 'baz'
>         barify = function (s) return s:gsub('baz', 'bar') end
>     }
> )
bar is bar.

Parameters:

  • str string A string.
  • mapping func or tab A mapping of variable names to values.

Returns:

    string A transformed string.

Or

  1. nil nil if an error occurred.
  2. string An error message.

Prototypes

Object
Base prototype.
Object:clone ([tab[, mt]])

Delegate to an object.

Set a table’s metatable to a copy of the objects’s metatable and the table’s __index metavalue to the object. If no table is given, create one. If a metatable is given, override the table’s new metatable with that table. In other words,

 Object:clone(tab, mt)

is roughly equivalent to

 do
     local mt = update({}, getmetatable(Object), {__index = Object}, mt)
     setmetatable(tab or {}, mt)
 end

Caveats:

    The table is changed in-place.

Parameters:

  • tab tab A table. (optional)
  • mt tab A metatable. (optional)

Returns:

    tab The table.

Usage:

    > Foo = Object:clone({}, {__tostring = function (t) return t.bar end})
    > Foo.bar = 'baz'
    > tostring(Foo)
    baz
    > bar = Foo()
    > tostring(bar)
    baz
    > bar.bar = 'bar'
    > tostring(bar)
    bar
Object:new (...)
Create and initialise a table that delegates to the object.

Object:new(...) is short for update(Object:clone(), ...).

Parameters:

  • ... tab Properties.

Returns:

    Object An object.

Usage:

    > foo = Object:new{foo = 'foo'}
    > foo.foo
    foo
Object.mt
Metatable for prototypes.
Object.mt.__call (...)
Shorthand for Object:new.

Parameters:

Returns:

    Object An object.
Values
A simple list.

Prototype:

Tip:

    You can sparse-copy a Values object by using it as a prototype:

    > foo = Values:new 'foo'
    > bar = foo()
    > bar:add 'bar'
    > #bar
    2
    > for i, v in ipairs(bar) do
    >     print(i, v)
    > end
    1    foo
    2    bar
    

Usage:

    > list = Values()
    > list:add 'a string'
    > list.n
    1
Values.mt
Metatable for values.
Values.mt.__len (obj)
Get the size of the list.

Parameters:

Returns:

    number The size of the list.
Values.mt.__newindex (obj, key, val)
Add items to the list.

Side-effects:

    Sets Values.n to the number of items in the list.

Parameters:

  • obj Values A list.
  • key An index.
  • val A value.
Values.mt.__pairs (obj)
Iterate over list items.

Parameters:

Returns:

    function A stateless iterator.
Values.n
The number of items in the list.
Values:new (...)

Create a new list.

list = Values:new(...)

is short for:

list = Values:new()
list:add(...)

Tip:

    You can convert an ‘ordinary’ list to a Values object by:

    tab.n = #tab
    Values:clone(tab)
    

Parameters:

  • ... Items.

Returns:

    Values A new list.
Values:add (...)
Add items to the list.

Side-effects:

    Sets Values.n to the number of items in the list.

Parameters:

  • ... Items.
getterify (tab)
Add getters to a table.

Getter protocol:

If an index is not present in a the table, look for a function of the same name in the table’s getters metavalue, which must be a mapping of indices to functions. If getters contains a function of that name, then that function is called with the table as its only argument and whatever it returns is returned as the value of the given index. If getters does not contain a function of that name, the name is looked up using the table’s old __index metavalue.

Caveats:

    • Tables are modified in-place.
    • Getters are not inherited.

Parameters:

  • tab tab A table.

Returns:

    tab The table.

Usage:

    > -- Enable getters for an object:
    > Foo = getterify(Object:clone())
    > Foo.foo = 'bar'
    > mt = getmetatable(Foo)
    > mt.getters = {}
    > function mt.getters.bar (obj) return obj.foo end
    > Foo.bar
    bar
    > -- The getter is reached via the prototype chain,
    > -- so it sees Foo.foo, not bar.foo:
    > baz = Foo()
    > baz.foo = 'bam!'
    > baz.bar
    bar
    > -- But you can make getters quasi-inheritable:
    > Foo.clone = function (...) return getterify(Object.clone(...)) end
    > baz = Foo()
    > baz.foo = 'bam!'
    > baz.bar
    bam!

Warnings

xwarn (...)
Print a message to STDERR.

Printout:

Prefixed with NAME .. ': ' and terminated with EOL. Non-string values are coerced to strings.

Message priority:

Messages are only printed if their priority is greater or equal to PANDOC_STATE.verbostiy.

Variable substitution:

If string values contain variable names, they are replaced with the values of the local variables or the upvalues of the calling function or, if there are no local variables or upvalues of the given names, the values of the global variables of the module. See vars_sub for the syntax and vars_get for limitations.

Options:

String values starting with an ‘@’ are interpreted as options:

  • ‘@error’, ‘@warning’, ‘@info’: Set the message’s priority. (default ‘warning’)
  • ‘@noopts’: Turn option processing off. (default on)
  • ‘@novars’: Turn variable substitution off. (default on)
  • ‘@plain’: Turn variable substitution and option processing off.
  • ‘@vars’: Turn variable substitution on.

Options are case-sensitive. Unknown options are ignored.

Parameters:

  • ... Messages. At least one must be given.

File I/O

path_normalise (path)
Normalise a path.

Parameters:

Returns:

    string A normalised path.
path_split (path)
Split a path into a directory and a filename.

Parameters:

Returns:

  1. string The directory the file is in.
  2. string The file’s name.
path_join (...)
Join multiple path segments.

Caveats:

    Accepts empty strings as arguments.

Parameters:

Returns:

    string A path.
path_is_abs (path)
Check whether a path is absolute.

Caveats:

    Accepts the empty string as path since Pandoc v2.12.

Parameters:

Returns:

    bool true if the path is absolute, false otherwise.
path_make_abs (path)
Make a path absolute.

Requires:

    Pandoc v2.8

Parameters:

  • path string An absolute or relative path.

Returns:

    string An absolute path.
path_prettify (path)
Prettify paths.

Removes the working directory from the beginning of the path. On POSIX systems, also replaces the user’s home directory with ‘~’.

Requires:

    The working directory is not removed from the beginning of a path under Pandoc < v2.12.

Parameters:

Returns:

    string A prettier path.
project_dir ()
Guess the project directory.

The project directory is the directory of the first input file not not named ‘-’ (i.e., of the first actual input file). If there is no such file, the project directory is the current working directory.

Requires:

    The working directory is represented by ‘.’ under Pandoc < v2.8.

Returns:

    string A directory.
file_exists (fname)
Check whether a file exists.

Caveats:

    Another process may create a file of the given name between the time file_exists tries to access that file and the time it returns.

Parameters:

Returns:

    boolean true if the file exists.

Or

  1. nil nil if the file does not exist.
  2. string An error message.
  3. int The error number 2.

Raises:

An error if the file cannot be closed again.
file_locate (fname)
Locate a file in Pandoc’s resource path.

Caveats:

    Absolute filenames are returned as they are.

Parameters:

Returns:

    string A filename in Pandoc’s resource path.

Or

  1. nil nil if the file could not be found.
  2. string An error message.
file_read (fname)
Read a file.

Parameters:

Returns:

    string The contents of the file.

Or

  1. nil nil if an error occurred.
  2. string An error message.
  3. int An error number.
file_write (fname, ...)
Write data to a file.

If a file of that name exists already, it is overwritten.

Caveats:

    Data is first written to a temporary file, that file is then renamed to the given filename. This is safe and secure starting with Pandoc v2.8. If you are using an older version of Pandoc, the caveats of with_tmp_file apply.

Side-effects:

    Creates and deletes a temporary file.

Parameters:

Returns:

    bool true if the data was written to the given file.

Or

  1. nil nil if an error occurred.
  2. string An error message.
  3. int An error number.

Raises:

Under Pandoc < v2.8, an error if no unused temporary filename could be generated. Otherwise, an error if the temporary directory could not be created; this error cannot be caught.
tmp_fname ([dir[, templ='pdz-XXXXXX']])
Generate a name for a temporary file.

Caveats:

    Another process may create a file of the same name between the time tmp_fname checks whether that name is in use and the time it returns.

Parameters:

  • dir string A directory to prefix the filename with. (optional)
  • templ string A template for the filename. ‘X’s are replaced with random alphanumeric characters. (default 'pdz-XXXXXX')

Returns:

    string A filename.

Or

  1. nil nil if the generated filename is in use.
  2. string An error message.
with_tmp_file (func[, dir[, templ]])
Run a function with a temporary file.

Generates a temporary filename. Does not create that file. If the function raises an error or returns nil or false, the temporary file is deleted.

Caveats:

    The temporary file may have been created by another process. If that file is located within a directory that other users have write access to (e.g., /tmp), then this is a security issue.

Side-effects:

    May print error messages to STDERR.

Parameters:

  • func func Given the name of the temporary file. Must not change the working directory.
  • dir string A directory to prefix the name of the temporary file with. See tmp_fname. (optional)
  • templ string A template for the name of the temporary file. See tmp_fname. (optional)

Returns:

    The values returned by the function.

Raises:

An error if no unused temporary filename could be generated.

Networking

http_get (url)
Retrieve data from a URL via an HTTP GET request.

Parameters:

Returns:

  1. string The MIME type of the HTTP content, in lower case.
  2. string The HTTP content itself.

Raises:

An error if the host cannot be connected to. This error can only be caught in Pandoc ≥ v2.11.

Markup converters

escape_markdown (str)
Escape Markdown syntax.

Caveats:

Parameters:

  • str string Non-Markdown text.

Returns:

    string Text with Markdown syntax escaped.

Usage:

    > escape_markdown '*text*'
    \*text*
markdownify (elem)
Convert a Pandoc element to Markdown text.

Requires:

Parameters:

  • elem pandoc.AstElement A Pandoc AST element.

Returns:

    string Markdown text.

Raises:

An error if the element cannot be converted.
yamlify (val[, ind=4])
Generate a YAML representation of a value.

Terminates lines with EOL.

Caveats:

    • Mangles strings in encodings other than UTF-8.
    • Does not escape all non-printable characters (because Unicode).

Parameters:

  • val A value.
  • ind int How many spaces to indent blocks. (default 4)

Returns:

    string A YAML string.

Raises:

An error if the value cannot be represented in YAML.
zotero_to_html (pseudo)
Convert Zotero pseudo-HTML to proper HTML.

Parameters:

  • pseudo string Zotero pseudo-HTML code.

Returns:

    string HTML code.

Or

  1. nil nil if opening and closing ´´ tags are unbalanced.
  2. string An error message.
zotero_to_markdown (pseudo)
Convert Zotero pseudo-HTML to Markdown.

Requires:

Parameters:

  • pseudo string Zotero pseudo-HTML code.

Returns:

    string Markdown text.

Or

  1. nil nil if an error occurred.
  2. string An error message.

CSL items

Appendix IV of the Citation Style Language (CSL) specification lists all CSL variable names.
CSL_VARS_ORDER
Preferred order of CSL variables.

Fields:

  • id Item ID.
  • citekey Citation key (CSL v1.2).
  • type For example, ‘paper’, ‘book’.
  • author Author(s).
  • original-author Original author(s).
  • recipient Recipient of the document.
  • status Publication status (e.g., ‘forthcoming’).
  • issued When the item was published.
  • original-date Original date.
  • title The title.
  • title-short A short version of the title.
  • short-title Ditto.
  • translator Translator(s).
  • editor The editor(s).
  • container-title Publication the item was published in.
  • container-title-short A short version of that title.
  • collection-title E.g., a series.
  • collection-title-short A short version of the title.
  • edition Container’s edition.
  • volume Volume no.
  • issue Issue no.
  • page-first First page.
  • page Pages or page range or number of pages.
  • publisher Publisher.
  • publisher-place City/cities the item was published in.
  • original-title Original title.
  • original-publisher Original publisher.
  • original-publisher-place Place the item was originally published in.
  • url The URL.
  • accessed When the URL was last accessed.
  • doi The DOI.
  • pmcid PubMed Central reference number.
  • pmid PubMed reference number.
  • isbn The ISBN of the item.
  • issn The ISSN of the container.
  • call-number Call number (of a library).
  • language Language the item is in.
  • abstract The abstract.

See also:

csl_item_extras (item)
Iterate over every key-value pair in the “note” field of a CSL item.

Caveats:

    Assumes that the “note” field is used to store entries that were added to Zotero’s “extra” field.

Parameters:

  • item tab A CSL item.

Returns:

    func A stateful iterator.

See also:

csl_item_add_extras (item)
Add CSL variables from the “note” field to the item proper.

Side-effects:

    May print error messages to STDERR.

Parameters:

  • item tab A CSL item.

Returns:

    table The item with variables from “extra” copied over.

Or

  1. nil nil if an “extra” field cannot be parsed.
  2. string An error message.
csl_item_to_meta (item)
Convert a CSL item to a Pandoc metadata value.

This allows to use CSL items in the references metadata field.

Parameters:

  • item tab A CSL item.

Returns:

    pandoc.MetaValue A Pandoc metadata value.

Or

  1. nil nil if a value cannot be converted.
  2. string An error message.
csl_items_filter_by_ckey (items, ckey)
Filter CSL items by their citation key.

Side-effects:

    May print error messages to STDERR.

Parameters:

  • items {tab,...} CSL items.
  • ckey string A citation key (e.g., 'doe:2020word', 'DoeWord2020').

Returns:

    {tab,...} Items with that citation key.
csl_items_ids (items)
Pick the IDs of CSL items out of a list of CSL items.

Side-effects:

    May print error messages to STDERR.

Parameters:

  • items {tab,...} CSL items.

Returns:

    Set Item IDs.
csl_items_sort (a, b)
Sort CSL items by their ID.

Caveats:

    Assumes that CSL item IDs are of the same type.

Parameters:

  • a tab A CSL item.
  • b tab Another CSL item.

Returns:

    bool Whether item A comes before item B.
csl_varname_normalise (var)
Normalise a CSL variable name.

Trim the variable name, lowercase it, and replace spaces with dashes.

Parameters:

  • var string A CSL variable name.

Returns:

    string A normalised variable name.

Or

  1. nil nil if the string is not a CSL variable name.
  2. string An error message.

Usage:

    > csl_varname_normalise 'Original date'
    original-date
csl_vars_sort (a, b)
Sort CSL variables.

Sorts variables in the order in which they are listed in CSL_VARS_ORDER. Unlisted variables are placed after listed ones in lexical order.

Parameters:

  • a string A CSL variable name.
  • b string Another CSL variable name.

Returns:

    bool Whether variable A should come before variable B.

Citation keys

CITEKEY_PARSERS
A mapping of citation key types to citation key parsers.

A citation key parser is a function that takes a citation key and returns search terms or nil if no search terms can be derived from the key.

CITEKEY_PARSERS.betterbibtexkey (ckey)
Guess search terms from a BetterBibTeX citation key.

Splits up a BetterBibTeX citation key at each uppercase letter and at each start of a string of digits.

Caveats:

    Non-letter characters must be encoded in ASCII.

Parameters:

  • ckey string A BetterBibTeX citation key (e.g., 'DoeWord2020').

Returns:

    {string,...} Search terms.
CITEKEY_PARSERS.easykey (ckey)
Guess search terms from an Easy Citekey.

Splits up an Easy Citekey into an author, a year, and a word.

Parameters:

  • ckey string A zotxt Easy Citekey (e.g., 'doe:2020word').

Returns:

    {string,...} Search terms.
CITEKEY_TYPIFIERS
A mapping of citation key type names to type guessing functions.

A type guessing function should take a citation key and return true if that key could be (not “is”) of that type and false otherwise.

CITEKEY_TYPIFIERS.betterbibtexkey (ckey)
Check if a citation key could be a Better BibTeX citation key.

Parameters:

Returns:

    bool Whether the key could be a Better BibTeX key.
CITEKEY_TYPIFIERS.key (ckey)
Check if a citation key is a Zotero item ID.

Parameters:

Returns:

    bool Whether the citation key is a Zotero item ID.
citekey_terms (ckey, types)
Guess search terms from a citation key.

Caveats:

Parameters:

  • ckey string A citation key (e.g., 'doe:2020word', 'DoeWord2020').
  • types {string,...} Types to try to parse the citation key as.

Returns:

    {string,...} Search terms.

Or

  1. nil nil if no search terms could be derived.
  2. string An error message.
citekey_types (ckey, types)
Check whether a citation key could be of a type.

Parameters:

Returns:

    {string,...} Citation key types that would fit the key.

Bibliography files

BIBLIO_DECODERS
A case-insensitive mapping of filename suffices to decoders.

A decoder is a function that takes a string and returns a list of CSL items.

BIBLIO_DECODERS.bib (str)
Parse the contents of a BibLaTeX file.

Requires:

    Only returns a list of mappings of the literal ‘id’ to CSL item IDs if run with Pandoc < v2.17.

Parameters:

  • str string The contents of a BibLaTeX file.

Returns:

    {tab,...} CSL items.

Or

  1. nil nil if the contents could not be parsed.
  2. string An error message.
BIBLIO_DECODERS.bibtex (str)
Parse the contents of a BibTeX file.

Requires:

    Only returns a list of mappings of the literal ‘id’ to CSL item IDs if run with Pandoc < v2.17.

Parameters:

  • str string The contents of a BibTeX file.

Returns:

    {tab,...} CSL items.

Or

  1. nil nil if the contents could not be parsed.
  2. string An error message.
BIBLIO_DECODERS.json (str)
Parse a CSL JSON string.

Parameters:

  • str string A CSL JSON string.

Returns:

    {tab,...} CSL items.

Or

  1. nil nil if the string could not be parsed.
  2. string An error message.
BIBLIO_DECODERS.yaml (str)
Parse a CSL YAML string.

Caveats:

    Converts formatting to Markdown, not Zotero pseudo-HTML.

Parameters:

  • str string A CSL YAML string.

Returns:

    {tab,...} CSL items.

Or

  1. nil nil if the string could not be parsed.
  2. string An error message.
BIBLIO_DECODERS.yml
Alternative suffix for YAML files.
BIBLIO_ENCODERS
A case-insensitive mapping of filename suffices to encoders.
BIBLIO_ENCODERS.bib (items)
Serialise a list of CSL items to a BibLaTeX string.

Requires:

    Pandoc ≥ 2.17.

Parameters:

  • items {tab,...} CSL items.

Returns:

    string A BibLaTeX string.

Or

  1. nil nil if the items could not be serialised.
  2. string An error message.
BIBLIO_ENCODERS.bibtex (items)
Serialise a list of CSL items to a BibTeX string.

Requires:

    Pandoc ≥ 2.17.

Parameters:

  • items {tab,...} CSL items.

Returns:

    string A BibTeX string.

Or

  1. nil nil if the items could not be serialised.
  2. string An error message.
BIBLIO_ENCODERS.json (items)
Serialise a list of CSL items to a JSON string.

Parameters:

  • items {tab,...} CSL items.

Returns:

    string A CSL JSON string.

Or

  1. nil nil if the items could not be serialised.
  2. string An error message.
BIBLIO_ENCODERS.yaml (items)
Serialise a list of CSL items to a YAML string.

Parameters:

  • items {tab,...} CSL items.

Returns:

    string A CSL YAML string.

Or

  1. nil nil if the items could not be serialised.
  2. string An error message.
BIBLIO_ENCODERS.yml
Alternative suffix for YAML files.
biblio_read (fname)
Read a bibliography file.

The filename suffix determines the file’s format. BIBLIO_DECODERS must contain a matching decoder.

Parameters:

Returns:

    Values CSL items.

Or

  1. nil nil if an error occurred.
  2. string An error message.
  3. optional int An error number.
biblio_write (fname[, items])
Write bibliographic data to a bibliography file.

The filename suffix determines the file’s format. BIBLIO_ENCODERS must contain a matching encoder.

If no CSL items are given, tests whether data can be serialised in the given format without chaging the file.

Caveats:

Parameters:

  • fname string A filename.
  • items tab CSL items. (optional)

Returns:

    string The filename suffix.

Or

  1. nil nil if an error occurred.
  2. string An error message.
  3. optional int An error number.
biblio_update (handle, fname, ckeys)
Add new items from Zotero to a bibliography file.

Caveats:

Side-effects:

    May print error messages to STDERR.

Parameters:

Returns:

    bool true if the file was updated or no update was required.

Or

  1. nil nil if an error occurrs.
  2. string An error message.
  3. optional int An error number if the error is a file I/O error.

Raises:

See connectors.Zotxt and connectors.ZoteroWeb.

Document parsing

elem_clone (elem)
Make a shallow copy of a Pandoc AST element.

Parameters:

  • elem pandoc.AstElement A Pandoc AST element.

Returns:

    pandoc.AstElement The clone.
elem_type (elem)
Get the type of a Pandoc AST element.

Parameters:

  • elem pandoc.AstElement A Pandoc AST element.

Returns:

  1. string A type (e.g., ‘Str’).
  2. string or nil A super-type (e.g., ‘Block’ or ‘Meta’).
  3. string or nil ⋮.

Or

  1. nil nil if the given value is not a Pandoc AST element.
  2. string An error message.
elem_walk (elem, filter)

Walk an AST and apply a filter to matching elements.

Differs from Pandoc’s walkers by:

  • walking AST elements of any type (inluding documents and metadata),
  • walking the AST bottom-up,
  • not accepting the traverse keyword,
  • applying the filter to the given element itself,
  • allowing functions in the filter to return data of arbitrary types,
  • never modifying the original element, and
  • accepting ‘AstElement’ as type that matches any element.

Parameters:

Returns:

    Typically but not necessarily, a new Pandoc AST element.
doc_srcs (doc)
Collect bibliographic data.

Reads the references metadata field and every bibliography file.

Parameters:

  • doc pandoc.Pandoc A document.

Returns:

    {tab,...} CSL items.

Or

  1. nil nil if an error occurred.
  2. string An error message.
doc_ckeys (doc[, undef])
Collect the citation keys used in a document.

Parameters:

  • doc pandoc.Pandoc A document.
  • undef bool Collect only undefind citation keys? (optional)

Returns:

  1. {string,...} Citation keys.
  2. int The number of citation keys found.

Or

  1. nil nil if an error occurred.
  2. string An error message.

Option parsing

Option
An option definition

Caveats:

    This table exists in documentation only.

Fields:

  • name string An option name.
  • type string A type to coerce the option’s value to. (default 'string')
  • parse func A parser. (optional)
  • prefix string A prefix. (optional)

See also:

Options
An option parser.

Prototype:

See also:

Options:new (...)

Create a new option parser.

parser = Options:new{name = 'foo'}

is equivalent to:

parser = Options()
parser:add{name = 'foo'}

Parameters:

See also:

Options:add (...)
Add an option to the parser.

Parameters:

See also:

Usage:

    parser = Options()
    parser:add{
        name = 'bar',
        type = 'number',
        parse = function (x)
            if x < 1 return return nil, 'not a positive number.' end
            return x
        end
    }
Options:parse (meta)
Read configuration options from a metadata block.

Parameters:

  • meta pandoc.MetaMap A metadata block.

Returns:

    tab A mapping of option names to values.

Or

  1. nil nil if an error occurred.
  2. string An error message.

See also:

Usage:

    > meta = pandoc.MetaMap{
    >     ['foo-bar'] = pandoc.MetaInlines(pandoc.List{
    >         pandoc.Str "0123"
    >     })
    > parser = Options()
    > parser:add{
    >     name = 'bar',
    >     type = 'number',
    >     parse = function (x)
    >         if x < 1 return return nil, 'not a positive number.' end
    >         return x
    >     end
    > }
    > opts = parser:parse(meta)
    > opts.bars
    123
    > type(opts.bar)
    number
opts_parse (meta, ...)
Read configuration options from a metadata block.

Mapping of option names to metadata fieldnames:

The name of the metadata field that is looked up by Options:parse is the name of the option with underscores replaced by dashes. If the option has a prefix, then the fieldname is prefixed with that prefix and a dash after underscores have been replaced with dashes.

In Lua:

fieldname = name:gsub('_', '-')
if prefix then fieldname = prefix .. '-' .. fieldname end

Type declaration grammar:

Configuration values can be of one of three types:

  • ‘number’
  • ‘string’
  • ‘list’

If you declare an option to be of the scalar types ‘number’ or ‘string’, its value is required to be of the Lua type of the same name. Values are converted automatically if possible.

If you declare an option to be of the type ‘list’, its value is required to be a pandoc.List. If a scalar is encountered where a list was expected, the value is wrapped in a single-item list.

The items of a list must all be of the same type, which you declare by appending ‘<T>’ to the literal ‘list’, where T is either the name of a scalar type or another list declaration and defaults to ‘string’.

In Extended Backus-Naur Form:

Scalar = ( ‘number’ | ‘string’ )

List = ‘list’, [ ‘<’, ( scalar | list ), ‘>’ ]

No type checks or conversions are performed for nil.

Parse protocol:

A parser is a function that takes the converted value and returns a new one or nil and an error message.

Parsers are not called for nil.

Parameters:

  • meta pandoc.MetaMap A metadata block.
  • ... Option Options.

Returns:

    tab A mapping of option names to values.

See also:

Usage:

    > meta = pandoc.MetaMap{
    >     ['foo-bar'] = pandoc.MetaInlines(pandoc.List{
    >         pandoc.Str "0123"
    >     })
    > opts = opts_parse(meta, {
    >     name = 'bar',
    >     type = 'number',
    >     parse = function (x)
    >         if x < 1 return return nil, 'not a positive number.' end
    >         return x
    >     end
    > })
    > opts.bars
    123
    > type(opts.bar)
    number

Zotero connectors

connectors
A case-insensitive namespace for connector prototypes.

Connector protocol:

A connector prototype must provide two methods:

  • new: Called to create handles. Must have the same function signature as Object:new and return nil and an error message if the handle cannot be created.

  • fetch: Called to fetch bibliographc data. Must take a citation key and return either a CSL item or nil and an error message.

Connector prototypes may register configuration settings by providing an options property that points to an Options object. That object’s Options:parse method is then called with the document’s metadata block as argument and whatever it returns is passed on to new.

connectors.Zotxt
Interface to zotxt.

Prototype:

Usage:

    handle = connectors.Zotxt()
    item = handle:fetch 'DoeWord2020'
connectors.Zotxt.options
Zotero options.

Defines zotero-citekey-types. See the manual for details.

Prototype:

connectors.Zotxt.citekey_types
Types of citation keys to expect.

List of strings. For example, {'betterbibtexkey', 'easykey'}.

Fields:

  • betterbibtexkey Better BibTeX citation key
  • easykey zotxt easy citekey
  • key Zotero item ID
connectors.Zotxt:fetch (ckey)
Fetch a CSL item via zotxt.

Side-effects:

Parameters:

  • ckey string A citation key (e.g., 'doe:2020word', 'DoeWord2020').

Returns:

    table A CSL item.

Or

  1. nil nil if an error occurred.
  2. string An error message.

Raises:

See http_get.
connectors.ZoteroWeb
Interface to Zotero’s Web API

Prototype:

Uninitialised properties:

  • api_key string A Zotero Web API key. (optional)
  • user_id number A Zotero user ID. (optional)
  • groups {number,...} Zotero groups to search in. (optional)
  • public_groups {number,...} Public Zotero groups to search in. (optional)

Usage:

    handle = connectors.ZoteroWeb{api_key = 'a0Bc1De2Fg3Hi4Jk5Lm6No7'}
    item = handle:fetch 'DoeWord2020'
connectors.ZoteroWeb.citekey_types
Types of citation keys to expect.

See connectors.Zotxt.citekey_types for details and citekey_terms for caveats.

connectors.ZoteroWeb.options
Zotero Web API options.

Defines:

  • zotero-api-key
  • zotero-user-id
  • zotero-groups
  • zotero-public-groups

See the manual for details.

Prototype:

connectors.ZoteroWeb.mt
Metatable for Zotero Web API connectors.
connectors.ZoteroWeb.mt.getters
Getters for Zotero Web API connectors.

See also:

connectors.ZoteroWeb.mt.getters.user_id (obj)
Get the user ID for the given API key.

Parameters:

Returns:

    string A Zotero user ID.

Raises:

An error if

  • the api_key field is not set.
  • the Zotero Web API could not be reached (see http_get for details),
  • the API’s response cannot be parsed, or
  • no user ID could be found for the given Zotero API key.
connectors.ZoteroWeb.mt.getters.groups (obj)
Get the groups the user is a member of.

Parameters:

Returns:

    {string,...} Zotero group IDs.

Raises:

An error if

  • the api_key field is not set.
  • the Zotero Web API could not be reached (see http_get for details), or
  • the API’s response cannot be parsed.
connectors.ZoteroWeb.clone ()
Delegate to the Zotero Web API interface.

See also:

connectors.ZoteroWeb.new
Create a new Zotero Web API handle.
connectors.ZoteroWeb.query (ep, params)
Retrieve data from the Zotero Web API.

Parameters:

Returns:

    string The response of the Zotero Web API.

Or

  1. nil nil if an error occurred.
  2. string An error message.

Raises:

See http_get.

See also:

connectors.ZoteroWeb:endpoints ([id])
Iterate over item endpoint URLs.

Parameters:

  • id string A Zotero item ID. (optional)

Returns:

    func A stateful iterator.
connectors.ZoteroWeb:search (...)
Search items by their author, publication year, and title.

Caveats:

    Does not correct Zotero’s CSL JSON export.

Parameters:

Returns:

    tab CSL items that match the given search terms.

Or

  1. nil nil if no items were found or an error occurred.
  2. string An error message.
  3. An error message.

Raises:

See connectors.ZoteroWeb.mt.getters.user_id and connectors.ZoteroWeb.mt.getters.groups.
connectors.ZoteroWeb:lookup (id)
Look up a CSL item by its Zotero ID.

Parameters:

Returns:

    tab A CSL item.

Or

  1. nil nil if no or more than one item has been found.
  2. string An error message.

Raises:

See connectors.ZoteroWeb.mt.getters.user_id and connectors.ZoteroWeb.mt.getters.groups.
connectors.ZoteroWeb:fetch (ckey)
Fetch a CSL item from the Zotero Web API.

Side-effects:

    Search terms for citation keys are printed to STDERR if the user has requested verbose output.

Parameters:

  • ckey string A citation key (e.g., 'doe:2020word', 'DoeWord2020').

Returns:

    table A CSL item.

Or

  1. nil nil if an error occurred.
  2. string An error message.

Raises:

See connectors.ZoteroWeb.mt.getters.user_id and connectors.ZoteroWeb.mt.getters.groups.

Main

add_biblio (fname, handle, doc)
Add bibliographic data to a bibliography file.

Updates the bibliography file as needed and adds its to the bibliography metadata field. Interpretes relative filenames as relative to the directory of the first input file passed to pandoc, or, if no input files were given, as relative to the current working directory.

Caveats:

Side-effects:

    May print error messages to STDERR.

Parameters:

Returns:

    pandoc.Meta An updated metadata block.

Or

  1. nil nil if nothing was done or an error occurred.
  2. string An error message, if applicable.

Raises:

See connectors.Zotxt and connectors.ZoteroWeb.
add_refs (handle, doc)
Add bibliographic data to the references metadata field.

Side-effects:

    May print error messages to STDERR.

Parameters:

Returns:

    table An updated metadata block.

Or

  1. nil nil if nothing was done or an error occurred.
  2. string An error message, if applicable.

Raises:

See connectors.Zotxt and connectors.ZoteroWeb.
main
Collect citations and add bibliographic data to the document.

See the manual for details.

Side-effects:

    May print error messages to STDERR.
  • doc pandoc.Pandoc A document.
generated by LDoc 1.4.6 Last updated 2022-03-29 11:56:26