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