diff --git a/src/nvim/window.c b/src/nvim/window.c index d0531e6589..c1b137890a 100644 --- a/src/nvim/window.c +++ b/src/nvim/window.c @@ -2684,6 +2684,7 @@ static bool close_last_window_tabpage(win_T *win, bool free_buf, tabpage_T *prev } buf_T *old_curbuf = curbuf; + tabpage_T *save_lastused = lastused_tabpage; Terminal *term = win->w_buffer ? win->w_buffer->terminal : NULL; if (term) { @@ -2706,6 +2707,12 @@ static bool close_last_window_tabpage(win_T *win, bool free_buf, tabpage_T *prev if (curtab != prev_curtab && valid_tabpage(prev_curtab) && prev_curtab->tp_firstwin == win) { win_close_othertab(win, free_buf, prev_curtab, false); } + + // Entering the other tab page made the closed one the last used tab page. + // Restore the previous one when it is still there. + if (valid_tabpage(save_lastused) && save_lastused != curtab) { + lastused_tabpage = save_lastused; + } entering_window(curwin); // Since goto_tabpage_tp above did not trigger *Enter autocommands, do diff --git a/test/old/testdir/test_tabpage.vim b/test/old/testdir/test_tabpage.vim index 89da59fe46..3465bc7a35 100644 --- a/test/old/testdir/test_tabpage.vim +++ b/test/old/testdir/test_tabpage.vim @@ -945,6 +945,23 @@ func Test_lastused_tabpage() tabonly! endfunc +" Closing a tab page must keep the last used tab page when it is another one. +func Test_lastused_tabpage_close() + tabonly! + tabnew + tabnew + tabfirst + tablast + call assert_equal(1, tabpagenr('#')) + + tabclose + call assert_equal(1, tabpagenr('#')) + call feedkeys("g\", "xt") + call assert_equal(1, tabpagenr()) + + tabonly! +endfunc + " Test for tabpage allocation failure func Test_tabpage_alloc_failure() CheckFunction test_alloc_fail