Creating Snippet in Visual Studio

There are times where we need to type out some skeleton codes, and if we smart enough, we copy it from existing one and change some variable, what if we can use shortcut to insert that skeleton codes, and using tab to change all the variable we needed to change?

To do this in Visual Studio (I’m using Visual Studio 2012)

Creating Snippet File

[cc lang=”xml” escaped=”true”]

<CodeSnippet Format=”1.1.0″ xmlns=”http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet”&gt;

<Header>
<Title>test</Title>
<Author>Stephen Saw</Author>
<Description>Code snippet QUnit test</Description>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal>
<ID>ClassName</ID>
<ToolTip>Class name for the testing class</ToolTip>
<Default>ClassName</Default>
</Literal>
<Literal>
<ID>FunctionName</ID>
<ToolTip>Function name for the testing funciton</ToolTip>
<Default>FunctionName</Default>
</Literal>
<Literal>
<ID>TestDescription</ID>
<ToolTip>Description for the current test</ToolTip>
<Default>TestDescription</Default>
</Literal>
<Literal>
<ID>setup</ID>
<ToolTip>Setup statement</ToolTip>
<Default>setup</Default>
</Literal>
<Literal>
<ID>execute</ID>
<ToolTip>Call the function</ToolTip>
<Default>execute</Default>
</Literal>
<Literal>
<ID>assert</ID>
<ToolTip>Assert for the test</ToolTip>
<Default>assert</Default>
</Literal>
</Declarations>
<Code Language=”JavaScript”>
test(“$ClassName$_$FunctionName$___$TestDescription$”, function () {
expect(1);

//setup
$setup$

//execute
$execute$

//assert
$assert$
});
</Code>
</Snippet>
</CodeSnippet>
[/cc]

This is the snippet for QUnit test. The key here is the Literal, we can define ‘token’ that we want Visual Studio to tab into, so that we can quick change those ‘token’.

The ID in the Literal should be matched with the one we define in the <Code>, by wrapping the text with $ sign, e.g. $ClassName$. Visual Studio will pick this up and allow us to use tab to jump into the token.

Save the xml file as *.snippet in Visual Studio’s snippet folder. E.g. C:UsersStephenDocumentsVisual Studio 2012Code SnippetsJavaScriptMy Code Snippets

On Visual Studio, the default shortcut to call the snippet is Ctrl+K, Ctrl+X, then you can select from there:Snippet Selector

Then after select the snippet:

Snippet

Then we can use tab to jump through those highlighted text and do modification, no mouse or arrow key required, we can press Esc to cancel off this anytime.

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s