Reputation: 12052
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
.
Upvotes: 8
Views: 5082
Reputation: 182331
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.
Upvotes: 13