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);
56 my $startlevel=($params{startlevel} ? $params{startlevel} : 0);
57 my $curlevel=$startlevel-1;
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 # Unless we're given startlevel as a parameter,
69 # take the first header level seen as the topmost level,
70 # even if there are higher levels seen later on.
73 $curlevel=$startlevel-1;
75 elsif (defined $params{startlevel} &&
76 $level < $params{startlevel}) {
79 elsif ($level < $startlevel) {
83 return if $level - $startlevel >= $params{levels};
85 if ($level > $curlevel) {
86 while ($level > $curlevel + 1) {
87 $index.=&$indent."<ol>\n";
89 $index.=&$indent."<li class=\"L$curlevel\">\n";
91 $index.=&$indent."<ol>\n";
95 elsif ($level < $curlevel) {
96 while ($level < $curlevel) {
97 $index.=&$indent."</li>\n" if $curlevel;
99 $index.=&$indent."</ol>\n";
104 $index.=&$indent."</li>\n" unless $liststarted;
106 $index.=&$indent."<li class=\"L$curlevel\">".
107 "<a href=\"#$anchor\">";
109 $p->handler(text => sub {
111 $index.=join("", @_);
113 $p->handler(end => sub {
115 if ($tagname =~ /^h(\d+)$/i) {
116 $p->handler(text => undef);
117 $p->handler(end => undef);
127 $p->handler(default => sub { $page.=join("", @_) }, "text");
131 while ($startlevel && $curlevel >= $startlevel) {
132 $index.=&$indent."</li>\n" if $curlevel;
134 $index.=&$indent."</ol>\n";
137 $page=~s/(<div class=\"toc\">)/$1\n$index/;