2

I would like to have a yasnippet to evaluate infix math expression on the current line. E.g., If the line is 1 + 2 = and I trigger yasnippet at the end of line, it will append the result at the end: 1 + 2 = 3.

I found this snippet from https://www.reddit.com/r/emacs/comments/6u0gmx

$1 = ${1:$(calc-eval
   (replace-regexp-in-string "p" "perm"
                 (replace-regexp-in-string "c" "choose"
                                   yas-text)))}$0

But it's a real-time interactive snippet that I don't prefer.

1 Answer 1

2

EDIT

a simple way to make it work in the middle of a line (that does not contain any other number of parentheses before the formula) is to replace the (line-beginning-position) with:

(save-excursion
(beginning-of-line)
(1- (re-search-forward "[0-9(]")))

Of course if you are trying to evaluate a formula starting with a letter (e.g. sin(2)), then surround it with parentheses.

END EDIT

The documentation for the Yasnippet Template Syntax can be found here.

Then we can easily modify the snippet of in your example to achieve what you want as follows

# -*- mode: snippet -*-
# name: =
# key: =
# --
= `(calc-eval
(buffer-substring-no-properties
(line-beginning-position)
(- (point) 2)))`$0

Note that you must add a space before = to make it get recognized as a (trigger) 'key'. Also, this example assumes that the line contains only the expression. If you would like to use the expansion on a line with additional text, then you should extend the logic in this snippet.

1
  • 1
    It works, thanks!
    – AhLeung
    Jan 17, 2023 at 18:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.