summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/toc.pm
blob: 279eef00837a66c901056096c89af1c1180e6a42 (plain)
  1. #!/usr/bin/perl
  2. # Table Of Contents generator
  3. package IkiWiki::Plugin::toc;
  4. use warnings;
  5. use strict;
  6. use IkiWiki;
  7. use HTML::Parser;
  8. sub import { #{{{
  9. hook(type => "preprocess", id => "toc", call => \&preprocess);
  10. hook(type => "format", id => "toc", call => \&format);
  11. } # }}}
  12. my %tocpages;
  13. sub preprocess (@) { #{{{
  14. my %params=@_;
  15. $params{levels}=1 unless exists $params{levels};
  16. # It's too early to generate the toc here, so just record the
  17. # info.
  18. $tocpages{$params{destpage}}=\%params;
  19. return "\n<div class=\"toc\"></div>\n";
  20. } # }}}
  21. sub format (@) { #{{{
  22. my %params=@_;
  23. my $content=$params{content};
  24. return $content unless exists $tocpages{$params{page}};
  25. %params=%{$tocpages{$params{page}}};
  26. my $p=HTML::Parser->new(api_version => 3);
  27. my $page="";
  28. my $index="";
  29. my %anchors;
  30. my $curlevel;
  31. my $startlevel=0;
  32. my $liststarted=0;
  33. my $indent=sub { "\t" x $curlevel };
  34. $p->handler(start => sub {
  35. my $tagname=shift;
  36. my $text=shift;
  37. if ($tagname =~ /^h(\d+)$/i) {
  38. my $level=$1;
  39. my $anchor="index".++$anchors{$level}."h$level";
  40. $page.="$text<a name=\"$anchor\" />";
  41. # Take the first header level seen as the topmost level,
  42. # even if there are higher levels seen later on.
  43. if (! $startlevel) {
  44. $startlevel=$level;
  45. $curlevel=$startlevel-1;
  46. }
  47. elsif ($level < $startlevel) {
  48. $level=$startlevel;
  49. }
  50. return if $level - $startlevel >= $params{levels};
  51. if ($level > $curlevel) {
  52. while ($level > $curlevel + 1) {
  53. $index.=&$indent."<ol>\n";
  54. $curlevel++;
  55. $index.=&$indent."<li class=\"L$curlevel\">\n";
  56. }
  57. $index.=&$indent."<ol>\n";
  58. $curlevel=$level;
  59. $liststarted=1;
  60. }
  61. elsif ($level < $curlevel) {
  62. while ($level < $curlevel) {
  63. $index.=&$indent."</li>\n" if $curlevel;
  64. $curlevel--;
  65. $index.=&$indent."</ol>\n";
  66. }
  67. $liststarted=0;
  68. }
  69. $p->handler(text => sub {
  70. $page.=join("", @_);
  71. $index.=&$indent."</li>\n" unless $liststarted;
  72. $liststarted=0;
  73. $index.=&$indent."<li class=\"L$curlevel\">".
  74. "<a href=\"#$anchor\">".
  75. join("", @_).
  76. "</a>\n";
  77. $p->handler(text => undef);
  78. }, "dtext");
  79. }
  80. else {
  81. $page.=$text;
  82. }
  83. }, "tagname, text");
  84. $p->handler(default => sub { $page.=join("", @_) }, "text");
  85. $p->parse($content);
  86. $p->eof;
  87. while ($startlevel && $curlevel >= $startlevel) {
  88. $index.=&$indent."</li>\n" if $curlevel;
  89. $curlevel--;
  90. $index.=&$indent."</ol>\n";
  91. }
  92. $page=~s/(<div class=\"toc\">)/$1\n$index/;
  93. return $page;
  94. }
  95. 1