class Kramdown::Converter::Toc

Converts a Kramdown::Document to an element tree that represents the table of contents.

The returned tree consists of Element objects of type :toc where the root element is just used as container object. Each :toc element contains as value the wrapped :header element and under the attribute key :id the header ID that should be used (note that this ID may not exist in the wrapped element).

Since the TOC tree consists of special :toc elements, one cannot directly feed this tree to other converters!

Public Class Methods

new(root, options) click to toggle source
Calls superclass method Kramdown::Converter::Base::new
   # File lib/kramdown/converter/toc.rb
26 def initialize(root, options)
27   super
28   @toc = Element.new(:toc)
29   @stack = []
30   @options[:template] = ''
31 end

Public Instance Methods

convert(el) click to toggle source
   # File lib/kramdown/converter/toc.rb
33 def convert(el)
34   if el.type == :header && in_toc?(el)
35     attr = el.attr.dup
36     attr['id'] = generate_id(el.options[:raw_text]) if @options[:auto_ids] && !attr['id']
37     add_to_toc(el, attr['id']) if attr['id']
38   else
39     el.children.each {|child| convert(child)}
40   end
41   @toc
42 end

Private Instance Methods

add_to_toc(el, id) click to toggle source
   # File lib/kramdown/converter/toc.rb
46 def add_to_toc(el, id)
47   toc_element = Element.new(:toc, el, :id => id)
48 
49   success = false
50   while !success
51     if @stack.empty?
52       @toc.children << toc_element
53       @stack << toc_element
54       success = true
55     elsif @stack.last.value.options[:level] < el.options[:level]
56       @stack.last.children << toc_element
57       @stack << toc_element
58       success = true
59     else
60       @stack.pop
61     end
62   end
63 end