Skip to content

Instantly share code, notes, and snippets.

@pasela
Created March 24, 2014 08:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pasela/9736113 to your computer and use it in GitHub Desktop.
Save pasela/9736113 to your computer and use it in GitHub Desktop.
[ruby] Markdown to HTML converter CLI
# encoding: utf-8
require "optparse"
require "redcarpet"
class HTMLWithSyntaxHighlighter < Redcarpet::Render::HTML
ESCAPE_HTML_TABLE = {
"'" => '&#39;',
'&' => '&amp;',
'"' => '&quot;',
'<' => '&lt;',
'>' => '&gt;',
}
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)
@pasela
Copy link
Author

pasela commented Mar 24, 2014

Bloggerで記事を書く時用のオレオレツール。要redcarpet

  • GFM(GitHub Flavored Markdown)に近いオプション設定。
  • SyntaxHighlighterとGoogle Code Prettify用のハイライトオプションを追加。
  • ハイライト用のclass属性をpreじゃなくてcodeに設定するオプションを追加。
  • ファイル指定と標準入力から読む(ARGF)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment