Created
February 12, 2014 03:25
-
-
Save jashank/8949579 to your computer and use it in GitHub Desktop.
Kramdown TOC->HTML wrapped in Jekyll
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'kramdown' | |
module Jekyll | |
module Converters | |
class Markdown | |
class KramdownParser | |
attr_accessor :kramdown | |
DISPATCHER = Hash.new {|h,k| h[k] = "convert_#{k}"} | |
include ::Kramdown::Utils::Html | |
include ::Kramdown::Parser::Html::Constants | |
# stolen and twiddled from Kramdown::Converter::Html | |
def inner(e, ind) | |
result = '' | |
ind += 2 | |
e.children.each do |inner_e| | |
result << send(DISPATCHER[inner_e.type], inner_e, ind) | |
end | |
result | |
end | |
# stolen from Kramdown::Converter::Html | |
def convert_text(e, ind) | |
escape_html(e.value, :text) | |
end | |
# much of this is gutted from the innards of Kramdown | |
def convert_toc(e, ind) | |
r = "" | |
r += (" " * ind) + "<li><a href=\"##{e.attr[:id]}\">#{e.value.children.first.value}</a>" | |
if (e.children.length > 1) | |
r += "<ul>\n" | |
r += "#{inner(e, ind)}" | |
r += (" " * ind) + "</ul>" | |
end | |
r += "</li>\n" | |
r | |
end | |
# stolen from Jekyll::Converters::Markdown::KramdownParser | |
def convert(content) | |
# Check for use of coderay | |
if @config['kramdown']['use_coderay'] | |
%w[wrap line_numbers line_numbers_start tab_width bold_every css default_lang].each do |opt| | |
key = "coderay_#{opt}" | |
@config['kramdown'][key] = @config['kramdown']['coderay'][key] unless @config['kramdown'].has_key?(key) | |
end | |
end | |
@kramdown = Kramdown::Document.new(content, @config["kramdown"].symbolize_keys) | |
puts inner(@kramdown.to_toc, 0) | |
@kramdown.to_html | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment