Don't attempt to syntax highlight anything big.
[catagits/Gitalist.git] / lib / Gitalist / View / SyntaxHighlight.pm
CommitLineData
7e54e579 1package Gitalist::View::SyntaxHighlight;
2use Moose;
7e54e579 3use namespace::autoclean;
4
5extends 'Catalyst::View';
6
7use Syntax::Highlight::Engine::Kate ();
8use Syntax::Highlight::Engine::Kate::Perl ();
9
c8870bd3 10use HTML::Entities qw(encode_entities);
11
7e54e579 12sub process {
13 my($self, $c) = @_;
c8870bd3 14
b2e0fe31 15 $c->res->body($self->render($c, $c->res->body, $c->stash));
f5da8e7a 16}
17
8deaad58 18sub render {
19 my ($self, $c, $blob, $args) = @_;
21ede19a 20
21 # Don't bother with anything over 64kb, it'll be tragically slow.
22 return encode_entities $blob if length $blob > 8192;
8deaad58 23
24 my $lang = $args->{language};
f5da8e7a 25
6cf4366a 26 my $ret;
f5da8e7a 27 if($lang) {
6cf4366a 28 # via http://github.com/jrockway/angerwhale/blob/master/lib/Angerwhale/Format/Pod.pm#L136
29 $ret = eval {
c8870bd3 30 no warnings 'redefine';
31 local *Syntax::Highlight::Engine::Kate::Template::logwarning
32 = sub { die @_ }; # i really don't care
33 my $hl = Syntax::Highlight::Engine::Kate->new(
f5da8e7a 34 language => $lang,
c8870bd3 35 substitutions => {
36 "<" => "&lt;",
37 ">" => "&gt;",
38 "&" => "&amp;",
39 q{'} => "&apos;",
40 q{"} => "&quot;",
41 },
42 format_table => {
43 # convert Kate's internal representation into
44 # <span class="<internal name>"> value </span>
45 map {
46 $_ => [ qq{<span class="$_">}, '</span>' ]
47 }
48 qw/Alert BaseN BString Char Comment DataType
49 DecVal Error Float Function IString Keyword
50 Normal Operator Others RegionMarker Reserved
51 String Variable Warning/,
52 },
53 );
54
4621ecf0 55 my $hltxt = $hl->highlightText($blob);
56 $hltxt =~ s/([^[:ascii:]])/encode_entities($1)/eg;
57 $hltxt;
c8870bd3 58 };
59 warn $@ if $@;
c8870bd3 60 }
6cf4366a 61
62 return $ret || encode_entities($blob);
7e54e579 63}
64
1ef8dc7d 65__PACKAGE__->meta->make_immutable;
775e96e0 66
67__END__
68
69=head1 NAME
70
71Gitalist::View::SyntaxHighlight - Responsible for syntax highlighting code
72
73=head1 DESCRIPTION
74
75Catalyst View for Syntax highlighting.
76
d137f7d5 77=head1 METHODS
78
79=head2 process
80
81=head2 highlight
82
775e96e0 83=head1 AUTHORS
84
85See L<Gitalist> for authors.
86
87=head1 LICENSE
88
89See L<Gitalist> for the license.
90
91=cut