Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically quit vim if NERDTree is last and only buffer

Tags:

vim

nerdtree

People also ask

How do I quit NERDTree?

If you want to close NERDTree window make sure you are inside the NERDTree menu. You can switch windows by using ctrl+w then type :q to close NERDTree window so that you will be left with the window for editing your code.

Is NERDTree a buffer?

This is a NERDTree plugin that highlights all visible nodes that are open in Vim. It also maps a key w to close (wipeout) the buffer associated with the current node.


A script to do exactly this has been posted on the NERDTree issue list. Checkout issue-21 on GitHub for nerdtree.

This leads to the single line command for your vimrc here:

autocmd bufenter * if (winnr("$") == 1 && exists("b:NERDTree") && b:NERDTree.isTabTree()) | q | endif

function! s:CloseIfOnlyControlWinLeft()
  if winnr("$") != 1
    return
  endif
  if (exists("t:NERDTreeBufName") && bufwinnr(t:NERDTreeBufName) != -1)
        \ || &buftype == 'quickfix'
    q
  endif
endfunction
augroup CloseIfOnlyControlWinLeft
  au!
  au BufEnter * call s:CloseIfOnlyControlWinLeft()
augroup END

From my vimrc, based on a version from janus repo.

Enhancements: also close if only a quickfix window is left. It uses the BufEnter autocommand instead, which is required for &bt to work properly.


An idea in need of implementation:

You could write a function which, when called, checks if the only buffer remaining (or perhaps the only non-help buffer, if you prefer) is a NERDTree buffer and, if so, deletes it (or just quits).

Then have an autocmd run it whenever a buffer is deleted / hidden / whatever actually happens when you :q (it shames me to admit I'm not entirely sure!).