github twitter email
Workspace Snippets in Visual Studio Code
Aug 30, 2021
2 minutes read

Visual Studio Code Snippet

What Is A Workspace Snippet?

Workspace snippets are only defined in the context of your workspace. In this context workspace is equal to the root folder you open in VS Code. You can also define global snippets. But this post will not go into that.

Create Workspace Snippets

To create a workspace snippet, you first have to create a folder with the name .vscode inside your project folder. Inside the .vscode folder you create a new file that will hold the definitions of your custom snippets.

The name of the new file is not important but it should have the .code-snippets extension. Go ahead and create snippets.code-snippets (or choose any other name that makes sense) inside your .vscode folder.

project/
├─ .vscode/
│  ├─ snippets.code-snippets
│  ├─ settings.json
├─ more-folders/
├─ ...
├─ more-files
├─ ...

Snippet definitions are written in JSON. I created one definition called Front Matter to help me write my notes in VS Code. If you are unfamiliar with the syntax, you can use it as a starting point:

{
  "Front Matter": {
    "scope": "markdown",
    "prefix": ["front", "fm", "matter"],
      "body": [
        "---",
        "title: ${TM_FILENAME_BASE/(^[a-z])|(-)([a-z])/${1:/upcase}${2:+ }${3:/upcase}/g}",
        "created: $CURRENT_YEAR-$CURRENT_MONTH-$CURRENT_DATE",
        "updated: $CURRENT_YEAR-$CURRENT_MONTH-$CURRENT_DATE",
        "tags: [\"$0\"]",
        "---"
      ],
      "description": "Insert front matter with current date and title based on file name."
  }
}

This snippet is scoped to Markdown files, so it will only show up if you are editing a Markdown file. If you want it scoped to other languages, you can list them separated by comma (like this "javascript,markdown"). In prefix you can define your trigger text and the body is the actual content that will be pasted when you insert a snippet.

Special Case Markdown

It took me a while to figure out, why VS Code wouldn’t suggest my new snippet when I typed my trigger word. It turns out that there is a hidden default setting in VS Code that needs to be overwritten for snippets to work with Markdown files.

In order to make VS Code suggest your newly created snippet, create a new file called settings.json inside your project’s .vscode folder and paste these lines into it:

{
  "[markdown]": {
    "editor.quickSuggestions": true
  }
}

Now, when you type your trigger word while editing a Markdown file VS Code should suggest your snippet.



Back to posts