vscode if/else conditions in user defined snippet

徘徊边缘 提交于 2019-12-11 08:49:22

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/57381007/vscode-if-else-conditions-in-user-defined-snippet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!