Snippets are the small portion of re-usable code wrapped in some prefix word, It allows programmers to bind a particular block of code in a single prefix keyword. Visual Studio Code is a Lightweight and powerful source code editor available in Windows, Linux, and macOS, It comes with many built-in snippets for the loops, control statements, and some keywords. But you know, we can also create our own custom code snippets for time saving and avoiding writing the same piece of code again and again. Users can code faster and productively with the help of custom code snippets.
Existing Snippet in VS Code
Now let’s take a look at how we can create our own code snippets for c++ language.
Steps need to be performed.
Here we were going to create a user snippet for the C++ language header template, In the Windows machine.
Step 1: Open the Visual Studio Code, and go to the ‘Manage’ (Gear icon in the bottom left corner).
Step 2: From opened options, Select the ‘User Snippets’ option.
Step 3: Select your programming language in which you are going to create a snippet. (Here we are selecting C++).
Step 4: Now, one cpp.json file will open Where we have to write a code for our code snippet. First, un-comment the code present below their instructions. (refer to screenshot).
Step 5: In this step, we have to do appropriate changes to their code.
First, Let’s understand the meaning of terms present in the code. Snippets generally have four main properties.
- Print to console: This is the word, which will open our snippet when we call it.
- Prefix: This prefix is used when selecting the snippet in intellisence.
- Body: In the body we are writing our main snippet code.
- Description: In this we have to mention brief description of snippet for our reference only.
- In body ‘$1’ sign determines the position of our cursor when the snippet is activated in code (Tab Stop).
- Note that while writing snippet code in the body, For multiline snippets, the body becomes an array with each line of the snippet becoming a string in that array.
- To format our code properly, we’re adding a “\t”, “\n” to lines for proper Indentation.
Our C++ Template Code Snippet
In our snippet, we have used a ‘boilerplate‘ as ‘print to console’, which means when we type boilerplate and press Enter, our snippet is executed.
Prefix gave as ‘boilerplate code’. This will visible while typing the name of the snippet.
In the body, we have included iostream header file and template code for c++. A description of the snippet is also added. “\t” and “\n” are added for proper formatting of code.
This is the snippet code result.
The tab is on the 6th line with four spaces.
Here all the above-mentioned steps are performed creating a Snippet. This will give you a clearer understanding.
That’s all. In this way, you can create a user snippet for different languages in Visual Studio Code. Each snippet is associated with a particular name, When we type that name and hit the enter key, Snippet code is executed.