ikiwiki (3.20130711) unstable; urgency=low
[ikiwiki.git] / IkiWiki / Plugin / headinganchors.pm
1 #!/usr/bin/perl
2 # quick HTML heading id adder by Paul Wise
3 package IkiWiki::Plugin::headinganchors;
4
5 use warnings;
6 use strict;
7 use IkiWiki 3.00;
8 use URI::Escape;
9
10 sub import {
11         hook(type => "getsetup", id => "headinganchors", call => \&getsetup);
12         hook(type => "sanitize", id => "headinganchors", call => \&headinganchors);
13 }
14
15 sub getsetup () {
16         return
17                 plugin => {
18                         safe => 1,
19                         rebuild => undef,
20                         section => "widget",
21                 },
22 }
23
24 sub text_to_anchor {
25         my $str = shift;
26         $str =~ s/^\s+//;
27         $str =~ s/\s+$//;
28         $str =~ s/\s/_/g;
29         $str =~ s/"//g;
30         $str =~ s/^[^a-zA-Z]/z-/; # must start with an alphabetical character
31         $str = uri_escape_utf8($str);
32         $str =~ s/%/./g;
33         return $str;
34 }
35
36 sub headinganchors (@) {
37         my %params=@_;
38         my $content=$params{content};
39         $content=~s{<h([0-9])>([^>]*)</h([0-9])>}{'<h'.$1.' id="'.text_to_anchor($2).'">'.$2.'</h'.$3.'>'}gie;
40         return $content;
41 }
42
43 1