2011-07-26 23:36:42 -04:00
|
|
|
require 'pygments'
|
|
|
|
require 'fileutils'
|
|
|
|
require 'digest/md5'
|
|
|
|
|
2011-09-18 07:45:25 -04:00
|
|
|
PYGMENTS_CACHE_DIR = File.expand_path('../../.pygments-cache', __FILE__)
|
2011-07-26 23:36:42 -04:00
|
|
|
FileUtils.mkdir_p(PYGMENTS_CACHE_DIR)
|
|
|
|
|
|
|
|
module HighlightCode
|
|
|
|
def highlight(str, lang)
|
2011-08-20 18:39:00 -04:00
|
|
|
lang = 'ruby' if lang == 'ru'
|
|
|
|
lang = 'objc' if lang == 'm'
|
|
|
|
lang = 'perl' if lang == 'pl'
|
|
|
|
lang = 'yaml' if lang == 'yml'
|
2011-07-30 09:06:38 -04:00
|
|
|
str = pygments(str, lang).match(/<pre>(.+)<\/pre>/m)[1].to_s.gsub(/ *$/, '') #strip out divs <div class="highlight">
|
2011-08-16 02:40:47 -04:00
|
|
|
tableize_code(str, lang)
|
2011-07-26 23:36:42 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def pygments(code, lang)
|
|
|
|
if defined?(PYGMENTS_CACHE_DIR)
|
|
|
|
path = File.join(PYGMENTS_CACHE_DIR, "#{lang}-#{Digest::MD5.hexdigest(code)}.html")
|
|
|
|
if File.exist?(path)
|
|
|
|
highlighted_code = File.read(path)
|
|
|
|
else
|
2013-01-30 01:53:04 -05:00
|
|
|
begin
|
|
|
|
highlighted_code = Pygments.highlight(code, :lexer => lang, :formatter => 'html', :options => {:encoding => 'utf-8'})
|
2013-01-30 21:51:26 -05:00
|
|
|
rescue MentosError
|
|
|
|
raise "Pygments can't parse unknown language: #{lang}."
|
2013-01-30 01:53:04 -05:00
|
|
|
end
|
2011-07-26 23:36:42 -04:00
|
|
|
File.open(path, 'w') {|f| f.print(highlighted_code) }
|
|
|
|
end
|
|
|
|
else
|
2011-10-21 03:23:56 -04:00
|
|
|
highlighted_code = Pygments.highlight(code, :lexer => lang, :formatter => 'html', :options => {:encoding => 'utf-8'})
|
2011-07-26 23:36:42 -04:00
|
|
|
end
|
|
|
|
highlighted_code
|
|
|
|
end
|
2011-08-16 02:40:47 -04:00
|
|
|
def tableize_code (str, lang = '')
|
2011-09-18 07:55:35 -04:00
|
|
|
table = '<div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers">'
|
2011-08-16 02:40:47 -04:00
|
|
|
code = ''
|
|
|
|
str.lines.each_with_index do |line,index|
|
2011-09-18 07:55:35 -04:00
|
|
|
table += "<span class='line-number'>#{index+1}</span>\n"
|
|
|
|
code += "<span class='line'>#{line}</span>"
|
2011-08-16 02:40:47 -04:00
|
|
|
end
|
2011-09-18 07:55:35 -04:00
|
|
|
table += "</pre></td><td class='code'><pre><code class='#{lang}'>#{code}</code></pre></td></tr></table></div>"
|
2011-08-16 02:40:47 -04:00
|
|
|
end
|
2011-07-26 23:36:42 -04:00
|
|
|
end
|