VS Code Snippets: Speed up Coding with Shortcuts

choubertsprojects

The Best WordPress plugins!

1. WP Reset

2. WP 301 Redirects

3. WP Force SSL

VS Code is a powerful Integrated Development Environment (IDE) that offers many features to help you speed up your coding.

VS Code Snippets are a feature that allows users to create their own shortcuts for the editor. The “vscode snippets” is a command-line tool that allows users to speed up the coding process with shortcuts.

VS Code Snippets: Speed up Coding with Shortcuts

Do you ever find yourself typing the same thing over and over again in Visual Studio Code (VS Code) while developing the newest piece of code? Perhaps you’ve entered a function declaration 10 times today, or you’ve specified the identical set of arguments on command for the twentieth time. Did you know that Visual Studio Code snippets may help you reclaim your time and sanity?

Snippets are short chunks of text saved in Visual Studio Code. These snippets may be accessed through a menu or a key sequence, and they can save you a lot of time if you find yourself repeating blocks of text with minimal alterations between them.

For example, you can see below that by merely entering wvb in VS Code, you may expand a lot more material, as shown by the Write-Verbose text in the box. Snippets have this kind of power!

Extending snippets in Visual Studio CodeExtending snippets in Visual Studio Code

You’ll learn how to use VS Code snippets in this post, including how to use default snippets, extension snippets, and even create your own!

Prerequisites

This will be a step-by-step guide on getting your hands filthy. If you want to learn how to deal with VS Code snippets, you’ll need version 1.17 or above of VS Code. To be completely transparent, I’ll be using VS Code 1.38.1 on Windows.

You may get the most recent version of VS Code for your platform here.

Snippets from Visual Studio Code

Before you can start creating your own snippets (which you will), you must first understand how to locate the built-in snippets.

All snippets may be found in the menu interface. You may evaluate and utilize snippets using the menu interface. To go to the menu, use F1 or Ctrl-Shift-P, then type “snippet” and hit Enter. A menu similar to the one shown below will appear.

List of snippets in Visual Studio CodeList of snippets in Visual Studio Code

When you press Enter on Insert Snippet, a list of possible snippets appears, as seen below. There are a lot of snippets accessible by default, and you may view more by scrolling down.

List of SnippetsList of Snippets

You may evaluate the built-in snippets that are accessible by adding a language extension in VS Code by using the drop-down menu of available snippets.

Extensions for Languages

You can use VS Code to work with many different languages. Each language has it’s own nuances. To support these differences, VS Code supports Extensions for Languages.

Extensions for Languages provide VS Code with smart editing features for different programming languages. Extensions for Languages give programming language additional support such as:

  • Highlighting of syntax
  • IntelliSense
  • Formatting
  • Checking for errors
  • Completion of the snippet

The Extensions menu in Visual Studio Code is where extensions are installed.

Extensions menu in Visual Studio CodeExtensions menu in Visual Studio Code

You can review the definition of these snippets given by the Extensions for Languages by opening the JSON file on Windows located at C:Users<UserName>.vscodeextensionsms-code.-snippets.

Extensions don’t have anything to do with snippets in and of themselves, but you’ll discover that many come with built-in snippets that you should be aware of.

Snippets Expansion

When you pick a snippet from the menu interface, the contents of the snippet are shown in the file. Expanding is the process of translating snippet definitions into meaningful code.

When you call the prefix, VS Code reads that exact prefix and executes the snippet’s instructions. These instructions may differ from one snippet to the next. Expanding refers to the full process of calling, converting, and inserting the snippet.

Snippets for VS Code Extensions

Some snippets are included by default in Visual Studio Code, but when you install an extension, it may include more snippets. The Python extension from Microsoft, the PowerShell extension from Microsoft, and the C# extension from Microsoft are all examples of extensions that incorporate snippets.

Extension Snippets: Where Do They Go?

These extensions are normally installed in Windows under the C:Users<UserName>.vscodeextensions directory of your computer as you can see below.

The naming standard for the extension folders is ms-vscode.-. Each of these folders includes a snippet folder, which contains the snippets that come with the extension.

Contents of C:Users<UserName>.vscodeextensionsContents of C:Users<UserName>.vscodeextensions

Example of Extension Code Snippet

Let’s look at the PowerShell extension as an example of how to use an extension snippet. This addon includes two handy snippets named region and for that will help you quickly create PowerShell region blocks and *for* loops.

Let’s imagine you need to put a for loop within a region block in a PowerShell script. The code to do this may be seen below. The code in the next screenshot is 50 characters long and forms a for loop inside a region block that iterates through the digits 1 to 10.

For Region Blocks in StatementsFor Region Blocks in Statements

You may utilize two snippets named region and for that come included with the PowerShell extension from Microsoft instead of typing out every single letter in this example.

Take a look at the examples below to see how simple it is to save time by using each of these snippets.

Using a SnippetUsing a Snippet

Custom Code Snippets in Visual Studio Code

You don’t have to stick to the snippets that come with VS Code or extensions. Perhaps current extensions lack the code structure you want, or you prefer to format these snippets yourself. You’re in luck since you can make your own snippets! You’ll learn how to accomplish it in this section.

To create a custom snippet, go to Files Preferences User Snippets in VS Code and select User Snippets. This will expand your snippet language selection options. This is where you may choose the language in which you want the snippet to be created. The screenshot below is an example of what this looks like.

By choosing a language, VS Code will create a language.json file in C:Users<UserName>AppDataRoamingCodeUsersnippets on Windows. All user snippets created for different languages will have a file in this directory.

Scope of Snippet LanguageScope of Snippet Language

The languages you see available to you may differ from what you see above. In the above VS Code installation, many Extensions for Languages have already been installed.

To access the language JSON file, find the language for which you wish to generate the snippet and press Enter. This is where your custom snippets will be saved, and it’s also where you’ll be able to create them.

For a custom snippet, there are four data pieces to specify:

  1. A name for a fragment (line 9 below)
  2. A prefix, which is the name you’ll give your snippet (line 8 below)
  3. A body, which contains the code snippets that are loaded into your scripts (lines 7 to 3 below)
  4. A description that will appear in IntelliSense (line 2 below)

The For statement is defined in this example snippet.The For statement is defined in this example snippet.

Creating a Python Snippet from Scratch

Let’s have a look at how to make a custom snippet for the Python programming language. In this case, the dt prefix command will run a custom Python snippet. This snippet will produce a message that includes the current time.

Make a JSON document

First open the snippet language selector, type Python, and hit Enter to create a python.json file. This will bring up a python.json file in the Windows C:Users<UserName>AppDataRoamingCodeUsersnippets folder.

The default state may be seen in the picture below.

JSON snippets by default in PythonJSON snippets by default in Python

Choosing a Prefix and a Name

Now you may start modifying the JSON file. Define the name and prefix first (dt). Because this is the value entered to invoke the snippet, Prefix for snippetses are short and obvious. When you wish to call it, the shorter the Prefix for snippets, the less characters you’ll have to write.

You can see an example of what this looks like in the image below.

Prefix for snippetsPrefix for snippets

Defining the Human Form

When the snippet is called, the body includes the code that will be expanded. Simple text and comments may be used in this code. It can also do various tasks, as you’ll see in the next sections. There are a few pitfalls to look out for if the body has a lot of lines.

  • Each line must be enclosed in double-quotes.
  • A comma must be included at the end of each line.
  • All lines should be included in square brackets (“[” and “]”).

Below is an example of what the example Body of a snippet should look like.

Body of a snippetBody of a snippet

Determining the Characteristics of the Description

The description is a message that describes the prefix specified below the body, as shown below.

Description of the snippetDescription of the snippet

The description will be shown below the prefix in the List of Snippets and provides more information on what the snippet does. It also helps differentiate the snippet from similar ones created.

A sample of fragments identifying prefixes and descriptions is shown below.

Prefix and description examplesPrefix and description examples

When you’re through generating the snippet, you should have a python.json file that looks like the code snippet below if you don’t already have any custom Python snippets defined.

“DateTime Snippet”: “prefix”: “dt,” “body”: [“import datetime,” “dt = datetime.datetime.now(),” “print(f”The time is dt and this is a message”)] “Prints a message containing the current time,” “description,” “description,” “description,” “description,” “description,” “description,” “description,” “description,” “description,” “de

Save the JSON file, and the custom snippet may now be used in any Python program in VS Code.

Now when you open a Python tab and type the prefix dt, the custom snippet below appears. Hitting Enter will expand the Body of a snippet into the Python tab.

Custom Using a SnippetCustom Using a Snippet

Using Included Text to Make a Custom JavaScript Snippet

Snippets are not isolated to the words you define in the Body of a snippet. Snippets also can include text from the file you are calling them from.

You may utilize internal variables in VS Code. These are placeholders that will insert the currently selected text into the snippet. You may display the chosen text, for example, by using the variable $TM SELECTED TEXT in the snippet. For a complete list of all internal VS Code variables, see the VS Code Variables Reference page.

To illustrate, build a snippet called log-it that just produces a line that outputs the chosen text to the console.

To create a javascript.json file, open the snippet language picker, type JavaScript, and click Enter. This file will resemble the python.json file prepared earlier in this step. This time, however, instead of Python code, it includes example Javascript code. The screenshot below shows it in its default form.

JSON file for JavaScript by defaultJSON file for JavaScript by default

Now make a snippet using the JSON below:

“Prefix”: “log-it”, “body”: [“console.log(‘$TM SELECTED TEXT’);”] “Print chosen line to console”: “prefix”: “log-it”, “body”: [“console.log(‘$TM SELECTED TEXT’);”] “Log selected text output to console,” “description,” “description,” “description,” “description,” “description,” “description,” “description,” “description,” “description,” “

You may now use this snippet in your JavaScript scripts after saving this JSON file.

This snippet will replace $TM SELECTED TEXT with any text you have highlighted when you call it with highlighted text. $TM SELECTED TEXT will be empty if you call this snippet without any highlighted text. In the screenshot below, you can see this in action.

JavaScript $TM_SELECTED_TEXTUsing a SnippetJavaScript $TM_SELECTED_TEXTUsing a Snippet

Using Tab Stops to Create a Custom PowerShell Snippet

So far, all of the instances you’ve seen have been finished when they were called. Even the JavaScript believes you’ve already highlighted text. But what if you need to input values into the snippet after it has been called?

What if you want to input the value instead of utilizing the highlighted text in console.log()? What if you want to type at different places throughout the snippet?

In this lesson, you’ll learn how to utilize tab stops to input content into the expanded code created by the snippet. Tab stops are designated locations in your snippet where the cursor will go. Each time you hit tab, these locations are accessed in sequence. You may enter values into the snippet once it has been enlarged using these tab stops.

Tab stops, defined by using the snippet variables $0, $1, $2 , and up in the Body of a snippet, specify to the snippet where your cursor will go next when you call your snippet and hit tab.

The tab stops are in sequence (1 follows 2 follows 3, etc.) with one exception: tab stop 0 is where the cursor will remain once all the other tab stops have been reached. The sample below extends to a Write-Output message with the current date and room for extra content to show this.

There are two tab stops on this body.

  • At the conclusion of the Write-Output message, there’s a $1.
  • On the following line, type $0 on the next line so the snippet will end on a blank line to terminate the snippet on a blank line.

“DateTime Snippet PS”: “prefix”: “dtPS”, “body”: [“Write-Output -Message “The time is $($($($($($($($($($($($($($($($($($($($($($($($($($($($($($ (Get-Date). $1″”,”{ “DateTime Snippet PS”: { “prefix”: “dtPS”, “body” : [ “Write-Output -Message “The time is $((Get-Date).ToLocalTime()) and $1″”,”$0″ ] “description”: “PSCustomObject with 3 lines” } }”] and ToLocalTime()) “PSCustomObject with 3 lines” is the description.

Save this snippet to a PowerShell file and call it with the prefix dtPS.

Your cursor goes to the location of tab stop 1 as the snippet expands. Add the desired value or code here, then press tab to move the pointer to the next tab stop. This will continue until all of the tab stops you specify have been reached.

In the screenshot below, you can see this in action.

Tab stopsTab stops

Tab Stops with Default Values

While tab stops are useful for a start, what if you require certain values in those areas on a regular basis but also want the flexibility to modify them if necessary? It’s now time to add default settings.

The sample above included a tab stop, but there was no text in its place when the snippet was extended. The user has to take control once the pointer went to the tab stop place.

If only there was a way to put a value where the tab stop is, the snippet would extend and the value would expand as well. The default value may be altered or tabbed past when the tab stop reaches that point.

Let’s look at how to make custom snippets with default values. You’ll accomplish so by modifying the JSON file for the PowerShell snippet shown above.

To begin, pick PowerShell from the snippet language choice and alter the tab stops from $1 to $1:this is my default message. After the colon, the value that follows after it becomes the default value. With the snippet, this value is enlarged.

When you press the tab stop, two things may happen. The default value may be altered, or it can be tabbed past and the default value will be retained.

The alteration in the body may be seen below.

“DateTime Snippet PS” “prefix”: “dtPS”, “body”: [“Write-Output -Message “The time is $($($($($($($($($($($($($($($($($($($($($($($($($($($($($( (Get-Date). $11:this is my default message””, “{ “DateTime Snippet PS” { “prefix”: “dtPS”, “body” : [ “Write-Output -Message “The time is $((Get-Date).ToLocalTime()) and $1{1:this is my default message}””, “$0” ], “description”: “PSCustomObject with 3 lines” } }”], “description”: “PSCustomObject with 3 lines”

These default values are enlarged and shown in the IntelliSense window when called after being modified and saved, as illustrated in the picture below.

Default Values in a SnippetDefault Values in a Snippet

Default messages are a nice illustration of what tab stops may be used for. Tab stops also allow you to make a decision. You’ll see an example of adding options to your tab stops in the following section.

Adding Tab Stops with Options

Tab stops don’t have to be set to a default value or have no value at all. They may be specified in the VS Code snippet definition to provide choices to the user as the snippet grows.

You can find yourself in a position where you need to change a snippet’s value or command. You may alter the snippet to offer an option with a tab stop, rather than generating three new snippets with various choices, as illustrated in the example below.

Choices in a snippetChoices in a snippet

When the following syntax is used in the body of the snippet, tab stops will provide a choice:

${N|Choice1,Choice2,Choice3[,Choice]|}

The tab stop pictured above has been changed to allow you to choose between:

  • Write-Output
  • Write-Warning
  • Write-Error

After the tab stop, two pipe characters (|) were used to accomplish this. Choices are separated by commas and placed within the pipe characters. This is shown in the code block below.

${1| Write-Output -Message “The time is $((Get-Date).ToLocalTime()) and this is my default message”, // <– Choice 1 Write-Warning -Message “The time is $((Get-Date).ToLocalTime()) and this is my default message”, // <– Choice 2 Write-Error -Message “The time is $((Get-Date).ToLocalTime()) and this is my default message” // <– Choice 3 |}

The sample snippet is shown below.

“DateTime Snippet PS” is an acronym for “DateTime Snippet.” “prefix”: “dtPS”, “body”: “dtPS”, “prefix”: “dtPS”, “body”: “dtPS”, ” [“Write-Output -Message “The time is $($($($($($($($($($($($($ (Get-Date). Write-Warning -Message “The time is $$$$$$$$$$$$$$$$$$$$$$$$$ (Get-Date). Write-Error -Message “The time is $,” Write-Error -Message “The time is $,” Write-Error -Message “The time is $,” Write-Error -Message “The time is $,” Write-Error (Get-Date). This is my default message”|”, “{ “DateTime Snippet PS” { “prefix”: “dtPS”, “body” : [ “Write-Output -Message “The time is $((Get-Date).ToLocalTime()) and this is my default message”, Write-Warning -Message “The time is $(Get-Date).ToLocalTime()) and this is my default message”, Write-Error -Message “The time is $(Get-Date).ToLocalTime()) and this is my default message”|}”, “$0” ], “description”: “PSCustomObject with 3 lines” } }”] (ToLocalTime()) and this is my default message”|”, “{ “DateTime Snippet PS” { “prefix”: “dtPS”, “body” : [ “Write-Output -Message “The time is $((Get-Date).ToLocalTime()) and this is my default message”, Write-Warning -Message “The time is $(Get-Date).ToLocalTime()) and this is my default message”, Write-Error -Message “The time is $(Get-Date).ToLocalTime()) and this is my default message”|}”, “$0” ], “description”: “PSCustomObject with 3 lines” } }”] (ToLocalTime()) and this is my default message”| “PSCustomObject with three lines” is the “description”

When the custom snippet grows now, an IntelliSense window will display with the options to pick from, as seen in the picture below.

You may choose the option you desire and see it evolve into that option from here. The whole line of code in the example screenshot below has been changed with the option to pick from three distinct Write commands, and each one may be called and performed without trouble.

Snippet in Action with a ChoiceSnippet in Action with a Choice

Summary

Simple text or code may be used as custom snippets. They may feature messages, default values, or options, as well as highlighted text, and they can include tab stops.

Typing out every single character of every single code block does not have to be a difficult chore. You don’t have to remember the precise syntax for a for, foreach, or switch statement every time you use snippets. Snippets are ideal for this kind of content.

In this article, I’ve included Python, JavaScript, and PowerShell samples. Many more languages are supported by VS Code snippets. Your only limitations are what you can conceive of and what you can utilize!

Additional Reading

The “vscode-snippets if else” is a snippet that can be used to speed up coding with the “if else” statement.

Frequently Asked Questions

How do I code faster in VSCode?

A: One of the best ways to speed up your coding is to use a dark editor theme.

How do I use code snippets in VSCode?

A: To insert a code snippet, click on the keyboard shortcut that corresponds to your input. Then you can use it just like any other text or symbol

How can I change code faster?

A: I cant do any changes for you. Youll need to ask a human being with the right permissions, like on Discord or Reddit, if they will help you out.

Related Tags

  • snippet generator
  • vscode insert snippet shortcut
  • vs code terminal snippets
  • vs code shortcuts
  • react snippets for vs code

Table of Content