Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Highlight fenced code-block contents with Rouge (#29)
Merge pull request 29
- Loading branch information
Showing
3 changed files
with
103 additions
and
2 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
# frozen_string_literal: true | ||
|
||
Jekyll::External.require_with_graceful_fail "commonmarker" | ||
|
||
module Jekyll | ||
module Converters | ||
class Markdown | ||
class CommonMark | ||
class HtmlRenderer < CommonMarker::HtmlRenderer | ||
def code_block(node) | ||
block do | ||
lang = extract_code_lang(node.fence_info) | ||
|
||
out('<div class="') | ||
out("language-", lang, " ") if lang | ||
out('highlighter-rouge"><div class="highlight">') | ||
out("<pre", sourcepos(node), ' class="highlight"') | ||
|
||
if option_enabled?(:GITHUB_PRE_LANG) | ||
out_data_attr(lang) | ||
out("><code>") | ||
else | ||
out("><code") | ||
out_data_attr(lang) | ||
out(">") | ||
end | ||
out(render_with_rouge(node.string_content, lang)) | ||
out("</code></pre></div></div>") | ||
end | ||
end | ||
|
||
private | ||
|
||
def extract_code_lang(info) | ||
return unless info.is_a?(String) | ||
return if info.empty? | ||
|
||
info.split(%r!\s+!)[0] | ||
end | ||
|
||
def out_data_attr(lang) | ||
return unless lang | ||
|
||
out(' data-lang="', lang, '"') | ||
end | ||
|
||
def render_with_rouge(code, lang) | ||
require "rouge" | ||
|
||
formatter = Rouge::Formatters::HTMLLegacy.new( | ||
:line_numbers => false, | ||
:wrap => false, | ||
:css_class => "highlight", | ||
:gutter_class => "gutter", | ||
:code_class => "code" | ||
) | ||
lexer = Rouge::Lexer.find_fancy(lang, code) || Rouge::Lexers::PlainText | ||
formatter.format(lexer.lex(code)) | ||
end | ||
end | ||
end | ||
end | ||
end | ||
end |
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