I want to make a snippet for a function with optional arguments. For example something like:

myfunc($1, $2, $3)

But in this case, $2 may be optional. I know I can press Ctrl-D to skip it, but it leaves behind the comma. How do I get a snippet to delete the comma if I skip the field?


You can achieve this by nesting the fields:

myfunc($1${2:, $3}, $4)

to fill all three, press A<tab><tab>B<tab>C. To skip the middle one, do A<tab><c-d>C

  • This does not seem to do what I described. When I use this snippet, I would have thought I could press a<tab>b<tab>c<tab> and get myfunc(a, b, c) but there is no comma between b and c. It does work for making two args. e.g. a<tab>b<tab><tab> results in myfunc(a, b). – John Kitchin Nov 24 '18 at 12:19
  • Sorry, I have made a mistake in the original answer. See the edited one - it should work now. – serycjon Nov 25 '18 at 20:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.