Last active
July 11, 2017 14:53
-
-
Save backflip/7446094 to your computer and use it in GitHub Desktop.
Using Redcarpet and Middleman Syntax for Markdown and HAML files
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
class CustomMarkdown < Middleman::Extension | |
$markdown_options = { | |
autolink: true, | |
fenced_code_blocks: true, | |
no_intra_emphasis: true, | |
strikethrough: true, | |
tables: true, | |
hard_wrap: true, | |
with_toc_data: true | |
} | |
# Markdown files | |
def initialize(app, options_hash={}, &block) | |
super | |
app.set :markdown_engine, :redcarpet | |
app.set :markdown, $markdown_options | |
end | |
# HAML Markdown filter | |
module Haml::Filters | |
remove_filter("Markdown") | |
module Markdown | |
include Haml::Filters::Base | |
def render text | |
markdown.render text | |
end | |
class MarkdownRenderer < Redcarpet::Render::HTML | |
def block_code(code, language) | |
Middleman::Syntax::Highlighter.highlight(code.force_encoding("UTF-8"), language) | |
end | |
end | |
private | |
def markdown | |
@markdown ||= Redcarpet::Markdown.new MarkdownRenderer.new($markdown_options), $markdown_options | |
end | |
end | |
end | |
# TOC helper | |
helpers do | |
# Based on https://github.com/vmg/redcarpet/pull/186#issuecomment-22783188 | |
def toc(page) | |
html_toc = Redcarpet::Markdown.new(Redcarpet::Render::HTML_TOC) | |
file = ::File.read(page.source_file) | |
# remove YAML frontmatter | |
file = file.gsub(/^(---\s*\n.*?\n?)^(---\s*$\n?)/m,'') | |
# quick fix for HAML: remove :markdown filter and indentation | |
file = file.gsub(/:markdown\n/,'') | |
file = file.gsub(/\t/,'') | |
html_toc.render file | |
end | |
end | |
end | |
::Middleman::Extensions.register(:custom_markdown, CustomMarkdown) | |
activate :custom_markdown | |
activate :syntax, :line_numbers => true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment