Visual Studio Code snippet as keyboard shortcut key

Note that the line below will open a list of snippets defined for the language you are currently using (and you don’t want that)

"args": { "snippet": "'$TM_SELECTED_TEXT'" }

Whereas with the below line the snippet given as argument will be executed right away

"args": { "name": "your_snippets_name" }

Here’s how I defined a snippet for HTML where I wanted to select a text and when pressing CTRL+B the text to become enclosed in <strong></strong> tags:

"make_strong": {
    "prefix": "strong",
    "body": [
        "<strong>$TM_SELECTED_TEXT${1:}</strong>"
    ],
    "description": "Encloses selected text in <strong></strong> tags"
}

Note the ${1:} above – what this does is that it places the cursor there. This enables you to press CTRL+B at cursor and then have the cursor placed inside the <strong></strong> tags. When selecting a string and pressing CTRL+B, the string will enclosed in <strong> tags and the cursor will be placed before the closing </strong> tag. Pressing TAB at this point, will put your cursor after the closing </strong> tag.

And added in my keybindings.json the following:

{
    "key": "ctrl+b",
    "command": "editor.action.insertSnippet",
    "args": { "name": "make_strong" }
}

UPDATE JUNE 2nd, 2021

Since this is getting lots of views, I am posting some of the snippets I use, maybe it will be useful to someone

{
    "key": "ctrl+alt+u",
    "command": "editor.action.transformToUppercase"
},
{
    "key": "ctrl+alt+l",
    "command": "editor.action.transformToLowercase"
},
{
    "key": "ctrl+b",
    "command": "editor.action.insertSnippet",
    "args": { "name": "insert_strong" }
},
{
    "key": "ctrl+i",
    "command": "editor.action.insertSnippet",
    "args": { "name": "insert_italic" }
},
{
    "key": "ctrl+u",
    "command": "editor.action.insertSnippet",
    "args": { "name": "insert_underline" }
},
{
    "key": "ctrl+alt+p",
    "command": "editor.action.insertSnippet",
    "args": { "name": "insert_paragraph" }
},
{
    "key": "ctrl+shift+space",
    "command": "editor.action.insertSnippet",
    "args": { "name": "insert_nbsp" }
},
{
    "key": "ctrl+enter",
    "command": "editor.action.insertSnippet",
    "args": { "name": "insert_br" }
},

Leave a Comment