Class: Gollum::Filter::TOC

Inherits:
Gollum::Filter show all
Defined in:
lib/gollum-lib/filter/toc.rb

Overview

Inserts header anchors and creates TOC

Constant Summary collapse

HEADERS =
(1..6).to_a

Constants inherited from Gollum::Filter

PLACEHOLDER_PATTERN

Instance Attribute Summary

Attributes inherited from Gollum::Filter

#close_pattern, #open_pattern

Instance Method Summary collapse

Methods inherited from Gollum::Filter

#initialize

Methods included from Helpers

#path_to_link_text, #trim_leading_slashes

Constructor Details

This class inherits a constructor from Gollum::Filter

Instance Method Details

#extract(data) ⇒ Object



6
7
8
# File 'lib/gollum-lib/filter/toc.rb', line 6

def extract(data)
  data
end

#process(data) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/gollum-lib/filter/toc.rb', line 10

def process(data)

  @doc               = Nokogiri::HTML::DocumentFragment.parse(data)
  @toc_doc           = nil
  @anchor_names      = {}
  @current_ancestors = []
  @headers_levels    = {}
  toc_str            = ''
  if @markup.sub_page && @markup.parent_page
    toc_str = @markup.parent_page.toc_data
  else
    @headers = @doc.css(headers_selector)
    get_toc_levels()

    @headers.each_with_index do |header, i|
      next if header.content.empty?
      # omit the first H1 (the page title) from the TOC if so configured
      next if (i == 0 && header.name =~ /[Hh]1/) && @markup.wiki && @markup.wiki.h1_title

      anchor_name = generate_anchor_name(header)
      add_anchor_to_header header, anchor_name
      add_entry_to_toc     header, anchor_name
    end
    if not @toc_doc.nil?
      toc_str = @toc_doc.to_xml(@markup.class.to_xml_opts)
    end

    data  = @doc.to_xml(@markup.class.to_xml_opts)
  end

  @markup.toc = toc_str

  data.gsub!(/\[\[_TOC_(.*?)\]\]/) do
    levels = nil
    levels_match = Regexp.last_match[1].match /\|\s*levels\s*=\s*(\d+)/
    if levels_match
      levels = levels_match[1].to_i
    end

    if levels.nil? || toc_str.empty?
      toc_str
    else
      @toc_doc ||= Nokogiri::HTML::DocumentFragment.parse(toc_str)
      toc_clone = @toc_doc.clone
      toc_clone.traverse do |e|
        if e.name == 'ul' and e.ancestors('ul').length > levels - 1
          e.remove
        end
      end
      toc_clone.to_xml(@markup.class.to_xml_opts)
    end
  end

  data
end