I often swap 2 most latest buffers back and forth with (switch-to-buffer (other-buffer)). This works just fine in most situations.

However, when I have 2 split windows, and the other window is opening a file I would switch to using the above command, other-buffer skips that buffer and it returns the 3rd-latest buffer instead. This is quite annoying.

Is there any way to swap 2 most latest buffers regardless of what other windows are opening?

1 Answer 1


other-buffer takes an optional third argument that says it's okay to use buffers visible in other windows. The relevant bit of the docstring:

(other-buffer &optional BUFFER VISIBLE-OK FRAME)

Return most recently selected buffer other than BUFFER. Buffers not visible in windows are preferred to visible buffers, unless optional second argument VISIBLE-OK is non-nil. Ignore the argument BUFFER unless it denotes a live buffer. If the optional third argument FRAME specifies a live frame, then use that frame’s buffer list instead of the selected frame’s buffer list.

So: the following code should do what you want:

(switch-to-buffer (other-buffer (current-buffer) t))

That's a lot to type, however, so you may as well wrap it in a command that you can bind to your key of choice:

(defun switcheroo ()
  "Switch to the most recent other buffer, even if it's visible
in another window."
  (switch-to-buffer (other-buffer (current-buffer) t)))
  • I'd suggest using nil as first argument.
    – YoungFrog
    Jul 18, 2017 at 15:07
  • 1
    @YoungFrog: I tested it lightly with nil as the second argument, and it didn't seem to behave as what I think OP wanted. It was only a light test, though, so I could be wrong about that.
    – Dan
    Jul 18, 2017 at 15:09
  • You're absolutely right, (other-buffer nil t) seems to return the currently selected buffer! Sorry for the noise.
    – YoungFrog
    Jul 18, 2017 at 15:17
  • @YoungFrog: no worries!
    – Dan
    Jul 18, 2017 at 15:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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