#!/usr/bin/env perl

use strict;
use warnings;

use PPI;
use PPI::HTML;
use HTML::TokeParser::Simple;

my %colors = (
    cast => '#339999',
    comment => '#008080',
    core => '#FF0000',
    double => '#999999',
    heredoc_content => '#FF0000',
    interpolate => '#883333',
    keyword => '#0000FF',
    line_number => '#666666',
    literal => '#999999',
    magic => '#0099FF',
    match => '#9900FF',
    number => '#990000',
    operator => '#DD7700',
    pod => '#008080',
    pragma => '#990000',
    regex => '#9900FF',
    single => '#664444',
    substitute => '#9900FF',
    transliterate => '#9900FF',
    word => '#40c080',
);

my $highlighter = PPI::HTML->new(line_numbers => 0);
my $html = $highlighter->html(\ do { local $/; open 0; <0> });

print qq{<pre style="background-color:#fff;color:#000">},
      map_class_to_style($html, \%colors),
      qq{</pre>\n}
;

sub map_class_to_style {
    my $html = shift;
    my $colors = shift;

    my $parser = HTML::TokeParser::Simple->new(string => $html);
    my $out;

    while (my $token = $parser->get_token) {
        next if $token->is_tag('br');
        my $class = $token->get_attr('class');
        if ($class) {
            $token->delete_attr('class');
            if (defined(my $color = $colors->{$class})) {
                # shave off some characters if possible
                $color =~ s{
                    \A \#
                    ([[:xdigit:]])\1
                    ([[:xdigit:]])\2
                    ([[:xdigit:]])\3
                    \z
                }{#$1$2$3}x;
                $token->set_attr(style => "color:$color");
            }
        }
        $out .= $token->as_is;
    }
    $out;
}