#207 Syntax Highlighting (revised)
Here I compare several syntax highlighting solutions and show how to use Pygments in a Rails app. I also show how to integrate it with Markdown and add caching.
- Download:
- source codeProject Files in Zip (108 KB)
- mp4Full Size H.264 Video (18.9 MB)
- m4vSmaller H.264 Video (10.6 MB)
- webmFull Size VP8 Video (11.8 MB)
- ogvFull Size Theora Video (24.5 MB)
Resources
- Pygments
- pygments.rb
- CodeRay
- UltraViolet
- Rainbow
- SyntaxHighlighter
- RedCarpet
- Episode 272: Markdown with Redcarpet
terminal
gem install coderay pygments.rb uv ruby syntax_benchmark.rb
Gemfile
gem 'pygments.rb' gem 'redcarpet'
snippets/show.html.erb
<%= raw Pygments.highlight(@snippet.code, lexer: @snippet.language) %>
app/assets/stylesheets/pygments.css.erb
<%= Pygments.css(style: "colorful") %>
articles/show.html.erb
<%= markdown @article.content %>
application_helper.rb
module ApplicationHelper class HTMLwithPygments < Redcarpet::Render::HTML def block_code(code, language) sha = Digest::SHA1.hexdigest(code) Rails.cache.fetch ["code", language, sha].join('-') do Pygments.highlight(code, lexer: language) end end end def markdown(text) renderer = HTMLwithPygments.new(hard_wrap: true, filter_html: true) options = { autolink: true, no_intra_emphasis: true, fenced_code_blocks: true, lax_html_blocks: true, strikethrough: true, superscript: true } Redcarpet::Markdown.new(renderer, options).render(text).html_safe end end
syntax_benchmark.rb
require "rubygems" require "benchmark" require "coderay" require "pygments" require "uv" repeat = 50 content = File.read(__FILE__) # run it once to initialize CodeRay.scan(content, "ruby").div(css: :class) Pygments.highlight(content, lexer: "ruby") Uv.parse(content, "xhtml", "ruby", true, "amy") Benchmark.bm(11) do |b| b.report("coderay") do repeat.times { CodeRay.scan(content, "ruby").div(css: :class) } end b.report("pygments") do repeat.times { Pygments.highlight(content, lexer: "ruby") } end b.report("ultraviolet") do repeat.times { Uv.parse(content, "xhtml", "ruby", true, "amy") } end end


