1

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
snippet '(\b\w+\b)\.iter' "loop list" r
for _, ${1:`!p snip.rv = match.group(1)[:-1]`} := range `!p snip.rv = match.group(1)` {
    ${0}
}
endsnippet

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

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.