まばらなドキュメントには次のように記載されています。
外部スタイルシートを使用したくない場合は、キーが CSS クラス (通常はトークン名と一致) で値が colors であるハッシュ参照として色を指定できます。
PPI::HTML::CodeFolderの POD には、使用できるクラス名のリストがあり、例として次の色が示されています。
cast => '#339999',
comment => '#008080',
core => '#FF0000',
double => '#999999',
heredoc_content => '#FF0000',
interpolate => '#999999',
keyword => '#0000FF',
line_number => '#666666',
literal => '#999999',
magic => '#0099FF',
match => '#9900FF',
number => '#990000',
operator => '#DD7700',
pod => '#008080',
pragma => '#990000',
regex => '#9900FF',
single => '#999999',
substitute => '#9900FF',
transliterate => '#9900FF',
word => '#999999',
次のコードは、指定されたスタイルを使用してスタイル設定された独自のソース コードを含む自己完結型の HTML ページを生成します。
#!/usr/bin/env perl
use strict;
use warnings;
use PPI;
use PPI::HTML;
my %colors = (
cast => '#339999',
comment => '#008080',
core => '#FF0000',
double => '#999999',
heredoc_content => '#FF0000',
interpolate => '#999999',
keyword => '#0000FF',
line_number => '#666666',
literal => '#999999',
magic => '#0099FF',
match => '#9900FF',
number => '#990000',
operator => '#DD7700',
pod => '#008080',
pragma => '#990000',
regex => '#9900FF',
single => '#999999',
substitute => '#9900FF',
transliterate => '#9900FF',
word => '#999999'
);
my $highlighter = PPI::HTML->new(page => 1, line_numbers => 1, colors => \%colors);
my $perl_doc = PPI::Document->new(
do {
local $/;
open 0;
\ <0>;
}
);
print $highlighter->html($perl_doc);
コンストラクターでこのオプションを使用しない場合page => 1
、CSS を含まない HTML フラグメントのみが取得されます。その場合、サイトのスタイルシートに必要なスタイルを含める必要があります。
一方、HTML::TokeParser::Simpleを使用して、HTML フラグメントを単純に後処理することもできます。
#!/usr/bin/env perl
use strict;
use warnings;
use PPI;
use PPI::HTML;
use HTML::TokeParser::Simple;
my %colors = (
# as above
);
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;
}
ちなみに、これは「自己完結型の例」です。つまり、何の苦労もせずに実行できる例です。のコンテンツの生成を支援しようとしている人々に任せたため、プログラムを実行できませんでした$perl_block
。