Inspired by this blog I wrote a function which replaces arithmetic expressions between two $ symbols with the mathematical result inline (and deletes the $ symbols). How can I modify this such that it recognizes if the expression is invalid and prints an error message (without without modifying or replacing the expression) in this case in the minibuffer.
(require 'calc) (defun calc-eval-and-insert () "Replaces an arithmetic expression between two $ sympols with the result. Example expression: $2*(3 + round(5.5))$" (interactive) (let (result p1 p2) (skip-chars-backward "^$“") (setq p1 (point)) (skip-chars-forward "^$“") (setq p2 (point)) (setq result (calc-eval (buffer-substring-no-properties p1 p2))) (goto-char p1) (delete-char -1) (setq p1 (point)) (goto-char p2) (delete-char -1) (delete-region p1 p2) ;(insert " = " result) (insert result) ) ) (global-set-key (kbd "C-c r") 'calc-eval-and-insert)
Since I am a beginner in elisp, other suggestions of how to improve the code are also welcome.
I just noticed that executing it on
$2 + 2.2.2$ results in a "Bad Format" error (as expected). But for example
$roundd(2.2)$ (instead of
$round(2.2)$ results in no error messages but replaces the expression with