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

114 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. 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
  26. hi, its very useful forever to post program code to my blog/websites thank you

    ReplyDelete
  27. Thanks for your helpful post.

    There is an updated version on http://alexgorbatchev.com/wiki/SyntaxHighlighter

    ReplyDelete
  28. 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
  29. 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
  30. 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
  31. 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
  32. 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
  33. Thanks dude! it helps me a lot.

    ReplyDelete
  34. Great Article! This is the tutorial most complete that i've found about syntaxhighlighter!

    ReplyDelete
  35. Thank you! This is the only tutorial that I have found to work.

    ReplyDelete
  36. 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
  37. 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
  38. 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
  39. Thanks man! I was finally able to make syntaxhighlighter work with my blog.

    ReplyDelete
  40. 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
  41. Thanks you very much.. this post very much help..

    ReplyDelete
  42. thanks, I finally found this tutorial..

    it's work... I think this version is better than new version that I've tried..

    ReplyDelete
  43. thanks... it's work fine in my blog

    ReplyDelete
  44. I am having this problem
    I need to highlight this php
    "echo $data."
    "; "
    but I can't get the "
    " to show :(

    ReplyDelete
  45. 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
  46. thanks for the walk-through :)
    still works nicely.

    ReplyDelete
  47. Thanks it works, first i use new version but it cause problem, then i follow your and it worked... thanks...

    ReplyDelete
  48. I Try this for 2 templates, the old and newest one.. and it's still working cool ... thx.
    keep sharing :)

    ReplyDelete
  49. 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
  50. 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
  51. great....you help me, i did all things you said...thanks....!!gretting from peru..!!

    ReplyDelete
  52. Thank you for nice post. This's very helpful.

    ReplyDelete
  53. thanks man. worked beautifully.

    ReplyDelete
  54. 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
  55. Maverick: Your blog is not public, so I cannot look at it to tell what the issue is.

    ReplyDelete
  56. Awesome!!!! I have successfully add the syntax highlighter using your tutorial. Great job.. Thank you for sharing.

    ReplyDelete
  57. Cool stuff! This is exactly what I need. Works like a charm :)

    ReplyDelete
  58. 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
  59. Thanks a lot! works perfect.
    http://progravanuno.blogspot.com/

    ReplyDelete
  60. thanks!! it works perfect.
    감사합니다. 많은 도움이 되었습니다.

    ReplyDelete
  61. Awesome ! Worked like charm !! Thanks.

    ReplyDelete
  62. Hey, thanks. It was a real time saver.

    ReplyDelete
  63. A big thank you from Corvallis Oregon too.

    ReplyDelete
  64. Very grateful for this. Thanks lots.

    ReplyDelete
  65. it breaks default template font and disables the background, bad guide

    ReplyDelete
  66. I don't know if I missed something, mine isn't working.

    Helen Neely

    ReplyDelete
  67. Thanks Matt, works perfectly :)

    http://theprogrammersnotebook.blogspot.com/

    ReplyDelete
  68. Thank you so much..it works for me....

    ReplyDelete
  69. 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
  70. 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
  71. 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
  72. Thanks dear its working for me in my blog code-solution.
    Thnx again:)

    ReplyDelete
  73. Thank u for short and clear solution Matthew. And hello to Google))

    ReplyDelete
  74. it was not work in my blog. who can help me? i try to follow carefully with your instruction...

    ReplyDelete
  75. 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
  76. 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
  77. just wanted to say that this works!!!!

    ReplyDelete
  78. 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
  79. Hi Matthew, I don't know what I'm doing wrong as I get this message: Your template could not be parsed as it is not well-formed. Please make sure that all XML elements are closed properly. XML error message: The element type "head" must be terminated by the matching end-tag "". I use blogger and placed everything in the right location. After looking for lots of explanations on how to use the syntax-highlighter I still get the same problem.

    In a comment someone says it's a syntax error with the script ending tag. So for bloggers how it should be as now I'm confused. Now I've changed the /script to script/ (looks like i'm not allowed to add the full tag with <> in the comment) and the template got saved, but when I add code in a post which has both html and php in I get "ERROR Your HTML cannot be accepted: Tag is broken: A". Any ideas in this case what div class should I use?

    Please I need help.

    ReplyDelete
  80. Hi Kady,
    I haven't edited this template in years, but I suspect that the newer blogger templates may be incompatible with the instructions given here. Several months ago I played with upgrading the template on this blog, but had to revert it because it messed-up the syntax highlighting.

    ReplyDelete
    Replies
    1. Thanks matt .... I tried it on my blog http://www.hubberspot.com and it worked really well ..... keep the good work up ....

      Delete
  81. Hi Matthew,

    Thank you for the answer, you could be right about the template.. in the meantime I'll keep on looking for a solution.

    Cheers,
    K

    ReplyDelete
  82. wow great.thanks buddy..... :D :D

    ReplyDelete
  83. Thanks a lot mate, you simplified this a hell lot for me :D

    ReplyDelete
  84. First of all Thanks for your post ! I followed all the steps exactly but I'm unable to get the color for code ?

    My code is formatted though but without color ! In step 2 Should we replace existing CSS or append at the end . I tried both ways with no luck :(

    Is there any specific template to use

    Thanks in advance

    ReplyDelete
  85. Hi Anonymous: Unfortunately, these instructions are outdated. My recommendation is to try SyntaxHighlighter 3, available at http://alexgorbatchev.com/SyntaxHighlighter/

    ReplyDelete
  86. It worked for me before, but stop working a month ago. Following your post and make it work now. Thanks!

    ReplyDelete
  87. how do you make "view plain" link??

    ReplyDelete
  88. Hi Scripter Zone: Unfortunately, this version of syntax highlighter does not support creating a cut-and-paste URL out of the "view plain" link. That is because the JavaScript hooks automatically generate the plain text on demand and are not a web server. You might be able to put the source code after a header or subheader, and then provide a link to that instead. Beyond that, I don't have any good ideas.

    ReplyDelete
  89. Is there any way to change the font and font size ?

    ReplyDelete
  90. Hi Shaeed: You can change the font and font size via the .dp-highlighter class selector in the CSS that was copied from http://syntaxhighlighter.googlecode.com/svn/trunk/Styles/SyntaxHighlighter.css. I think that you'd want to edit the font-family and font-size properties.

    ReplyDelete

Note: Only a member of this blog may post a comment.