patch 9.1.0001: when closing window, wincmd p may fail

Avoid `prevwin == curwin` when closing `curwin`

Problem:  When closing the current window (or when moving it to a tabpage), the
          previous window may refer to the new current window
          (`winnr() == winnr('#')`) if that window is selected as the
          new current window.

Solution: Set `prevwin = NULL` when switching away from an invalid `curwin` and
          the target window was the `prevwin`.
          (Sean Dewar)

related: #4537
closes: #13762

Signed-off-by: Sean Dewar <seandewar@users.noreply.github.com>
Signed-off-by: Christian Brabandt <cb@256bit.org>
diff --git a/src/window.c b/src/window.c
index 9f80657..54e17be 100644
--- a/src/window.c
+++ b/src/window.c
@@ -5381,11 +5381,15 @@
     // may have to copy the buffer options when 'cpo' contains 'S'
     if (wp->w_buffer != curbuf)
 	buf_copy_options(wp->w_buffer, BCO_ENTER | BCO_NOHELP);
+
     if (curwin_invalid == 0)
     {
 	prevwin = curwin;	// remember for CTRL-W p
 	curwin->w_redr_status = TRUE;
     }
+    else if (wp == prevwin)
+	prevwin = NULL;		// don't want it to be the new curwin
+
     curwin = wp;
     curbuf = wp->w_buffer;
     check_cursor();