Sunday, January 18, 2009

Adding Syntax Highlighting to Blogger

(Note: This article is somewhat dated because SyntaxHighlighter 2.0 was released in February 2009.  However, this article is still valid for those who prefer the older 1.5.x version or who don't want to upgrade)

As we all know, any self-respecting blogger needs some kind of syntax-highlighting plug-in before posting source code on a blog. I've been amiss in this regard, but decided it was high time to correct this particular deficiency.

From doing a little web searching, it looks like the favorite choice is a Java script tool called syntaxhighlighter. As of this writing, syntaxhighlighter hasn't been updated since version 1.5.1 was release in August 2007. It's been surprisingly robust all this time, except that it appears to have some trouble with scrollbars in the more recent Firefox versions, and Safari can be pegged at 100% CPU utilization. Also, the documentation is a little sparse.

That said, here are the steps I followed to make syntax highlighting work with Blogger (the host for this blog) using the syntaxhighlighter suite of javascript and css code.

In the blogger back end (reachable by logging into your blog and clicking "New Post" or "Customize", or other methods), click the"Layout" tab, then the "Edit HTML" sub-tab. Within the textbox within the "Edit Template" section, do the following:

1. Go to http://syntaxhighlighter.googlecode.com/svn/trunk/Styles/SyntaxHighlighter.css, then perform a "select all" and "copy". The css information is now in the clipboard.

2. Paste the css information at the end of the css section of your blogger html template (i.e., after <b:skin><!--[CDATA[/* and before ]]--></b:skin>).

3. [Updated March 25, 2009 to include closing script tags] Before the </head> tag, paste the following:
<!-- Add-in CSS for syntax highlighting -->
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shCore.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushCpp.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushCSharp.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushCss.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushDelphi.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushJava.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushJScript.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushPhp.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushPython.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushRuby.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushSql.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushVb.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushXml.js' type='text/javascript'></script>
Feel free to remove lines for languages you'll never use (for example, Delphi) -- it will save some loading time.

4. [Updated to add final /script] Before the </body> tag, insert the following:
<!-- Add-in Script for syntax highlighting -->
<script language='javascript'>
dp.SyntaxHighlighter.BloggerMode();
dp.SyntaxHighlighter.HighlightAll('code');
</script>

5. Use the "Preview" button to make sure your website is correct, then click "Save Template".

6. When composing a blog entry that contains source code, click the "Edit Html" tab and put your source code (with html-escaped characters) between these tags:
<pre name="code" class="cpp">
...Your html-escaped code goes here...
</pre>

Substitute "cpp" with whatever language you're using (full list). (Choices: cpp, c, c++, c#, c-sharp, csharp, css, delphi, pascal, java, js, jscript, javascript, php, py, python, rb, ruby, rails, ror, sql, vb, vb.net, xml, html, xhtml, xslt)

For performing the HTML escaping, you can get a good list of tools by searching for 'html esaper' or a similar term. Here's the one I used while writing this post.

Let me know how it works!

Notes:
  1. Step 2 is a work-around to accommodate Firefox browsers, which for some reason refuse to load the css when linked, because it thinks the type is mime/plain instead of mime/css (I don't personally understand this -- I'm just using a workaround recommended from elsewhere)
  2. See full documentation here for Syntaxhighlighter.

Sources:
  1. Enjoy Web Tech - Publish Source code in Blogger
  2. Using Syntaxhighlighter on Blogger

95 comments:

  1. Step 4. Is lacking a "</script>", but otherwise, it works great.

    Thanks!
    ReplyDelete
  2. Brent: Good catch! I've updated the post with the final /script... :)
    ReplyDelete
  3. Syntaxhighlighter v2.0 is now available at http://alexgorbatchev.com/wiki/SyntaxHighlighter.
    ReplyDelete
  4. What is your settings for 'Convert line breaks' set to? In my case, if I set it to 'Yes', it's inserting <br /> into codes defined under <pre> tag.
    ReplyDelete
  5. My "Convert line breaks" setting is set to "yes". However, I typically use the raw html editor instead of the WYSIWYG editor when entering in code. I think this avoids the problem of inserting the "br" tags. Also, the Syntaxhighlighter script has some provision for removing the "br" tags within a "pre" section. That is basically what the dp.SyntaxHighlighter.BloggerMode() function accomplishes. Does that work for you?
    ReplyDelete
  6. Thanks a lot! It was previously so irritating that I came accross a blogger whose last post on his blog was "Thinking of getting my own blog since I am tired of formatting code in blogger" and he had a programming blog (like mine, so I understand him! Now neat and clean syntax highlighting has landed. Safe landing! Thanks again for the simple tips. Let me know you that there in the world I found a post on this technique which scared me because it was pointed out that I need to host the scripts myself! But coming to your post has eased me a lot and surely to thousand others also! Thanks again!!
    ReplyDelete
  7. Great, It works well for me..
    Thank you so much dude..
    ReplyDelete
  8. For anyone who is having trouble I wanted to note that this did not work for me until I made the script tags valid XML by having them not be self-closing, ie <script></script> instead of <script />.

    Thanks for the instructions, getting this working was pretty painless, now it's time to see how many lines of code it takes to throttle the js engine ;)
    ReplyDelete
  9. Hi jonz: By doing a "view source" on this page, I've discovered that blogger converts the self-closing javascript tags (i.e., <script.../>) into tag pairs (i.e., <script...></script>). If you're not using blogger, then it won't automatically update the text for you. I'll update the main example to use the tag pairs for the non-blogger users. Thanks for noticing this!
    ReplyDelete
  10. I've got problem. when I add lines like
    dp.SyntaxHighlighter.HighlightAll('code');

    blogger automatically converts it after saving into:
    dp.SyntaxHighlighter.HighlightAll('code');

    Blogger does that to many other characters in JS code. what can I do?
    ReplyDelete
  11. Hi Pawel: Unfortunately, I fail to see the difference in the two lines you've given as an example. Maybe Blogger converted your comment? Could you explain in more detail what was changed?
    ReplyDelete
  12. Useful stuff
    Great job man
    Thank you
    ReplyDelete
  13. Thanks Matthew. I have successfully add the syntax highlighter using your tutorial. Great job..
    ReplyDelete
  14. Thank You Matthew... your tutorial was the better i found on this argument! Ciao
    ReplyDelete
  15. Thanks Matthew . It was very useful and i added Mxml and As3 from Shigeru Nakagaki blog
    ReplyDelete
  16. Great Job. I referred lot many blogs but found your helpful.
    ReplyDelete
  17. Neat Highlighter is a great highlighter and supports many languages
    ReplyDelete
  18. Thank you! Worked first time - you have brought to an end hours of frustration!
    ReplyDelete
  19. Hey Mathew,
    Thanks for the good post, it helped me to set my blog with syntax highlighter in 10 minutes.
    ReplyDelete
  20. Hi,
    Its now working sir
    ReplyDelete
  21. Man, I found your post is really useful. Thanks man
    ReplyDelete
  22. Thanks for the tip on syntax highlighting. I got it working on my blog.

    However, I am finding that it chews up CPU on the Google chrome browser. I dont know if this is a known issue?
    ReplyDelete
  23. Feroze: I remember seeing that issue too, where the CPU pegs. I thought it might have been on Mac's Safari, but wouldn't be surprised if they both do it, since Chrome is based on the same browser code as Safari is.

    The SyntaxHighlighter project has since been upgraded to version 2, so I suspect that bugs in this version won't get fixed. I should probably spend some time to upgrade and maybe write a newer blog post, but I'm a bit lazy... :)
    ReplyDelete
  24. Took me a while to figure out, but that is because I think I was having the same problem as Pawel.

    I was following another blog that said to use the link tag for the css. Blogger is replacing the ' with &-#-3-9-; (added - in the sequence so it would not be rendered as a ' ). At first I thought this was the problem until I read your blog that says FF has problems with loading the css in this manner. I tried everything to stop those ' from turning into the code, and I got it to stop using a CDATA. It still didnt work so I tried copying the css into the template's css. No luck. Finally, I decided to remove the CDATA and lo and behold it works with the ' converted into the above code (&-#-3-9-;).
    ReplyDelete
  25. Thanks a lot...really helpful.
    ReplyDelete
  26. Almost works for me. I did a test post to see if it works, but it only shows the highlighter and any regular text I put into the pre tags, but not any code.
    ReplyDelete
  27. hi, its very useful forever to post program code to my blog/websites thank you
    ReplyDelete
  28. Thanks for your helpful post.

    There is an updated version on http://alexgorbatchev.com/wiki/SyntaxHighlighter
    ReplyDelete
  29. easy way to install updated version on blogger this post seems to use the old version... ive made a post that describes how to use the updated one...
    ReplyDelete
  30. Hi, Thanks a lot
    but I have a problem with it because
    when I want to preview my blog in step 4, it asked me username and password!
    What's wrong?
    ReplyDelete
  31. Alex's Blog: I'm guessing that you somehow logged out of Google on a different window or through a timeout. For example, logging out of gmail may cause this behavior. I don't think that it's related to the instructions in this post.
    ReplyDelete
  32. great stuff man!

    now I'm adding php syntax hightlight to all my blog!

    http://yuppframework.blogspot.com/2010/01/testing-del-orm.html
    ReplyDelete
  33. great article.
    i tried ur method. it worked. but i tried
    link rel=stylesheet href="http://...syntaxhighlighter.css" type="text/css"
    instead of copying css information in the clipboard. it doesnt work.
    ReplyDelete
  34. Thanks dude! it helps me a lot.
    ReplyDelete
  35. Great Article! This is the tutorial most complete that i've found about syntaxhighlighter!
    ReplyDelete
  36. Thank you! This is the only tutorial that I have found to work.
    ReplyDelete
  37. wonderful and great. anyone can do it with the help of your article. thanks a lot. fantastic.
    this is the best article among others about syntaxhighlighter. i have added it to my blog....
    Have a nice day. take care. bye.
    Rajeshkumar Govindarajan.
    oracle dba
    http://oracleinstance.blogspot.com
    ReplyDelete
  38. Wouldn't it be more clever to use a tagged version of syntaxhighlighter to have it stable e.g.
    http://syntaxhighlighter.googlecode.com/svn/tags/1.5.1/Scripts/shBrushCss.js
    instead of
    http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushCss.js
    ReplyDelete
  39. This is the best tutorial for this on the web. I swear I looked forever and slogged through unclear, cryptic instructions.

    I'm frustrated that it took so long to find, though.
    ReplyDelete
  40. Thanks man! I was finally able to make syntaxhighlighter work with my blog.
    ReplyDelete
  41. Thankx man.... i check lot of links to work syntaxhighlighter in ma blog. finally with your help i did it. this is better one i ever read abt
    syntaxhighlighter
    ReplyDelete
  42. Thanks you very much.. this post very much help..
    ReplyDelete
  43. thanks, I finally found this tutorial..

    it's work... I think this version is better than new version that I've tried..
    ReplyDelete
  44. thanks... it's work fine in my blog
    ReplyDelete
  45. I am having this problem
    I need to highlight this php
    "echo $data."
    "; "
    but I can't get the "
    " to show :(
    ReplyDelete
  46. You don't need to host the css and js file at your site, have a look at here:

    http://practician.blogspot.com/2010/07/color-my-world-syntax-highlighter.html#links
    ReplyDelete
  47. thanks for the walk-through :)
    still works nicely.
    ReplyDelete
  48. Thanks a lot :)
    Now my blog looking nice
    ReplyDelete
  49. Thanks it works, first i use new version but it cause problem, then i follow your and it worked... thanks...
    ReplyDelete
  50. I Try this for 2 templates, the old and newest one.. and it's still working cool ... thx.
    keep sharing :)
    ReplyDelete
  51. hi Matt if i follow your code i am getting nice syntax highlighter but prblem is i am unable to get scrollbar if my data more how should i implement scroll bar please let me know
    ReplyDelete
  52. suresh dasari: I poked around a bit, but couldn't find an obvious way to get scroll bars working for large snippets of code. This may not be possible with recent browsers when using SyntaxHighlighter version 1.5. Just recently, Alex G released version 3.0, so it might be time to upgrade.
    ReplyDelete
  53. great....you help me, i did all things you said...thanks....!!gretting from peru..!!
    ReplyDelete
  54. Thank you for nice post. This's very helpful.
    ReplyDelete
  55. thanks man. worked beautifully.
    ReplyDelete
  56. Hello, It works for my blog, but when I try to embed my code, I get the same code repeated twice.I dont understand why??
    Please let me know ..Thank you..
    here is the link for the bloG:
    http://maverickworkplace.blogspot.com/2010/11/swing.html
    ReplyDelete
  57. Maverick: Your blog is not public, so I cannot look at it to tell what the issue is.
    ReplyDelete
  58. Awesome!!!! I have successfully add the syntax highlighter using your tutorial. Great job.. Thank you for sharing.
    ReplyDelete
  59. Cool stuff! This is exactly what I need. Works like a charm :)
    ReplyDelete
  60. Thanks for sharing this howto! I've just seen on my blog that it works: http://martin-thoma.blogspot.com/2011/01/how-to-post-code-on-bloggercom.html
    ReplyDelete
  61. Thanks a lot! works perfect.
    http://progravanuno.blogspot.com/
    ReplyDelete
  62. thanks!! it works perfect.
    감사합니다. 많은 도움이 되었습니다.
    ReplyDelete
  63. Awesome ! Worked like charm !! Thanks.
    ReplyDelete
  64. Hey, thanks. It was a real time saver.
    ReplyDelete
  65. A big thank you from Corvallis Oregon too.
    ReplyDelete
  66. great (:
    thank u very much
    ReplyDelete
  67. Very grateful for this. Thanks lots.
    ReplyDelete
  68. it breaks default template font and disables the background, bad guide
    ReplyDelete
  69. Thanks Matthew. It works perfectly
    ReplyDelete
  70. I don't know if I missed something, mine isn't working.

    Helen Neely
    ReplyDelete
  71. Thanks Matt, works perfectly :)

    http://theprogrammersnotebook.blogspot.com/
    ReplyDelete
  72. Thank you so much..it works for me....
    ReplyDelete
  73. You solution does not work with this piece of code:

    /**

    * Sort a map according to values.

    * @param the key of the map.
    * @param the value to sort according to.
    * @param mapToSort the map to sort.

    * @return a map sorted on the values.

    */

    public static > Map
    sortMapByValues(final Map mapToSort)
    {
    List> entries =
    new ArrayList>(mapToSort.size());

    entries.addAll(mapToSort.entrySet());

    Collections.sort(entries,
    new Comparator>()
    {
    @Override
    public int compare(
    final Map.Entry entry1,
    final Map.Entry entry2)
    {
    return entry1.getValue().compareTo(entry2.getValue());
    }
    });

    Map sortedMap = new LinkedHashMap();

    for (Map.Entry entry : entries)
    {
    sortedMap.put(entry.getKey(), entry.getValue());
    }

    return sortedMap;
    }
    ReplyDelete
  74. Recently the mirror for Syntaxhighlighter was offline, leaving hundreds of thousands of sites without code rendering:

    I made a quick Fallback function, which will render the code within script elements even when no Syntaxhighlighter script is loaded.

    http://xhr2.blogspot.com/2011/09/alexgorbatchevcom-down-changing.html
    ReplyDelete
  75. Hi Lo Sauer,

    I'm not sure if the recommendations on my blog post were affected by the outage of alexgorbatchev.com since my instructions use code.google.com as the content distribution server instead. Is there a dependency on alexgorbatchev.com that I wasn't aware of?
    ReplyDelete
  76. Thanks dear its working for me in my blog code-solution.
    Thnx again:)
    ReplyDelete
  77. Thank u for short and clear solution Matthew. And hello to Google))
    ReplyDelete
  78. it was not work in my blog. who can help me? i try to follow carefully with your instruction...
    ReplyDelete
  79. Chi: I suspect that these instructions may need to be tweaked for some of the newer blogger templates. That said, I haven't looked into upgrading my own template yet, so I don't know what the specific issues are. Anyone else tried the new Blogger templates yet?
    ReplyDelete
  80. Works here on one of the newest blogger templates, but I can't do right or left angle brackets. They get converted to the escaped HTML, whether or not I convert them beforehand with an encoder like this one: http://www.accessify.com/tools-and-wizards/developer-tools/quick-escape/default.php. Strange.

    Tried to upgrade syntaxhighlighter, but the latest versions don't wrap long lines, so they won't work with my template.
    ReplyDelete
  81. just wanted to say that this works!!!!
    ReplyDelete
  82. Works brilliantly well with the new design template. The only slight difference is, I used "Template/Customize/Advanced/Add CSS" to paste the CSS there. Here is the outcome:
    http://macergun.blogspot.com/2012/01/syntax-highlighter-from-google-code.html
    ReplyDelete