Search code examples
emacselispyasnippet

How to add values of two yasnippet fields


I'm trying to write a snippet whose inputs (tab-stop fields) are two numbers, and which returns their sum. But I don't know how to reference the values of both fields at the same time, and it seems like I can't reference the values of the tab-stop within embedded elisp code.

Here is what I tried:

First number: $1
Second number: $2
Sum of two numbers: `(+ (string-to-number $1) (string-to-number $2))`

But when I expand the snippet, the text [yas] elisp error! appears where the sum should go. What am I doing wrong?


Solution

  • joaotavora recently pointed out that this can be done using yas-field-value:

    First number: ${1:0}
    Second number: ${2:0}
    Sum of two numbers: ${2:$(+ (string-to-number (or (yas-field-value 1) "0")) (string-to-number (or yas-text "0")))}