0

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?

MTS
  • 268
  • 2
  • 6
  • Maybe try `string-to-number` instead of `string-to-text`? – Dan May 01 '14 at 18:29
  • @Dan Oops, that's what I wrote in the actual snippet but not in the question. Edited. – MTS May 01 '14 at 18:32
  • In general, you should write the solution to your problem in an answer and set it as marked. That way, this question can bubble down since it is solved. – PythonNut May 01 '14 at 21:39
  • @PythonNut When writing the code in the question here, I incorrectly wrote string-to-text, while I had string-to-number in the actual snippet on my computer (which still doesn't work). So the problem isn't solved. – MTS May 01 '14 at 21:44

2 Answers2

1

and sorry for the confusion. According to the official snippet writing guide, what you are looking for is called a mirror. Unfortunately, a mirror can only mirror a single variable, so you seem to be out of luck.

This is probably because yasnippet needs to know which mirrors to update when you type a field. (It doesn't want to update them all, because that could be costly), so it needs a way of determining which mirrors are affected by which fields. If it allowed arbitrary substitutions, that would be impossible to determine. (A simple keyword search isn't enough because the variable could be hidden behind metaprogramming).

PythonNut
  • 6,182
  • 1
  • 25
  • 41
1

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")))}
npostavs
  • 4,877
  • 1
  • 24
  • 43
  • Thank you! Glad to hear it can be done. Of course, four years after asking the question, I have no recollection of why I asked it... – MTS Feb 20 '18 at 17:50