Search code examples
visual-studio-codevscode-snippets

Visual Studio Code Snippets: How to transform user input in snippet?


I'm trying to write a snippet in Visual Studio Code that outputs something like this:

console.log('variable: ', variable);

This is pretty easy, just something like:

 "Debug Labeled String": {
    "scope": "javascript",
    "prefix": "c,",
    "description": "Debug Labeled String",
    "body": [
      "console.log('$1', ${1})",
    ]
  }

An issue with this is if the string I'm debugging has single quotes in it, it's no longer valid code. So I'm trying to replace single quotes in the contents of the first $1 with nothing. According to the docs you can apply transforms to variables. However, I can't figure out how to apply transforms to user variables.

I've tried

"console.log('${1:/'//g}', $1);"

But this just outputs literally /'/ in place of $1. I've also tried doing something like capturing all of the input and referencing that capture group by number:

"console.log('${1:/'//g}', ${1:/(.*)});"

But this doesn't work either. Is it possible in Visual Studio Code to transform the result of user input?


Solution

  • This works for me:

    "console.log('${1/'//g}', $1);",  
    

    I just removed the : which makes it into a placeholder without a default value and transforms on placeholders are tricky. For instance, this also works:

     "console.log('${1/'//g}', ${1:default});"  // or
     "console.log('${1/'//g}', ${1:});"
    

    I think the key is you need a non-transformed placeholder somewhere and then the transform will work. The non-transformed placeholder can be before or after the transformed version. Hence this doesn't work:

    "console.log('${1/'//g}', ${1:default/'//g});"  // the second transform does nothin
    

    I also think there are some bugs in placehlder transforms.