My Technical Notes

Tuesday, 26 February 2013

Adding a Snippet to Visual Studio 2010

Before adding a snippet to Visual Studio 2010, we need to work out where to save our .snippet file. There are different folders for each language. In the case of Javascript, we must store our .snippet file in the Javascript Snippet directory.

Using Javascript as an example, go to


Tools -> Code Snippets Manager

In the new dialog, select the language as "JScript" and then click on "My JScript Snippets" in the left hand column. This will reveal the path of where we store our .snippet file:

For JScript, the path is:


C:\Users\<username>\Documents\Visual Studio 2010\Code Snippets\Visual Web Developer\My JScript Snippets\

To create a Snippet file we create a new XML file (later to be saved as a .snippet file in the above folder location), and then add an outline of a snippet by right clicking inside the open file and selecting


Insert Snippet -> Snippet

For this example, I wanted to create a snippet where typing jqready would expand to the following:


$(function() {
   
});

It would also be preferable that the cursor is positioned in the empty line so that I can start writing the code. In the end I wrote the following snippet file:


<?xml version="1.0" encoding="utf-8"?>
<CodeSnippet Format="1.0.0" xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <Header>
    <Title>JQ Ready</Title>
    <Author>Tahir Hassan</Author>
    <Shortcut>jqready</Shortcut>
    <Description>Inserts a JQ Ready block</Description>
    <SnippetTypes>
      <SnippetType>Expansion</SnippetType>
    </SnippetTypes>
  </Header>
  <Snippet>
    <Declarations>
      <Literal>
        <ID>expression</ID>
        <ToolTip>Expression to evaluate</ToolTip>
        <Default><![CDATA[;]]></Default>
      </Literal>
    </Declarations>
    <Code Language="jscript">
      <![CDATA[
      $$(function() { 
        $expression$$end$
      });]]></Code>
  </Snippet>
</CodeSnippet>

The reason why we insert a semi-colon is to trigger Visual Studio to indent the line so we do not have to tab across ourselves.

No comments: