Scott Hanselman

How to Post Code To Your Blog and other Religious Arguments

August 10, '10 Comments [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
Sponsored By
Hosting By
Dedicated Windows Server Hosting by ORCS Web
Tuesday, August 10, 2010 12:36:33 AM UTC
Definitely gotta go with the PreCode and SyntaxHighlighter. Its just awesome being able to copy/paste text thats ready to go into VS2010.
Tuesday, August 10, 2010 12:39:48 AM UTC
More timely impossible. Thanks!!
Tuesday, August 10, 2010 12:43:58 AM UTC
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!
Nathan Blevins
Tuesday, August 10, 2010 12:44:31 AM UTC
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.
Tuesday, August 10, 2010 1:11:36 AM UTC
I've been using Google's Prettify which is another client-side tool. It supports plenty of languages (including Haskell, my favorite).
Tuesday, August 10, 2010 1:54:36 AM UTC
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.
Tuesday, August 10, 2010 1:54:52 AM UTC
Doesn't Scott Gu use images for code? Your assertion seems somewhat... harsh? :)
Tuesday, August 10, 2010 2:13:16 AM UTC
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).
Tuesday, August 10, 2010 2:30:16 AM UTC
I use SyntaxHighlighter and is not a bad thing
Tuesday, August 10, 2010 3:14:27 AM UTC
@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)
Tuesday, August 10, 2010 3:22:14 AM UTC
"Don't do this. You're a bad person."

I love this line.
Tuesday, August 10, 2010 3:23:47 AM UTC
"Don't do this. You're a bad person."

I love this line.

Trying again, without OpenID this time.
Tuesday, August 10, 2010 4:19:23 AM UTC
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.
Tuesday, August 10, 2010 4:42:29 AM UTC
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!
Tuesday, August 10, 2010 4:49:28 AM UTC
Forgot to mention: Gists can be forked and edited by other users too, which give them some cool social features like user contributed patches ;-)
Tuesday, August 10, 2010 4:56:14 AM UTC
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? :-)
Tuesday, August 10, 2010 5:18:47 AM UTC
Thanks for this article! this is exactly what i was looking for ;)
Tuesday, August 10, 2010 5:22:52 AM UTC
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.
Tuesday, August 10, 2010 6:30:40 AM UTC
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).
Tuesday, August 10, 2010 7:19:57 AM UTC
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
Tuesday, August 10, 2010 8:28:13 AM UTC
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
Tuesday, August 10, 2010 8:51:13 AM UTC
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.
Tuesday, August 10, 2010 8:52:55 AM UTC
What about images with all the code in the ALT tag? :)
Tuesday, August 10, 2010 9:00:55 AM UTC
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.
Tuesday, August 10, 2010 9:10:24 AM UTC
Actually, Code Formatter Plug in for Windows by Steve Dunn works in Google Reader (R)(TM). So, some RSS readers can display it correctly.
Tuesday, August 10, 2010 12:32:28 PM UTC
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.
Tuesday, August 10, 2010 12:46:11 PM UTC
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...
Tuesday, August 10, 2010 1:25:52 PM UTC
BlogTrog.com has a severe case of spanitis, as it uses actipro, but it works in RSS feeds...
Tuesday, August 10, 2010 2:16:11 PM UTC
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.
Tuesday, August 10, 2010 4:59:54 PM UTC
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?
Tuesday, August 10, 2010 7:16:55 PM UTC
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.

Tuesday, August 10, 2010 7:50:54 PM UTC
Thanks for the clarification.

OpenID isn't working for some reason (names Terry)
Wednesday, August 11, 2010 2:21:47 PM UTC
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
Wednesday, August 11, 2010 5:28:34 PM UTC
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.
Wednesday, August 11, 2010 7:43:42 PM UTC
I normally post the source code for a small sample application (zipped), that way my readers have something that works.
Wednesday, August 11, 2010 10:45:34 PM UTC
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?
Monday, August 16, 2010 2:57:57 PM UTC
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?
Wednesday, August 18, 2010 6:32:55 AM UTC
Great post!
Thursday, August 19, 2010 12:11:49 PM UTC
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
Dave R.
Friday, August 20, 2010 9:14:31 AM UTC
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.
Monday, December 06, 2010 12:18:12 AM UTC
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.