ACC

Creating, Installing, and Using VS Snippets

About Snippets

Snippets in Visual Studio enable developers to quickly insert pre-written code in a source code file at the point of the cursor. This is a great tool to quickly insert template and boilerplate code. This tutorial covers snippets in Visual Studio C++. The information is very similar for other language and can be reviewed here.

Create Snippets

The snippet must be coded in an XML format as shown. In the example below, there are two snippets. You can create multiple snippets that each contain different code.

The first snippet is named KeepConsoleOpen and consists of lines 6-21.
The precise insertion code for KeepConsoleOpen is contained in lines 14-17.

The second snippet is named ProgramTemplate and consists of lines 23-52.
The precise insertion code for ProgramTemplate is contained in lines 31-48.

The XML code elements are on lines 12-19 and 29-50 and are containers for the code that will be inserted when that snippet is used.

To add more snippets to the existing two, copy lines 6-21 and insert those lines after line 52. You can also have multiple snippet files each containing multiple snippets. The files can have any appropriate file name but must be in the XML format shown and have the .snippet extension.


This xml file can be downloaded from: cppsnippets.snippet.

Installing Snippets

After coding or downloading the cppsnippets.snippet file, you need to place it in the directory that Visual Studio searches for snippet files. To determine the location of that directory, navigate to the following in Visual Studio:

Tools | Code Snippets Manager

This dialog box appears. Ensure you have Visual C++ selected for the language. Note the location where your Visual Studio looks for your snippets.

Open File Explorer and move the cppsnippets.snippet file to the location shown for you.

After placing the cppsnippets.snippet file in that destination folder, close and reopen the Code Snippets Manager. Expand My Code Snippets to see the two snippets. Note that both snippets are in the cppsnippets.snippet file.

To modify existing snippets or add new ones, navigate to the file and double-click to open it in Visual Studio. Make the updates, save and close the file.

Using Snippets

Fortunately, using snippets is efficient. In a source file, postion the cursor where you want the snippet, R-click and select:

Snippet | Surround With...

This dialog box appears. Double-click My Code Snippets

Select the snippet you want to inset. I am choosing ProgramTemplate.

Notice that the entirety of the code from the ProgramTemplate snippet is inserted.

Note that you can become even more efficient by using the Ctrl-k,s, <ENTER>, and arrow key combinations.

Yea.