Welcome to AddressOf.com Sign in | Join | Help

Format Code to HTML within a VS.NET 2K3 Macro (leveraging Microsoft Word)

Brad Abrams pointed out that he uses copy and paste into Word from Visual Studio 2005 Express Edition.   Mike Parsons commented that he uses a VS.NET macro to help automate the same task.  I really liked the idea of doing this directly within VS.NET.

After looking through it, I found what I thought were some flaws in the implementation; not removing the file upon finishing the task being one of them causing a lot of temporary files being created and the fact that he wasn't leveraging some System.IO methods to handle the creation of the temporary file.  In addition, you still had to switch to another task (your system default browser) in order to select the text, yet again, to paste it in your blogging software.  In addition, the final HTML was still pretty ugly.  I decided to fix some of these deficiencies. 

I think this macro pretty solid, however, I've not really done a whole lot of dogfooding just yet.  If you find any problems, please let me know. 

Here is the final product.

Option Explicit On

Option Strict Off ' Using late binding.

 

Imports System

Imports EnvDTE

Imports System.Diagnostics

 

Public Module Module1

 

  Private Const WdPasteDefault As Integer = 0

  Private Const WdFormatFilteredHTML As Integer = 10

  Private Const WdWebView As Integer = 6

  Sub FormatSourceCode()

 

    ' Get the currently selected code snippet.

    Dim selection As TextSelection = CType(DTE.ActiveDocument.Selection(), TextSelection)

 

    ' Check that something is selected.

    If selection.Text = "" Then

      MsgBox("No code selected!", MsgBoxStyle.Critical Or MsgBoxStyle.OKOnly, "Format Code")

      Return

    End If

 

    ' Create a temporary file.

    Dim path As String = System.IO.Path.GetTempFileName()

 

    ' Copy the selected code to clipboard (using VS.NET).

    selection.Copy()

 

    ' Instantiate a new Word document to achieve HTML code formatting.

    Dim oleDocument As Type = Type.GetTypeFromProgID("Word.Document")

    Dim document As Object = Activator.CreateInstance(oleDocument)

    document.ActiveWindow.Selection.PasteAndFormat(WdPasteDefault)

    document.SaveAs(path, WdFormatFilteredHTML, False, "", True, "", False, False, False, False, False)

    document.Close()

    document = Nothing

    oleDocument = Nothing

 

    ' Open a new instance of Word.

    Dim oleApplication As Type = Type.GetTypeFromProgID("Word.Application")

    Dim application As Object = Activator.CreateInstance(oleApplication)

    ' Open the temporary document.

    document = application.Documents.Open(path)

    ' Switch to the WebView mode within Word.

    document.ActiveWindow.View.Type = WdWebView

    ' Select the whole document.

    document.ActiveWindow.Selection.WholeStory()

    ' Copy it to the clipboard.

    document.ActiveWindow.Selection.Copy()

    ' Close the document.

    document.Close()

    document = Nothing
    application.Quit()

    application = Nothing

    oleApplication = Nothing

 

    ' Cleanup after ourselves.

    IO.File.Delete(path)

 

  End Sub

 

End Module

And yes, I did use this macro to format the code within here ;-)

Note: I tried a couple of methods to get the final result saved within the clipboard... the one I settled on produced the best result.  However, because it has to launch a new instance of Word; it takes a second or two.  Still faster than doing everything by hand :-D

[update] Josh Ledgard pointed out a nice step by step process for adding macros in Visual Studio.  Also, I'm not an expert in the Microsoft Word object model.  I should point out that I've only tested this with Microsoft Word 2003.  What other versions of Microsoft Word this macro works with (or doesn't) is anyones guess.  If your using other versions of Microsoft Word, please let me (and others) know whether it's working or not by leaving a comment.

[update] Modified the code listing to include the application.Quit() call.

[update] Modified the code to conform to the VB.NET Coding Guidelines, add it to the code samples / articles document and created a text file version of the macro for download.

Published Wednesday, October 6, 2004 5:36 PM by CorySmith
Filed under: , ,

Comments

# re: Format Code to HTML within a VS.NET 2K3 Macro (leveraging Microsoft Word)

Wednesday, October 6, 2004 6:46 PM by Mike Parsons
Hey Cory ... Great job :-) I've already replaced my version.

# re: Format Code to HTML within a VS.NET 2K3 Macro (leveraging Microsoft Word)

Wednesday, October 6, 2004 7:29 PM by Cory Smith
Thanks for the great idea and giving me something to start from :-D

# .NET Nightly 166

Wednesday, October 6, 2004 11:58 PM by .Avery Blog

# re: Format Code to HTML within a VS.NET 2K3 Macro (leveraging Microsoft Word)

Thursday, October 7, 2004 2:37 AM by Drew Robbins
Wow. Great job.

# Simple Macro for Formatting Code to HTML from within VS 2003

Thursday, October 7, 2004 6:05 PM by Powertoys WebLog

# re: Format Code to HTML within a VS.NET 2K3 Macro (leveraging Microsoft Word)

Thursday, October 7, 2004 9:03 PM by Johann Gerell
When I run that macro in VS.Net 2003, I get an error:

Public member 'PasteAndFormat' on type 'Selection' not found.

Any ideas why?

# re: Format Code to HTML within a VS.NET 2K3 Macro (leveraging Microsoft Word)

Thursday, October 7, 2004 10:41 PM by Cory Smith
I would guess something to do with the version of Word you are running. I suppose I should have mentioned that I'm using Word 2003. What version are you using?

# re: Format Code to HTML within a VS.NET 2K3 Macro (leveraging Microsoft Word)

Friday, October 8, 2004 6:59 PM by Jose Luis Manners
Good job !! I wonder if there''s a way of making the macro format the code with a color background. Like what you see in my blog only that I'm doing it manually from Word.

Regards,

Jose Luis Manners

# re: Format Code to HTML within a VS.NET 2K3 Macro (leveraging Microsoft Word)

Saturday, October 9, 2004 1:04 PM by Oliver
I am running the macro and it seems to run ok, except: It's not putting anything into the clipboard. Using Word 2003. Any ideas?

Thanks.

# HTML Formatted Code directly from VS.NET

Friday, October 29, 2004 12:09 PM by Dim Blog As New ThoughtStream(Me)

# Superb Blog-Related Marketing

Friday, November 12, 2004 5:34 PM by Needs Improvement
Hilton Giesenow says I have some superb blog-related marketing going on. I guess we all become Robert Scoble in time. I must just have an accelerated case of the Scobles. :) Seriously though, I have been marketing. My first...

# HTML Formatted Code directly from VS.NET

Monday, November 15, 2004 4:18 PM by Dim Blog As New ThoughtStream(Me)

# re: Format Code to HTML within a VS.NET 2K3 Macro (leveraging Microsoft Word)

Friday, January 21, 2005 10:34 PM by JH.Apeland
after closing document you forgot to application.quit()

# re: Format Code to HTML within a VS.NET 2K3 Macro (leveraging Microsoft Word)

Sunday, April 17, 2005 7:24 AM by Dmitri
word remains in memory

add line
application.Quit()

# re: Format Code to HTML within a VS.NET 2K3 Macro (leveraging Microsoft Word)

Thursday, May 19, 2005 1:40 PM by Christopher G. Lewis
Love the code formatter!

You might want turn of conversion confirmation when you open the html temp file:

' Open the temporary document.
document = application.Documents.Open(path, ConfirmConversions:=False)

to avoid a prompt (for those of us who are paranoid about what Word opens :-)

Chris

# Formatting HTML code snippets with Ten Ton Wrecking Balls

Tuesday, June 14, 2005 10:28 PM by Coding Horror
If you've ever tried to cut and paste code from the VS.NET IDE, you may have noticed that the code generally comes across looking like crap. The root of this problem is that VS.NET copies code into your clipboard...

# Copying and Pasting HTML Code in VS.NET 2003 Sucks (Less)

Wednesday, June 15, 2005 11:25 PM by -:[web caboodle]:-

# re: Format Code to HTML within a VS.NET 2K3 Macro (leveraging Microsoft Word)

Friday, June 24, 2005 9:55 PM by Tlaloc
Thanks for the Macro it works great!

# re: Format Code to HTML within a VS.NET 2K3 Macro (leveraging Microsoft Word)

Friday, June 24, 2005 9:55 PM by Tlaloc
Thanks for the Macro it works great!

# Copying VS.NET code snippets to the clipboard as HTML

Thursday, October 27, 2005 5:01 PM by Coding Horror
As I mentioned in Formatting HTML code snippets with Ten Ton Wrecking Balls, copying code to your clipboard in Visual Studio .NET is often an excercise in futility if you want anything more than plain vanilla text. VS.NET copies...

# CopySourceAsHTML for VS2005

Saturday, January 21, 2006 4:24 PM by Douglas Rohm
I know this is old, but I just found it today.  I've knew about the latest version of CopySourceAsHTML...

# re: Format Code to HTML within a VS.NET 2K3 Macro (leveraging Microsoft Word)

Tuesday, June 6, 2006 9:30 AM by weasel
thanks for code it has been very useful
Anonymous comments are disabled