Formatting code in blog entries

One of the most annoying things I’ve found when blogging code is getting the colour coding right. It seems like a lot of people don’t bother – all code on MSDN just has a grey background.

In the past, I’ve tried using CopySourceAsHtml, which is a Visual Studio .NET add-in allowing users to highlight some code, and copy it to the clipboard, during which it automatically gets formatted, ready for pasting into your blog.

This worked well for small bits of code, but generally, I found that when there were long lines of code, it would mess up the design of the site, and eventually, I gave up using it.

But, those woes are now over… Recently came across the fantastic dp.SyntaxHighlighter, which is a free Javascript tool for source code syntax highlighting.

It supports C#, VB/VB.NET, Delphi/Pascal, JavaScript, PHP, Python, SQL, XML, HTML, XSLT (and other XML style code). Implementation is easy – just download, reference the CSS and relevant ‘brushes’ in your page, and then whenever you want to reference code in your page, put it inside a textarea tag – eg. <textarea name=’code’ class=’c#’>your code here</textarea>

I reckon this is a must-have for anyone who blogs code! Check out the sample page or download it! :-)

Collapsing & expanding regions in VS.NET

Regions are great for collapsing a bunch of code into a single line. Combined with Resharper, you can just select a whole bunch of code, hit Ctrl+J (Surround With), Region, and voila – it’ll automatically add the #region and #endregion keywords around the selected text.

It’s annoying that there’s no keyboard shorcuts to collapse and expand specific regions. It would be great if when the cursor was inside a region, I could use a shorcut to collapse it. Anyone know of a way to do this?

Update: Ater Googling around a little bit, I found Tips and tricks for the Visual Studio .NET IDE which provided the answer: Outlining.

  • Fold/Unfold the current code block – Ctrl+M, Ctrl+M
  • Unfold all – Ctrl+M, Ctrl+L
  • Stop outlining – Ctrl+M, Ctrl+P
  • Fold all – Ctrl+M, Ctrl+O