compass/doc-src/lib/data_sources/syntax_highter.rb

43 lines
1.1 KiB
Ruby
Raw Normal View History

2010-02-07 21:58:52 +00:00
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", "r+") do |io|
2010-02-07 21:58:52 +00:00
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)
2010-02-07 21:58:52 +00:00
end
def run(content, params={})
doc = Nokogiri::HTML.fragment(content)
[:html, :css, :sass, :scss].each do |format|
2010-03-28 04:18:29 +00:00
doc.css("pre.source-code.#{format}, code.#{format}").each do |el|
new_element = Nokogiri.make(highlight(el.inner_text, format))
new_element.set_attribute("class", new_element.attribute("class").value+" "+el.attribute("class").value)
if id = el.attribute("id")
new_element.set_attribute("id", id)
end
el.replace new_element
2010-02-07 21:58:52 +00:00
end
end
doc.to_s
end
end