I'm coding a lot in go these days and one pattern I use often is iterating over slices and would like to use a snippet for this. There are generic for loop snippets that work well, but I'd like to take it a step forward.

The below is my expected behavior of the snippet:

Imagine there's a slice (could be an array/list in other languages) of name apples. Now when i type apples.iter followed by the expand trigger(Tab in my config) it should expand to the following:

for _, apple := range apples {


stripping the s from the list name is doable using python interpolation. But, I'm not sure on what should be set as the snippet expand word when defining my custom snippet.

My little research makes me believe, some kind of regular expression could be used, but didn't find any useful examples yet.

Can this be done, using ultisnips?

I know we could always use a regular snippet, expand and then type apples. But the .iter would feel more natural (at least to me) and can be extended to other use-cases like .isnull, .isempty etc.

P.S: I'm on the latest version of vim and ultisnips

1 Answer 1

snippet '(\b\w+\b)\.iter' "loop list" r
for _, ${1:`!p snip.rv = match.group(1)[:-1]`} := range `!p snip.rv = match.group(1)` {

Add trailing r to use regular expression style trigger_word. (\b\w+\b)\.iter matches apples.iter. match is returned value of the match of the regular expression. match.group(1) is list name.

  • :h UltiSnips-python
  • Thank you, that works really well!
    – Harish
    May 22, 2019 at 13:45
  • 1
    I was trying to make this work and was close. This topic is covered in this video: sirver.net//blog/2012/03/31/…
    – Harish
    May 22, 2019 at 13:49

Your Answer

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

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