1

I want to make snippet for console.log(variable) but instead to have prefix I want to make this with "suffix". Here's an example:

var name = "Marco";
var car = "Volvo";

name.log > TAB > console.log(name);

When I write my variable "name" after that ".log" like in example above. After that pressing TAB key on keyboard i want to get my "console.log(name);". When I do it like this: car.log > TAB, I want to get "console.log(car);".

starball
  • 20,030
  • 7
  • 43
  • 238
  • 1
    What would you want to happen if the object you're operating on in this type of context actually has an attribute or method literally named `log`? – esqew May 04 '23 at 16:11
  • 1
    Counter-proposal: you don't actually want this. What you want is a way to log a given thing, e.g., by wrapping a given "chunk" of code with `console.log(CHUNK)` *(also more versatile, IMO)*. – Dave Newton May 04 '23 at 17:49
  • @esqew log.log > TAB > console.log(log); – andrijadenic9 May 05 '23 at 19:52
  • @DaveNewton Yes that is it, but how to achive that without snippet? – andrijadenic9 May 05 '23 at 19:53

3 Answers3

1

what you can do is

  • type name
  • select name, useCtrl+D
  • type clog

clog is the following snippet:

"consolelog": {
    "prefix": "clog",
    "body": "console.log(${TM_SELECTED_TEXT})"
}
rioV8
  • 24,506
  • 3
  • 32
  • 49
1

There are a couple of other options, notably see How can I customize a suffix snippet, replacing the variable in VS Code? and the extension mentioned there:

TS/JS postfix completion built-in support for someVar.log => console.log(someVar)

You can also automate the process that of replacing the existing text with a snippet, BUT then you must use a keybinding trigger and not a snippet prefix. No extension is necessary though. In your keybindings.json:

{
  "key": "alt+c",            // whatever keybinding you want
  "command": "runCommands",
  "args": {
    "commands": [
      "cursorHomeSelect",
      {
        "command": "editor.action.insertSnippet",
        "args": {
          "snippet": "console.log(${TM_SELECTED_TEXT})",
        }
      },
    ]
  },
}

For this second version you just type name and then alt+c.

Mark
  • 143,421
  • 24
  • 428
  • 436
0

Looking at the documentation for Snippets, I don't think what you're asking for is supported.

The mechanism for using snippets is based on exact matches of text (the prefix field), and while the variables include things like TM_CURRENT_LINE and TM_CURRENT_WORD, and even given those, I can't see a way to work them to do what you want.

The closest I could get was

"test": {
    "prefix": ".log",
    "body": "console.log(${TM_CURRENT_LINE/^(\\s+.*?)?(\\w+)\\.log(.*)$/$2/})"
}

But I don't know how to "consume" / remove the pre-existing text preceding the snippet prefix.

starball
  • 20,030
  • 7
  • 43
  • 238