@@ -1665,7 +1665,8 @@ set_curbuf(buf_T *buf, int action)
16651665#ifdef FEAT_SYN_HL
16661666 long old_tw = curbuf -> b_p_tw ;
16671667#endif
1668- bufref_T bufref ;
1668+ bufref_T newbufref ;
1669+ bufref_T prevbufref ;
16691670
16701671 setpcmark ();
16711672 if (!cmdmod .keepalt )
@@ -1675,18 +1676,22 @@ set_curbuf(buf_T *buf, int action)
16751676 /* Don't restart Select mode after switching to another buffer. */
16761677 VIsual_reselect = FALSE;
16771678
1678- /* close_windows() or apply_autocmds() may change curbuf */
1679+ /* close_windows() or apply_autocmds() may change curbuf and wipe out "buf"
1680+ */
16791681 prevbuf = curbuf ;
1680- set_bufref (& bufref , prevbuf );
1682+ set_bufref (& prevbufref , prevbuf );
1683+ set_bufref (& newbufref , buf );
16811684
16821685#ifdef FEAT_AUTOCMD
1686+ /* Autocommands may delete the curren buffer and/or the buffer we wan to go
1687+ * to. In those cases don't close the buffer. */
16831688 if (!apply_autocmds (EVENT_BUFLEAVE , NULL , NULL , FALSE, curbuf )
1689+ || (bufref_valid (& prevbufref )
1690+ && bufref_valid (& newbufref )
16841691# ifdef FEAT_EVAL
1685- || (bufref_valid (& bufref ) && !aborting ())
1686- # else
1687- || bufref_valid (& bufref )
1692+ && !aborting ()
16881693# endif
1689- )
1694+ ) )
16901695#endif
16911696 {
16921697#ifdef FEAT_SYN_HL
@@ -1696,9 +1701,9 @@ set_curbuf(buf_T *buf, int action)
16961701 if (unload )
16971702 close_windows (prevbuf , FALSE);
16981703#if defined(FEAT_AUTOCMD ) && defined(FEAT_EVAL )
1699- if (bufref_valid (& bufref ) && !aborting ())
1704+ if (bufref_valid (& prevbufref ) && !aborting ())
17001705#else
1701- if (bufref_valid (& bufref ))
1706+ if (bufref_valid (& prevbufref ))
17021707#endif
17031708 {
17041709 win_T * previouswin = curwin ;
0 commit comments