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.
(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
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)