Visual Studio code snippets

What I really like in Visual Studio as development environment is code snippets. Well actually probably other IDE have something very similar but I do not have much of a choice in that matter as C# developer 🙂
Anyway this feature is really useful. For example while refactoring I very often use if surround snippet.

Unfortunately there are no easy way to edit/add new snippets since VS do not have built in snippets editor. But their syntax is almost XML and quite simple. I will cover few simple examples in this short article.

Ok. Let’s start with what we have in VS. There is Code Snippets Manager available Tool menu.

There is not much we can do in that window: add or remove snippets directory or import single snippets. In my opinion only real useful feature is possibility to check where we can find existing snippets. Also I do not recommend to add new folders because of extra need to specify search directory when we search for desired snippet after using insert snippet Visual Studio shortcut (Ctrl K, X by default for Visual C# environment setting). For example when selecting for surround statement in Java Script; after adding new folder we have to choose folder before we choose snippet, which is waste of time for me.

Ok. Let’s try a simple example. While developing in Java Script it is good idea to use Require JS or other AMD library.
It would be really painful to write every time same formula for new JS module. Instead it is better to create code snippet. Using Code Snippets Manager we can obtain directory in which JS snippets resides. By default this is: C:Program Files (x86)Microsoft Visual Studio 11.0JavaScriptSnippets1033JavaScript for VS 2012.

Desired code for starting a new module for me was:

define([''],
    function (dep) {	
        return new function () {
			//private variables
			//private functions
			//public functions
			$selected$end$
			//globals
			//onload
		};
    });

To define code snippet with above template we have to create new file {name}.snippet in above directory.

File contents should be similar to following:

  
<CodeSnippet Format="1.1.0" >
  <Header>
    <Title>module</Title>
    <Author>Natan Podbielski</Author>
    <Shortcut>mdl</Shortcut>
    <Description>Code snippet Require JS module</Description>
    <SnippetTypes>
      <SnippetType>Expansion</SnippetType>
      <SnippetType>SurroundsWith</SnippetType>
    </SnippetTypes>
  </Header>
  <Snippet>
    <Code Language="JavaScript"><![CDATA[
define([''],
    function (dep) {	
        return new function () {
			//private variables
			//private functions
			//public functions
			$selected$end$
			//globals
			//onload
		};
    });
]]></Code>
  </Snippet>
</CodeSnippet>

Keep in mind that white space in <Code> tag are very meaningful and should look exactly like it should look in destination code in VS. With file like this you can use it in VS. Press insert snippet shortcut in JS file. You should see something like this (sometimes it is necessary to open Code Snippets Manager or restart VS to force to reread all snippets):

Quick explanation about tags:

<Title> is a title that is shown in Code Snippet Manager and ‘select snippet menu’.

<Author> is an author of the snipper. Visible in Code Snippet Manager.

<Shortcut> is a string of characters you have to type which make available to you Tab shortcut which will expand typed characters into desired code from snippet. Like ctor is a shortcut for built in VS constructor snippet.

<Description> is a description visible from Code Snippet Manager and from ‘select snippet menu’.

<SnippetTypes> is an enumeration of snippet type. There is only two types of snippets: Expansion and SurroundsWith. With <SnippetType> tag you can decide which is it and from what menu or shortcut it will be available.

<Code> is an actual code for snippet. Should be 1 to 1 to desired code. Besides snippets variables which I will describe bellow.

You should be very specific about white space, indentation of code of snippet (about syntax too of course but it is obvious) etc. It is better to write it right once in snippet than correct it every time you use it 🙂

There are available plenty of variables inside of snippet. They are defined like $name$ inside actual code.

Most important for example for surround type of snippets is variable $selected$, which describe where VS should put text that you selected before inserting desired template. $end$ specifies when cursor should be after inserting snippet. It is useful for snippets that you should populate with specific code, method for example: you should write method body so this is useful to put $end$ inside method body. There are some variables defined by snippet engine, like $classname$, which is current class name. You can also defines your own variables, which then can be easily changed while using snippet. Consider built in snippet for property with backing field: propfull.

It has declaration as follows:

		<Snippet>
			<Declarations>
				<Literal>
					<ID>type</ID>
					<ToolTip>Property type</ToolTip>
					<Default>int</Default>
				</Literal>
				<Literal>
					<ID>property</ID>
					<ToolTip>Property name</ToolTip>
					<Default>MyProperty</Default>
				</Literal>
				<Literal>
					<ID>field</ID>
					<ToolTip>The variable backing this property</ToolTip>
					<Default>myVar</Default>
				</Literal>
			</Declarations>
			<Code Language="csharp"><![CDATA[private $type$ $field$;

	public $type$ $property$
	{
		get { return $field$;}
		set { $field$ = value;}
	}
	$end$]]>
			</Code>
		</Snippet>

Declaration of variables $type$ and $field$ allow us to write name of field and type of field and property one time in one place:

Changing myVar for something more meaningful and submitting a snippet will change highlighted places with myVar value inside snippet code too. Pretty useful!

As you can see in actual declaration of snippet variables there is possibility of setting default value and tool tip so and end user could know what we meant for variable while creating a template. There is a really world of possibilities from such snippets. If we using some kind of elaborate code structures inside of our project (custom data contracts for example, or ASP.NET custom controls etc.) it is best to create snippets for them. Or for other broadly used code samples.

For example I created snippet for jQuery ready function:

 <CodeSnippet Format="1.1.0" >
  <Header>
    <Title>jQuery ready</Title>
    <Author>Natan Podbielski</Author>
    <Shortcut>docrd</Shortcut>
    <Description>Code snippet for jQuery document ready event</Description>
    <SnippetTypes>
      <SnippetType>Expansion</SnippetType>
      <SnippetType>SurroundsWith</SnippetType>
    </SnippetTypes>
  </Header>
  <Snippet>
    <Code Language="JavaScript"><![CDATA[$(function(){
	$selected$end$
});]]></Code>
  </Snippet>
</CodeSnippet>

Important: as you can see above to achieve $ inside destination code (after using a snippet inside VS) you have to escape it with $, so jQuery $ becomes $$ inside snippet code declaration!

Or for console.log(); JS function, which is very similar but with <Code> tag like this:

<Code Language="JavaScript"><![CDATA[console.log($end$);]]></Code>

I hope this will help in your journey into VS code snippets world. 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

Solve : *
11 + 30 =