Skip to content

Brief overview and reference on how to cope with code snippets in Visual Studio Code.

License

Notifications You must be signed in to change notification settings

moma-lab/VS-Code-Snippets

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

10 Commits
 
 
 
 
 
 
 
 

Repository files navigation

How To Create Custom Code Snippets in VS Code

Maintenance status MIT license

With "snippets" Visual Studio Code provides the possibility of pre-defining custom code blocks that are accessible via custom defined trigger commands. Once you type in a trigger command the built in IntelliSense immediately provides a preview of the corresponding code snippet to insert. This is a simple and efficient way to speed up the overall code writing process.

This tutorial aims to give a brief overview on how to create, write and include such custom code snippets into VSCode.

General Information

Structure/Design

VS Code snippets have to be defined as JSON objects. In general they

  • support C-style comments,
  • can define an unlimited number of snippets,
  • support most TextMate syntax for dynamic behavior,
  • intelligently format whitespace based on the insertion context,
  • support different scoping methods,
  • perform 'Substring matching' on trigger words (e.g. typing "fc" could match "for-const") and
  • allow for easy multiline editing (via tabstops).

Storage location (Mac)

Custom created snippets are stored in:

  • ~/Library/Application\ Support/Code/User/snippets/ or
  • /Users/{username}/Library/Application\ Support/Code/User/snippets/.

Scope & file extensions

The availability of a snippet is scoped to one, several, or all ("global") programming languages based on whether it is defined in:

  • a language specific snippet file (has a .json suffix, e.g. <language>.json) or
  • a global snippets file (has a .code-snippets suffix, e.g. <description>.code-snippets)
    • Exception: if optional "scope" key is set to some specific languages inside a global snippet.

Global snippets (JSON with file suffix .code-snippets) can also be scoped to specific projects. Project-folder snippets are created with the 'New Snippets file for ...' option in the Preferences: Configure User Snippets dropdown menu and are located at the root of the project in a .vscode folder. Project snippet files are useful for sharing snippets with all users working in a project. Project-folder snippets are similar to global snippets and can be scoped to specific languages through the scope property.

Create a custom snippet

(1.) Automatically

  • open Code > Preferences > User Snippets (Mac)

  • select the programming language (by language identifier) for which the snippet should appear, or the "New Global Snippets file ..." option if they should appear for all languages

  • Write your snippet code inside the provided template, save it and you are ready to go.

(2.) Manually

  • open a text editor (or use VS Code)

  • create a JSON object and define your custom snippet (see Code Snippet Examples)

  • save the file in ~/Library/Application\ Support/Code/User/snippets/ as:

    • <language>.json, where <language> denotes the specific programming language the snippet shall be available for
    • <description>.code-snippets, which will make the snippet available in all programming languages (except the scope key is set to just some specific languages in the snippet object)

Snippets versus Emmet (WIP)

To modify/change built in code macros you can either edit the emmet code file (where all the macros are defined).

BUT: you need to modify this file EVERY single time you update VSCode (just a copy would suffice because emmet is not updated frequently).

It is much easier to instead write a snippet for the alternative syntax you want. Furthermore 'snippets' are part of the VSC sync!

Snippet Syntax

Basic Snippet Template

{
  "Snippet name": {
    "scope": "Comma, separated, list, of, all, applicable, programming, languages",
    "prefix": ["All", "commands", "that", "will", "trigger", "the", "code", "snippet"],
    "body": [
      "// The actual code snippet that shall be included.",
      "const firstSnippet = {",
      "  messsage: \"Hello, world!\",",
      "  origin: \"Custom VS Code Snippet\"",
      "};"
    ],
    "description": "Insert short code snippet description here."
  }
}

Explanation:

The key-value pairs of the JSON object above define a new code snippet.

  • object key ("Snippet name"):
    • a string displayed via IntelliSense when typing in the snippet triggering command and no description is provided
  • scope (optional):
    • a string of comma separated names of programming languages that are allowed to use the snippet (e.g. "scope": "javascript, typescript",)
    • if not specified general scope is expected (meaning: snippet will be available in all programming languages)
  • prefix (single string or array of string elements):
    • defines one or more trigger words/commands that display the snippet in IntelliSense when typed in (Substring matching is performed on 'prefixes', so in this case, "fc" could match "for-const").
  • body:
    • array of string elements building the actual output (the code to be inserted)
  • description:
    • info string that shows up under the command in IntelliSense

Special body Constructs

The body key of a snippet JSON object can use special constructs to control cursors and the text being inserted. The following constructs are supported:

Assign Keybindings to Snippets

You can create custom keybindings to insert specific snippets. Open keybindings.json (Preferences: Open Keyboard Shortcuts File), which defines all your keybindings, and add a keybinding passing "snippet" as an extra argument (see example here: Assign Keybindings to Snippets).

Code Snippet Examples

Real World Example #1: console.log

Custom code snippet to log to the console in JavaScript/TypeScript (console.log), saved as global snippet file console log.code-snippets. $1 and $2 are jump marks for tab stops.

{
  "Console log": {
    "scope": "javascript, typescript",
    "prefix": ["cl", "log"],
    "body": [
      "console.log('$1');",
      "$2"
    ],
    "description": "Log to the console"
  }
}

Usage:

  • in your js/ts file just start typing one of the defined commands cl or log

Real World Example #2: 'made by' console info

Custom code snippet to create my created by credentials in JavaScript/TypeScript, saved as global snippet file credentials.code-snippets.

{
  "moma.dev.lab credentials": {
    "scope": "javascript, typescript",
    "prefix": ["credentials", "moma", "who", "created", "made", "by"],
    "body": [
      "// Print 'created by' info to console.",
      "console.info(",
      "  '\\n                    MADE WITH ♥ BY MOMA.DEV.LAB\\n                    https://github.com/moma-lab\\n\\n'",
      ");"
    ],
    "description": "Creates 'made by...' text for console output."
  }
}

Usage:

  • in your js/ts file just start typing one of the defined commands credentials, moma, who, created, made or by

Real World Example #3: FOR-Loop

Below is an example of a for loop snippet (including tabstops and placeholders) for JavaScript:

// in file 'Code/User/snippets/javascript.json'
{
  "For Loop": {
    "prefix": ["for", "for-const"],
    "body": ["for (const ${2:element} of ${1:array}) {", "\t$0", "}"],
    "description": "A custom for loop."
  }
}

Additionally, the body of our example #3 has three placeholders (listed in order of traversal): ${1:array}, ${2:element}, and $0. You can quickly jump to the next placeholder with Tab, at which point you may edit the placeholder or jump again the next one. The string after the colon (if any) is the default text, for example element in ${2:element}. Placeholder traversal order is ascending by number, starting from one; zero is an optional special case that always comes last, and exits snippet mode with the cursor at the specified position.

References

Contributions welcome

Created with ♥ by moma.dev.lab. Feel free to submit a pull request. Help is always appreciated.

  1. Fork this repo

  2. Clone fork into your local repo:
    $ git clone https://github.com/YOUR-USERNAME/VS-Code-Snippets

  3. Create your own feature branch:
    $ git checkout -b my-branch-name

  4. Commit your changes:
    $ git commit -am 'some new feature'

  5. Push to the branch:
    $ git push origin my-new-feature

  6. Create new Pull Request

License

Published under the MIT Licence.

About

Brief overview and reference on how to cope with code snippets in Visual Studio Code.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published