2

For example, imagine I have two windows and three buffers. Both windows are displaying buffer 1 and I do the following,

  1. in window 1, switch to buffer 2;
  2. in window 2, switch to buffer 3, then to buffer 2.

Now both widows are displaying buffer 2. This command, invoked in window 1 would switch to buffer 1 and invoked in window 2 would switch to buffer 3. Invoked again it would bring back the selected window to buffer 2, that is, it should just cycle between the last two buffers displayed in the selected window, not transverse the window's buffer history.

1
  • +1. But I have a feeling this is a FAQ. If not here, elsewhere at least. You might try searching here to see if it's a dup...
    – Drew
    Commented Feb 12, 2021 at 21:13

2 Answers 2

1

I took a look at the implementation of switch-to-prev-buffer (thanks Tobias! I didn't think to look there…), found the function window-prev-buffers and came up with this:

(defun previous-buffer-cycle ()
  "Switch to the buffer previously displayed in the current
window."
  (interactive)
  (pop-to-buffer-same-window (caar (window-prev-buffers))))

I bound it to C-c c and I'll see if it's worthy of that key.


Update: The function above does nothing when the buffer it ought to move to is dead. For example, you're in buffer 1, you type C-c c (if you've bound it to that key) to go to buffer 2 and then you kill it. Now you're back to buffer 1, you hit C-c c and nothing happens because previous-buffer-cycle should switch to buffer 2 but that's not alive anymore. When that happens, the following version switches to the last live buffer that was displayed in the current window.

(defun previous-buffer-cycle ()
  "Switch to the last live buffer that was displayed in the
current window."
  (interactive)
  (pop-to-buffer-same-window
   (caar (assq-delete-all (current-buffer) (window-prev-buffers)))))
0

Doc-string of the command previous-buffer:

In selected window switch to ARGth previous buffer. Call switch-to-prev-buffer unless the selected window is the minibuffer window or is dedicated to its buffer.

It is bound to C-x C-left.

There is also the command mode-line-previous-buffer which does the same as previous-buffer but first selects the window from which the mouse event originates.

This command is bound to mouse-1 clicks on the buffer name in the mode line.

There are analogous commands for the next buffer bound to C-x C-right and mouse-3, respectively.

1
  • Thanks but I meant to cycle between the last two buffer, not to transverse the history. (My fault, it wasn't clear. I've edited the question now.) Commented Feb 13, 2021 at 9:35

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.