Scott Hanselman

How to Post Code To Your Blog and other Religious Arguments

August 10, 2010 Comment on this post [41] Posted in ASP.NET | Blogging | Open Source
Sponsored By

If you've got a programming blog, chances are you'll want to post some code snippets. Posting code sounds easy but it's surprisingly tricky if you consider all the ways that people will be reading your blog. There's a number of ways. Here's a few and their pros and cons.

Copy Paste from your IDE (like Visual Studio, for example)

If I copy paste directly from VS into my editor of choice, Windows Live Writer, I'll get a <pre> section.

using System;

namespace WindowsGame1
{
#if WINDOWS || XBOX
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main(string[] args)
        {
            using (Game1 game = new Game1())
            {
                game.Run();
            }
        }
    }
#endif
}

Pros:

  • It's just text.
  • Looks the same everywhere.
  • Code is in a pre and you can apply css rules to pre's if you like.

Cons:

  • It's just text.
  • Looks the same everywhere.

I can also go to the Visual Studio Gallery and get the Copy As HTML Extension from inside the "Productivity Power Tools." When someone names something "Productivity Power Tools" but doesn't include it out of the box that means they are "things that aren't totally tested and that would blow your mind if we did include them in the box so just get them and be happy but we are sorry we didn't ship them straight away."

Once this extension is plugged in, when I Ctrl-C some text, VS adds not just plain text to the clipboard but also rich HTML and what-not.

using System;

namespace WindowsGame1
{
#if WINDOWS || XBOX
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main(string[] args)
        {
            using (Game1 game = new Game1())
            {
                game.Run();
            }
        }
    }
#endif
}

This looks lovely, but it includes a pile of <spans> and now my code is a bunch of marked up HTML, rather than a block of code.

Pros:

  • Looks the same everywhere, RSS or on your site. Consistent.
  • Will always look like this, no need to change anything.

Cons:

  • Inline styles and colors. Ick.
  • Span-itis.
  • Stores the formatting in your blog system directly (in the DB, etc)
  • Will always look like this, you can't change anything.

Using PreCode and SyntaxHighlighter

PreCode is Anthony Bouch's Windows Live Writer plugin. SyntaxHighlighter is Alex Gorbatchev's JavaScript (that's client-side) syntax highlighter. SyntaxHighlighter highlights your code locally using <pre> blogs that are marked for specific languages. You include "brushes" for just the langugaes you care about. This is the combination that I currently use.

SyntaxHighlighter is definitely the client-side highlighter of choice, but there are others you might also check out including:

  • Chili Highlighter - Hosted on Google Code
  • Google Code Prettify - This is the code highlighter that Google themselves use on Google Code. It doesn't require you to specify the language. It works on most C-style languages, works iffy on Ruby, PHP and VB, and needs extensions for LISP and F# and others.

NOTE: Make sure whatever one you pick that you're cool with the OSS license for your library of choice.

From within Live Writer you click "Insert PreCode Snippet" and paste your snippet in. It has a number of nice options. I use HTML encode and "replace line endings with <br/> which is required for use in DasBlog for historical reasons. It also has a number of SyntaxHighlighter specific options for doing line-highlights or turning the toolbar on and off.

PreCode Code Snippet Manager

This creates output like this. Here's the trick, though. If you are reading this post via RSS, you're seeing just plain text. You need to visit this post on my site directly in order to see pretty fonts and colors because the JavaScript isn't firing in your RSS Reader.

It's created a <pre> that looks like this <pre class="brush: csharp; auto-links: false;"> and the JavaScript comes around later and processes it in the browser.

using System;

namespace WindowsGame1
{
#if WINDOWS || XBOX
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main(string[] args)
{
using (Game1 game = new Game1())
{
game.Run();
}
}
}
#endif
}

Pros:

  • Having code stored in a pre means there's no formatting stored in your blog system.
  • Looks great in any browser with JavaScript
  • You can choose themes and change the look and feel of your code whatever
  • You also get nice printing support, toolbars, line highlighting, etc.

Cons:

  • RSS readers effectively lose out and see just text.
    • NOTE: There really is no "good" solution for RSS viewers unless your blog engine's RSS Feed Generator does the processing on the server-side for code blocks and sends <span>itis when the feed is requested.
  • Once you've inserted code in WLW with PreCode, you can't easily edit the code. I usually edit it outside and paste again.

Using Code Formatter Plugin for Windows by Steve Dunn

Another Windows Live Writer plugin is Steve Dunn's Code Formatter. It has a few features that differ from PreCode, and a few quirks (as of the current version). It supports not just Syntax Highlighter style <pre>'s for code but also <span>itis inline styles using ActiPro's SyntaxHighlighter.

1 using System; 2 3 namespace WindowsGame1 4 { 5 #if WINDOWS || XBOX 6 static class Program 7 { 8 /// <summary> 9 /// The main entry point for the application. 10 /// </summary> 11 static void Main(string[] args) 12 { 13 using (Game1 game = new Game1()) 14 { 15 game.Run(); 16 } 17 } 18 } 19 #endif 20 }

You can also insert code as images, which people do, so I mention it here, but I think is rude to blind folks, and not useful as GoogleBing can't see it. Don't do this. You're a bad person.

 

Pros:

  • Supports WLW's "Smart Content Editing" so you can edit your code after you insert it.
  • When using ActiPro
    • Looks the same everywhere, RSS or on your site.
    • Will always look like this, no need to change anything.
  • When using SyntaxHighlighter
    • Looks great when users visit your site
  • Supports images (if you're into that kind of thing and you are Satan)

Cons:

  • When using ActiPro
    • Intense Span-itis and embedded colors.
    • Inline styles and colors. Ick.
    • Stores the formatting in your blog system directly (in the DB, etc)
  • RSS readers effectively lose out and see just text.
  • The plugin inserts unneeded (IMHO) inline styles like width and height.
  • Supports images (if you're NOT into that kind of thing or you're blind.)

Hosting your Code elsewhere like GitHub

GitHub is a social code hosting and sharing site, and Gist is a part of their site where you can easily share code without logging in. You can create private or public Gists, or you can create your own GitHub login and keep the source you host on your blog in one place.

You can share your code by using embedded JavaScript like this: <script src="http://gist.github.com/516380.js?file=Hanselman%20Sample%201"></script>. You don't get too much control over the look and feel of it, but it "just works." 

using System;

namespace WindowsGame1
{
#if WINDOWS || XBOX
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main(string[] args)
        {
            using (Game1 game = new Game1())
            {
                game.Run();
            }
        }
    }
#endif
}

Pros:

  • You can store all your code in an external service, just like you might store all your pictures at Flickr.
  • All your code is in once place.
  • Dead simple.

Cons:

  • You're no longer storing your code with your blog posts. You're storing a JavaScript link.
  • You need Javascript running within your RSS reader for the code to show up. Most won't do this for security reasons. Otherwise, you'll see nothing.
  • You can't control it. It's alive!

Conclusion

As with all religious arguments, I don't care who you choose to go with, just that you pick one and be excited about it, and that you know the pros and cons. You can certainly switch back and forth if you like, but I personally believe there's something to be said for consistency, so pick something you can live with for a few years, or your life on earth. ;)

Currently, I'm using PreCode with SyntaxHighlighter until a better solution comes along. Did I miss any good options?

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
August 10, 2010 4:36
Definitely gotta go with the PreCode and SyntaxHighlighter. Its just awesome being able to copy/paste text thats ready to go into VS2010.
August 10, 2010 4:39
More timely impossible. Thanks!!
August 10, 2010 4:43
I prefer the Syntax Highlighter w/ PreCode. The GitHub thing is fun, but I don't like the thought of having to update all my posts b/c the site goes down, changes ToS, etc.

As for the no image thing, THANK YOU! I hate this. Someone should poke at ScottGu to read this post. /sigh

Useful post, thanks!
August 10, 2010 4:44
I've been using PreCode and SyntaxHighlighter for a while and it seems to work best for me. My blog readers also enjoy copy/pasting functionality built-in.
August 10, 2010 5:11
I've been using Google's Prettify which is another client-side tool. It supports plenty of languages (including Haskell, my favorite).
August 10, 2010 5:54
Eerie that you posted this, as I'm just now starting a new series of articles -- to be published elsewhere than on my blog -- for which I've also been looking into the current state of play.

Like you, I'm in favor of avoiding span-itis and like SyntaxHighlighter for that reason. But you wind up depending on its particular set of regexes. When I fed it this:

public static Object DictObjToObj(Dictionary<string, object> dict_obj, Type type)

it produced this (text only, no effort to reproduce colors here):

public static Object DictObjToObj(Dictionary<string, object=""> dict_obj, Type type)

Given that we are (I hope) in the Age of Services, here's a scenario I'd like to see. Every language is intimately known by a compiler and/or IDE. Instances of those compilers/environments would reside in the cloud, as services that would take in raw source and return structurally-annotated source. One or more companion services would then colorize the structurally-annotated source. That transformation could be done client-side, a la SyntaxHighlighter, but also server-side, as I'd need to do because I won't be able to source JavaScript into the site I'll be posting to.

With this arrangement you could also compose pipelines of transformations. So, for example, where-defined and where-used annotations, relative to some line-number-addressable data store, might be injected into a pipeline.

There are sites that do colorizing interactively, e.g. http://tohtml.com/, http://www.quickhighlighter.com/. But I'm not finding anything that's a service in the sense I mean here.
August 10, 2010 5:54
Doesn't Scott Gu use images for code? Your assertion seems somewhat... harsh? :)
August 10, 2010 6:13
I love the idea of using Gists for code in posts, but since it is added via javascript it also does not show via RSS since most (all) aggregators don't allow the script to execute (with good reason of course, but that is a con for using Gists).
August 10, 2010 6:30
I use SyntaxHighlighter and is not a bad thing
August 10, 2010 7:14
@judell - I also like the idea of a service.
@Scott - that's an older screen shot of PreCode. Are you not using the latest WPF version? (Props to Alex who did all the really hard work in Syntaxhighlighter)
August 10, 2010 7:22
"Don't do this. You're a bad person."

I love this line.
August 10, 2010 7:23
"Don't do this. You're a bad person."

I love this line.

Trying again, without OpenID this time.
August 10, 2010 8:19
As Scott politely noted in email, you can avoid the problem I noted above by means of a clever procedure known as RTFM:

"One important thing to watch out for is opening triangular bracket <. It must be replaced with an HTML equivalent of &lt; in all cases." (http://code.google.com/p/syntaxhighlighter/wiki/Usage)

There's still a question about where/how to do the transformation. I like the idea of decoupling the production of structural annotation, which is what SyntaxHighlighter creates, so it can be deployed independently of the browser in environments that allow user-supplied CSS but not user-supplied JavaScript. But that may not be practical.
August 10, 2010 8:42
Another GREAT post! I've tried all the methods you mentioned, and while I usually prefer Syntax Highlighter w/ PreCode, I have found that Gists on GitHub have one other cool feature: They are MUCH easier to update! If I am posting a full JS bookmarklet or a full IronPython script, there is bound to be a few bugs in it. And sure I could edit the code and copy/paste the new results into the blog to update it, or I could just use a Gist and then deal with the updates like I would any other code file (aka using source control).

So while I do primarily use Syntax Highighter because it makes things look pretty, For any full source code files that may need to be maintained Gists are definitely the way to go!

Keep up the great work!
August 10, 2010 8:49
Forgot to mention: Gists can be forked and edited by other users too, which give them some cool social features like user contributed patches ;-)
August 10, 2010 8:56
Call me old-fashioned, but I just copy code, paste it into Word, "cut" it out of word (it will then be in rich-text-format), then paste per normal and it keeps all of the formatting. Doesn't need to be more complicated than that, right? :-)
August 10, 2010 9:18
Thanks for this article! this is exactly what i was looking for ;)
August 10, 2010 9:22
I go the Github route, since I can organize multiple snippets into one 'gist', and then the description of the gist is a link back to the blog post. Keeps things organized, looks good, and I wrote some middleware for my blog to make them load more efficiently.
August 10, 2010 10:30
if you use Visual Studio, there is a very simple way that copy-paste code to a Word document and again copy/paste everywhere you want!(that is colored indeed).
August 10, 2010 11:19
Great post. Thanks for pointing out the Github option, which appeals to me after years of using code and pre tags. Now I need to go through and rework my past code snippets!

Stu
stu
August 10, 2010 12:28
I'm using the Pygments for Windows live writer which I find very useful.
Has the same span-itis and inline style issues, but it's got lexers for a LOT of languages..

Erik
August 10, 2010 12:51
One con of SyntaxHighlighter that you didn't highlight as a con is that it does rely on JavaScript to deliver its benefits. It would be my solution of choice, but my blogging host doesn't permit script in posts.
August 10, 2010 12:52
What about images with all the code in the ALT tag? :)
August 10, 2010 13:00
I see one missing option in here!

Have you tried C\opysourceAsHtml Visual Studio plug-in?
http://copysourceashtml.codeplex.com/

This is basically similar to the VS copy-paste style but with the extra context-coloring added (for classes, etc..), captures also your custom colors and background, etc...

Sometimes the context does matter in coloring. For example, how to tell if some word is an identifier or a class name or so (different coloring...).

Also (probably not you), you may have special fonts/colors setup and want to show the code the same way it looks in your editor.
August 10, 2010 13:10
Actually, Code Formatter Plug in for Windows by Steve Dunn works in Google Reader (R)(TM). So, some RSS readers can display it correctly.
August 10, 2010 16:32
Thanks for sharing! You've quickly become my favorite developer to read and learn from and your podcast is awesome! I hope you don't mind if I link to your blog post from my blog. Is that kosher? I'm new to this blogging thing.
August 10, 2010 16:46
To add to the religion: thou shalt not use line numbers unless they are referenced in your post. Cut-and-paste programmers hate line numbers, because they have to remove them after pasting. Then again, maybe thou shalt not be a cut and paste programmer...
August 10, 2010 17:25
BlogTrog.com has a severe case of spanitis, as it uses actipro, but it works in RSS feeds...
August 10, 2010 18:16
GitHub: You don't get too much control over the look and feel of it, but it "just works."

Ironically, this is the only one that DIDN'T show up at all on my Android phone email reader (I get the blog posts as emails). There literally was no code at all.
August 10, 2010 20:59
For the Copy As HTML Extension from inside the "Productivity Power Tools." you state that storing in the DB is a Con but for Code Formatter Plugin for Windows by Steve Dunn you state it as a Pro.

Did I miss something when reading the article?
August 10, 2010 23:16
Random Google OpenID Person - Sorry, that was a copy paste error. I think having formatting in your DB is a con.

JasonHS - Yes, good point. You need JS running inline on your phone (and/or RSS reader) to get GitHub snippets to work.

August 10, 2010 23:50
Thanks for the clarification.

OpenID isn't working for some reason (names Terry)
August 11, 2010 18:21
I just started using Windows Live Writer for my blog and find it takes the pain out of the admin tools for writing posts. I'll now write more cause it's easier.

The one pain point was source code and with PreCode you've just solved that for me.

Thank you for this post.

Ralph
August 11, 2010 21:28
I use WLW plugin "Paste from Visual Studio". It just does a pre class="code" block with spans for colors; I want a post to not have external dependencies for its content. Relying on a script means there will be RSS issues (I don't want to have to test my feed on an iPad for example). This plugin does not add any width settings, so I can set those with CSS to fit the blog design.
August 11, 2010 23:43
I normally post the source code for a small sample application (zipped), that way my readers have something that works.
August 12, 2010 2:45
I'm hoping Scott Gu reads this. He posts so much good source code in his blogs and they are darn near worthless to those of us who like to copy+paste+adapt stuff. To the point that I tend to ignore hits to his blogs when Bing'ing for answers. Images for source code?!?! Why, God, why?
August 16, 2010 18:57
Hi Scott, thanks for your blog coding tips. You covered multiple pros and cons to a variety of options, but what about if I want to add flash, and people are reading my blog using phones? I am into images (sorry!) and would like to use flash, but will people not be able to view it using a phone?
August 18, 2010 10:32
Great post!
August 19, 2010 16:11
You should definitely forward this on to The Gu. He needs to be taught a lesson as he's been naughty for far too long :D
August 20, 2010 13:14
Image or any technique forbidding plain text copy/paste of code is definitively a no-no.
The "Code Formatter Plugin for Windows by Steve Dunn" is bad with this regard as the line numbers (come on, we no longer code in old school Basic!) are copied with the code.
The "Span-itis" as con is strange, as JavaScript will just generate similar code (or, in the case of "SyntaxHighlighter", code-itis), so at the end, it is as verbose (hard to avoid, anyway).
The "Inline styles and colors" can be avoided with smarter generators (SciTE exports to HTML by generating a CSS section and using short name classes for the spans).
The argument against frozen formatting is interesting, but frankly, you don't change formatting that often, do you?

I am not fan of JavaScript formatting. The RSS argument is a good one (HTML in e-mail client is a similar one), and too often I see sites taking time to convert the code boxes on the fly, because of a slow computer, busy CPU, heavy page, etc.

So, my personal choice is to paste pre-formatted code, but I appreciate your survey of the available solutions.
December 06, 2010 4:18
Nice list....
I tried PreCode and Synatxhighlighter plugins for Window Live Writer but none of them worked well.
I found this called Code Snippet for WLW and it seems to be prettey decent. There might be some issues but so far it has served my purpose.
http://lvildosola.blogspot.com/2009/03/code-snippet-plugin-for-windows-live.html
http://wlwplugincollection.codeplex.com/wikipage?title=Code%20Snippet&referringTitle=Home
gs

Comments are closed.

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