Jaa


Tip: Beautifully Formatted .NET C# Code in Blog Post

I’ve been searching for a way to nicely display code on my blog for a long time!!  These old posts prove it Well Formatted Blog, Can't Directly Copy from MS Word and Moving Away from Word Based Blogs.  I think I’ve on to something now!

Here’s a snippet, like it?  I just copy code to the clipboard from VS, click a button in Word, and paste into BlogJet (or Community Server’s rich text editor).  Pasting directly into BlogJet doesn’t work well, so this tips leverages Word.

using System;

namespace LittleClassForFormattingExample

{

   public class ICar : IVehicle

   {

      // all cars have basic engine funtionality

      public void StartEngine();

      public void StopEngine();

   }

}

Here’s how it works…

I created two macros in MS Word 2003 (code below) and assign them to buttons on the toolbar.  I tried using a Word Style, but it can’t be saved as a style without loosing some coloring, so the macro does the trick.  It is important that VS is set to keep tabs (not converting tabs to spaces).  I had to go back and reformat my code in VS since my tabs had been converted to spaces.  There are tools that do this automatically, like CodeRush and ReSharper.

Make sure VS is set to “Keep tabs”
VS Options to Set Tabs - Modified

I placed my macros in the Normal.dot template (stored at "%UserProfile%\Application Data\Microsoft\Templates\Normal.dot").  You can open the template with just a copy/paste the file path (without quotes) into MS Word’s open file dialog:

Using environment variables in file names
MS Word Open File Dialog for Normaldot - Modified

From MS Word’s “Tools / Macro / Visual Basic Editor” menu, I create a “Main” module under the “TemplateProject (Normal.dot)” project node and put these two macros in it.

Here is my Normal.dot Word template (with this code) you can use too:
https://coad.net/blog/resources/NormalWordTemplate.zip

Sub FormatCodeBlock()

'

' FormatCodeBlock Macro

' Macro created 7/6/2006 by Noah Coad

'

  Dim i As Integer

 

  ' do some error checking

  If Len(Selection.Text) < 2 Then

    MsgBox "There must be some text selected first."

    Exit Sub

  End If

 

  ' apply the paragraph formatting with borders and shading

  With Selection.ParagraphFormat

    .Shading.BackgroundPatternColor = wdColorGray05

   

    .Borders(wdBorderLeft).LineStyle = wdLineStyleSingle

    .Borders(wdBorderRight).LineStyle = wdLineStyleSingle

    .Borders(wdBorderTop).LineStyle = wdLineStyleSingle

    .Borders(wdBorderBottom).LineStyle = wdLineStyleSingle

    .Borders(wdBorderHorizontal).LineStyle = wdLineStyleNone

   

    With .Borders

      .DistanceFromTop = 6

      .DistanceFromLeft = 4

      .DistanceFromBottom = 6

      .DistanceFromRight = 4

      .Shadow = False

    End With

  End With

 

  ' set tabs

  For i = 0 To 11

    Selection.ParagraphFormat.TabStops.Add Position:=InchesToPoints(0.25 + i / 4#), _

      Alignment:=wdAlignTabLeft, Leader:=wdTabLeaderSpaces

  Next

 

End Sub

 

Sub FormatCodeBlockInClipboard()

'

' FormatCodeBlockInClipboard Macro

' Macro created 7/6/2006 by Noah Coad

' Depends on the "FormatCodeBlock" macro

'

 

  ' create a new document

  Documents.Add Template:="Normal", NewTemplate:=False, DocumentType:=0

 

  ' paste clipboard contents

  Selection.PasteAndFormat wdPasteDefault

 

  ' remove the extra space that VS puts on the selected text, if it exists

  If Asc(Mid(ActiveDocument.Content.Text, Len(ActiveDocument.Content.Text) - 1, 1)) = 13 Then Selection.TypeBackspace

 

  ' select everything

  Selection.WholeStory

 

  ' apply the code block formatting

  FormatCodeBlock

 

  ' copy the changes to the clipboard

  Selection.Copy

 

  ' close this workspace

  ActiveWindow.Close False

 

  ' notify the user

  MsgBox "Clipboard contents have been HTML formatted inside a Code Block."

End Sub

Then I create a button on the toolbar to both of these macros.  Right-click the toolbar area, choose “Customize…”, then “Macros”, and just drag & drop the two macros (one at a time) onto the toolbar.  Right-click the new long text button on the toolbar and change the “Name” property to something easier.

“Code Block in Clipboard” toolbar button to the macro
MS Word Custom Toolbar w Code Block in Clipboard

You’re set!  Just copy code to the clipboard in VS, click the button (for the “FormatCodeBlockInClipboard” macro), and paste into BlogJet (or Community Server).

Comments

  • Anonymous
    July 07, 2006
    news of the daya grab bag for what&amp;#39;s happening in Community ServerWow! The Telligent Front Officehas

  • Anonymous
    July 08, 2006
    I'm still a fan of either using http://www.manoli.net/csharpformat/ or

    Copy Source as HTML

    http://www.jtleigh.com/people/colin/software/CopySourceAsHtml/

  • Anonymous
    July 18, 2006
    I've tried your macro with Community Server 2.0 and for some reason it look correct in the post editor but once published it loses its formatting. Any idea why this is? Do I need to add some CSS styles or something?

  • Anonymous
    November 22, 2006
    Microsoft&#39;s Noah Coad gives step-by-step instructions (along with a downloadable .ZIP) on how to

  • Anonymous
    March 12, 2007
    Microsoft&#39;s Noah Coad gives step-by-step instructions (along with a downloadable .ZIP) on how to

  • Anonymous
    February 04, 2008
    I use the following tools, all free.. Visual Web Developer 2008 Express Edition SQL Server Express Management

  • Anonymous
    February 23, 2008
    PingBack from http://condron.wordpress.com/2008/02/24/blogging-code/

  • Anonymous
    March 19, 2010
    A bit round-about, but still good. There are some very nice web options, but I have never found a decent desktop application to do the same thing. So I made my own.