Search code examples
visual-studio-codevscode-snippets

When defining a snippet in VS Code keybindings.json, how do I have a portion of text selected after keybind usage?


I am switching over to VS Code and trying to understand how to define keybindings. I currently have this as my first attempt:

{
    "key": "F8",
    "command": "editor.action.insertSnippet",
    "args": { "snippet": "<cfqueryparam cfsqltype=\"$1integer\" value=\"$TM_SELECTED_TEXT\">" }
}

This works fine. If I select "test" in my document and hit F8, it adds the snippet around my text:

<cfqueryparam cfsqltype="integer" value="test">

And it places the cursor just before the word "integer" because of the $1.

How do I instead have it select the word "integer" after inserting the snippet?

Right now I need to hit F8, then hit ctrl+shift+right arrow, then type what I want as the cfsqltype; I'd like to just hit F8 and then start typing. I don't want to leave cfsqltype blank because it's "integer" 70% of the time.


Solution

  • In order to select the word integer, instead of position the cursor before it, you should use the ${1:integer} syntax.

    So, your keybinding should be:

    {
        "key": "F8",
        "command": "editor.action.insertSnippet",
        "args": { "snippet": "<cfqueryparam cfsqltype=\"${1:integer}\" value=\"$TM_SELECTED_TEXT\">" }
    }
    

    More details and other features, you can find in the official Snippets documentation