2 # Table Of Contents generator
3 package IkiWiki::Plugin::toc;
11 hook(type => "preprocess", id => "toc", call => \&preprocess);
12 hook(type => "format", id => "toc", call => \&format);
17 sub preprocess (@) { #{{{
20 $params{levels}=1 unless exists $params{levels};
22 # It's too early to generate the toc here, so just record the
24 $tocpages{$params{destpage}}=\%params;
26 return "\n<div class=\"toc\"></div>\n";
31 my $content=$params{content};
33 return $content unless exists $tocpages{$params{page}};
34 %params=%{$tocpages{$params{page}}};
36 my $p=HTML::Parser->new(api_version => 3);
43 my $indent=sub { "\t" x $curlevel };
44 $p->handler(start => sub {
47 if ($tagname =~ /^h(\d+)$/i) {
49 my $anchor="index".++$anchors{$level}."h$level";
50 $page.="$text<a name=\"$anchor\" />";
52 # Take the first header level seen as the topmost level,
53 # even if there are higher levels seen later on.
56 $curlevel=$startlevel-1;
58 elsif ($level < $startlevel) {
62 return if $level - $startlevel >= $params{levels};
64 if ($level > $curlevel) {
65 while ($level > $curlevel + 1) {
66 $index.=&$indent."<ol>\n";
68 $index.=&$indent."<li class=\"L$curlevel\">\n";
70 $index.=&$indent."<ol>\n";
74 elsif ($level < $curlevel) {
75 while ($level < $curlevel) {
76 $index.=&$indent."</li>\n" if $curlevel;
78 $index.=&$indent."</ol>\n";
83 $p->handler(text => sub {
85 $index.=&$indent."</li>\n" unless $liststarted;
87 $index.=&$indent."<li class=\"L$curlevel\">".
88 "<a href=\"#$anchor\">".
91 $p->handler(text => undef);
98 $p->handler(default => sub { $page.=join("", @_) }, "text");
102 while ($startlevel && $curlevel >= $startlevel) {
103 $index.=&$indent."</li>\n" if $curlevel;
105 $index.=&$indent."</ol>\n";
108 $page=~s/(<div class=\"toc\">)/$1\n$index/;