visual-studio-codevscode-snippets

Conditional Transform in VSCode Snippet


Here is a vscode snippet i am using to replace first colon of each line with double colon.

"Description List": {
    "body": [
        "${TM_SELECTED_TEXT/^(.+:)(.+)$/$1:$2/gm}"
    ],
    "description": "Description List"
},

The issue is, if there is no : at any line then a : is placed at the beginning of it anyways.

For example, if the input is:

Point One: This is first line
Point Two: This is second line
This is third line

Then the output becomes:

Point One:: This is first line
Point Two:: This is second line
:This is third line

Then expected output is:

Point One:: This is first line
Point Two:: This is second line
This is third line

I have tried, ${1:+$1:} but it prints $1:.

How to say that if there is no colon then print the line as it is without any transformation.


Solution

  • Try this version:

    {
      "key": "alt+p",
      "command": "editor.action.insertSnippet",
      "args": {
        // "snippet": "${TM_SELECTED_TEXT/^(.+:)(.+)$/$1:$2/gm}"  // your original version
    
        "snippet": "${TM_SELECTED_TEXT/^(.+)(:)(.+)$/$1$2${2:+:}$3/gm}"
      }
    },
    

    My versi9on treats the : as its own capture group. And then adds an additional : if that group exists with this:

    $2${2:+:}   // reinsert the original :, add another : if there is a capture group 2
    

    [I still am having trouble reproducing your issue, but this form of the snippet transform should be a little "safer" because it really focuses on the presence of the : as its own capture group.]