#207 Syntax Highlighting
Here I talk about three popular choices for syntax highlighting in Rails: CodeRay, Ultraviolet and Pygments.
- Download:
- source codeProject Files in Zip (94.8 KB)
- mp4Full Size H.264 Video (19.9 MB)
- m4vSmaller H.264 Video (11.6 MB)
- webmFull Size VP8 Video (27.9 MB)
- ogvFull Size Theora Video (25 MB)
There is a newer version of this episode, see the revised episode.
Resources
rhtml
<%= textilize(coderay(@article.content)) %>
config/environment.rb
config.gem "coderay" config.gem "RedCloth"
application_helper.rb
def coderay(text) text.gsub(/\<code( lang="(.+?)")?\>(.+?)\<\/code\>/m) do content_tag("notextile", CodeRay.scan($3, $2).div(:css => :class)) end end
syntax_benchmark.rb
require "rubygems" require "benchmark" require "coderay" require "uv" path = __FILE__ content = File.read(__FILE__) # run it once to initialize CodeRay.scan("print 'hello'", "ruby").div(:css => :class) Uv.parse("print 'test'", "xhtml", "ruby", true, "amy") Benchmark.bm(11) do |b| b.report("coderay") do 50.times { CodeRay.scan(content, "ruby").div(:css => :class) } end b.report("ultraviolet") do 50.times { Uv.parse(content, "xhtml", "ruby", true, "amy") } end b.report("pygments") do 50.times { `pygmentize -f html "#{path}"` } end end
css
.CodeRay { background-color: #232323; border: 1px solid black; font-family: 'Courier New', 'Terminal', monospace; color: #E6E0DB; padding: 3px 5px; overflow: auto; font-size: 12px; margin: 12px 0; } .CodeRay pre { margin: 0px; padding: 0px; } .CodeRay .an { color:#E7BE69 } /* html attribute */ .CodeRay .c { color:#BC9358; font-style: italic; } /* comment */ .CodeRay .ch { color:#509E4F } /* escaped character */ .CodeRay .cl { color:#FFF } /* class */ .CodeRay .co { color:#FFF } /* constant */ .CodeRay .fl { color:#A4C260 } /* float */ .CodeRay .fu { color:#FFC56D } /* function */ .CodeRay .gv { color:#D0CFFE } /* global variable */ .CodeRay .i { color:#A4C260 } /* integer */ .CodeRay .il { background:#151515 } /* inline code */ .CodeRay .iv { color:#D0CFFE } /* instance variable */ .CodeRay .pp { color:#E7BE69 } /* doctype */ .CodeRay .r { color:#CB7832 } /* keyword */ .CodeRay .rx { color:#A4C260 } /* regex */ .CodeRay .s { color:#A4C260 } /* string */ .CodeRay .sy { color:#6C9CBD } /* symbol */ .CodeRay .ta { color:#E7BE69 } /* html tag */ .CodeRay .pc { color:#6C9CBD } /* boolean */