5

I was switching to vim for the C-support mode, and then I discover yasnippet for emacs, it is awesome I love it !

So now I'm adding basic snippets to insert code and I am currently having a bit of difficulties to make a good for ( ...; ...; ... ) snippet.

I can do this : for ( $1; $2; $3 )

But I would like to have some defaults values, or else benefit from the mirror functionality of yast.

I know I can set default values with ${$1value} but in my case I think need to imbricate them, I haven't succeed trying it. I ewplain what I'd like : By default, I should be for ( int i = 0; i < $something; i++ )

With the possibility to modify the int type (could be nothing), the variable name, which I want to mirror in the second and third part, and the affectation.

The condition could also be different, but it needs to contain the first variable, same for incrementation. Is it possible ?

It might be a better idea to keep it simple and define more snippets, I wonder if some of you have results with complex snippets.

  • 2
    Please format your answer in to something readable – Squidly Nov 27 '15 at 14:11
5

To have a value repeat like you're asking, simply repeat the $N. For example, I have this for snippet:

# -*- mode: snippet; require-final-newline: nil -*-
# name: for
# key: for
# --
for(${1:int} ${2:i} = 0; $2 < ${3:N}; $2++) {
    $0
}

The default expansion is:

for(int i = 0; i < N; i++) {
    //cursor
}

It only prompts for the first instance of $2, and automatically updates the others to match it.

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.