Register now and start sharing your code snippets.
-->
Syntax highlighting code with Ruby and Ultraviolet
Ruby posted about 1 year ago by christian
This site uses Ultraviolet for syntax highlighting. Ultraviolet supports 50 languages and 20 themes, so it’s sometimes difficult to pick the best theme, which is why I created the following code snippet that renders the code in all available themes and creates an HTML page displaying them all:
1 require 'uv' 2 3 language = ARGV[1] 4 input_file = ARGV[0] 5 line_numbers = true 6 output_format = "xhtml" 7 8 input = File.read(input_file) 9 10 # Render input using all available themes 11 syntax_highlighted_code = "" 12 Uv.themes.each do |theme| 13 syntax_highlighted_code << "<h2>#{theme}</h2>" 14 syntax_highlighted_code << Uv.parse( input, output_format, language, line_numbers, theme) 15 end 16 17 # Template for output file 18 page_template = <<HTML_DOC 19 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 20 21 <html> 22 <head> 23 <title>test</title> 24 #{Uv.themes.map{|theme| %Q(<link rel="stylesheet" type="text/css" href="css/#{theme}.css" />\n)}} 25 <script type="text/javascript" src=""></script> 26 <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> 27 </head> 28 <body> 29 #{syntax_highlighted_code} 30 </body> 31 </html> 32 HTML_DOC 33 34 # Write highlighted text to output 35 File.open("output.html", "w") do |file| 36 file << page_template 37 end
Yes, using ERB templates would be better but interpolated strings work just fine… Save the code in highlight.rb and run it as follows:
1 highlight.rb ruby input_file.rb