blib/lib/Search/Tools/HiLiter.pm

filter: Statementstmt 77.7% 7 / 9 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 3 / 3 Podpod n/a totaltotal 83.3% 10 / 12 SCAR 0.1
CC
1
Cov
78%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« blib/lib/Search/Tools/Query.pm ↑ Summary blib/lib/Search/Tools/XML.pm »
1 package Search::Tools::HiLiter;
2 4 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 extends 'Search::Tools::Object';
4 with 'Search::Tools::ArgNormalizer';
5 4 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 4 ▶use Search::Tools::Tokenizer;
Subroutine BEGIN: called CC=1 SCAR=2.6
7 use Search::Tools::XML;
8 use Search::Tools::UTF8;
9 use Data::Dump qw( dump );
10  
11 use namespace::autoclean;
12  
13 our $VERSION = '1.004';
14  
15 my $XML = Search::Tools::XML->new;
16  
17 my @attrs = qw(
18 query
19 tag
20 class
21 style
22 text_color
23 colors
24 tty
25 ttycolors
26 no_html
27 );
28  
29 for my $attr (@attrs) {
30 has $attr => ( is => 'rw' );
31 }
32  
33 sub BUILD {
34 my $self = shift;
35  
36 if ( $self->debug ) {
37 carp "debug level set at " . $self->debug;
38 }
39  
40 $self->{_tokenizer} = Search::Tools::Tokenizer->new(
41 re => $self->query->qp->term_re,
42 debug => $self->debug,
43 );
44  
45 $self->{tag} ||= 'span';
46 $self->{colors} ||= [ '#ffff99', '#99ffff', '#ffccff', '#ccccff' ];
47 $self->{ttycolors} ||= [ 'bold blue', 'bold red', 'bold green' ];
48  
49 if ( $self->tty ) {
50 eval { require Term::ANSIColor };
51 $self->tty(0) if $@;
52 }
53  
54 $self->_build_tags;
55 }
56  
57 sub terms {
58 return shift->{query}->terms;
59 }
60  
61 sub keywords {
62 return @{ shift->terms };
63 }
64  
65 sub _phrases {
66 my $self = shift;
67 my $q = $self->{query};
68 return grep { $self->_regex_for($_)->is_phrase } @{ $q->terms };
69 }
70  
71 sub _singles {
72 my $self = shift;
73 my $q = $self->{query};
74 return grep { !$self->_regex_for($_)->is_phrase } @{ $q->terms };
75 }
76  
77 sub _kworder {
78 my $self = shift;
79 my $q = $self->{query};
80 my $qstr = $q->str;
81 if ( exists $self->{_kworder_cache}->{$qstr} ) {
82 return @{ $self->{_kworder_cache}->{$qstr} };
83 }
84  
85 # do phrases first so that duplicates privilege phrases
86 my ( @phrases, @singles );
87  
88 for ( @{ $q->terms } ) {
89 if ( $self->_regex_for($_)->is_phrase ) {
90 push @phrases, $_;
91 }
92 else {
93 push @singles, $_;
94 }
95 }
96  
97 $self->{_kworder_cache}->{$qstr} = [ @phrases, @singles ];
98  
99 return ( @phrases, @singles );
100 }
101  
102 sub _build_tags {
103 my $self = shift;
104  
105 my $t = {};
106 my @colors = @{ $self->colors };
107 my @ttycolors = @{ $self->ttycolors };
108 my $tag = $self->tag;
109  
110 my $n = 0;
111 my $m = 0;
112  
113 for my $q ( $self->_kworder ) {
114  
115 # if tty flag is on, use ansicolor instead of html
116 # if debug flag is on, use both html and ansicolor
117  
118 my ( %tags, $opener );
119 $tags{open} = '';
120 $tags{close} = '';
121 if ( $self->class ) {
122 $opener = qq/<$tag class='/ . $self->class . qq/'>/;
123 }
124 elsif ( $self->style ) {
125 $opener = qq/<$tag style='/ . $self->style . qq/'>/;
126 }
127 elsif ( $self->text_color ) {
128 $opener
129 = qq/<$tag style='color:/
130 . $self->text_color
131 . qq/;background:/
132 . $colors[$n] . qq/'>/;
133 }
134 else {
135 $opener = qq/<$tag style='background:/ . $colors[$n] . qq/'>/;
136 }
137  
138 if ( $self->tty ) {
139 $tags{open} .= $opener if $self->debug && !$self->no_html;
140 $tags{open} .= Term::ANSIColor::color( $ttycolors[$m] );
141 $tags{close} .= Term::ANSIColor::color('reset');
142 $tags{close} .= "</$tag>" if $self->debug && !$self->no_html;
143 }
144 else {
145 $tags{open} .= $opener;
146 $tags{close} .= "</$tag>";
147 }
148  
149 $t->{$q} = \%tags;
150  
151 $n = 0 if ++$n > $#colors;
152 $m = 0 if ++$m > $#ttycolors;
153 }
154  
155 $self->{_tags} = $t;
156 }
157  
158 sub open_tag {
159 my $self = shift;
160 my $q = shift or croak "need query to get open_tag";
161 return $self->{_tags}->{$q}->{open} || '';
162 }
163  
164 sub close_tag {
165 my $self = shift;
166 my $q = shift or croak "need query to get close_tag";
167 return $self->{_tags}->{$q}->{close} || '';
168 }
169  
170 sub light {
171 my $self = shift;
172 my $text = shift or return '';
173  
174 # force upgrade. this is so regex will match ok.
175 $text = to_utf8($text);
176  
177 if ( $XML->looks_like_html($text) && !$self->no_html ) {
178  
179 #warn "running ->html";
180 if ( $self->query->qp->stemmer ) {
181 return $self->html_stemmer($text);
182 }
183 return $self->html($text);
184 }
185 else {
186  
187 #warn "running ->plain";
188 if ( $self->query->qp->stemmer ) {
189 return $self->plain_stemmer($text);
190 }
191 return $self->plain($text);
192 }
193 }
194  
195 *hilite = \&light;
196  
197 sub _get_real_html {
198 my $self = shift;
199 my $text = shift;
200 my $re = shift;
201 my $m = {};
202 my $debug = $self->debug > 1 ? 1 : 0;
203  
204 # $1 should be st_bound, $2 should be query, $3 should be end_bound
205 # N.B. The XS version of this algorithm is only a hair faster,
206 # since the $re is the bottleneck.
207 while ( $$text =~ m/$re/g ) {
208  
209 my $pos = pos($$text);
210  
211 if ($debug) {
212 carp "$2 matches $re";
213 carp "\$1='$1'\n\$2='$2'\n\$3='$3'\npos=$pos";
214 }
215  
216 $m->{$2}++;
217  
218 # move back and consider $3 again as possible $1 for next match
219 if ( length($3) ) {
220 pos($$text) = $pos - 1;
221 }
222  
223 }
224  
225 return $m;
226  
227 }
228  
229 sub _regex_for {
230 my $self = shift;
231 my $term = shift or croak "term required";
232 if ( exists $self->{_regex_for}->{$term} ) {
233 return $self->{_regex_for}->{$term};
234 }
235 $self->{_regex_for}->{$term} = $self->query->regex_for($term);
236 return $self->{_regex_for}->{$term};
237 }
238  
239 # based on HTML::HiLiter hilite()
240 sub html {
241 my $self = shift;
242 my $text = shift or croak "need text to light()";
243  
244 ###################################################################
245 # 1. create hash of query -> [ array of real HTML to hilite ]
246 # using the prebuilt regexp
247 # 2. hilite the real HTML
248 ###################################################################
249  
250 ## 1
251  
252 my $q2real = {};
253  
254 # this is going to be query => [ real_html ]
255  
256 # if the query text matched in the text, then we need to
257 # use our prebuilt regexp
258 my @kworder = $self->_kworder;
259  
260 # don't consider anything we've marked
261 # with a 'nohiliter' attribute
262 my $text_copy = $text;
263 $text_copy =~ s/\002.*?\003//sgi;
264  
265 Q: for my $query (@kworder) {
266 my $re = $self->_regex_for($query)->html;
267 my $real = $self->_get_real_html( \$text_copy, $re );
268  
269 R: for my $r ( keys %$real ) {
270 push( @{ $q2real->{$query} }, $r ) while $real->{$r}--;
271 }
272 }
273  
274 ## 2
275  
276 HILITE: for my $q (@kworder) {
277  
278 my %uniq_reals = ();
279 $uniq_reals{$_}++ for @{ $q2real->{$q} };
280  
281 REAL: for my $real ( keys %uniq_reals ) {
282  
283 $self->_add_hilite_tags( \$text, $q, $real );
284  
285 }
286  
287 }
288  
289 return $text;
290 }
291  
292 sub _add_hilite_tags {
293 my $self = shift;
294 my $text = shift; # reference
295 my $query = shift;
296 my $html = shift;
297  
298 # $text is reference to original text
299 # $html is the real html that matched our regexp
300  
301 # we still check boundaries just to be safe
302 my $st_bound = $self->query->qp->start_bound;
303 my $end_bound = $self->query->qp->end_bound;
304  
305 my $o = $self->open_tag($query);
306 my $c = $self->close_tag($query);
307  
308 my $safe = quotemeta($html);
309  
310 # pre-fix nested tags in match
311 my $pre_fixed = $html;
312 my $tag_re = $self->query->qp->tag_re;
313 my $pre_added = $pre_fixed =~ s(${tag_re}+)$c$1$og;
314 my $len_added = length( $c . $o ) * $pre_added;
315  
316 # should be same as length( $to_hilite) - length( $prefixed );
317 my $len_diff = ( length($html) - length($pre_fixed) );
318 $len_diff *= -1
319 if $len_diff < 0; # pre_added might be -1 if no subs were made
320 if ( $len_diff != $len_added ) {
321 carp "length math failed!"
322 . "len_diff = $len_diff\nlen_added = $len_added";
323 }
324  
325 while ( $$text =~ m/($st_bound)($safe)($end_bound)/g ) {
326 my $s = $1;
327 my $m = $2;
328 my $e = $3;
329 if ( $self->debug > 1 ) {
330 carp "matched:\n'$s'\n'$m'\n'$e'\n"
331 . "\$1 is "
332 . ord($s)
333 . "\$3 is "
334 . ord($e);
335 }
336  
337 # use substr to do what s// would normally do if pos() wasn't an issue
338 # -- is this a big speed hit?
339 my $len = length( $s . $m . $e );
340 my $pos = pos($$text);
341 my $newstring = $s . $o . $pre_fixed . $c . $e;
342 substr( $$text, $pos - $len, $len, $newstring );
343  
344 pos($$text) = $pos + length( $o . $c ) + $len_added - 1;
345  
346 # adjust for new text added
347 # $pre_fixed is the hard bit, since we must take $len_added into account
348 # move back 1 to reconsider $3 as next $1
349  
350 # warn "pos was $pos\nnow ", pos( $html ), "\n";
351 # warn "new: '$html'\n";
352 # warn "new text: '$newstring'\n";
353 # warn "first chars of new pos are '", substr( $html, pos($html), 10 ), "'\n";
354  
355 }
356  
357 $self->_clean_up_hilites( $text, $query, $o, $c, $safe );
358  
359 }
360  
361 # no algorithm is perfect. fix it as best we can.
362 sub _clean_up_hilites {
363  
364 my $self = shift;
365 my ( $text, $query, $o, $c, $safe ) = @_;
366  
367 # empty hilites are useless
368 my $empty = ( $$text =~ s,\Q$o$c\E,,sgi ) || 0;
369  
370 #$self->debug and carp "looking for split entities: (&[\\w#]*)\Q$o\E(?:\Q$c\E)(${safe})\Q$c\E([\\w#]*;)";
371  
372 # to be safe: in some cases we might match against entities or within tag content.
373 my $ent_split = (
374 $$text
375 =~ s/(&[\w#]*)\Q$o\E(?:\Q$c\E)?(${safe})\Q$c\E([\w#]*;)/$1$2$3/igs # is i and s necessary?
376 ) || 0;
377  
378 #$self->debug and carp "found $ent_split split entities";
379  
380 my $tag_split = 0;
381 while (
382 $$text
383 =~ m/(<[^<>]*)\Q$o\E($safe)\Q$c\E([^>]*>)/gxsi # are these xsi flags necessary?
384 )
385 {
386  
387 my $first = $1;
388 my $second = $2;
389 my $third = $3;
390 carp "appears to split tag: $first - $second - $third"
391 if $self->debug > 1;
392  
393 # TODO this would be one place to highlight text where attributes match
394  
395 $tag_split += (
396 $$text =~ s/(<[^<>]*)\Q$o\E($safe)\Q$c\E([^>]*>)/$1$2$3/gxsi );
397  
398 }
399  
400 }
401  
402 sub html_stemmer {
403 my $self = shift;
404 my $text = shift;
405 return $self->plain_stemmer($text);
406 }
407  
408 sub plain_stemmer {
409 my $self = shift;
410 my $text = shift or croak "need text";
411 my $debug = $self->debug;
412  
413 my @kworder = $self->_kworder;
414  
415 # if stemmer is on, we must stem each token to look for a match
416 my $qre = $self->query->terms_as_regex(1);
417 $qre =~ s/(\\ )+/\|/g; # TODO OR phrases together if (0) above?
418  
419 my $re = qr/^$qre$/;
420 my $stemmer = $self->query->qp->stemmer;
421 my $qp = $self->query->qp;
422 my $wildcard = $qp->wildcard;
423 my $heat_seeker = sub {
424 my ($token) = @_;
425 my $st = $stemmer->( $qp, $token->str );
426 return $st =~ m/$re/;
427 };
428  
429 my $tokens = $self->{_tokenizer}->tokenize( $text, $heat_seeker );
430  
431 # create a new string
432 my $buf;
433  
434 # iterate over tokens, looking for any hot ones,
435 # and create a new string
436 TOK: while ( my $tok = $tokens->next ) {
437 my $str = $tok->str;
438 if ( $tok->is_hot ) {
439  
440 # find the matching query term
441  
442 my $stemmed = $stemmer->( $qp, $str );
443 my $found_match = 0;
444 Q: for my $query (@kworder) {
445 my $regex = $self->_regex_for($query);
446 my @regex_to_try;
447  
448 # if it is a phrase, try each term in the phrase
449 if ( $regex->is_phrase ) {
450 @regex_to_try = @{ $regex->phrase_terms };
451 }
452 else {
453 @regex_to_try = ($regex);
454 }
455 REGEX: for my $r (@regex_to_try) {
456 my $term_re = $r->term_re;
457 $debug
458 and warn
459 "testing '$stemmed' against '$query' with '$term_re'";
460 if ( $stemmed =~ m/$term_re/ ) {
461 my $open = $self->open_tag($query);
462 my $close = $self->close_tag($query);
463 $debug and warn "$str is hot with match '$query'";
464 $str = $open . $str . $close;
465 $found_match = 1;
466 last Q;
467 }
468  
469 }
470 }
471  
472 if ( !$found_match ) {
473  
474 # common case is phrases?
475 $debug and warn "failed to find match for '$stemmed'";
476  
477 }
478 }
479 $buf .= $str;
480 }
481 return $buf;
482 }
483  
484 # based on HTML::HiLiter plaintext()
485 sub plain {
486 my $self = shift;
487 my $text = shift or croak "need text to light()";
488 my $debug = $self->debug;
489 my $query_obj = $self->{query};
490 my @kworder = $self->_kworder;
491  
492 my $i = 0;
493 my @markers;
494 Q: for my $query (@kworder) {
495 my $regex = $self->_regex_for($query);
496 my $re = $regex->plain;
497 my $term_re = $regex->term_re;
498 my $open = $self->open_tag($query);
499 my $close = $self->close_tag($query);
500  
501 # use open/close markers rather than actual html tags
502 # because we do not want to get double matches on text
503 # like 'span' or 'style'
504 my $o = chr($i) . "\002";
505 my $c = chr($i) . "\003";
506 my $length_we_add = length( $o . $c ) - 1;
507 push @markers, [ $open, $close ];
508  
509 # cache this
510 my $query_re = $self->{_compiled_query_regex}->{"$query"}
511 || quotemeta($query);
512 if ( !$self->{_compiled_query_regex}->{"$query"} ) {
513 $self->{_compiled_query_regex}->{"$query"} = qr/$query_re/;
514 }
515  
516 $debug > 1
517 and carp
518 "plain hiliter looking for: $re against '$query' in '$text'";
519  
520 # because s/// fails to find duplicate instances like 'foo foo'
521 # we use a while loop and increment pos()
522  
523 # this can suck into an infinite loop because increm pos()-- results
524 # in repeated match on nonwordchar: > (since we just added a tag)
525  
526 if ($debug) {
527 if ( $text =~ m/\b$query_re\b/i && $text !~ m/$re/i ) {
528 my ($snip) = ( $text =~ m/(.....$query_re.....)/gi );
529 croak "bad regex for '$query' [$snip]: $re";
530 }
531 }
532  
533 my $found_matches = 0;
534 while ( $text =~ m/$re/g ) {
535  
536 my $s = $1 || '';
537 my $m = $2 || $query;
538 my $e = $3 || '';
539  
540 $found_matches++;
541  
542 $debug > 1 and carp "matched $s $m $e against $re";
543  
544 # use substr to do what s/// would normally do
545 # if pos() wasn't an issue -- is this a big speed diff?
546 my $len = length( $s . $m . $e );
547 my $pos = pos($text);
548 $debug > 1 and carp "pos==$pos len==$len";
549 my $newstring = $s . $o . $m . $c . $e;
550 substr( $text, $pos - $len, $len, $newstring );
551  
552 last if $pos == length $text;
553  
554 # need to account for all the new chars we just added
555 pos($text) = $pos + $length_we_add;
556 $debug > 1
557 and carp "length_we_add==$length_we_add pos==" . pos($text);
558  
559 }
560  
561 $debug and warn "found $found_matches matches";
562  
563 # sanity check similar to Snipper->_re_snip()
564 if ( $debug and !$found_matches and $text =~ m/$query_re/ ) {
565 $debug and warn "ERROR: regex failure for '$query'";
566 $text = $self->html($text);
567 }
568  
569 # increment the marker
570 $i++;
571  
572 }
573  
574 # now our markers replaced with actual tags
575 $i = 0;
576 for my $set (@markers) {
577 my $ichr = quotemeta( chr($i) );
578 $text =~ s/$ichr\002/$set->[0]/g;
579 $text =~ s/$ichr\003/$set->[1]/g;
580 $i++;
581 }
582  
583 #warn "plain done";
584  
585 return $text;
586  
587 }
588  
589 1;
590 __END__
« blib/lib/Search/Tools/Query.pm ↑ Summary blib/lib/Search/Tools/XML.pm »