Windows 10, Emacs 25.1
I want to do some arithmetic operation I do this:
The result is in the echo area, but I want the result to be in cursor place in the buffer. Something like this:
How do I do this?
Windows 10, Emacs 25.1
I want to do some arithmetic operation I do this:
The result is in the echo area, but I want the result to be in cursor place in the buffer. Something like this:
How do I do this?
Instead of C-x C-e
to evaluate the expression, give it a prefix
argument. C-u C-x C-e
will print the output to the buffer.
You can investigate how Emacs does these things by looking in the manual, or asking Emacs itself.
To see what a particular keybinding does, you can use C-h k
(describe-key
). You were evaluating the expression with C-x
C-e
, and you can figure out what that keybinding calls with C-h
k C-x C-e
. That will display the command's docstring, the first
part of which is:
C-x C-e
runs the commandeval-last-sexp
(found in global-map), which is an interactive compiled Lisp function inelisp-mode.el
.It is bound to
C-x C-e
.
(eval-last-sexp EVAL-LAST-SEXP-ARG-INTERNAL)
Evaluate sexp before point; print value in the echo area. Interactively, with a non
-
prefix argument, print output into current buffer....
I highlighted the key phrase: giving it a prefix argument (C-u
)
will print the output to the buffer, rather than the echo area.
Bind this to some key.
(defun foo ()
"Replace sexp before point by result of its evaluation."
(interactive)
(let ((result (pp-to-string (eval (pp-last-sexp) lexical-binding))))
(delete-region (save-excursion (backward-sexp) (point)) (point))
(insert result)))
If you want to do an arithmetic operation and insert the value into the buffer, but don't care where you do the operation, then you can also do C-u M-:
and type the operation info the minibuffer.
This blog has
(defun eval-and-replace (value)
"Evaluate the sexp at point and replace it with its value"
(interactive (list (eval-last-sexp nil)))
(kill-sexp -1)
(insert (format "%S" value)))
I prefer to do (also complex) computations in Emacs' calc C-x * *
and then copy its result in the buffer where my cursor was with y
, q
closes the calc buffers and I'm back at this location.
I had the same wish and hadn't used Emacs in a long while and forgot how to do it :) Very simple and touched on by some above answers with the prefix command C-u
Simply C-u M-:
(Eval buffer appears for your function) such as
Eval: (- 5 2)
and the result of 3
will appear in your buffer cursor location
This is very handy for kbd-macros where you need to manipulate some arithmetic and replace values