2 # Table Of Contents generator
3 package IkiWiki::Plugin::toc;
11 hook(type => "getsetup", id => "toc", call => \&getsetup);
12 hook(type => "preprocess", id => "toc", call => \&preprocess);
13 hook(type => "format", id => "toc", call => \&format);
29 if ($params{page} eq $params{destpage}) {
30 $params{levels}=1 unless exists $params{levels};
32 # It's too early to generate the toc here, so just record the
34 $tocpages{$params{destpage}}=\%params;
36 return "\n<div class=\"toc\"></div>\n";
39 # Don't generate toc in an inlined page, doesn't work
47 my $content=$params{content};
49 return $content unless exists $tocpages{$params{page}};
50 %params=%{$tocpages{$params{page}}};
52 my $p=HTML::Parser->new(api_version => 3);
59 my $indent=sub { "\t" x $curlevel };
60 $p->handler(start => sub {
63 if ($tagname =~ /^h(\d+)$/i) {
65 my $anchor="index".++$anchors{$level}."h$level";
66 $page.="$text<a name=\"$anchor\"></a>";
68 # Take the first header level seen as the topmost level,
69 # even if there are higher levels seen later on.
72 $curlevel=$startlevel-1;
74 elsif ($level < $startlevel) {
78 return if $level - $startlevel >= $params{levels};
80 if ($level > $curlevel) {
81 while ($level > $curlevel + 1) {
82 $index.=&$indent."<ol>\n";
84 $index.=&$indent."<li class=\"L$curlevel\">\n";
86 $index.=&$indent."<ol>\n";
90 elsif ($level < $curlevel) {
91 while ($level < $curlevel) {
92 $index.=&$indent."</li>\n" if $curlevel;
94 $index.=&$indent."</ol>\n";
99 $index.=&$indent."</li>\n" unless $liststarted;
101 $index.=&$indent."<li class=\"L$curlevel\">".
102 "<a href=\"#$anchor\">";
104 $p->handler(text => sub {
106 $index.=join("", @_);
108 $p->handler(end => sub {
110 if ($tagname =~ /^h(\d+)$/i) {
111 $p->handler(text => undef);
112 $p->handler(end => undef);
122 $p->handler(default => sub { $page.=join("", @_) }, "text");
126 while ($startlevel && $curlevel >= $startlevel) {
127 $index.=&$indent."</li>\n" if $curlevel;
129 $index.=&$indent."</ol>\n";
132 $page=~s/(<div class=\"toc\">)/$1\n$index/;