Scott Hanselman

Best Code Syntax Highlighter for Snippets in your Blog

December 2, '08 Comments [36] Posted in ASP.NET | DasBlog | Javascript | Open Source
Sponsored By

I get a few emails a day of folks asking what Syntax Highlighter I use in my blog for my code samples. Specifically, the newer code samples, as some of the old ones sucked as I was experimenting, trying to find the best one to settle on.

The tool I use is actually called SyntaxHighlighter and it's from Alex Gorbatchev. The trick is that the syntax highlighter is all javascript on the client side.

I was having all sorts of troubles with other code highlighters. First, there were ones that put css classes and stuff all through your code, trying to decorate each keyword. This just bloated my feed and site and made the code look weird in some Feed Readers. Then I tried using images for code, like ScottGu does, but that is just wrong. You can't copy paste the code, you can't search it, it's disrespectful for the blind, etc. Meh.

How I post code to my blog

I use Windows Live Writer to post all my blog posts, and it has a great plugin model. I've actually written a WLW plugin for the CueCat...it's really easy. I use a plugin from DasBlog contributor Anthony Bouch called PreCode that directly targets/supports SyntaxHighlighter from within WLW.

Screenshot of my plugins in Windows Live WriterThat means I see this from inside Live Writer. I slick Insert PreCode Snippet, and paste in my code.

If you're reading this blog post from inside an aggregator or feed reader, the next two code snippets look identical to you. However, if you visit my blog, you'll see that one is different.

// Hello3.cs
using System;

public class Hello3
{
public static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
Console.WriteLine("You entered the following {0} command line arguments:",
args.Length );
for (int i=0; i < args.Length; i++)
{
Console.WriteLine("{0}", args[i]);
}
}
}
// Hello3.cs
using System;

public class Hello3
{
public static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
Console.WriteLine("You entered the following {0} command line arguments:",
args.Length );
for (int i=0; i < args.Length; i++)
{
Console.WriteLine("{0}", args[i]);
}
}
}

One looks like this, as HTML:

// Hello3.cs
using System;

public class Hello3
{

public static void Main(string[] args)
{

Console.WriteLine("Hello, World!");
Console.WriteLine("You entered
the following {0} command line arguments:",
args.Length );

for (int i=0; i < args.Length; i++)
{

Console.WriteLine("{0}", args[i]);
}
}
}

See the 'class="c#" name="code"' part? Alex's Javascript SyntaxHighlighter is looking for those and parsing them on the client side. I choose to add
breaks, but that's an option in PreCode. Other options for SyntaxHighlighter include line numbering, gutters, copy/paste support, a toolbar and more.

P.S. If you don't use Windows Live Writer (and seriously, stop and ask yourself, WHY NOT?) and use instead a web interface, you can integrate SyntaxHighlighter into your web-based rich text editor. For example, Darren made a SyntaxHighlighter Plugin for the popular FCKeditor. Perhaps we'll put that in DasBlog.

Installing SyntaxHighlighter to Your Blog

You install the SyntaxHighlighter by adding it to your blog's template. It doesn't care what blog engine you run, as it doesn't need anything on the server:









Just add the shCore library and just the languages you require. If you want your blog to feel snappy and you have some control over your server, don't forget to set the files/directories to cache on the client by making them expire far in the future. You don't want your user's browsers to keep asking for these scripts each page view.

Even better, you can create your own plugins for SyntaxHighlighter if you use a language Alex hasn't supported officially. This guy threw together a Scala SyntaxHighlighter file by editing the Java one and adding a regex.

There are a few bugs but I think folks forget that Alex is doing this all alone, so I have to give him mad props for the effort. It can be lonely and unforgiving when you do something awesome and either no one cares, or folks only care to complain.

UPDATE: There's some great un-bundled brushes collected here.

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. I am a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by ORCS Web
Tuesday, December 02, 2008 10:58:57 AM UTC
This is something I've been struggling with for some time now. Ideally I would just add some code to the blog software to run it automatically through GeSHi or something similar, however I'm a lazy bastard and use a hosted blog on Blogger :-). The problem with the JS solution is that

a) it supposes that you have JS on (not always the case, especially when using NoScript)
b) it doesn't work in Google Reader (and possible other feedreaders)
Tuesday, December 02, 2008 11:00:30 AM UTC
I tried to use it. Unfortunately the scrolling errors I see on your and other sites are too much to bear. Wish I could help him out, but time...oh, precious time. Also, not being able to add acceents (e.g. bold or italic) to point out important things to look for was hard to give up. I use a simple non-highlighted PRE tag on my site.
Tuesday, December 02, 2008 11:25:42 AM UTC
Without script, the code just loses the syntax highlighting. It's still perfectly readable, and ready for copy and paste straight into an IDE. That seems like a pretty reasonable fallback to me.
Tuesday, December 02, 2008 12:10:46 PM UTC
What is the purpose of adding the <br /> tags?
Tuesday, December 02, 2008 12:11:17 PM UTC
I have been using another alternative, CopySourceAsHtml Visual Studio 2005 plug-in. I got it to work on VS 2008 and have not seen such a comprehensive tool like it for this. The nice extra is that it uses my color schema giving a nice personal style to it.
Tuesday, December 02, 2008 12:34:54 PM UTC
Yes, I use SyntaxHighlighter too... I came to the same conclusion as well.

Since there wasn't a built in F# brush, I went ahead and created one.

If you are interested you can find the F# brush on my tech blog.
Tuesday, December 02, 2008 1:27:59 PM UTC
Don't forget you can also customize the colors by changing the CSS.
Tuesday, December 02, 2008 1:41:21 PM UTC
My problem with this approach has always been that there often isn't enough from the context to highlight properly. Not usually a problem but one or two snippets I've posted are confusing at first glance because it thinks things are classes when they're not and vice versa.

For a primitive example, in the sample you provice "Console" isn't highlighted, and while not crucial in this case it can sometimes, as I say, become confusing.

Those corner cases probably aren't enough to stop this technique being useful though :)
Tuesday, December 02, 2008 2:51:21 PM UTC
I've been using this for quite some time too and I completely agree. Its THEE best snippet highlighter. Thanks for the link to the WLW plug-in. Now its darn near perfect!
Tuesday, December 02, 2008 4:08:46 PM UTC

Mohamed Meligy:
I have been using another alternative, CopySourceAsHtml Visual Studio 2005 plug-in.


I agree. I really like the options in CopySourceAsHtml. Even with all the style applied, it's easy to copy and paste the snippet generated (as long as you have line numbers turned off). Previously I have fought with several MovableType plugins, but found them lacking for the current C# specification.

It would be nice if Microsoft could tack a webservice onto MSDN that would return marked-up HTML with all the latest language bits from passed-in plain text. It would be dead simple to call with jQuery and then inject into the DOM on the fly.
Tuesday, December 02, 2008 4:24:46 PM UTC
Tuesday, December 02, 2008 4:29:13 PM UTC
I used to use CopySourceAsHtml, but now I use Syntax Highlighter. I use more than just Visual Studio in my day-to-day work, so I need highlighting on just Visual Studio code; CopySourceAsHtml can't help me. Also, if I want to change the style of my highlighting, it is just an easy javascript file to update the brush, whereas with CopySourceAsHtml, the embedded styling makes the code very ugly, and tough to restyle.
Tuesday, December 02, 2008 5:04:47 PM UTC
Hi Scott,

Will it also highlight if it the data is coming from a database and the returned text contained code.

Like the following:

<%# Eval("Body") %> //
Tuesday, December 02, 2008 5:40:30 PM UTC
Great!
I must switch to it too! (First I must start blogging again!)
Tuesday, December 02, 2008 6:30:59 PM UTC
P.S. If you don't use Windows Live Writer (and seriously, stop and ask yourself, WHY NOT?)


An install program that: 1) tried to install 5 other things; 2) tried to steal search provider and home page; 3) wanted me to make a new account.
What the heck do those have to do with a post editor?!

Tuesday, December 02, 2008 6:32:59 PM UTC
Don't you think it's a little lame to not show the syntax highlighting to feed readers? That seems like an incomplete solution. I had no idea you were using any special syntax highlighting until I visited this post.
Tuesday, December 02, 2008 7:46:39 PM UTC
Domenic - I'm not exactly sure, but the HTML/XHTML cleaner that DasBlog uses REALLY gets confused if there isn't a BR talk inside a PRE. It's valid per the HTML spec, so I don't sweat it too much.

Mark - The issue was that I couldn't find a syntax highlighting solution that worked in EVERY feed reader (there are lots of problems with online ones like Google Reader and BlogLines if I, as the publisher, try to get tricky with the CSS. Every solution I had would also make the feed 10x larger with tags and styles around the code.

SGraham - Sure, totally agreed the whole Windows Live Virus thing is lame, but uncheck those boxes and move on.
Tuesday, December 02, 2008 7:56:36 PM UTC
I prefer to use a Visual Studio plugin called Copy Source as HTML. No JavaScript required and it works in feed readers which is where the vast majority of views come from.

http://james.newtonking.com/archive/2008/05/13/display-nicely-formatted-net-source-code-on-your-blog.aspx
Wednesday, December 03, 2008 12:00:12 AM UTC
I would consider the plain text display inside feed readers to be a show-stopper. What percentage of your readers use a, well, reader? I would imagine it's a very high percentage.

I prefer the Code Snippet plugin for WLW, as discussed and shown here: http://blog.jeffhandley.com/archive/0001/01/01/posting-code-samples.aspx
Wednesday, December 03, 2008 12:21:04 AM UTC
Hi Scott, you might want to look at this one too: http://www.cdolivet.net/editarea/ It has an amazing list of features for a pure javascript implementation.

I have used it in an open source IDE project at http://globalsystembuilder.com and found it works extremely well.

Cheers!
Wednesday, December 03, 2008 12:10:00 PM UTC
Yea, I've been using my wordpress-hosted blog. It's pretty easy to use.
Wednesday, December 03, 2008 6:51:30 PM UTC
Scott,

I'm going to be looking at Google Prettify which seems more lightweight and robust than SyntaxHighlighter. We currently use SyntaxHighlighter and enjoy it, but need something faster.

http://code.google.com/p/google-code-prettify/
Wednesday, December 03, 2008 8:54:31 PM UTC
I tried using CopySourceAsHtml but it couldn't handle even simple code without messing things up. It uses a static algorithm such that the order in which you select your code determines what colors things showed up as. Inline CSS didn't help matters.

I eventually found CodeHtmler (http://www.codeplex.com/CodeHtmler) and really liked what I saw. It could handle code from any number of languages and properly handle colorizing them. Furthermore it could be configured to use my existing CSS classes rather than creating new ones of its own. It was a standalone library so I put a wrapper around it for use in VS and now that is all I use.
Wednesday, December 03, 2008 10:14:37 PM UTC
Not having an osx version keeps me from using Writer. Before I left Windows, I did use Writer and liked it but...msft no likey osx too much, eh? :-)
Wednesday, December 03, 2008 10:15:00 PM UTC
Hey, how about fixing your site - I'm getting Javascript errors everytime I leave a page - looks like its probably coming from your ads?

Better yet, how about you use your insider position at microsoft to have them put an option in IE, to only show debug messages for domains of my choosing?

Dave
Wednesday, December 03, 2008 10:42:51 PM UTC
Well said Scott !

I too use Alex's highlighter and like it for one more reason.

If CSS and Javascript is disabled, the code still shows up nicely and is usable by CTRL C + CTRL V....
Shiva
Wednesday, December 03, 2008 11:32:04 PM UTC
I've to give it a try, once I find the time to play with my blog skin again :(
Thursday, December 04, 2008 1:59:26 AM UTC
Thanks Scott for introducing me to both Windows Live Writer and Syntax Highlighter. (And in only one post!)

I found that I had to add these lines to my blog template to get the highlighting to work:

<script language='javascript'>
dp.SyntaxHighlighter.ClipboardSwf = 'http://howard.ross.work.googlepages.com/clipboard.swf';
dp.SyntaxHighlighter.HighlightAll('code');
</script>
Thursday, December 04, 2008 2:13:07 PM UTC
<pre name="code" is not standards compliant. however you can tweak the highlighter to use the class tag instead of the name attribute that doesn't exist.

i.e.
<pre class="code csharp"
Thursday, December 04, 2008 10:22:32 PM UTC
Thanks for this post. I'd always been meaning to, but never quite getting around to, figuring out how you were doing the formatting (beyond the obvious that it had to be a script).

I've made a start at adding brushes for F#. and <a href="http://stevegilham.blogspot.com/2008/12/syntax-highlight-brush-for-erlang.html>Erlang</a>, as my two "most wanted".
Friday, December 05, 2008 10:48:07 PM UTC
Good post! But I'm just using some plug-ins for Windows Live Writer. I've tried many of them...
Monday, December 08, 2008 6:03:44 PM UTC
WLW looks interesting. Unfortunately, I can only run it on 1/3 of my machines, which makes it rather inconvenient.
Wednesday, December 10, 2008 7:54:48 AM UTC
"P.S. If you don't use Windows Live Writer (and seriously, stop and ask yourself, WHY NOT?)"

Scott: because it support only 2 operating systems (xp,vista) ? This is WRONG. In these days of .NET/Mono everybody expect that it runs on more than 2 OS.

I know you are ms guy and trying to propagate ms products, but seriously - such "marketing" makes that kind of products not usable.
slavomir
Friday, December 12, 2008 3:59:21 PM UTC
I use WLW with the "Paste from Visual Studio" plugin; which formats the code block as well as adding span tags for the colors.
Tuesday, December 16, 2008 10:31:47 AM UTC
I wrote a Plugin called PostCodeWithDignity for WLW a very long time ago to post code to the Syntaxhighlighter Plugin because I couldn't stand the RTF Syntaxhighlighters that completely obscured markup (and Live Writer always stripped out the attributes on the pre tags back then).

http://www.codeplex.com/wlwPostCode

greetings Daniel
Tuesday, December 16, 2008 8:11:23 PM UTC
Ok I got this working no problem its a handy little tool and you described hwo to set it up very well. However you mentioned this in your post "don't forget to set the files/directories to cache on the client by making them expire far in the future". How might one do this? I'm still learning and am not sure how. It's my server so I've got complete control, and it's my app so thats one better. Can it be done programmatically, or is it just a server side item? A point in the right direction is all I really need.
Tim
Comments are closed.

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.