Search code examples
visual-studio-codekeyboard-shortcutsvscode-snippets

In Visual Studio code, how do I assign a single keyboard shortcut to multiple languages?


I couldn't find anybody asking how to do this: if I'm using typescript, I may want a keyboard shortcut for generating the boilerplate of an "if statement" like so:

if (/* cursor starts here */) {
  /* selected text goes here */
}

But if I'm using another language, like Python, I would want a different "if statement":

if /* cursor starts here */:
  /* selected text goes here */

The official documentation explains how to map a single keyboard shortcut to a single snippet. But as far as I could tell, it doesn't explain how to map a single keyboard shortcut to multiple snippets (each in a separate language file).

It felt like the documentation left enough clues to figure this out on my own:

{
  "key": "cmd+k 1",
  "command": "editor.action.insertSnippet",
  "when": "editorTextFocus",
  "args": {
    "langId": "csharp",
    "name": "myFavSnippet"
  }
}

I assumed this would be as easy as copying and pasting that in the keyboard shortcuts bindings file, and modifying the langId and name where appropriate. But this just seemed to call the snippet of the last matching entry in the file.

So, how do I assign a single shortcut to multiple snippets, depending on what language file I'm typing in?


Solution

  • Though the documentation doesn't elaborate on these details, these fields are only used to scope what snippet to use when the keyboard is pressed:

        "langId": "csharp",
        "name": "myFavSnippet"
    

    It doesn't matter where you're typing, that's the snippet that'll be used.

    To execute different snippets depending on the language, you must modify the when. "when": "editorTextFocus" applies no matter what file you're in, as long as it has text focus. Trying to do two things at once is probably undefined.

    Here's how you should change the when clause to do what you want:

    {
      "key": "cmd+k 1",
      "command": "editor.action.insertSnippet",
      "when": "editorTextFocus && editorLangId == csharp",
      "args": {
        "langId": "csharp",
        "name": "myFavSnippet"
      }
    },
    {
      "key": "cmd+k 1",
      "command": "editor.action.insertSnippet",
      "when": "editorTextFocus && editorLangId == typescript",
      "args": {
        "langId": "typescript",
        "name": "myFavSnippet"
      }
    },
    

    Also, keep in mind that if you give the snippet the same name in every snippet file, you don't need to include the langId.