I use javascript snippet with keybinding.
I have this code below:
{
"key": "alt+c",
"command": "editor.action.insertSnippet",
"when": "editorTextFocus",
"args": {
"snippet": " const $TM_CURRENT_WORD = $1"
}
},
If I type box
and than press alt+c, I get...
box const box =
But I expected
const box =
How can I achieve that?
Snippets will always insert text wherever the cursor is at the time the snippet is triggered - that is why you are seeing the behaviour you get. If the word was first selected, an insertion would replace that word like normal.
The easiest way is just to select the box
text and then alt+c and you will get your result. But with the extra step of selecting.
Here is a macro solution as well.
Using a macro extension like multi-command put this into your settings.json:
"multiCommand.commands": [
{
"command": "multiCommand.insertConst", // whatever name you want to give it
"sequence": [
"cursorWordLeftSelect",
{
"command": "editor.action.insertSnippet",
"args": {
"snippet": "const $TM_SELECTED_TEXT = $1"
}
}
]
}
]
and some keybinding:
{
"key": "alt+c",
"command": "extension.multiCommand.execute",
"args": { "command": "multiCommand.insertConst" }, // use same name here
"when": "editorTextFocus"
},
or you could just modify your snippet so that you don't first type the variable name. You would trigger the snippet, then type the variable name, tab and then its value like so:
{
"key": "alt+c",
"command": "editor.action.insertSnippet",
"when": "editorTextFocus",
"args": {
"snippet": " const $1 = $2"
}
},