2

Looking at the vscode documentation for user defined snippets, it would appear that using the regex transform, you can do if/else conditions.

However, I can't seem to find any examples of this and I'm struggling to understand the correct syntax based on the BNF alone.

Can someone explain the syntax for this?

For example,

Lets say I have a snippet like this:

"body": [
    "let color = '${1|white,black|}';",
    "let hex = '${???}';"
]

If color==white, I want hex to output #fff, otherwise if black #000.

Mark
  • 143,421
  • 24
  • 428
  • 436
NSjonas
  • 10,693
  • 9
  • 66
  • 92
  • not sure if what I'm trying to do is even possible. I can only get the example regex to work with the system variables. Seems like maybe it doesn't work with user defined tab stops. Bummer – NSjonas Aug 06 '19 at 19:41
  • I'll add an answer shortly. It is possible but apparently not with default placeholders. – Mark Aug 06 '19 at 19:57

1 Answers1

9

This works:

"color conditional": {
  "prefix": "_hex",
  "body": [

    "let color = '${1};",      
    "let hex = '${1/(white)|(black)|(red)/${1:+#fff}${2:+#000}${3:+#f00}/}';" //works      
  ],
  "description": "conditional color"
},

However, as soon as I try it with default placeholders and choices, like

"let color = '${1|white,black|}';",   // does not work

Apparently, you cannot do snippet transforms on default placeholder values. See transforms on placeholder values issues

I used the simpler if transform style, so here:

${1/(white)|(black)|(red)/${1:+#fff}${2:+#000}${3:+#f00}

if there is a group 1 $[1} in this case white then replace that group 1 with #fff and if group 2 (black) replace with #000, etc.

You could make it just an if/else (white) or not pretty easily.

"let hex = '${1/(white)/${1:?#fff:#000}/}';"  // any non-`white` entry will print `#000`.  

${1:? => if group 1 (white) print #fff , else print #000

The vscode docs are not very helpful on these conditional replacements, if you have more questions on their syntax, let me know.

Mark
  • 143,421
  • 24
  • 428
  • 436
  • the first example actually doesn't work for me for some reason... It just edits each like they are one tab stop. Could you maybe provide the entire snippet so I can see if something else is going on... – NSjonas Aug 06 '19 at 21:56
  • You probably have to hit `tab` one more time for the transform in the `let hex` line to take effect - it does so after a tab. – Mark Aug 06 '19 at 22:32
  • yup that was it. Thanks for a very complete answer! – NSjonas Aug 07 '19 at 05:06