Subject: bug#71616: switch-to-buffer behaves inconsistently when switch-to-buffer-obey-display-actions is t and nil .

From: martin rudalics <[email-masked]>
Date: Wed, 19 Jun 2024 11:37:32 +0200

>> ## Test with switch-to-buffer-obey-display-actions = t
 >> 1. Emacs -Q
 >> 2. M-x eval-expression (setq switch-to-buffer-obey-display-actions t)
 >> 2. Open a .el file, e.g. window.el, and keep the cursor location at 1
 >> 3. Click buffers menu -> *scratch* to switch buffer
 >> 4. Click buffers menu -> window.el to switch buffer back
 >> 5. Move the current location to L24
 >> 6. M-x switch-to-buffer window.el
 >> The result is that the current cursor location jumps to location at 1!
 >> This inconsistent behavior convinced me that this is a bug.
 >
 > I confirm this in Emacs 30.  Maybe Martin could suggest how to fix
 >> this.

A recipe without involving a file is

1. M-: (setq switch-to-buffer-obey-display-actions t)
2. C-x b *Messages*
3. C-x b *scratch*
4. Move point
5. C-x b *scratch*

In step 2 we record the point of *scratch*.  In 5 we go there because
the 'set-window-buffer' called by C-x b decides that the window already
shows buffer and does not record its current position.  I attach a patch
that should fix this and the original scenario.  It does _not_ fix the
case where instead of C-x b plain 'set-window-buffer' is used.  If we
wanted to fix that, we'd have to call 'record-window-buffer' from there
even when the old and the new buffer are the same.  I'm not sure whether
we want to do that.

martin

diff --git a/lisp/window.el b/lisp/window.el
index 604b9868921..2ff4928c11e 100644
--- a/lisp/window.el
+++ b/lisp/window.el
@@ -9171,9 +9243,14 @@ switch-to-buffer
         (pop-to-buffer buffer norecord)))
      (t
       (when switch-to-buffer-obey-display-actions
-        (let ((selected-window (selected-window)))
+        (let* ((selected-window (selected-window))
+	       (old-window-buffer (window-buffer selected-window)))
           (pop-to-buffer-same-window buffer norecord)
-          (when (eq (selected-window) selected-window)
+	  ;; Do not ask for setting start and point when showing the
+	  ;; same buffer in the old selected window (Bug#71616).
+          (when (and (eq (selected-window) selected-window)
+		     (not (eq (window-buffer selected-window)
+			      old-window-buffer)))
             (setq set-window-start-and-point t))))
 
       (when set-window-start-and-point