]> Lady’s Gitweb - Gitweb/blobdiff - gitweb.perl
gitweb: Introduce esc_html_match_hl and esc_html_hl_regions
[Gitweb] / gitweb.perl
index 4c4e2d02b5e9f139653d56cc5033603d65c5c08cd5ff1b761166a8ef60845f21..3398de3323bfa232e49bebacab5e9b6fa0eb3b5f43591064aa3c68f4d208aa89 100755 (executable)
@@ -1716,6 +1716,47 @@ sub chop_and_escape_str {
        }
 }
 
+# Highlight selected fragments of string, using given CSS class,
+# and escape HTML.  It is assumed that fragments do not overlap.
+# Regions are passed as list of pairs (array references).
+#
+# Example: esc_html_hl_regions("foobar", "mark", [ 0, 3 ]) returns
+# '<span class="mark">foo</span>bar'
+sub esc_html_hl_regions {
+       my ($str, $css_class, @sel) = @_;
+       return esc_html($str) unless @sel;
+
+       my $out = '';
+       my $pos = 0;
+
+       for my $s (@sel) {
+               $out .= esc_html(substr($str, $pos, $s->[0] - $pos))
+                       if ($s->[0] - $pos > 0);
+               $out .= $cgi->span({-class => $css_class},
+                                  esc_html(substr($str, $s->[0], $s->[1] - $s->[0])));
+
+               $pos = $s->[1];
+       }
+       $out .= esc_html(substr($str, $pos))
+               if ($pos < length($str));
+
+       return $out;
+}
+
+# highlight match (if any), and escape HTML
+sub esc_html_match_hl {
+       my ($str, $regexp) = @_;
+       return esc_html($str) unless defined $regexp;
+
+       my @matches;
+       while ($str =~ /$regexp/g) {
+               push @matches, [$-[0], $+[0]];
+       }
+       return esc_html($str) unless @matches;
+
+       return esc_html_hl_regions($str, 'match', @matches);
+}
+
 ## ----------------------------------------------------------------------
 ## functions returning short strings
 
This page took 0.218569 seconds and 4 git commands to generate.