File: syntax_highter.rb

package info (click to toggle)
ruby-compass 0.12.2~dfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 8,308 kB
  • sloc: ruby: 10,474; makefile: 42; xml: 14
file content (37 lines) | stat: -rw-r--r-- 923 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
require 'nokogiri'
require 'coderay'
class SyntaxHighlighterFilter < Nanoc3::Filter
  identifier :highlight

  def highlight(code, type)
    hl_map = Hash.new(:coderay)
    hl_map[:sass] = :pygmentize
    send(hl_map[type], code, type)
  end

  def pygmentize(code, type)
    # -O linenos=table
    IO.popen("pygmentize -l #{type} -f html -O encoding=utf-8", "r+") do |io|
      io.write(code)
      io.close_write
      return io.read
    end
  end

  def coderay(code, type)
    # :line_numbers => :table,
    type = :css if type == :scss
    CodeRay.scan(code, type).div(:css => :class)
  end

  def run(content, params={})
    doc = Nokogiri::HTML.fragment(content)
    [:css, :sass, :scss, :html, :haml].each do |format|
      doc.css("pre.source-code.#{format}, code.#{format}").each do |el|
        el.set_attribute("class", "brush: #{format} "+el.attribute("class").value)
      end
    end
    doc.to_s
  end

end