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

In vscode, how to define a shortcut to invoke a custom snippet for current active language?


Let's say I have a Ruby user snippet to output the string ruby and a Python user snippet to output the string python. How can I make Ctrl+b to invoke the aforementioned Ruby snippet when in ruby-mode, and invoke the Python snippet when in python-mode?


Solution

  • {
        "key": "ctrl+b",
        "command": "editor.action.insertSnippet",
        "args": {
            "snippet": "ruby"
        },
        "when": "editorLangId == ruby"
    },
    {
        "key": "ctrl+b",
        "command": "editor.action.insertSnippet",
        "args": {
            "snippet": "python"
        },
        "when": "editorLangId == python"
    },
    

    Also, instead of using the snippet argument value to define your snippet inline, you can reference an existing snippet by using the langId and name arguments.

    https://code.visualstudio.com/docs/getstarted/keybindings#_when-clause-contexts

    https://code.visualstudio.com/docs/languages/identifiers#_known-language-identifiers

    https://code.visualstudio.com/docs/editor/userdefinedsnippets#_assign-keybindings-to-snippets