Sha256: f0d784a8d73a34494c7f446f89ccc0f419a186b38c1f6d6bcaa1993dd36ae765

Contents?: true

Size: 1.28 KB

Versions: 9

Compression:

Stored size: 1.28 KB

Contents

description  'Auto-generated table of contents'
dependencies 'utils/xml'

Page.attributes do
  boolean :toc
end

Filter.create :toc do |context, content|
  return content if !context.page.attributes['toc']

  doc = XML::Fragment(content)
  toc = ''
  level = 0
  count = [0]

  elem = doc.css('h1, h2, h3, h4, h5, h6').first
  offset = elem ? elem.name[1..1].to_i - 1 : 0

  doc.traverse do |child|
    if child.name =~ /^h(\d)$/
      nr = $1.to_i - offset
      if nr > level
        while nr > level
          toc << (level == 0 ? '<ol class="toc">' : '<ol>')
          count[level] = 0
          level += 1
          toc << '<li>' if nr > level
        end
      else
        while nr < level
          level -= 1
          toc << '</li></ol>'
        end
        toc << '</li>'
      end
      count[level-1] += 1
      headline = child.children.first ? child.children.first.inner_text : ''
      section = ['sec', count[0..level-1], headline.strip.gsub(/[^\w]/, '-')].flatten.join('-').downcase
      toc << %{<li class="toc#{level-offset+1}"><a href="##{section}">#{headline}</a>}
      child.inner_html = %{<span class="number" id="#{section}">#{count[0..level-1].join('.')}</span> #{child.inner_html}}
    end
  end

  while level > 0
    level -= 1
    toc << '</li></ol>'
  end

  toc + doc.to_xhtml
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
olelo-0.9.8 plugins/filters/toc.rb
olelo-0.9.7 plugins/filters/toc.rb
olelo-0.9.6 plugins/filters/toc.rb
olelo-0.9.5 plugins/filters/toc.rb
olelo-0.9.4 plugins/filters/toc.rb
olelo-0.9.3 plugins/filters/toc.rb
olelo-0.9.2 plugins/filters/toc.rb
olelo-0.9.1 plugins/filters/toc.rb
olelo-0.9.0 plugins/filters/toc.rb