The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.

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 text nodes.
my $doc->massage ( { NODE_TEXT => 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, to a subroutine. For example:

{ NODE_TEXT => \&fixit }

The subroutine is called with three arguments, the doc tree, the node, and a boolean indicating whether the call is upon an EVENT_ENTER (true) or EVENT_EXIT (false).

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

See EXAMPLES and the example directory 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.