new version of the ikiwiki vim plugin. docs upgraded. new forum post
[ikiwiki] / doc / plugins / contrib / headinganchors.mdwn
1 [[!template id=plugin name=headinganchors author="[[PaulWise]]"]]
2 [[ikiwiki/directive/cosa]]
3
4 This is a simple plugin to add ids (which will serve as [[anchor]]s) to all headings, based on their text. It
5 works as a postprocessing filter, allowing it to work on mdwn, wiki, html,
6 rst and any other format that produces html. The code is available here:
7
8         #!/usr/bin/perl
9         # quick HTML heading id adder by Paul Wise
10         package IkiWiki::Plugin::headinganchors;
11
12         use warnings;
13         use strict;
14         use IkiWiki 2.00;
15
16         sub import {
17                 hook(type => "sanitize", id => "headinganchors", call => \&headinganchors);
18         }
19
20         sub text_to_anchor {
21                 my $str = shift;
22                 $str =~ s/^\s+//;
23                 $str =~ s/\s+$//;
24                 $str = lc($str);
25                 $str =~ s/[&\?"\'\.,\(\)!]//mig;
26                 $str =~ s/[^a-z]/_/mig;
27                 return $str;
28         }
29
30         sub headinganchors (@) {
31                 my %params=@_;
32                 my $content=$params{content};
33                 $content=~s{<h([0-9])>([^>]*)</h([0-9])>}{'<h'.$1.' id="'.text_to_anchor($2).'">'.$2.'</h'.$3.'>'}gie;
34                 return $content;
35         }
36
37         1