Created
March 24, 2014 08:07
-
-
Save pasela/9736113 to your computer and use it in GitHub Desktop.
[ruby] Markdown to HTML converter CLI
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
# encoding: utf-8 | |
require "optparse" | |
require "redcarpet" | |
class HTMLWithSyntaxHighlighter < Redcarpet::Render::HTML | |
ESCAPE_HTML_TABLE = { | |
"'" => ''', | |
'&' => '&', | |
'"' => '"', | |
'<' => '<', | |
'>' => '>', | |
} | |
def initialize(options = {}) | |
@custom_opts = { | |
:prettify => options[:prettify] || false, | |
:syntax_highlighter => options.delete(:syntax_highlighter) || false, | |
:class_for_code_tag => options.delete(:class_for_code_tag) || false, | |
} | |
super(options) | |
end | |
def block_code(code, language) | |
class_value = highlight_class_value(language) | |
if class_value | |
if @custom_opts[:class_for_code_tag] | |
"\n<pre><code class=\"#{escape_html(class_value)}\">#{escape_html(code)}</code></pre>\n" | |
else | |
"\n<pre class=\"#{escape_html(class_value)}\"><code>#{escape_html(code)}</code></pre>\n" | |
end | |
else | |
"\n<pre><code>#{escape_html(code)}</code></pre>\n" | |
end | |
end | |
def escape_html(html) | |
html.gsub(/['&\"<>]/, ESCAPE_HTML_TABLE) | |
end | |
private | |
def highlight_class_value(language) | |
case | |
when @custom_opts[:syntax_highlighter] | |
"brush:#{language || "plain"}" | |
when @custom_opts[:prettify] | |
language ? "prettyprint lang-#{language}" : "prettyprint" | |
else | |
language | |
end | |
end | |
end | |
config = { | |
:renderer_opts => { | |
:hard_wrap => true, | |
}, | |
:markdown_opts => { | |
:no_intra_emphasis => true, | |
:tables => true, | |
:fenced_code_blocks => true, | |
:autolink => true, | |
:strikethrough => true, | |
:lax_spacing => false, | |
:space_after_headers => true, | |
} | |
} | |
OptionParser.new do |opts| | |
opts.on("--code-tag", "Add highlight classes for code tag instead of pre tag") do | |
config[:renderer_opts][:class_for_code_tag] = true | |
end | |
opts.on("--prettify", "Add prettify classes") do | |
config[:renderer_opts][:prettify] = true | |
end | |
opts.on("--highlighter", "Add SyntaxHighlighter classes") do | |
config[:renderer_opts][:syntax_highlighter] = true | |
end | |
opts.banner << " [file...]" | |
opts.parse! | |
end | |
# renderer = Redcarpet::Render::HTML.new(config[:renderer_opts]) | |
renderer = HTMLWithSyntaxHighlighter.new(config[:renderer_opts]) | |
markdown = Redcarpet::Markdown.new(renderer, config[:markdown_opts]) | |
puts markdown.render(ARGF.read) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Bloggerで記事を書く時用のオレオレツール。要redcarpet