Thursday, 12 December 2013

A Prism Syntax Highlighter for R

(Update: description of a known issue, below the numbered list.) As I mentioned in a previous post, I've recently begun to use Lea Verou's fantastic PrismJS to do syntax highlighting on this blog.

As I could not find an R plugin for PrismJS, I wrote one myself. PrismJS highlighting is regex based, which means that while it sometimes makes mistakes with highlighting, it's easy to add in a new language.

You can see a demo here and get the script/style from my gist (I've also embedded the gist at the end of this post). It's similar to Yihui Xie's SyntaxHighlighter brush for R.

Without further ado, here's a demonstration:

n <- 10
for (i in seq_len(n)) {
    # say hello, many times
    message("hello world")
}

You can grab the files from my gist; you can also view an example page demonstrating 3 different themes I modified earlier.

To use it:

  1. Host the the PrismJS and R PrismJS script somewhere and include them (note: you may wish to minify the R script and add it to the end of your PrismJS script so you only need to include one file):

    <script src='prism.js'></script> 
    <script src='prism.r.js'></script>
  2. Include the stylesheet of your choice. You may wish to also define style classes for .token.function, .token.variable and .token.namespace, to determine how functions, variables, and namespaces are styled (the stylesheets on my gist have this already):

    <link rel='stylesheet' href='prism.css' />
  3. Any R code you want to be syntax highlighted should have class="language-r" on it (note: on the code tag, not the pre tag). Works for inline code too.

Et Voila!

Update: There is a known issue whereby hash tags within strings will be highlighted as comments. There are a number of workarounds mentioned in the link, though each has a use that will break it (regex-based highlighters always have these problems).

You can view my gist via bl.ocks.org to see a larger code snippet, and play around with a few themes I modified to make the R look pretty: Okaidia (the one from PrismJS), Zenburn (based off the vim theme by Jami Nurminen), and Tomorrow Night 80s (like the one from RStudio, by Chris Kempson). I'm using Tomorrow Night 80s on my blog.