 Java, Spring and Web Development tutorials  1. Introduction
As developers, we usually repeat the same patterns while writing code. Although each repetition seems small, it gradually slows our workflow. Fortunately, Visual Studio Code provides user-defined snippets, which allow us to expand short triggers into full code templates. As a result, we can reduce repetitive typing, improve consistency, and focus more on solving problems.
In this tutorial, we’ll explain how snippets work in Visual Studio Code and demonstrate how to create and use them effectively.
2. Code Snippets in VS Code
A snippet is a reusable code template that expands when we type a specific keyword. VS Code stores snippets in JSON files, where each definition controls how the editor expands the template.
Typically, a snippet includes three main fields: the prefix, which acts as the trigger keyword; the body, which inserts the code; and the description, which provides a short explanation in IntelliSense.
Once we type the prefix and press Tab (or select it from suggestions), VS Code inserts the snippet into the editor.
VS Code also provides built-in snippets and extension-based snippet packs, so we should check existing options before creating new ones.
3. Creating a Simple Snippet
To start writing a snippet, we first need to open the snippet configuration interface. We can open it through the Command Palette (Ctrl + Shift + P on Windows or Cmd + Shift + P on Mac).
Next, we search for Configure Snippets and proceed to select the desired scope. There are several scopes to choose from, including global snippets that work across all file types and language-specific snippets that apply only to a particular language.
After we make the selection, VS Code lets us choose a name for the file and then opens a JSON file where we can define our snippets.
Let’s create a snippet that inserts a section header comment:
"Section Header": {
"prefix": "sechead",
"body": [
"// ============================",
"// ${1:Section Title}",
"// ============================",
"// ${2:Author}",
"// ============================"
],
"description": "Insert a section header comment"
}
Here, ${1:Section Title} and ${2:Author} define placeholders and control cursor navigation order.
After saving the file, we can immediately try it out by typing the prefix sechead in a new file or, alternatively, by pressing Ctrl + Space on Windows or Cmd + Space on Mac to open the snippet dropdown. With the snippet selected, pressing Tab or Enter will insert our Section Header:
// ============================
// Section Title
// ============================
// Author
// ============================
Once the snippet is added, the cursor immediately jumps to the first position. After entering the section title, we can press Tab to move it to the next position, which is the author.
3.2. Snippet Shortcuts
Snippets are especially useful for frequently typed statements. For instance, Java developers often write System.out.println() for debugging.
We can create a shortcut like this:
"System.out.println": {
"prefix": "sysout",
"body": [
"System.out.println(${1:value});"
],
"description": "Print a value to the console"
}
After saving, we can type sysout and expand it. VS Code inserts:
System.out.println(value);
The cursor appears inside the parentheses, allowing us to quickly replace the placeholder.
4. Advanced Snippet Controls
Now that we’ve created basic snippets, we can explore more advanced features available in VS Code.
4.1. Language Specific Snippets
Every snippet is scoped to one, several, or all (“global”) languages based on where it is defined.
Single-language user-defined snippets are defined in a specific language’s snippet file (for example, java.json), which we can access through Snippets: Configure Snippets using the language identifier.
For example, we can add a scope to our sysout snippet:
"scope": "java",
By adding this line, we ensure the snippet is available only when we edit files in Java.
Multi-language and global user-defined snippets are all defined in “global” snippet files (JSON with the file extension .code-snippets). For example, we can add another language to the previously defined scope:
"scope": "java,kotlin"
Now, sysout will appear when working with Java or Kotlin files only.
4.2. Choices and Variables
Placeholders can include predefined choices. For example, we can define them using a comma-separated list inside pipe characters, such as ${1|one,two,three|}. When the snippet expands, the editor prompts us to select one of the values, so we can choose quickly instead of typing.
Additionally, we can insert variables using $name or ${name:default}. If the variable exists, the editor inserts its value. Otherwise, it uses the default or an empty string. However, if the variable is unknown, the editor inserts its name and turns it into an editable placeholder.
Let’s rewrite our sysout snippet to use choices and variables:
"Java Log with Choice and Variable": {
"scope": "java,kotlin",
"prefix": "sysout",
"body": [
"System.out.println(\"[${1|INFO,DEBUG,ERROR|}] ${TM_FILENAME_BASE}: ${2:message}\");"
],
"description": "Log statement with level choice and filename variable"
}
First, ${1|INFO,DEBUG,ERROR|} allows us to select a value when the snippet expands, and we can cycle through the available options (INFO → DEBUG → ERROR).
Next, ${TM_FILENAME_BASE} automatically inserts the current file name without the extension, so we don’t need to type it manually. VS Code provides many predefined variables that we can use in snippets.
Finally, ${2:message} inserts a default value (message) while still allowing us to overwrite it immediately.
In addition to basic placeholders, VS Code supports placeholder transforms, which allow us to modify input using regular expressions. As a result, we can dynamically format text without rewriting it manually.
The syntax follows this structure:
${variable/regex/format/options}
Let’s look at a practical example. Suppose we want to generate a Java getter method where the field name is automatically capitalized:
"Java Getter": {
"scope": "java",
"prefix": "getter",
"body": [
"public ${1:String} get${2/(.*)/${1:/capitalize}/}() {",
" return ${2:fieldName};",
"}"
],
"description": "Generate getter with capitalized field name"
}
Here, ${2:fieldName} defines the input placeholder. Then, ${2/(.*)/${1:/capitalize}/} transforms that input by capitalizing its first letter.
For example, if we enter userName, the snippet expands to:
public String getUserName() {
return userName;
}
Therefore, we can reuse user input while automatically adjusting its format. This feature becomes especially useful when generating method names, constants, or formatted identifiers.
4.4. Assigning Keyboard Shortcuts to Snippets
In addition to prefixes, we can trigger snippets using keyboard shortcuts. Let’s open the keybind file for our user by using the Command Palette and typing in Open Keyboard Shortcuts (JSON).
Here, we can define and possibly override existing default keybinds. For our scope, let’s use the shortcut Ctrl + Alt + P on Windows or Cmd + Option + P on Mac :
{
"key": "ctrl+alt+p",
"command": "editor.action.insertSnippet",
"args": {
"name": "Java Log with Choice and Variable"
},
"when": "editorTextFocus && editorLangId == 'java'"
}
Once the file has been saved, we can now quickly insert our custom snippet:
By assigning a keyboard shortcut, we can insert our custom snippet instantly, which improves both speed and workflow efficiency.
5. Conclusion
In this article, we explored how to create and customize snippets in Visual Studio Code to reduce repetitive coding and improve development efficiency.
We first opened the snippet configuration and chose the appropriate scope.
Next, we defined snippets using a prefix, body, and description.
Then, we enhanced them with placeholders, tab stops, choices, variables, and regex-based transforms.
By investing a small amount of time in creating snippets, we can significantly improve our development speed and maintain consistent code across projects. The post How to Create Shortcut Snippets in Visual Studio Code? first appeared on Baeldung.
Content mobilized by FeedBlitz RSS Services, the premium FeedBurner alternative. |