Class: VimwikiTOCFilter

Inherits:
HTML::Pipeline::TableOfContentsFilter
  • Object
show all
Defined in:
lib/vimwiki_markdown/vimwiki_toc_filter.rb

Instance Method Summary collapse

Instance Method Details

#ascii_downcase(str) ⇒ Object



26
27
28
# File 'lib/vimwiki_markdown/vimwiki_toc_filter.rb', line 26

def ascii_downcase(str)
  str.downcase(:ascii)
end

#callObject



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/vimwiki_markdown/vimwiki_toc_filter.rb', line 4

def call
  result[:toc] = String.new('')

  headers = Hash.new(1)
  doc.css('h1, h2, h3, h4, h5, h6').each do |node|
    text = node.text
    id = ascii_downcase(text)
    id.gsub!(PUNCTUATION_REGEXP, '') # remove punctuation
    id.tr!(' ', '-') # replace spaces with dash

    uniq = headers[id] > 1 ? "-#{headers[id]}" : ''
    headers[id] += 1
    if header_content = node.children.first
      result[:toc] << %(<li><a href="##{id}#{uniq}">#{CGI.escape_html(text)}</a></li>\n)
      header_content.add_previous_sibling(%(<a id="#{id}#{uniq}" class="anchor" href="##{id}#{uniq}" aria-hidden="true">#{anchor_icon}</a>))
    end
  end
  result[:toc] = %(<ul class="section-nav">\n#{result[:toc]}</ul>) unless result[:toc].empty?
  doc
end