Pandoc::Elements(3pm)

๐Ÿ“ฆ
version 0.38 ยท 3 versions
, in debian trixie, ubuntu resolute, ubuntu stonking

๐Ÿ’– Pandoc::Elements ๐Ÿ’–

okay bestie, welcome to Pandoc::Elements(3pm) โ€” yes it's from the User Contributed Perl Documentation and yes it's giving very much "the lore doc for making Pandoc documents with Perl". Sit down, hydrate, we're doing this ๐Ÿซถ

This package is literally for creating and processing Pandoc documents, and I'm gonna walk you through every single thing in here, no skips, no cap.


โœจ NAME โœจ

Pandoc::Elements โ€” create and process Pandoc documents. that's it, that's the whole job description bestie ๐Ÿ’…


๐ŸŒธ SYNOPSIS ๐ŸŒธ

so here's this little script called hello.pl and look at the output it produces:

use Pandoc::Elements;
use JSON;

print Document(
    {
        title => MetaInlines [ Str "Greeting" ]
    },
    [
        Header( 1, attributes { id => 'top' }, [ Str 'Hello' ] ),
        Para [ Str 'Hello, world!' ],
    ],
    api_version => '1.17.0.4'
)->to_json;

and the way that output can be converted to, say, HTML is iconic, watch:

./hello.pl | pandoc -f json -t html5 --standalone

aaaaand if you wanted the equivalent Pandoc Markdown document instead, it would be:

% Greeting
# GruรŸ {.de}
Hello, world!

(not the GruรŸ {.de} sneaking in there while the Perl says Hello โ€” we don't ask questions, we just report the facts โœจ)


๐Ÿฆ‹ DESCRIPTION ๐Ÿฆ‹

Pandoc::Elements hands you utility functions to parse, serialize, and modify abstract syntax trees (AST) of Pandoc documents (Pandoc lives at http://pandoc.org/, go say hi).

Pandoc can take that data structure and convert it into so many other document formats โ€” we're talking HTML, LaTeX, ODT, and ePUB. range, honestly ๐Ÿ‘‘

also!! go look at:

  • module Pandoc::Filter
  • command line script pod2pandoc
  • the internal modules Pandoc::Walker and Pod::Simple::Pandoc

๐ŸŒˆ PANDOC VERSIONS ๐ŸŒˆ

the Pandoc document model is defined in the file Text.Pandoc.Definition (at https://hackage.haskell.org/package/pandoc-types/docs/Text-Pandoc-Definition.html), which is part of the Haskell package pandoc-types (at https://hackage.haskell.org/package/pandoc-types).

Pandoc::Elements is compatible with pandoc-types 1.12.3 (that one shipped with pandoc 1.12.1) all the way up to pandoc-types-1.21 (first released with pandoc 2.10). The JSON output of every single pandoc release since 1.12.1 can be parsed with the function pandoc_json, the Document constructor, or the parse method of module Pandoc. And here's the slay: the AST is always upgraded to pandoc-types 1.22 and then downgraded to another api version on serialization with to_json. glow-up AND glow-down, we contain multitudes ๐Ÿ’…

to figure out which api version a given pandoc executable needs (any version since 1.18), just run pandoc with the --version option and check which version of the pandoc-types library pandoc was compiled with.

starting with version 1.18, pandoc will not decode a JSON AST representation unless the major and minor version numbers (that's the Document method api_version) match the ones built into that version of pandoc. so like, be careful, it's a vibe check that actually rejects you ๐Ÿ˜ญ

here are the changes in the pandoc document model that have been implemented:

  • pandoc-types 1.22, released for pandoc 2.11, further modified the representation of the Table element.
  • pandoc-types 1.21, released for pandoc 2.10, introduced the Underline element and modified the representation of the Table element.
  • pandoc-types 1.17, released for pandoc 1.18, introduced the LineBlock element and modified the representation of the root Document element.
  • pandoc-types 1.16, released with pandoc 1.16, introduced attributes to Link and Image elements.
  • pandoc-types 1.12.3, released with pandoc 1.12.1, modified the representation of elements to objects with fields t and c. This is also the internal representation of documents used in this module.

๐ŸŽ€ FUNCTIONS ๐ŸŽ€

these functions and keywords are exported by default:

  • Constructors for all Pandoc document elements โ€” block elements like Para, inline elements like Emph, metadata elements, and the Document too.
  • Type keywords like Decimal and LowerAlpha, to be used as types in other document elements.
  • These helper functions: pandoc_json, pandoc_version, attributes, metadata, citation, and element.

๐ŸŒŸ pandoc_json $json

parse a JSON string, exactly as emitted by pandoc in JSON format. This is the reverse of method to_json, but โ€” plot twist โ€” it can read both the old format (before Pandoc 1.16) and the new one. inclusive queen ๐Ÿซถ


๐ŸŒŸ attributes { key => $value, ... }

maps a hash reference (or an instance of Hash::MultiValue) into the internal structure of Pandoc attributes. The special keys id (a string) and class (a string, or an array reference with space-separated class names) are recognized. Details? go see attribute methods. iykyk ๐Ÿ’…


๐ŸŒŸ citation { ... }

a citation, as part of document element Cite, has to be a hash reference with these fields:

  • citationId (string)
  • citationPrefix (list of inline elements)
  • citationSuffix (list of inline elements)
  • citationMode (one of NormalCitation, AuthorInText, SuppressAuthor)
  • citationNoteNum (integer)
  • citationHash (integer)

the helper method citation is here to build such a hash for you by filling in default values, and optionally letting you use shorter field names โ€” id, prefix, suffix, mode, note, and hash:

citation {
    id => 'foo',
    prefix => [ Str "see" ],
    suffix => [ Str "p.", Space, Str "42" ]
}

# in Pandoc Markdown

[see @foo p. 42]

the values returned by this function โ€” and any citations inside document objects returned by pandoc_json โ€” are blessed hashrefs with getter/setter accessors for both the full field names and the short ones. so like, $citation->citationId(...) and $citation->id(...) get or set the exact same value. two names, one truth, main character energy โญ


๐ŸŒŸ pandoc_version( [ $document ] )

returns a Pandoc::Version object with the expected version number of the pandoc executable you'd use to serialize documents with to_json.

if you pass a Document element as the argument, you get back the minimal pandoc release version compatible with its api version.

with no argument, the package variable $PANDOC_VERSION gets checked for a preferred pandoc release. By default that variable is set from an environment variable of the same name. and if no preferred pandoc release has been specified at all, the function returns version 1.18 โ€” because that's the first pandoc release compatible with the most recent api version this module supports. it's the default for a reason bestie ๐Ÿ’œ

see also method version of module Pandoc if you want the current version of the pandoc executable on your system.


๐ŸŒŸ element( $name => $content )

creates a Pandoc document element of arbitrary name. heads up though: this function is only exported on request ๐Ÿ™ˆ


๐Ÿ‘‘ ELEMENTS AND METHODS ๐Ÿ‘‘

document elements are encoded as Perl data structures equivalent to the JSON structure, emitted with pandoc output format json. this JSON structure is subject to minor changes between versions of pandoc (we love a moving target ๐Ÿ’€).

all elements are blessed objects that provide:

  • common element methods (all elements, no exceptions)
  • attribute methods (for the elements that have attributes)
  • plus additional element-specific methods

๐Ÿ’– COMMON METHODS ๐Ÿ’–

to_json

return the element as a JSON encoded string. these two lines are equivalent:

$element->to_json;
JSON->new->utf8->canonical->convert_blessed->encode($element);

the serialization format can be adjusted to different pandoc versions with module and environment variable PANDOC_VERSION, or with the Document element properties api_version and pandoc_version.

and when you're writing filters, you can normally just rely on the api version value obtained from pandoc โ€” because pandoc expects to receive the same JSON format as it emits. symmetry, we love her ๐ŸŽ€

name

return the name of the element. like Para for a paragraph element.

content

return the element content. for most elements (Para, Emph, Str...) the content is an array reference with child elements. other elements consist of multiple parts โ€” for instance the Link element has attributes (attr, id, class, classes, keyvals), a link text (content), and a link target (target) with url and title. she's layered โœจ

is_block

true if the element is a Block element.

is_inline

true if the element is an inline Inline element.

is_meta

true if the element is a Metadata element.

is_document

true if the element is a Document element.

as_block

return the element unmodified if it's a block element โ€” or wrapped in a Plain or Div if it isn't.

match( $selector )

check whether the element matches a given Pandoc::Selector (given as an instance or as a string).

walk(...)

walk the element tree with Pandoc::Walker.

query(...)

query the element to extract results with Pandoc::Walker.

transform(...)

transform the element tree with Pandoc::Walker.

string

returns a concatenated string of element content, leaving out all formatting. just the words, the raw essence, no packaging ๐Ÿ’…


๐Ÿ’œ ATTRIBUTE METHODS ๐Ÿ’œ

some elements have attributes, which can be an identifier, ordered class names, and ordered key-value pairs. elements with attributes provide these methods:

attr

get or set the attributes in Pandoc internal structure:

[ $id, [ @classes ], [ [ key => $value ], ... ] ]

see helper function attributes to create this structure.

keyvals

get all attributes (id, class, and key-value pairs) as a new Hash::MultiValue instance โ€” or replace all key-value pairs plus id and/or class if those are included as field names. all class fields are split by whitespaces. look at all these moves:

$e->keyvals                           # return new Hash::MultiValue
$e->keyvals( $HashMultiValue )        # update by instance of Hash::MultiValue
$e->keyvals( key => $value, ... )     # update by list of key-value pairs
$e->keyvals( \%hash )                 # update by hash reference
$e->keyvals( { } )                    # remove all key-value pairs
$e->keyvals( id => '', class => '' )  # remove all key-value pairs, id, class

id

get or set the identifier. also see Pandoc::Filter::HeaderIdentifiers for utility functions to handle Header identifiers, if that's your thing ๐Ÿซถ

class

get or set the list of classes, separated by whitespace.

add_attribute( $name => $value )

append an attribute. and the special attribute names id and class set or append the identifier or class, respectively. iconic behavior ๐Ÿ’…


๐Ÿงš DOCUMENT ELEMENT ๐Ÿงš

Document

the root element! she consists of a metadata hash (meta), a document element array (content = blocks), and an optional api_version.

the constructor accepts either two arguments plus an optional named parameter api_version:

Document { %meta }, [ @blocks ], api_version => $version_string

or a hash with three fields for metadata, document content, and an optional pandoc API version:

{
    meta               => { %metadata },
    blocks             => [ @content ],
    pandoc-api-version => [ $major, $minor, $revision ]
}

that latter form is used as pandoc JSON format since pandoc release 1.18. if no api version is given, it will be set to 1.21, which was also introduced with pandoc release 2.10.

and there's a third ("old") form accepted for compatibility with the pandoc JSON format before release 1.18 and since release 1.12.1: an array with two elements for metadata and document content respectively.

[ { unMeta => { %meta } }, [ @blocks ] ]

in this case the api version is set to 1.16 โ€” but heads up, older versions down to 1.12.3 used the same format.

๐Ÿซถ reminder bestie: this is part 1 โ€” Document elements provide more special methods in addition to the common element methods, and we are NOT done yet. no signing off, the lore continuesโ€ฆ ๐Ÿ’–

api_version( [ $api_version ] ) โœจ

Okay bestie, this one returns the pandoc-types version (aka pandoc-api-version) of this document as a Pandoc::Version object โ€” or, if you pass an argument, it sets it to a new value. This version is literally the thing that decides how method to_json serializes the document. No cap.

See "PANDOC VERSIONS" for details, bestie.


pandoc_version( [ $pandoc_version ] ) ๐Ÿฆ‹

Returns the minimum required version of the pandoc executable that's compatible with the api_version of this document. These two are equivalent, fr fr:

$doc->pandoc_version;
pandoc_version( $doc );

If you use it as a setter, it sets the api version of this document to be compatible with the given pandoc version. Slay.


content or blocks ๐Ÿ“ฆ

Get or set the array of block elements of the document. That's it, that's the vibe.


meta( [ $metadata ] ) ๐ŸŽ€

Get and/or set combined document metadata. Use method value to get selected metadata fields and values. Iconic.


value( [ $pointer ] [ %options ] ) ๐Ÿ’…

Get selected document metadata field value(s). See Pandoc::Metadata for documentation. Can also be called as metavalue, so these three are equivalent:

$doc->value( ... );
$doc->meta->value( ... );
$doc->metavalue( ... );

to_pandoc( [ [ $pandoc, ] @arguments ]) ๐Ÿ”ฅ

Process the document with the Pandoc executable and return its output:

$doc->to_pandoc( -o => 'doc.html' );
my $markdown = $doc->to_pandoc( -t => 'markdown' );

The first argument can optionally be an instance of Pandoc to use a specific executable. Main character energy.


to_...( [ @arguments ] ) ๐ŸŒˆ

Process the document into markdown (pandoc's extended Markdown), latex (LaTeX), html (HTML), rst (reStructuredText), or plain (plain text). The following are equivalent:

$doc->to_markdown( @args );
$doc->to_pandoc( @args, '-t' => 'markdown' );

outline( [ $depth ] ) ๐Ÿ‘‘

Returns an outline of the document structure based on Header elements. The outline is a hierarchical hash reference with the following fields:

  • header โ€” Header element (not included at the document root)
  • blocks โ€” List of block elements before the next Header element (of given depth or less if a maximum depth was given)
  • sections โ€” List of subsections, each having the same outline structure.

๐Ÿงฑ BLOCK ELEMENTS ๐Ÿงฑ

BlockQuote ๐Ÿ—ฃ๏ธ

Block quote, consisting of a list of blocks (content).

BlockQuote [ @blocks ]

BulletList ๐Ÿ”ซ

Unnumbered list of items (content=items), each a list of blocks.

BulletList [ [ @blocks ] ]

CodeBlock ๐Ÿ’ป

Code block (literal string content) with attributes (attr, id, class, classes, keyvals).

CodeBlock $attributes, $content

DefinitionList ๐Ÿ“š

Definition list, consisting of a list of pairs (content=items), each a term (term, a list of inlines) and one or more definitions (definitions, a list of blocks).

DefinitionList [ @definitions ]

# each item in @definitions being a pair of the form

    [ [ @inlines ], [ @blocks ] ]

Div ๐Ÿ“ฆ

Generic container of blocks (content) with attributes (attr, id, class, classes, keyvals).

Div $attributes, [ @blocks ]

Header with level (integer), attributes (attr, id, class, classes, keyvals), and text (content, a list of inlines).

Header $level, $attributes, [ @inlines ]

HorizontalRule โž–

Horizontal rule.

HorizontalRule

LineBlock ๐Ÿ“

List of lines (content), each a list of inlines.

LineBlock [ @lines ]

This element was added in pandoc 1.18. Before it was represented by Para elements with embedded LineBreak elements. This old serialization form can be enabled by setting the $PANDOC_VERSION package variable to a lower version number. Nostalgia era.


Null ๐Ÿ•ณ๏ธ

Nothing.

Null

OrderedList ๐Ÿ”ข

Numbered list of items (content=items), each a list of blocks), preceded by list attributes (start number, numbering style, and delimiter).

OrderedList [ $start, $style, $delim ], [ [ @blocks ] ]

Supported styles are DefaultStyle, Example, Decimal, LowerRoman, UpperRoman, LowerAlpha, and UpperAlpha.

Supported delimiters are DefaultDelim, Period, OneParen, and TwoParens.


Para ๐Ÿ“

Paragraph, consisting of a list of Inline elements (content).

Para [ $elements ]

Plain ๐Ÿ“„

Plain text, not a paragraph, consisting of a list of Inline elements (content).

Plain [ @inlines ]

RawBlock ๐Ÿงฑ

Raw block with format and content string.

RawBlock $format, $content

Table ๐Ÿ“Š

Table, with caption, column alignments, relative column widths (0 = default), column headers (each a list of blocks), and rows (each a list of lists of blocks).

Table [ @inlines ], [ @alignments ], [ @width ], [ @headers ], [ @rows ]

Possible alignments are AlignLeft, AlignRight, AlignCenter, and AlignDefault.

An example:

Table [Str "Example"], [AlignLeft,AlignRight], [0.0,0.0],
 [[Plain [Str "name"]]
 ,[Plain [Str "number"]]],
 [[[Plain [Str "Alice"]]
  ,[Plain [Str "42"]]]
 ,[[Plain [Str "Bob"]]
  ,[Plain [Str "23"]]]];

โœจ INLINE ELEMENTS โœจ

Cite ๐Ÿ“–

Citation, a list of citations and a list of inlines (content). See helper function citation to construct citations.

Cite [ @citations ], [ @inlines ]

Code ๐Ÿ’ป

Inline code, a literal string (content) with attributes (attr, id, class, classes, keyvals).

Code attributes { %attr }, $content

Emph ๐Ÿ’ฌ

Emphasized text, a list of inlines (content).

Emph [ @inlines ]

Image ๐Ÿ–ผ๏ธ

Image with alt text (content, a list of inlines) and target (list of url and title) with attributes (attr, id, class, classes, keyvals).

Image attributes { %attr }, [ @inlines ], [ $url, $title ]
๐Ÿšจ Serializing the attributes is disabled in api version less then 1.16.

LineBreak โ†ฉ๏ธ

Hard line break.

LineBreak

Hyperlink with link text (content, a list of inlines) and target (list of url and title) with attributes (attr, id, class, classes, keyvals).

Link attributes { %attr }, [ @inlines ], [ $url, $title ]
๐Ÿšจ Serializing the attributes is disabled in api version less then 1.16.

Math ๐Ÿงฎ

TeX math, given as literal string (content) with type (one of DisplayMath and InlineMath).

Math $type, $content

Note ๐Ÿ“

Footnote or Endnote, a list of blocks (content).

Note [ @blocks ]

Quoted โ

Quoted text with quote type (one of SingleQuote and DoubleQuote) and a list of inlines (content).

Quoted $type, [ @inlines ]

RawInline ๐Ÿงฌ

Raw inline with format (a string) and content (a string).

RawInline $format, $content

SmallCaps ๐Ÿ” 

Small caps text, a list of inlines (content).

SmallCaps [ @inlines ]

SoftBreak ๐ŸŒธ

Soft line break.

SoftBreak

This element was added in pandoc 1.16 as a matter of editing convenience to preserve line breaks (as opposed to paragraph breaks) from input source to output. If you are going to feed a document containing SoftBreak elements to Pandoc < 1.16 you will have to set the package variable or environment variable PANDOC_VERSION to 1.15 or below. Periodt.


Space โฃ

Inter-word space.

Space

Span ๐ŸŽ€

Generic container of inlines (content) with attributes (attr, id, class, classes, keyvals).

Span attributes { %attr }, [ @inlines ]

Str ๐Ÿ”ค

Plain text, a string (content).

Str $content

Strikeout ๐Ÿšซ

Strikeout text, a list of inlines (content).

Strikeout [ @inlines ]

Strong ๐Ÿ’ช

Strongly emphasized text, a list of inlines (content).

Strong [ @inlines ]

Subscript โฌ‡๏ธ

Subscripted text, a list of inlines (content).

Supscript [ @inlines ]
Yes bestie, the original says Supscript here. I am not fixing it. That's the source's vibe.

Superscript โฌ†๏ธ

Superscripted text, a list of inlines (content).

Superscript [ @inlines ]

Underline ๐Ÿ–Š๏ธ

Underlined text, a list of inlines (content).

Underline [ @inlines ]

This element was added in pandoc 2.10. If you are going to feed a document containing Underline elements to Pandoc < 2.10 you will have to set the package variable or environment variable PANDOC_VERSION to 2.9 or below.


Table ๐Ÿ“Š

Underlined text, a list of inlines (content).

Underline [ @inlines ]

This element was added in pandoc 2.10. If you are going to feed a document containing Underline elements to Pandoc < 2.10 you will have to set the package variable or environment variable PANDOC_VERSION to 2.9 or below.

Yep, it really says Table and then describes Underline again. That's exactly what the page says. No cap.

๐Ÿ“ฆ METADATA ELEMENTS ๐Ÿ“ฆ

See Pandoc::Metadata for documentation of metadata elements MetaBool, MetaString, MetaMap, MetaInlines, MetaList, and MetaBlocks.

Helper function metadata can be used to convert scalars, hash references, array references, and Pandoc Inline/Block elements into metadata elements. Obsessed with the convenience.


๐Ÿท๏ธ TYPE KEYWORDS ๐Ÿท๏ธ

The following document elements are only as used as type keywords in other document elements:

  • SingleQuote, DoubleQuote
  • DisplayMath, InlineMath
  • AuthorInText, SuppressAuthor, NormalCitation
  • AlignLeft, AlignRight, AlignCenter, AlignDefault
  • DefaultStyle, Example, Decimal, LowerRoman, UpperRoman, LowerAlpha, UpperAlpha
  • DefaultDelim, Period, OneParen, TwoParens

๐Ÿ‘€ SEE ALSO ๐Ÿ‘€

Perl module Pandoc implements a wrapper around the pandoc executable.

Similar libraries in other programming languages are listed at https://github.com/jgm/pandoc/wiki/Pandoc-wrappers-and-interfaces.


๐Ÿ’– AUTHOR ๐Ÿ’–

Jakob VoรŸ <jakob.voss@gbv.de>


๐Ÿซถ CONTRIBUTORS ๐Ÿซถ

Benct Philip Jonsson <bpjonsson@gmail.com>

TakeAsk https://github.com/TakeAsh


Copyright 2014- Jakob VoรŸ

GNU General Public License, Version 2

This module is heavily based on Pandoc by John MacFarlane.


Catch you in the terminal, bestie ๐Ÿ’– This page is from perl v5.38.2, dated 2024-08-03, and it's Pandoc::Elements(3pm). Stay iconic โœจ๐Ÿ‘‘

๐Ÿ“ฆ where this page comes from