Home > Software design >  custom snippets to surround a selected code
custom snippets to surround a selected code

Time:11-15

I'm working on a javascript project using VS Code there is a feature which surrounds the code with a snippets like below

enter image description here

is there a way to add a custom surround snippet

for example, this is my code

`<td>${x.debit}</td>`

and I want to Surround it with parseFloat(MYCODE).toFixed(2)

`<td>${parseFloat(x.debit).toFixed(2)}</td>`

CodePudding user response:

I managed to make it work using this extension. The setting needed is something like the following added to your settings.json:

"surround.custom": {
  "toFixed2": {
    "label": "tf2",
    "description": "Some description that will show in the picker",
    "snippet": "parseFloat($TM_SELECTED_TEXT).toFixed(2)",
    "languageIds": [
      "javascript"
    ]
  }
}

You don't have to include "languageIds" but it's useful to limit when these are available; "description" is not mandatory either.

A bit of limitation is that for this to work, you'd need a specific selection (let's denote it by [ and ]) as opposed to having the whole string selected:

`<td>${[x.debit]}</td>`

From there you invoke the command surround.with (might be useful to bind it to a key combintion) and look for tf2. Of course you can change the label to what makes more sense to you. The $TM_SELECTED_TEXT seems to be hardcoded and used to pick up the selected text. You can also tweak the snippet like this:

"snippet": "parseFloat($TM_SELECTED_TEXT).toFixed(2$0)"

The $0 token denotes where the caret will be after you finish your input, and placing it right after the 2 might be useful if you want to quickly change the number of decimal places for example.

  • Related