Visual Studio Code snippet as keyboard shortcut ke

2020-02-17 10:36发布

问题:

I know how to modify and create code snippets and I know how to modify shortcut keys, but how does one bring those 2 together?

回答1:

Note that the line below will open a list of snippets defined for the language you are currently using

"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 be placed between <strong> tabs 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" }
}


回答2:

It would seem that, as of version 1.9, Visual Studio Code can do what you are looking for, no other extensions necessary.

From https://code.visualstudio.com/updates/v1_9#_insert-snippets

"You can now bind your favorite snippets to key bindings. A sample that encloses a selection with single quotes looks like this:"

Add the snippet below to keybindings.json (open Keyboard Shortcuts editor and click on the For advanced customizations open and edit keybindings.json link)

{
    "key": "cmd+k",
    "command": "editor.action.insertSnippet",
    "args": { "snippet": "'$TM_SELECTED_TEXT'" }
}