NAME

CommonMark::Massage - Manipulate CommonMark AST

SYNOPSIS

use CommonMark qw(:node :event);
use CommonMark::Massage;

my $parser = CommonMark::Parser->new;
$parser->feed("Hello world");
my $doc = $parser->finish;

# Apply function to exit event of text nodes.
my $doc->massage ( { NODE_TEXT =>
                     { EVENT_EXIT => sub { ... } } } );
$doc->render_html;

DESCRIPTION

The massage function can be used to manipulate the AST as produced by the CommonMark parsers.

METHODS

The methods are defined in the CommonMark::Node namespace, so they can be applied to the result of parsing.

massage

One argument: a hash ref of node names, each containing a hashref of events that point to a subroutine. For example:

{ NODE_TEXT => { EVENT_EXIT => \&fixit } }

The subroutine is called with two arguments, the doc tree and the node.

It is free to do whatever it wants, but caveat emptor.

See EXAMPLES for some example routines.

reveal

This method dumps the AST nodes/events for entertainment and debugging.

The result is returned as a string.

EXAMPLES

This example manipulates links. Normally a link is rendered as

<a href="uri">text</a>

After massaging with

$doc->massage( { NODE_LINK => { EVENT_EXIT => \&fixlink } } )

this will become for non-local links:

<a href="http://www.example.com" target="_blank">text</a>

This is the subroutine

    sub fixlink {
	my ( $doc, $node ) = @_;
        # Get the link and title.
	my $link = $node->get_url // "";
	my $title = $node->get_title // "";

	# Create a new custom node.
	my $n = CommonMark::Node->new(NODE_CUSTOM_INLINE);

	# The replacement 'enter' text.
	my $enter = "<a href=\"$link\"";
	$enter .= " title=\"$title\"" if $title;
	$enter .= " target=\"_blank\"" if $link =~ /^\w+:\/\//;
	$enter .= ">";
	$n->set_on_enter($enter);

	# The 'exit' text.
	$n->set_on_exit("</a>" );

	# NODE_LINK has a single child, copy it to the new node.
	my $t = $node->first_child;
	$n->append_child($t);
	$t->unlink;

	# Replace the LINK node by the CUSTOM node.
	$node->replace($n);
    }

AUTHOR

Johan Vromans, <JV at cpan.org>

SUPPORT AND DOCUMENTATION

Development of this module takes place on GitHub: https://github.com/sciurius/perl-CommonMark-Massage.

You can find documentation for this module with the perldoc command.

perldoc CommonMark::Massage

Please report any bugs or feature requests using the issue tracker on GitHub.

SEE ALSO

CommonMark

COPYRIGHT & LICENSE

Copyright 2020 Johan Vromans, all rights reserved.

This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.