Subject: Re: bug#32790: 27.0.50; point jumps unexpectedly after delete-window

From: Juri Linkov <[email-masked]>
Date: Sun, 25 Nov 2018 01:40:29 +0200

> Would we avoid that 'switch-to-buffer-pop-to' affects C-x b?

'C-x b' is one of main beneficiaries of this feature.

> Anyway, if you know what you want, please write the code.
> We can iron out any differences in the doc-strings, if needed.

Do you see a problem with this implementation?

diff --git a/lisp/window.el b/lisp/window.el
index 43a742b2d8..b76729e752 100644
--- a/lisp/window.el
+++ b/lisp/window.el
@@ -7779,6 +7787,13 @@ switch-to-buffer-in-dedicated-window
   :group 'windows
   :version "25.1")
 
+(defcustom switch-to-buffer-pop-to nil
+  "If non-nil, use `pop-to-buffer-same-window' in the selected window.
+This allows custmization of conditional actions for `display-buffer'."
+  :type 'boolean
+  :group 'windows
+  :version "27.1")
+
 (defun switch-to-buffer (buffer-or-name &optional norecord force-same-window)
   "Display buffer BUFFER-OR-NAME in the selected window.
 
@@ -7838,11 +7853,13 @@ switch-to-buffer
               (`pop nil)
               (_ (set-window-dedicated-p nil nil) 'force-same-window))))))
      (list (read-buffer-to-switch "Switch to buffer: ") nil force-same-window)))
-  (let ((buffer (window-normalize-buffer-to-switch-to buffer-or-name)))
+  (let ((buffer (window-normalize-buffer-to-switch-to buffer-or-name))
+        (set-window-data-p t))
     (cond
      ;; Don't call set-window-buffer if it's not needed since it
      ;; might signal an error (e.g. if the window is dedicated).
-     ((eq buffer (window-buffer)))
+     ((and (eq buffer (window-buffer))
+           (not switch-to-buffer-pop-to)))
      ((window-minibuffer-p)
       (if force-same-window
           (user-error "Cannot switch buffers in minibuffer window")
@@ -7852,6 +7869,13 @@ switch-to-buffer
           (user-error "Cannot switch buffers in a dedicated window")
         (pop-to-buffer buffer norecord)))
      (t
+      (when switch-to-buffer-pop-to
+        (let ((selected-window (selected-window)))
+          (pop-to-buffer-same-window buffer norecord)
+          (unless (eq (selected-window) selected-window)
+            (setq set-window-data-p nil))))
+
+      (when set-window-data-p
         (let* ((entry (assq buffer (window-prev-buffers)))
 	       (displayed (and (eq switch-to-buffer-preserve-window-point
 				   'already-displayed)
@@ -7863,7 +7887,7 @@ switch-to-buffer
 	    ;; Try to restore start and point of buffer in the selected
 	    ;; window (Bug#4041).
 	    (set-window-start (selected-window) (nth 1 entry) t)
-	  (set-window-point nil (nth 2 entry))))))
+	    (set-window-point nil (nth 2 entry)))))))
 
     (unless norecord
       (select-window (selected-window)))