Search code examples
javascriptvisual-studio-codecode-snippetsvscode-snippets

How can I create VS Code snippets that consume pre-existing text placed before the snippet prefix and use it in the snippet body?


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);".


Solution

  • 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.