patch 9.0.0965: using one window for executing autocommands is insufficient

Problem:    Using one window for executing autocommands is insufficient.
Solution:   Use up to five windows for executing autocommands.
diff --git a/src/buffer.c b/src/buffer.c
index f99da25..eba5dd2 100644
--- a/src/buffer.c
+++ b/src/buffer.c
@@ -150,11 +150,15 @@
     {
 	aco_save_T	aco;
 
+	// Make sure the buffer is in a window.  If not then skip it.
 	aucmd_prepbuf(&aco, buf);
-	if (swap_exists_action != SEA_READONLY)
-	    swap_exists_action = SEA_NONE;
-	open_buffer(FALSE, NULL, 0);
-	aucmd_restbuf(&aco);
+	if (curbuf == buf)
+	{
+	    if (swap_exists_action != SEA_READONLY)
+		swap_exists_action = SEA_NONE;
+	    open_buffer(FALSE, NULL, 0);
+	    aucmd_restbuf(&aco);
+	}
     }
 }
 #endif
@@ -361,21 +365,26 @@
 	{
 	    aco_save_T	aco;
 
-	    // Go to the buffer that was opened.
+	    // Go to the buffer that was opened, make sure it is in a window.
+	    // If not then skip it.
 	    aucmd_prepbuf(&aco, old_curbuf.br_buf);
-	    do_modelines(0);
-	    curbuf->b_flags &= ~(BF_CHECK_RO | BF_NEVERLOADED);
+	    if (curbuf == old_curbuf.br_buf)
+	    {
+		do_modelines(0);
+		curbuf->b_flags &= ~(BF_CHECK_RO | BF_NEVERLOADED);
 
-	    if ((flags & READ_NOWINENTER) == 0)
+		if ((flags & READ_NOWINENTER) == 0)
 #ifdef FEAT_EVAL
-		apply_autocmds_retval(EVENT_BUFWINENTER, NULL, NULL, FALSE,
-							      curbuf, &retval);
+		    apply_autocmds_retval(EVENT_BUFWINENTER, NULL, NULL,
+						       FALSE, curbuf, &retval);
 #else
-		apply_autocmds(EVENT_BUFWINENTER, NULL, NULL, FALSE, curbuf);
+		    apply_autocmds(EVENT_BUFWINENTER, NULL, NULL,
+								FALSE, curbuf);
 #endif
 
-	    // restore curwin/curbuf and a few other things
-	    aucmd_restbuf(&aco);
+		// restore curwin/curbuf and a few other things
+		aucmd_restbuf(&aco);
+	    }
 	}
     }
 
@@ -5942,8 +5951,14 @@
 	return TRUE;
     }
 
-    // set curwin/curbuf to buf and save a few things
+    // Set curwin/curbuf to buf and save a few things.
     aucmd_prepbuf(&aco, newbuf);
+    if (curbuf != newbuf)
+    {
+	// Failed to find a window for "newbuf".
+	wipe_buffer(newbuf, FALSE);
+	return TRUE;
+    }
 
     if (ml_open(curbuf) == OK
 	    && readfile(buf->b_ffname, buf->b_fname,