4

Is there a way to make switch-to-buffer more dwim in this regard? Let's say I have two windows with foo.el and bar.el open. With my point in foo.el, if I switch-to-buffer and open bar.el, I'd like to just be taken to the other window, rather than be left with two windows of bar.el.

sooheon
  • 481
  • 2
  • 8

1 Answers1

3
(defun my-switch-to-buffer (buffer)
  "Display BUFFER in the selected window.
If BUFFER is displayed in an existing window, select that window instead."
  (interactive
   (list (get-buffer (read-buffer
                      "Switch to buffer: "
                      (other-buffer (current-buffer))))))
  (if-let ((win (get-buffer-window buffer)))
      (select-window win)
    (switch-to-buffer buffer)))

Update: while defining a new command is a clear and clean solution, advising switch-to-buffer will make switch-to-buffer and other commands which call switch-to-buffer (such as ido-switch-buffer and helm-buffers-list) have the new behavior.

(defun switch-to-buffer--hack (orig-fun &rest args)
  (if-let ((win (get-buffer-window (car args))))
      (select-window win)
    (apply orig-fun args)))

(advice-add 'switch-to-buffer :around #'switch-to-buffer--hack)

(This doesn't work with Ivy's ivy-switch-buffer for some reason)

xuchunyang
  • 14,302
  • 1
  • 18
  • 39
  • Is it possible to do this as an advice, to make it more general? What if no matter the function used to select the buffer, I could apply this logic? – sooheon Mar 22 '16 at 14:23
  • Sounds like very reasonable request! I will update my answer soon for this. – xuchunyang Mar 22 '16 at 17:23
  • @xuchunyang Maybe you can use `get-buffer-window` to get rid of the `dolist` loop? – cutejumper Mar 22 '16 at 18:30
  • @cutejumper I didn't know about it. Thanks for the reminder. – xuchunyang Mar 22 '16 at 18:41
  • 1
    Thanks for the update. `(advice-add 'ivy--switch-buffer-action :around #'switch-to-buffer--hack)` lets it also work with ivy-switch-buffer :) – sooheon Mar 23 '16 at 15:57
  • Using advice with `switch-to-buffer` seems to automatically work for `ivy-switch-buffer` now. – gsgx Sep 15 '22 at 07:15