Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 677
ivarg Avatar asked Oct 24 '13 21:10

ivarg


3 Answers

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
}
like image 98
Carl Groner Avatar answered Oct 20 '22 06:10

Carl Groner


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

func () FuncName

and remove the parenthese if they are left empty?

like image 1
Stefan Avatar answered Oct 20 '22 06:10

Stefan


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

like image 1
phils Avatar answered Oct 20 '22 06:10

phils