總算可以簡單偵測分頁關閉,發生順序是 TabLeaveTabClosedTabEnter,在 TabClosed 的時候就能取得新的 tabpagenr('$') 了。

簡化 Vim 切換至最後選取的 tab 功能:

if exists('##TabClosed')
  function! LastTab(act)
    let lt = g:lasttab

    if a:act ==# 'TabLeave'
      let lt.prevLeave = lt.leave
      let lt.leave = tabpagenr()
    elseif a:act ==# 'TabClosed'
      let lt.leave = lt.prevLeave
    elseif a:act ==# 'switch'
      let to = lt.leave
      if to == tabpagenr()
        echo 'Already on last tab.'
      else
        execute "tabnext " . lt.leave
      endif
    endif
  endfunction

  if !exists('g:lasttab')
    let g:lasttab = {'leave':1, 'prevLeave':1}
  endif

  autocmd TabLeave * call LastTab('TabLeave')
  autocmd TabClosed * call LastTab('TabClosed')

  nnoremap <silent> <LocalLeader>t :call LastTab('switch')<CR>
  inoremap <silent> <LocalLeader>t <C-\><C-N>:call LastTab('switch')<CR>
endif