class Rote::Filters::RedCloth_WithToc

Redcloth filter that adds a table of contents at the top of the given text and sufficent hyperlinks to access the various headings in the text. This can be used instead of the standard TOC filter to get TOC capabilities during page (rather than layout) rendering.

Contributed by Suraj Kurapati.

Constants

Heading

Public Instance Methods

handler(text, *args) click to toggle source
# File lib/rote/filters/redcloth.rb, line 48
def handler text, *args
  # determine structure of content and insert anchors where necessary
    headings = []
 
    text = text.gsub(/^(\s*h(\d))(.*?)(\.(.*))$/) do
    target = $~.dup
 
     if target[3] =~ /#([^#]+)\)/
       anchor = $1
       result = target.to_s
     else
       anchor = headings.length
       result = "#{target[1]}#{target[3]}(##{anchor})#{target[4]}"
     end
 
     headings << Heading.new( target[2].to_i, anchor, target[5] )
     result
   end
 
   # add table of contents at top of text
   toc = headings.map do |h|
     %Q{#{'*' * h.depth} "#{h.title}":##{h.anchor}}
   end.join("\n")
 
   text.insert 0, "\n\n\n"
   text.insert 0, toc
 
   super text, *args
 end