Thursday, August 16, 2007

Custom Code Snippets

I'm not exactly sure when snippets were added to VisualStudio. I'm also not sure why I neglected them this long. I guess I just wasn't one of the Cool Kids. Hopefully I can make amends.

In case you are unfamiliar with snippets, this is the feature that lets you type 'prop' inside a class definition, press 'Tab' twice, and end up with a complete property definition. Even better, it highlights the items to modify, and you can easily Tab between them as you edit.


This is cool. Knowing this is there and using the built-in snippets, however, doesn't make one cool. True coolness occurs when one creates one's own. My journey began with an existing .snippet file. The path to these can be found in the Code Snippet Manager (under the Tools menu.) A few changes and I had the following:



<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>test</Title>
<Shortcut>test</Shortcut>
<Description>Code snippet for NUnit test</Description>
<Author>Pedro</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal>
<ID>testName</ID>
<ToolTip>Test name</ToolTip>
<Default>myUnitTest</Default>
</Literal>
</Declarations>
<Code Language="csharp">
<![CDATA[[Test]
public void $testName$()
{
Assert.Fail("TODO: Implement test");$end$
}]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>


For those following along at home, save the above as a .snippet file. This can either be placed with the existing snippets, or in the "My Code Snippets" folder buried under "My Documents." Once saved, the Snippet Manager should list the new file.


To try it out, open up a .cs file containing unit tests. In a blank area between existing tests, type 'test' and press 'Tab' twice. Assuming I didn't screw up the above xml, you should now have the start of a new unit test.