ivarg
ivarg

Reputation: 785

yasnippet conditional transformation on leaving field

I'm writing a snippet (for Go) and would like to have a field conditionally transformed when I move to the next field. Specifically, I want the field empty if I leave it unedited, and enclosed in parentheses if I leave it edited.

My unsuccessful snippet, expressing what I want but failing to transform an edited field:

func ${1:$$(when (and yas-modified-p yas-moving-away-p) 
             (concat "(" yas-text ")"))} FuncName

What I want is, that when typing t Type in the field, the snippet would expand as such:

func (t Type) FuncName

and when skipping over the field unedited it would expand like this:

func FuncName

I know that the condition executes as one would expect, because if I change (concat ...) to (message "XXX"), I see the trace printed in the mini buffer, but I can't figure out why my transformation doesn't work.

Upvotes: 5

Views: 998

Answers (3)

phils
phils

Reputation: 73344

The documentation suggests you need to wrap elisp forms in `backticks` to incorporate the return value into the snippet (much like command substitution in shell scripts).

Source

Upvotes: 1

Stefan
Stefan

Reputation: 28571

Wouldn't it be easier to have the snippet start as

func () FuncName

and remove the parenthese if they are left empty?

Upvotes: 1

Carl Groner
Carl Groner

Reputation: 4359

In your example it seems to me that the result of your concatenated string is discarded. I think you need to actually insert the new string into the buffer.

I'm not really very familiar with yasnippet syntax, so this may not be the cleanest solution, but the following seems to work for me:

func ${1:$$(when (and yas-modified-p 
                      yas-moving-away-p) 
              (insert ")" )
              (backward-char (+ 1 (length yas-text)))
              (insert "("))} ${2:funcName} {
    $0
}

Upvotes: 3

Related Questions