As I mentioned in Formatting HTML code snippets with Ten Ton Wrecking Balls, copying code to your clipboard in Visual Studio is often an excercise in futility if you want anything more than plain vanilla text. VS copies code to the clipboard with bizarro-world RTF formatting instead of the sane, simple HTML markup you might expect. This is true even of the brand spanking new VS.NET 2005.
I previously developed a macro that converted highlighted code to simple HTML on the clipboard using two different methods. I've since removed the Word interop method entirely because it's clunky. And I have improved the RTF-to-HTML conversion method substantially. Take this code, for example:
Let's highlight the code execute the FormatToHtml.Modern macro, and then paste the contents of the clipboard into something like FreeTextBox:
/// I heart GUIDs
public class MyClass
public void test()
string s = "test";
int i = 1234;
That's extra clean, well-formatted <span> colored HTML wrapped in a simple <div>. It preserves the color scheme and indentation from your IDE exactly*, although it does substitute a standard monospace IDE font. View source on this post to see the raw markup.
Now compare this with the craptacular results you'll get when you do a traditional copy and paste! This is how VS.NET 2005's CTRL+C copy functionality should behave. You could even map the CTRL+C shortcut to the macro if you like.
My favorite new feature, however, is that the macro now dynamically removes excessive indenting from copied code. That makes it a lot cleaner when copying code snippets from the TotallyUnnecessaryNamespace namespace. As Cartman would say, super sweet. And it works in Visual Studio 2002, 2003, and 2005. Try it yourself!
Download the FormatToHtml macro (5kb) Updated 4/2006
Here's how to get started with this macro
- go to Tools - Macros - IDE
- create a new Module named "FormatToHtml" under "MyMacros"
- paste the downloaded code into the module
- add references to System.Drawing and System.Web via the Add Reference menu
- save and close the macro IDE window
- go to Tools - Macros - Macro Explorer
- Four new macros will be under "FormatToHtml"; double-click to run the macro, then paste away..
* Background colors are lost, but that's because the RTF markup VS.NET places in the clipboard doesn't contain the background colors, either. Total bummer.