plugins/pygments_code.rb
7b81aab5
 require 'pygments'
 require 'fileutils'
 require 'digest/md5'
 
f6bf8943
 PYGMENTS_CACHE_DIR = File.expand_path('../../.pygments-cache', __FILE__)
7b81aab5
 FileUtils.mkdir_p(PYGMENTS_CACHE_DIR)
 
 module HighlightCode
   def highlight(str, lang)
358d02a4
     lang = 'ruby' if lang == 'ru'
     lang = 'objc' if lang == 'm'
     lang = 'perl' if lang == 'pl'
     lang = 'yaml' if lang == 'yml'
cb6442e6
     str = pygments(str, lang).match(/<pre>(.+)<\/pre>/m)[1].to_s.gsub(/ *$/, '') #strip out divs <div class="highlight">
ef4a42f9
     tableize_code(str, lang)
7b81aab5
   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
2043c543
         highlighted_code = Pygments.highlight(code, :lexer => lang, :formatter => 'html', :options => {:encoding => 'utf-8'})
7b81aab5
         File.open(path, 'w') {|f| f.print(highlighted_code) }
       end
     else
2043c543
       highlighted_code = Pygments.highlight(code, :lexer => lang, :formatter => 'html', :options => {:encoding => 'utf-8'})
7b81aab5
     end
     highlighted_code
   end
ef4a42f9
   def tableize_code (str, lang = '')
347e855d
     table = '<div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers">'
ef4a42f9
     code = ''
     str.lines.each_with_index do |line,index|
347e855d
       table += "<span class='line-number'>#{index+1}</span>\n"
       code  += "<span class='line'>#{line}</span>"
ef4a42f9
     end
347e855d
     table += "</pre></td><td class='code'><pre><code class='#{lang}'>#{code}</code></pre></td></tr></table></div>"
ef4a42f9
   end
7b81aab5
 end