Wednesday, October 1, 2008

Ruby Syntax Highlighting on Web Pages

Here's a fast and easy way to do syntax highlighting on web pages (e.g. blogs). This works for ruby and html/xml:

First Install Jamis Buck's syntax gem
gem install syntax

Then create a file ruby2html.rb with the following content
require 'rubygems'
require 'syntax/convertors/html'

#create a new ruby2Html-converter and convert clipboard-content to html
converter = Syntax::Convertors::HTML.for_syntax "ruby"
html_code = converter.convert(IO.popen('pbpaste', 'r+').read, false)

#wrap the code in a pre-tag with class 'ruby'
html_code = ["<pre class='ruby'>", html_code, "</pre>"].join

#output the generated html-code to the console
puts html_code

#write the html_code back to the clipboard
IO.popen('pbcopy', 'r+').puts html_code

Then just copy the content of the clipboard into your blog or webpage.

Warning: the code uses the cmd-line tools 'popen' and 'pbcopy' to access the clipboard. Those tools are MacOSX specific. If you're on Linux see this blog post, something similar for windows users is describe here.

Add this css declarations to the header of your web page (change them to fit your need):
pre {
background-color: #f1f1f3;
color: #112;
padding: 10px;
font-size: 1.1em;
overflow: auto;
margin: 4px 0px;
width: 95%;

/* Syntax highlighting */
.ruby .normal {}
.ruby .comment { color: #6a6969; font-style: italic; }
.ruby .keyword { color: #7f2a53; font-weight: bold; }
.ruby .method { color: #077; }
.ruby .class { color: #683c2b; font-weight: bold;}
.ruby .module { color: #050; }
.ruby .punct { color: #000; font-weight: bold; }
.ruby .symbol { color: #000; }
.ruby .string { color: #2a9a67; background: #e8f5f5; }
.ruby .char { color: #F07; }
.ruby .ident { color: #004; }
.ruby .constant { color: #07F; }
.ruby .regex { color: #B66; background: #FEF; }
.ruby .number { color: #F99; }
.ruby .attribute { color: #7BB; }
.ruby .global { color: #7FB; }
.ruby .expr { color: #227; }
.ruby .escape { color: #277; }

If you need syntax highlighting for XML or HTML you can modify the ruby2html.rb to use the XML-Converter of the syntax gem.

1 comment:

Natalie said...
This comment has been removed by a blog administrator.