class SectionIDFilter

Public Instance Methods

run(content, params={}) click to toggle source
# File lib/filters/section_id.rb, line 11
def run(content, params={})
  parser = HTMLTokenizer.new(content)

  # Table of Contents: Saved for use in the layout
  toc = ""
  
  # Last level of the ToC seen
  last_toc_level = 0
  
  # Final HTML returned for viewing in the browser
  output = ""

  begin
    # Get a chunk of text, up to the next tag
    output << parser.getText

    # Process the header tags
    next_tag = parser.getNextToken
    if next_tag.kind_of?(HTMLTag)
      case next_tag.tag_name
        when "h1"
           # Assemble the new header
           header_text = parser.getTextAndTags("/h1")
           output << "<h1 id=\"#{header_id(header_text)}\">"
                        
           last_toc_level = 1
        
        when "h2"
          # Assemble the new header
          header_text = parser.getTextAndTags("/h2")
          output << "<h2 id=\"#{header_id(header_text)}\">"
          
          # Add to the Table of Contents
          if last_toc_level != 2 then
            toc << "%ul\n"
          end
          
          toc << "%li\n"
          toc << "  %a{:href => \"##{header_id(header_text)}\"}= \"" << header_text << "\"\n"
                     
          last_toc_level = 2
            
        when "h3"
          # Assemble the new header
          header_text = parser.getTextAndTags("/h3")
          output << "<h3 id=\"#{header_id(header_text)}\">"
          
          # Add to the Table of Contents
          if last_toc_level != 3 then
            toc << "  %ul\n"
          end
          
          toc << "    %li\n"
          toc << "      %a{:href => \"##{header_id(header_text)}\"}= \"" << header_text << "\"\n"
         
          last_toc_level = 3

        when "h4"
          # Assemble the new header
          header_text = parser.getTextAndTags("/h4")
          output << "<h4 id=\"#{header_id(header_text)}\">"
        
        when "h5"
          # Assemble the new header
          header_text = parser.getTextAndTags("/h5")
          output << "<h5 id=\"#{header_id(header_text)}\">"
           
        when "h6"
          # Assemble the new header
          header_text = parser.getTextAndTags("/h6")
          output << "<h6 id=\"#{header_id(header_text)}\">"
        
        else
          output << next_tag.raw         
      end
    end

  end until (parser.peekNextToken.nil?)

  engine = Haml::Engine.new(toc)
  
  @item[:toc] = engine.render
  
  return output
end