8

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.

2
  • 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 Commented Aug 6, 2019 at 19:41
  • I'll add an answer shortly. It is possible but apparently not with default placeholders. Commented Aug 6, 2019 at 19:57

1 Answer 1

13

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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...
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.
yup that was it. Thanks for a very complete answer!
I wanted to replace .<Number> or ,<Number> with . or , respectively. ${TM_SELECTED_TEXT/(,\\d+)|(\\.\\d+)/${1:+,}${2:+.}/g} worked. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.