Instantly share code, notes, and snippets.

Embed
What would you like to do?
Old plugin to get line numbers and code highlighting available on Jekyll <= 0.12
require 'redcarpet'
require 'pygments'
# Provides a custom Redcarpet renderer with some tweaks for code blocks and links.
class HTMLwithPygmentsCodeblocks < Redcarpet::Render::HTML
def initialize(extensions = {})
super extensions.merge(:link_attributes => { :target => "_blank" }) # Open link in new window
end
def block_code(code, language)
colorized = Pygments.highlight(code, :lexer => language, :options => {:lineanchors => "line"}) # Add lineanchors for line numbers
colorized.sub(/<pre>/, "<pre><code class=\"#{language}\">").sub(/<\/pre>/, "</code></pre>")
end
def codespan(code)
"<code class=\"inline-code\">#{code}</code>" # Inline code custom class
end
end
class Jekyll::MarkdownConverter
def extensions
Hash[ *@config['redcarpet']['extensions'].map {|e| [e.to_sym, true] }.flatten ]
end
def markdown
@markdown ||= Redcarpet::Markdown.new(HTMLwithPygmentsCodeblocks, :fenced_code_blocks => true)
end
def convert(content)
return super unless @config['markdown'] == 'redcarpet-pygments'
markdown.render(content)
end
end
@leonardfactory

This comment has been minimized.

Owner

leonardfactory commented May 7, 2013

You can find more info and new version for Jekyll v1 on this article.

@darkuranium

This comment has been minimized.

darkuranium commented Apr 2, 2015

The class=\"#{language}\" part conflicts with Pygments files for some short-name languages (such as C or D). I've fixed it by changing the class to language-#{language}, and setting the language to "unknown" just before this if it is not known:

language = 'unknown' if language.nil?
colorized.sub(/<pre>/, "<pre><code class=\"language-#{language}\">").sub(/<\/pre>/, "</code></pre>")

The first line is optional, and added for neatness (if omitted, unknown languages will have the class language-).

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