in html/css, Rails

Adding CodeHighlighter to Typo

Recently, I ran across CodeHighlighter by Dan Webb. This looked like a pretty cool javascript, and I thought a better way than to do it on the server side.

Adding it to typo is fairly straightforward, baring a small patch.

Get the code

Get it from Dan’s site via subversion: http://svn.danwebb.net/external/CodeHighlighter/trunk

svn co http://svn.danwebb.net/external/CodeHighlighter/trunk

Adding CodeHightlighter to your template

Add to your template (themes/[YOUR THEME]/layouts/default.rhtml)

<%= javascript_include_tag "code_highlighter" %>
<%= javascript_include_tag "javascript" %>
<%= javascript_include_tag "css" %>
<%= javascript_include_tag "html" %>
<%= javascript_include_tag "ruby" %>

The code as provided by Dan has a small incompatibility with prototype used by Ruby on Rails. The following line

for (var i in this.styleSets) highlightCode(this.styleSets[i]);

behaves quite strangely and will pretty much kill your browser (Firefox runs out of memory and displays a bunch of “undefined” after several minutes) because it ends up calling hightlightCode way too many time because of all the methods added to all objects.

To make codehighlighter.js play nicely with prototype.js, replace that last line with:

if (this.styleSets.each) {
  this.styleSets.each(highlightCode)
} else {
    for (var i in this.styleSets) {
      highlightCode(this.styleSets[i]);
    }
}

Essentially, if prototype is present, we can use each to iterate on the styles, otherwise it is safe to used the old code.

Using Codehightlighter

Now, addng styling is easy. Using Textile, you can just put your code around a <pre> and a <code> block. If you have a javascript snippet, use a class of “javascript”.

For example:


<pre><code class="javascript">
if (this.styleSets.each) {
  this.styleSets.each(highlightCode)
} else {
    for (var i in this.styleSets) {
      highlightCode(this.styleSets[i]);
    }
</code></pre>

The other available styles are “html”, “css” and “ruby”.

For example, here’s how ruby would look like:

  def display_article(article = nil)
    begin
      @article      = block_given? ? yield : article
      @comment      = Comment.new
      @page_title   = @article.title
      auto_discovery_feed :type => 'article', :id => @article.id
      render :action => 'read'
    rescue ActiveRecord::RecordNotFound, NoMethodError => e
      error("Post not found...")
    end
  end

And it looks easy to create other styles. See the stylesetguide.html file for details.

Update: Turns out Dan already had a fix, so if you grab the trunk, you will be fine.

Here’s his version of the patch:

    for (var i=0; i < this.styleSets.length; i++) {
        highlightCode(this.styleSets[i]);
    }