16 Nov 2011

Using SyntaxHighlighter and R Brush in Blogger

If you're thinking it is time to give the code examples in your blog a more readable look, you may follow this path and use the SyntaxHighlighter

First thing: check the SyntaxHighlighter Website for the basics.

Then follow this example, which I did. I will illustrate this below, including the implementation of the Java-script that is needed for R-syntax:

Add the subsequent lines just before the head closing tag in your HTML-template:


You'll see that the brushes for nearly all languages are by Alex Gorbatschev (SyntaxHighlighter), except the last one which is by Yihui Xie (Statistics, R, Graphics and Fun - Blog). That's the part you have to edit in your HTML-template. Then when adding R-syntax (or syntax in any other language for which we had just added the scripts) that should be highlighted, just use the following tags when posting in HTML-edit mode..
<pre class="brush: r">
test.function = function(r) {
    return(pi * r^2)
}
test.function(1)
</pre>
and get the below result:
test.function = function(r) {
    return(pi * r^2)
}
test.function(1)

That was easy, wasn't it?

Stephen Turner reported troubles with < and > signs (see comments below). A quick glimpse on this didn't approve of that. However I will keep an eye on the issue...
# testing potential problems with > and <:
if x > 0 {y = 1}: if x < 0 {y = 0}

6 comments :

  1. I found the pre:class tags to be somewhat problematic in blogger, especially with R code that has < or > characters. I find using either Github gists or revolution-r's highlighter to be more robust and easier.

    ReplyDelete
  2. Thanks it was useful for me.

    ReplyDelete
  3. Hi,

    I get the following error when I open this page in firefox/chrome/ie. Probably the javascript link is not working.

    ReplyDelete
  4. NOT WORKING. https://raw.github.com/gist/05699292f522111bb77d/d36b731e7573602e809e34b3bedf0c3f71b023c7/shBrushR.js
    does'nt exist

    ReplyDelete
    Replies
    1. Ashish, fixed the dead link, should be working now..

      Delete