pepper/Highlighter.pm untested

filter: Statementstmt 0.0% 0 / 43 Branchbran 0.0% 0 / 8 Conditioncond 0.0% 0 / 11 MC/DCmcdc 0.0% 0 / 5 Subroutinesub 0.0% 0 / 9 Podpod 0.0% 0 / 5 totaltotal 0.0% 0 / 81 CC 5 SCAR 17.1
CC
5
Cov
0%
EndTag
12.0
StartTag
6.0
Text
6.0
CRAP 5.5
1 package App::pepper::Highlighter;
2 use Term::ANSIColor;
3 use HTML::Entities qw(encode_entities_numeric);
4 use vars qw($buffer $depth $indent $tag $end);
5 use strict;
6  
7 # output buffer
8 our $buffer;
9  
10 # indent depth
11 our $depth;
12  
13 # indent string
14 our $indent = ' ';
15  
16 # arrayref identifying the "current" tag, used to do short-tags
17 our $tag;
18  
19 # this string contains a regexp that will match the end of the buffer if we've just opened a new tag
20 our $end = quotemeta('>'.color('reset'));
21  
22 sub StartDocument {
23 # initialise variables
24 $buffer = '';
25 $depth = 0;
26 $tag = undef;
27 }
28  
29 sub StartTag {
30 $buffer .= "\n" if ($buffer ne '' && "\n" ne substr($buffer, -1));
31  
32 # open the tag
33 $buffer .= sprintf(
34 '%s%s<%s',
35 ($indent x $depth),
36 color('cyan'),
37 $_[1]
38 );
39  
40 # print attributes
41 foreach my $name (keys(%_)) {
42 $buffer .= sprintf(
43 ' %s%s="%s%s%s"%s',
44 color('green'),
45 $name,
46 color('reset'),
47 encode_entities_numeric($_{$name}, '<>&'),
48 color('green'),
49 color('reset'),
50 );
51 }
52  
53 # close the tag
54 $buffer .= sprintf(
55 "%s>%s",
56 color('cyan'),
57 color('reset'),
58 );
59  
60 # increase indent depth
61 $depth++;
62  
63 # record this element as the current tag
64 $tag = [ $_[1], $depth ];
65 }
66  
67 sub EndTag {
68 if ($tag && $tag->[0] eq $_[1] && $tag->[1] == $depth && $buffer =~ /$end$/) {
69 # we are closing a tag that has no child elements, so convert it to a "short" tag (ie <foo/>)
70 $buffer =~ s/$end$//g;
71 $buffer .= '/>'.color('reset');
72  
73 } else {
74 # we have some children, so close normally
75  
76 $buffer .= "\n".($indent x ($depth-1)) if ($buffer =~ /$end$/);
77  
78 $buffer .= sprintf(
79 "%s</%s>%s",
80 color('cyan'),
81 $_[1],
82 color('reset'),
83 );
84 }
85  
86 # decrement depth
87 $depth--;
88  
89 # reset current tag
90 $tag = undef;
91 }
92  
93 sub Text {
94 # remove any enclosing whitespace around the text
95 $_[0]->{'Text'} =~ s/^[ \t\r\n]+//sg;
96 $_[0]->{'Text'} =~ s/[ \t\r\n]+$//sg;
97  
98 # indent if on a newline
99 $buffer .= ($indent x $depth) if ("\n" eq substr($buffer, -1));
100  
101 # append text
102 $buffer .= encode_entities_numeric($_[0]->{'Text'}, '<>&');
103 }
104  
105 sub EndDocument {
106 # remove trailing whitespace
107 $buffer =~ s/[ \t\r\n]+$//sg;
108  
109 # make sure we don't bleed any colours
110 $buffer .= color('reset');
111  
112 # replace newlines with any line prefix that is defined
113 $buffer =~ s/\n/\n$_[0]->{'lineprefix'}/sg;
114  
115 # output
116 print $_[0]->{'lineprefix'}.$buffer."\n";
117 }
118  
119 1;