Windows 10, Emacs 25.1
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?
Emacs Stack Exchange is a question and answer site for those using, extending or developing Emacs. It only takes a minute to sign up.Sign up to join this community
C-x C-e to evaluate the expression, give it a prefix
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
describe-key). You were evaluating the expression with
C-e, and you can figure out what that keybinding calls with
k C-x C-e. That will display the command's docstring, the first
part of which is:
C-x C-eruns the command
eval-last-sexp(found in global-map), which is an interactive compiled Lisp function in
It is bound to
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 (
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
q closes the calc buffers and I'm back at this location.