Tuesday, August 26, 2014

Displaying Code with SyntaxHighlighter on Blogger

It took me a while to get code displaying nicely with syntax highlighting in Blogger. The most popular solution is definitely SyntaxHighlighter. It is a very nice tool that is written purely in Javascript, so it will work in any modern browser. The SyntaxHighlighter website has direction spread around it's documentation on how to get it working, and it's all there, but the docs assume it is obvious where different commands should be included in a page's source and it was not obvious to me. You can glean how to make it work from the following pages if you know a little about how javascript is loaded in HTML:

http://alexgorbatchev.com/SyntaxHighlighter/manual/installation.html
http://alexgorbatchev.com/SyntaxHighlighter/hosting.html
http://alexgorbatchev.com/SyntaxHighlighter/manual/configuration/

At the time of writing this SyntaxHighlighter 3.0.83 was the latest version.  While trying to get syntax highlighting working, I found quite a few resources of varying ages that provided some insight but none of them got me all the way there. One import piece of info is that getting SyntaxHighlighter working in Blogger requires and extra config to be set. The most up-to-date resource that I found was One-Q-One-A but due to a incompatibility of SyntaxHighlighter with Blogger Preview mode I had to do some more experimentation before I figured it out. More on this below. Here is my attempt to document the process so it isn't such a pain next time I need to do it and maybe it will be helpful to someone else too.

There are two options for "installing" SyntaxHighlighter. One is to download the source code and host it directly on the server that is running your website. Since, I am using blogger that isn't an option. The second option, which I will be using, is to load the code from a site that hosts it online. The author of SyntaxHighlighter has been very kind and is hosting the SyntaxHighlighter code on his personal website. Since this is such a popular tool, hosting the source code cost the author money; so, if you find it useful, consider making a donation.

Steps:
  1. Login to Blogger
  2. Backup your template in case you break it or want to revert it
  3. Edit Template in HTML mode (google it if you don't know how)
  4. Add the commands to the template that load the SyntaxHighlighter CSS, Javascript files, and run SyntaxHighlighter. Do this by adding the following lines right before the </head> tag (these commands can be anywhere between <head> and </head>):
<link href='http://alexgorbatchev.com/pub/sh/current/styles/shCore.css' rel='stylesheet' type='text/css'/>
<link href='http://alexgorbatchev.com/pub/sh/current/styles/shThemeRDark.css' rel='Stylesheet' type='text/css'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shCore.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPlain.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPython.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushXml.js' type='text/javascript'/>
<script type='text/javascript'>
    SyntaxHighlighter.config.bloggerMode = true;
    SyntaxHighlighter.all();
</script>

Here is a description of what each line does and what changes you may want to make:
  • Load the "shCore.ssh" style. Without loading this I had an annoying header line included before each code block.
  • Load a specific theme. I chose "shThemeRDark.css". Here is a link to the default Themes with examples (you can change the theme href to link to any of those on this page).
  • Load "shCore.js" which is the heart of SyntaxHighlighter
  • Load the plain text, Python,  and XML, which includes HTML, "brushes". These are syntax definitions and lots of them are available here (brushes). Only include those you need to decrease the load times of your blog and minimize the load to the code host.
  • Run a script that configures SyntaxHighlighter for Blogger and calls the entry function. Without doing the config you won't get it working in Blogger.

  1. Now, create or edit a post. Edit the HTML and add the code you want to display between a set of <pre class="brush: ALIAS"></pre>, where ALIAS is the name of the brush that should be used (e.g. "xml", "plain", "python"). Here is an example of what the blog post HTML could look like:

<pre class="brush: py">
#!/usr/bin/env python

import sys

def main():
  print 'Program name', sys.argv[0]

if __name__ == '__main__':
  main()
</pre>

And this is the result:

#!/usr/bin/env python

import sys

def main():
  print 'Program name', sys.argv[0]

if __name__ == '__main__':
  main()

My big problem. After making the changes above in a my template and a test post, I tried to preview the post but the page didn't show any syntax highlighting for the code in the <pre> tags. Entering developer mode in the browser revealed that there was a MixedContent error. That error is cause by having an page served by HTTPS attempting to make HTTP requests. Apparently, Blogger serves the post Preview via HTTPS which means that SyntaxHighlighter won't ever work in the Blogger Preview page, at least in Firefox and Chrome. This is because the SyntaxHighlighter load requests made using HTTP. Too bad. In order to verify that SyntaxHighlighter was indeed working I had to publish the post and then view it.

One note about the <pre> tag. All code between the <pre> tags needs to be HTML escaped, meaning it can't include the following characters: ' " < > &. There are lots of resources performing the escaping. Blogger will do it for you when you paste you code in compose mode (not html mode). Here is one such free resource: http://www.freeformatter.com/html-escape.html

A nice feature of SyntaxHighlighter that became available in version 3 is the autoloader. This makes it so only the brushes that are used on a page are loaded. I haven't been able to get this working in Blogger yet. It requires that SyntaxHighlighter.autoloader is run after the page has loaded, such as with Javascript window.onload(), but I'm not familiar enough with Blogger yet to know if that's possible and I haven't experimented much.

There are quite a few more options for formating and highlighting code blocks and those can be easily figured out via the SyntaxHighlighting website. Enjoy!