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