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
<CodeSnippet Format=”1.1.0″ xmlns=”http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet”>
<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>
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:\\Users\\Stephen\\Documents\\Visual Studio 2012\\Code Snippets\\JavaScript\\My Code Snippets
On Visual Studio, the default shortcut to call the snippet is Ctrl+K, Ctrl+X, then you can select from there: Then after select the 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.