vs code: code snippets



~3 min read


445 words

One of the productivity enhancements I’ve been meaning to learn more about for a while is making better use of code snippets.

Code snippets are great for rote work and boiler plate by enabling, with relatively little effort.

Today, I decided to dive in with a basic example to understand the mechanics and get the juices flowing for more sophisticated use cases later.

Every day, I add an entry to a markdown file for a dev log I maintain. I wanted to avoid the hassle of typing that date out. This felt like a great use case for a code snippet, particularly because dates are among the variables accessible to snippets.

Let’s dive in.

Steps To Create A Snippet

  1. The first decision we have to make when creating a snippet is whether it will be a global snippet or project specific. In most cases global makes sense, however, in my case I was interested in a project specific snippet since the use case for the date is fairly narrowly limited to a particular project.

    To get started, open the command pallette ⌘-⇧-p and select Preferences: Configure User Snippets

    configure user snippets

    Choosing a project specific snippet will create a *.code-snippets file in the .vscode directory of the project.

  2. Design and write the snippet. This is the step where we actually get to configure the snippet. For creating a header with the day’s date in markdown, I came up with the following:

     "Create Header for Today": {
       "scope": "markdown",
       "prefix": "today",
       "description": "Creates a header for daily journal"

    The prefix is how the snippet will be identified with intellisense.

  3. Now that the snippet is defined and saved, we can invoke it in two ways. From within the appropriate scope (in our case, a markdown file):

    1. Use the command pallette:

    snippett via pallette

    1. Use intellisense ⌃-space

    snippet via intellisense

Simplifying Further: Key Bindings

Both the command pallette and intellisense are good solutions, but a key binding might be preferred.

Fortunately, configuring key bindings for code snippets is well supported.

Keybindings are managed in Open Keyboard Settings (JSON) and new ones can be added there.

For the snippet I created, the new keybinding could look like:

    "key": "cmd+k 1",
    "command": "editor.action.insertSnippet",
    "when": "editorTextFocus",
    "args": {
      "langId": "markdown",
      "name": "today-h1"

The name in the args comes from the filename, which in my case is today-h1.code-snippets

Wrap Up

That’s all there is to it. With just a few steps of configuration, VS Code can be made even more powerful and suited to your personal workflow.

Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!