aboutsummaryrefslogtreecommitdiff
path: root/doc/plugins/contrib/headinganchors.mdwn
blob: becbf89a518daf924e38d102f60a9ce299c85dd8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
[[!template id=plugin name=headinganchors author="[[PaulWise]]"]]

This is a simple plugin to add ids (which will serve as [[anchor]]s) to all headings, based on their text. It
works as a postprocessing filter, allowing it to work on mdwn, wiki, html,
rst and any other format that produces html. The code is available here:

	#!/usr/bin/perl
	# quick HTML heading id adder by Paul Wise
	package IkiWiki::Plugin::headinganchors;

	use warnings;
	use strict;
	use IkiWiki 2.00;

	sub import {
	        hook(type => "sanitize", id => "headinganchors", call => \&headinganchors);
	}

	sub text_to_anchor {
	        my $str = shift;
	        $str =~ s/^\s+//;
	        $str =~ s/\s+$//;
	        $str = lc($str);
	        $str =~ s/[&\?"\'\.,\(\)!]//mig;
	        $str =~ s/[^a-z]/_/mig;
	        return $str;
	}

	sub headinganchors (@) {
	        my %params=@_;
	        my $content=$params{content};
	        $content=~s{<h([0-9])>([^>]*)</h([0-9])>}{'<h'.$1.' id="'.text_to_anchor($2).'">'.$2.'</h'.$3.'>'}gie;
	        return $content;
	}

	1