Discussion  - 
Question about Emacs calc:

Is there a simple way to replace a simple expression in a buffer with a calculated result, without a lot of hassle of copying back and forth between a calc window?  For example, if I put the cursor on "72 * 11 + 8" in a buffer, I'd like to have it replaced with "800".

I looked in the manual and found "quick calculator mode", C-x * q, but that prompts you for an expression and simply displays the result in the modeline. I found "embedded mode", and I can make that do what I want, but it's kind of awkward. I have to highlight the expression, then
    C-0 C-x * e C-x * e
(You have to repeat the C-x * e to exit embedded mode).

I may wind up wrapping that sequence in a function and binding it to a keystroke, but does anyone know of a simpler way? 
Andrew Hyatt's profile photoEric Roode's profile photoDarlan Cavalcante Moreira's profile photoJay Belanger's profile photo
You can select the region you want to evaluate and do C-u C-x * e C-u y.  Does that work for you?:
No. When I select the region and do C-u C-x * e, the result of the calculation replaces the formula in the current buffer. But it also switches the buffer's mode to CalcEmbed. The C-u y is unnecessary, but I still have to do C-x * e to get back to the buffer's usual mode.
Hmmm. That's a little better, especially since C-u y quits out of the Calc buffer it pops up.
If you need this multiple times, you can also add "C-x (" at the begining and "C-x )" to save this as a keyboard macro. Then you can execute the macro with "C-x e".

But if you also want to save it for the future, assign a name for the macro with "M-x name-last-kbd-macro". Emacs will ask for a name for the macro, for instance, "calc-replace-region". After that, you can ask emacs for the code defining the macro with "M-x insert-kbd-macro".
Emacs will insert in the current buffer something like this
        (fset 'calc-replace-region

Put this in your emacs initialization and you will always have this macro available. You can even set a keybinding for this macro with global-set-key or local-set-key.
If you just want to replace the expression and nothing else, you might use calc-eval instead of calc-embedded.  For example:

(defun replace-math-expression (beg end)
  (interactive "r")
  (require 'calc)
  (let ((result
              (buffer-substring beg end))))
    (kill-region beg end)
    (insert result)))

Or, instead of choosing the region yourself, have Emacs find the expression:

(defun replace-current-expression ()
  (require 'thingatpt)
  (let ((expr-regexp
             " ?\\([ 0-9\\.\\*\\+-/\\]+\\) ?"))
    (if (thing-at-point-looking-at
                             (match-beginning 1)
                             (match-end 1))
      (message "No formula at point"))))

(I'm sure the regular expression can be improved, to deal with trailing spaces at least...)
Add a comment...