Optional lines in Ultisnips using parameters

1.1k Views Asked by At

I am trying to have some additional lines inserted in snippets based on a parameter. I am not sure how design such snippet.

snippet 'mysnip' 'snippets with optional lines'
  This snippet line1 is inserted by default
  <This line1a should be inserted if parameter1 is true>
  This snippet line2 is inserted by default
  <This line2a should be inserted if parameter1 is true>
endsnippet
3

There are 3 best solutions below

5
On BEST ANSWER

It is not very clear to me how/where you want to enter your parameters.

One option is to define two snippets, one called mysnip and the other one mysnip1 - in this case you pass the parameter in the snippet name, and the definition of these two snippets should be straightforward.

Another option is to just define one snippet mysnip, and pass the parameter somewhere within this snippet. A working example could look like this:

snippet mysnip1
${1:Change this snippet line to have the text "True" (without quotes).}
This line is always present. `!p
if t[1]=="True":
    snip += "A line displayed when $1 has the text True.
`
endsnippet
0
On

Can't you put your optional lines in a variable that your snippet engine will expand?

In case it doesn't join automatically empty lines produced from a empty variable, you may have to have your variable contain a newline character and put it or the line before/after.

0
On

You can fake this using regular expression triggers. It only works if you do not want to have tabstops in your optional arguments though:

snippet /mysnip([a-z]*)/ "Optionals" r
this is always here!`!p
if "a" in match.group(1):
  snip += "only when a" 
if "b" in match.group(1):
  snip += "only when b"`
endsnippet

If you type mysnip it will just be the first line, mysnipb the first and thirdm and mysnipab will be all of it.