Ansharja
Ansharja

Reputation: 1123

Pass typed text inside vscode snippets

After reading the snippets documentation I'm still searching a way to pass some text inside the snippet body by typing it after the snippet prefix.

Let's say I have a snippet with log prefix, I would like to transform the prefix in something like log(*+) to capture the text after.

If I type loganObject, the snipped should capture "anObject" and call my snippet to insert some text like console.log ("the value of anObject is: ", anObject);.

Is that possible?

I think that it is not possible because vscode should recognize that I'm still typing the prefix of the snippet and the text after the prefix should be captured and used inside the snippet body, but I hope they realized something like this.

Upvotes: 0

Views: 411

Answers (1)

Mark
Mark

Reputation: 181319

Here is a keybinding that does what you want, but you have to select the text first Shift+Home and that is the only text on the line.

Using log.myTextHere as the matched text, i.e., log. at the beginning just to be clear.

In your keybindings.json:

{
  "key": "alt+l",                   // whatever keybinding you want
  "command": "editor.action.insertSnippet",
  "args": {
    // get the extra text into capture group 1
    "snippet": "console.log (\"${TM_SELECTED_TEXT/^log\\.(.*)/the value of $1 is: \", $1/});"
  }
}

console.log snippet demo


Alternatively, and a little easier and more flexible, is to use an extension I wrote, Find and Transform, to do this. Use this keybinding:

{
  "key": "alt+y",                   // whatever keybinding you want
  "command": "findInCurrentFile",
  "args": {
    "preCommands": "cursorHomeSelect",    // does the selection for you
    "replace": [
      "$${",
              // log. = 4
      "let myVar = '${selectedText}'.substring(4);",
      "return `console.log (\"the value of ${myVar} is: \", ${myVar});`",
      "}$$"
    ],
    "restrictFind": "line"
  }
}

You could change substring(4) if you just want to use log and not log..

log snippet with Find and Transform extension

Upvotes: 1

Related Questions