aboutsummaryrefslogtreecommitdiff
path: root/plugins/pygments_code.rb
diff options
context:
space:
mode:
authorBrandon Mathis <brandon@imathis.com>2011-07-26 23:36:42 -0400
committerBrandon Mathis <brandon@imathis.com>2011-07-26 23:36:42 -0400
commit7b81aab5ac225fb12a100d9eb463340f322704fd (patch)
treef46adc303a4f5b4510d8880c8d5820173c931414 /plugins/pygments_code.rb
parent727a1492278c5e22aa68019f14d4e60319476f74 (diff)
downloadmy_new_personal_website-7b81aab5ac225fb12a100d9eb463340f322704fd.tar.xz
my_new_personal_website-7b81aab5ac225fb12a100d9eb463340f322704fd.zip
added support for pygments.rb removing dependency on pygments, added support for caching highlighted code from pygments.rb and added default line numbering. Javascript auto line numbering now only occurs for embedded gists
Diffstat (limited to '')
-rw-r--r--plugins/pygments_code.rb34
1 files changed, 34 insertions, 0 deletions
diff --git a/plugins/pygments_code.rb b/plugins/pygments_code.rb
new file mode 100644
index 00000000..05b4fb57
--- /dev/null
+++ b/plugins/pygments_code.rb
@@ -0,0 +1,34 @@
+require 'pygments'
+require 'fileutils'
+require 'digest/md5'
+
+PYGMENTS_CACHE_DIR = File.expand_path('../../_code_cache', __FILE__)
+FileUtils.mkdir_p(PYGMENTS_CACHE_DIR)
+
+module HighlightCode
+ def highlight(str, lang)
+ str = pygments(str, lang).match(/<pre>(.+)<\/pre>/m)[1].to_s.gsub(/\s*$/, '') #strip out divs <div class="highlight">
+ table = '<div class="highlight"><table cellpadding="0" cellspacing="0"><tr><td class="gutter"><pre class="line-numbers">'
+ code = ''
+ str.lines.each_with_index do |line,index|
+ table += "<span class='line'>#{index+1}</span>\n"
+ code += "<div class='line'>#{line}</div>"
+ end
+ table += "</pre></td><td class='code' width='100%'><pre><code class='#{lang}'>#{code}</code></pre></td></tr></table></div>"
+ 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
+ highlighted_code = Pygments.highlight(code, :lexer => lang, :formatter => 'html')
+ File.open(path, 'w') {|f| f.print(highlighted_code) }
+ end
+ else
+ highlighted_code = Pygments.highlight(code, :lexer => lang, :formatter => 'html')
+ end
+ highlighted_code
+ end
+end