5

When I want to do something in another buffer and then restore the original, I currently do this:

(let ((this-buffer (current-buffer)))
  (switch-to-buffer (other-buffer))
  (insert "I was here!")
  (switch-to-buffer this-buffer))

Is there a less verbose way to this, something like:

(save-buffer-and-switch (other-buffer)
  (insert "I was here!"))
  • 1
    switch-to-buffer is just plain wrong here: it changes which buffer is displayed in the currently selected window, whereas you just want to change the currently selected buffer. IOW instead of switch-to-buffer you would want set-buffer. See C-h f switch-to-buffer RET. – Stefan Oct 21 '15 at 21:56
7

You want with-current-buffer:

(with-current-buffer (other-buffer)
  (insert "I was here!"))

There is also save-current-buffer, which is a simpler mechanism used to implement the with-current-buffer macro:

(save-current-buffer
  (set-buffer (other-buffer))
  (insert "I was here!"))

The combination of save-current-buffer and set-buffer mostly seems to show up in older code. Most of the time, with-current-buffer is clearer, IMO.

  • Wow, I even searched for with-buffer in helm-apropos, but missed it (HA lists all commands before functions, so it was far down in the list). – 24HrRevengeTherapist Oct 21 '15 at 19:20
  • 1
    @24HrRevengeTherapist You can use C-o to switch sources in helm. You can also use C-h v look up function/macro's docstring, don't forget to turn on helm-mode since it provides a very handy persistent-action. – xuchunyang Oct 21 '15 at 19:44
  • @xuchunyang Did you mean C-h f (describe-function)? C-h v is bound to describe-variable in my Emacs. But maybe this is different under Helm, I don't know. – Jon O. Oct 21 '15 at 20:02
  • @JonO. Yes, it's a typo, I meant C-h f. – xuchunyang Oct 21 '15 at 20:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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