Scott Hanselman

Best Code Syntax Highlighter for Snippets in your Blog

December 02, 2008 Comment on this post [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. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Hosting By
Hosted in an Azure App Service
December 02, 2008 14:58
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)
December 02, 2008 15:00
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.
December 02, 2008 15:25
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.
December 02, 2008 16:10
What is the purpose of adding the <br /> tags?
December 02, 2008 16:11
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.
December 02, 2008 16:34
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.
December 02, 2008 17:27
Don't forget you can also customize the colors by changing the CSS.
December 02, 2008 17:41
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 :)
December 02, 2008 18:51
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!
December 02, 2008 20:08

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.
December 02, 2008 20:29
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.
December 02, 2008 21:04
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") %> //
December 02, 2008 21:40
Great!
I must switch to it too! (First I must start blogging again!)
December 02, 2008 22:30
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?!

December 02, 2008 22:32
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.
December 02, 2008 23:46
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.
December 02, 2008 23:56
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
December 03, 2008 4:00
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
December 03, 2008 4:21
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!
December 03, 2008 16:10
Yea, I've been using my wordpress-hosted blog. It's pretty easy to use.
December 03, 2008 22:51
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/
December 04, 2008 0:54
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.
December 04, 2008 2:14
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? :-)
December 04, 2008 2:15
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?

December 04, 2008 2:42
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....
December 04, 2008 3:32
I've to give it a try, once I find the time to play with my blog skin again :(
December 04, 2008 5:59
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>
December 04, 2008 18:13
<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"
December 05, 2008 2:22
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".
December 06, 2008 2:48
Good post! But I'm just using some plug-ins for Windows Live Writer. I've tried many of them...
December 08, 2008 22:03
WLW looks interesting. Unfortunately, I can only run it on 1/3 of my machines, which makes it rather inconvenient.
December 10, 2008 11:54
"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.
December 12, 2008 19:59
I use WLW with the "Paste from Visual Studio" plugin; which formats the code block as well as adding span tags for the colors.
December 16, 2008 14:31
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
December 17, 2008 0:11
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.