Question

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.

Was it helpful?

Solution

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
}

OTHER TIPS

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

func () FuncName

and remove the parenthese if they are left empty?

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top