NAME

Pandoc::Walker - utility functions to traverse Pandoc documents

SYNOPSIS

use Pandoc::Walker;
use Pandoc::Elements qw(pandoc_json);

my $ast = pandoc_json(<>);

# extract all links and image URLs
my $links = query $ast, 'Link|Image' => sub { $_[0]->url };

# print all links and image URLs
walk $ast, 'Link|Image' => sub { say $_[0]->url };

# remove all links
transform $ast, sub {
    return ($_[0]->name eq 'Link' ? [] : ());
};

# replace all links by their link text angle brackets
use Pandoc::Elements 'Str';
transform $ast, Link => sub {
    return (Str "<", $_[0]->content->[0], Str ">");
};

DESCRIPTION

This module provides to helper functions to traverse the abstract syntax tree (AST) of a pandoc document (see Pandoc::Elements for documentation of AST elements).

Document elements are passed to action functions by reference, so don't shoot yourself in the foot by trying to directly modify the element. Traversing a single element is not reliable neither, so put the element in an array reference if needed. For instance to replace links in headers only by their link text content:

transform $ast, Header => sub {
    transform [ $_[0] ], Link => sub { # make an array
        return $_[0]->content;         # is an array
    };
};

See also Pandoc::Filter for an object oriented interface to transformations.

FUNCTIONS

walk( $ast, [ $names => ] $action [, @arguments ] )

walk( $ast, \%actions [, @arguments ] )

Walks an abstract syntax tree and calls an action on every element or every element of given name(s). Additional arguments are also passed to the action.

query( $ast, [ $names => ] $query [, @arguments ] )

query( $ast, \%queries [, @arguments ] )

Walks an abstract syntax tree and applies one or multiple query functions to extract results. The query function is expected to return a list. The combined query result is returned as array reference. For instance the stringify method of Pandoc::Elements is implemented as following:

join '', @{ 
    query( $ast, { 
        'Str|Code|Math'   => sub { $_[0]->content },
        'LineBreak|Space' => sub { ' ' } 
    } );

transform( $ast [ $names => ] $action [, @arguments ] )

transform( $ast, \%actions [, @arguments ] )

Walks an abstract syntax tree and applies an action on every element, or every element of given name(s), to either keep it (if the action returns undef), remove it (if it returns an empty array reference), or replace it with one or more elements (returned by array reference or as single value).

COPYRIGHT AND LICENSE

Copyright 2014- Jakob Voß

GNU General Public License, Version 2

This module is heavily based on Pandoc by John MacFarlane.

SEE ALSO

Haskell module Text.Pandoc.Walk for the original.