Skip to content

Instantly share code, notes, and snippets.

@leonardfactory
Created May 7, 2013 14:28
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 leonardfactory/5532966 to your computer and use it in GitHub Desktop.
Save leonardfactory/5532966 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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

@darkuranium
Copy link

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