0

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.

4
  • It isn't possible like you want. You would have to use a tabstop, like $1 , and type your extra text there. Or an extension like HyperSnips could probably do that. You could make a keybinding that inserts a snippet though that reads the log(...) text and outputs what you want. Commented Mar 30, 2022 at 22:29
  • what is wrong with typing the additional text in a field ($1), by placing a $0 you control where the cursor ends, could be inside the snippet. Commented Mar 31, 2022 at 1:00
  • @rioV8, Could you provide an example of what you mean? Commented Mar 31, 2022 at 13:32
  • it is all in the doc pages you have read Commented Mar 31, 2022 at 15:03

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.