Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using TM_SELECTED_TEXT in my custom snippets

With the November 2016 (version 1.8) release of VSCode Snippet Variables are now supported, specifically TM_SELECTED_TEXT.

This makes me happy as I have used these heavily in both Sublime Text and TextMate.

I can't figure out how to get it to work in VSCode. I've created the snippet they use as an example:

"in quotes": {
    "prefix": "inq",
    "body": "'${TM_SELECTED_TEXT:${1:type_here}}'"
}

I then enter some text, highlight it and that's where things start to break.

The idea is highlight some text, run the snippet and then ${TM_SELECTED_TEXT:${1:type_here}} is replaced with the highlighted text. The problem I'm having is that to run the snippet you need to type the prefix value (in this case inq) to run the snippet which over-writes your highlighted text which messes everything up.

In Sublime/Textmate I launched the snippet from a keyboard combination which left my text highlighted.

Is there a way, in VSCode, to either make this work as is or launch the snippet from a key combination like was available in Sublime?

like image 858
Jason Avatar asked Dec 16 '16 19:12

Jason


2 Answers

Coming in 1.49 (it is in the Insiders' Build as of this edit) your example will finally work as you expected. See merged pull request.

Vscode will now "remember" your selected text if any, and when you type your snippet prefix, insert it into the TM_SELECTED_TEXT variable even though you seemingly over-typed that selected text.

selected text snippet


As of v1.20 this has become easier as a new variable $CLIPBOARD has been added, see new snippet variables. So there is no need to assign and run a shortcut - but you must copy the selection to clipboard CTRL-C.

Your example could now be:

"in quotes": {
    "prefix": "inq",
    "body": "'$CLIPBOARD:${1:type_here}'"
}

Note: $CLIPBOARD works. There's no need for the extra curly brackets {$CLIPBOARD}.

like image 158
Mark Avatar answered Oct 01 '22 01:10

Mark


With the word highlighted, press F1 and run the command "Insert Snippet", then select your snippet on the list.

Also you can edit your keybindings by going to File>Preferences>Keyboard Shortcuts and add some shortcut to the "editor.action.showSnippets" command, like this:

{
    "key": "ctrl+alt+s",
    "command": "editor.action.showSnippets",
    "when": "editorTextFocus"
}
like image 29
gabrielmdu Avatar answered Sep 30 '22 23:09

gabrielmdu