'How to use inline JavaScript inside a snippet to process variables?
I need to process $TM_SELECTED_TEXT. The processing is more than RegEx. Can I use inline JavaScript inside keybindings.json?
Current code:
[
{
"key": "cmd+k t",
"command": "editor.action.insertSnippet",
"when": "editorTextFocus",
"args": {
"snippet": "${TM_SELECTED_TEXT /_/g}"
}
}
]
I couldn't find any step by step guide to use inline JavaScript.
Solution 1:[1]
There is no built-in way to run javascript in a snippet transform. An extension I wrote, Find and Transform, allows you to use javascript string and math operations (and more) to create replacement text.
For example, this keybinding (in keybindings.json):
{
"key": "alt+y", // whatever keybinding you want
"command": "findInCurrentFile",
"args": {
// "preCommands": "cursorHomeSelect", // if necessary
// "find": "<text or regex>", // not necessary here
"replace": [
"$${", // syntax to start a js operation
// note the ticks around the variable, so it is seen by js as a string
// must use semicolons at the end of each statement
"let myVar = '${selectedText}'.substring(2).toLocaleUpperCase();",
"myVar += ' Hello';",
"return myVar;", // must use return
"}$$" // syntax to close js operation
],
// "isRegex": true, // not necessary here
"restrictFind": "selections"
}
}
would replace the selected text with the string operation <the selected text>.substring(2).toLocaleUpperCase(). You can do any other string operations you want. Or Math operations if your selected text was a Number.
You can also use other types of variables, like https://code.visualstudio.com/docs/editor/variables-reference#_predefined-variables and more.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
