Subject: bug#54028: Window is not a valid window

From: martin rudalics <[email-masked]>
Date: Thu, 17 Feb 2022 11:06:13 +0100

> I don't know if the author of
 > https://www.reddit.com/r/emacs/comments/sthusa/window_xxx_is_not_a_valid_window_on_switching_tabs/
 > will report the bug here,

Please encourage the author again to report such bugs here.

 > but since it's easily reproducible,
 > here is the short test case, just evaluate this:
 >
 > (window-state-put
 > ...
 >   nil 'safe)
 >
 > It fails with:
 >
 >    Debugger entered--Lisp error: (error "#<window 9> is not a valid window")
 >      error("%s is not a valid window" #<window 9>)
 >      window-normalize-window(#<window 9>)
 >      window-deletable-p(#<window 9>)
 >      window-state-put

I think the attached fixes it, please check.  I have no idea whether the
state is restored as intended, though.

Thanks, martin

diff --git a/lisp/window.el b/lisp/window.el
index 582600e1c6..38b58712b4 100644
--- a/lisp/window.el
+++ b/lisp/window.el
@@ -6394,7 +6394,8 @@ window-state-put
 	(window--state-put-2 ignore pixelwise))
       (while window-state-put-stale-windows
 	(let ((window (pop window-state-put-stale-windows)))
-	  (when (eq (window-deletable-p window) t)
+	  (when (and (window-valid-p window)
+                     (eq (window-deletable-p window) t))
 	    (delete-window window))))
       (window--check frame))))