# Hpricot + Ultraviolet 0.1.3 # # See the tests at the bottom for usage examples # # Released into the public domain # # Please send bug reports and improvements to # christoffer.sawicki@gmail.com # # Noteworthy changes # * 0.1.3: Hpricot 0.6 is buggy, use +gem+ to load a older version # # Canonical source # http://code.vemod.net/svn/misc/hpricot_goodies/hpricot_plus_ultraviolet.rb if Kernel.methods.include?("gem") gem "hpricot", "<0.6" # 0.6 is buggy end require "hpricot" require "uv" module HpricotPlusUltraviolet extend self def color_syntax(html, theme = "active4d") doc = Hpricot(html) strip_unwanted_newlines!(doc) doc.search("//code[@lang]") do |tag| code = CGI.unescapeHTML(tag.inner_html) language = tag.attributes.delete("lang") if Uv.syntaxes.include?(language) uv = Uv.parse(code, "xhtml", language, false, theme) tag.inner_html = strip_outer_pre_tag(uv) tag.attributes["class"] = "ultraviolet" end end return doc.to_html end private def strip_unwanted_newlines!(doc, tag_names = %w
)
    # FIXME
    tag_names.each do |tag_name|
      doc.search("//#{tag_name}") do |tag|
        tag.inner_html = tag.inner_html.sub(/\A[\r\n]*/, "").sub(/[\r\n]*\Z/, "")
      end
    end
  end
  
  def strip_outer_pre_tag(html)
    match = html.match(/^(.*?)<\/pre>$/m)
    
    if match
      match.captures.first
    else
      raise("No 
 tag to remove in #{html.inspect}")
    end
  end
end

if __FILE__ == $0
  require("test/unit")

  class HpricotPlusUltravioletTest < Test::Unit::TestCase
    def test_stripping_of_newlines
      input = "
\n\nanswer = 42\n\n
" expected = "
answer = 42
" actual = HpricotPlusUltraviolet.color_syntax(input) assert_equal(expected, actual) end def test_coloring_with_default_theme input = "@answer = 42" expected = "@answer = 42\n" actual = HpricotPlusUltraviolet.color_syntax(input) assert_equal(expected, actual) end def test_coloring_with_brilliance_black_theme input = "@answer = 42" expected = "@answer = 42\n" actual = HpricotPlusUltraviolet.color_syntax(input, "brilliance_black") assert_equal(expected, actual) end def test_ultraviolet_with_invalid_language input = "HELLO WORLD" expected = "HELLO WORLD" actual = HpricotPlusUltraviolet.color_syntax(input) assert_equal(expected, actual) end end end