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.


1 Answer 1

(defun my-switch-to-buffer (buffer)
  "Display BUFFER in the selected window.
If BUFFER is displayed in an existing window, select that window instead."
   (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)

  • 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, 2016 at 14:23
  • Sounds like very reasonable request! I will update my answer soon for this.
    – xuchunyang
    Mar 22, 2016 at 17:23
  • @xuchunyang Maybe you can use get-buffer-window to get rid of the dolist loop?
    – cutejumper
    Mar 22, 2016 at 18:30
  • @cutejumper I didn't know about it. Thanks for the reminder.
    – xuchunyang
    Mar 22, 2016 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, 2016 at 15:57

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.