class Madness::InlineTableOfContents
Generate a markdown Table of Contents for a single document
Attributes
text[R]
Public Class Methods
new(text)
click to toggle source
# File lib/madness/inline_table_of_contents.rb, line 9 def initialize(text) @text = text end
Public Instance Methods
markdown()
click to toggle source
# File lib/madness/inline_table_of_contents.rb, line 13 def markdown @markdown ||= ([caption, ''] + items).join "\n" end
Protected Instance Methods
caption()
click to toggle source
# File lib/madness/inline_table_of_contents.rb, line 46 def caption @caption ||= config.auto_toc.is_a?(String) ? config.auto_toc : '## Table of Contents' end
headers()
click to toggle source
# File lib/madness/inline_table_of_contents.rb, line 23 def headers @headers ||= text.lines(chomp: true).select do |line| next if inside_code_block? line line.match(/^(?<level>\#{2,3})\s+(?<text>.+)/) end end
inside_code_block?(line)
click to toggle source
# File lib/madness/inline_table_of_contents.rb, line 50 def inside_code_block?(line) @marker ||= false if !@marker && line.start_with?('```') @marker = line[/^`{3,4}/] elsif @marker && line.start_with?(@marker) @marker = false end !!@marker end
items()
click to toggle source
# File lib/madness/inline_table_of_contents.rb, line 19 def items @items ||= headers.map { |line| toc_item line } end
toc_item(line)
click to toggle source
# File lib/madness/inline_table_of_contents.rb, line 31 def toc_item(line) matches = line.match(/^(?<level>\#{2,3})\s+(?<text>.+)/) return nil unless matches text = matches[:text] level = matches[:level].size - 2 spacer = ' ' * level slug = text.to_slug # pandoc removes leading numbers and dots from header slugs, we do the same slug = slug.remove(/^[\d\-]+/) if config.renderer == 'pandoc' "#{spacer}- [#{text}](##{slug})" end