Today I was informed of (what I believe is) a better the best WordPress plugin for R syntax highlighting called WP-CodeBox. This plugin doesn’t require any hacks to make it work (as opposed to the WP-Syntax plugin, which I wrote about in the past). WP-CodeBox can be downloaded and installed on a WordPress by searching for it in the “Add New” section in the plugins menu.
WP-CodeBox provides some nice features (some AJAX based) to the display of the code in the post:
The code box in the post can now be folded (top right of the code box) so the code can be hidden so to not clutter the post (if the code is too long)
The code box is added with another button (top left of the code box) which allows the reader to see the code in a new window – so to easily enable a copy paste of the code.
The options of the plugin allows automatic row numbering of the code, control over “tab” length and some other features.
The simplest solution would be to just paste the code as plain text, which will look like this:
x <- rnorm(100, mean = 2, sd = 3)
plot(x, xlab = “index”, main = “Example code”)
But if you would like to help our readers orient themselves inside your code by giving different colors to different commands in the code (a.k.a: syntax highlighting). So it would like something like this:
x <-rnorm(100, mean=2, sd=3)# Creating a vectorplot(x, xlab ="index", main ="Example code")# Plotting it
WP-Syntax provides clean syntax highlighting using GeSHi — supporting a wide range of popular languages (including R). It supports highlighting with or without line numbers and maintains formatting while copying snippets of code from the browser.
But there is a problem. The current WP-Syntax version is using an old version of GeSHi, and only the newer version (currently GeSHi version 184.108.40.206) includes support for R syntax. In order to solve this I patched the plugin and I encourage you to download (the fixed version of) WP-Syntax from here, which will allow you to highlight your R code.
After installing (and activating) the plugin, in order to add R code to your post you will need to:
1) Only work in HTML mode (not the Visual mode). Or else, the code you will paste will be messed up.
2) Put your code between the <pre> tag, like this:
(Note: make sure that you rewrite the ” – so it will work.)
<pre lang=”rsplus” line=”1″>
…Your R code here…
Final note: R Syntax highlight in other ways
If you wish to have R syntax higlight inside an HTML file, I encourage you can have a look at the highlight package, by Romain Francois.
If you want to higlight your R syntax inside wordpress.com, here is a blog post by Erik Iverson showing how to do that using Emacs.
p.s: If you have a blog in which you write about R, please let me know about it in the comments (Or just join R-bloggers.com) – I’d love to follow you