class Kramdown::Converter::Html

def generate_toc_tree(toc, type, attr)

Generate and return an element tree for the table of contents.
def generate_toc_tree(toc, type, attr)
  sections = Element.new(type, nil, attr)
  sections.attr['id'] ||= 'markdown-toc'
  stack = []
  toc.each do |level, id, children|
    li = Element.new(:li, nil, nil, {:level => level})
    li.children << Element.new(:p, nil, nil, {:transparent => true})
    a = Element.new(:a, nil)
    a.attr['href'] = "##{id}"
    a.attr['id'] = "#{sections.attr['id']}-#{id}"
    a.children.concat(remove_footnotes(Marshal.load(Marshal.dump(children))))
    li.children.last.children << a
    li.children << Element.new(type)
    success = false
    while !success
      if stack.empty?
        sections.children << li
        stack << li
        success = true
      elsif stack.last.options[:level] < li.options[:level]
        stack.last.children.last.children << li
        stack << li
        success = true
      else
        item = stack.pop
        item.children.pop unless item.children.last.children.size > 0
      end
    end
  end
  while !stack.empty?
    item = stack.pop
    item.children.pop unless item.children.last.children.size > 0
  end
  sections
end