Automatically quit vim if NERDTree is last and only buffer

VimNerdtree

Vim Problem Overview


I have the following in my .vimrc:

""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Open NERDTree by default
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
autocmd VimEnter * NERDTree
autocmd VimEnter * wincmd p

So,

% vim file.txt

opens NERDTree and focuses the cursor in the file.txt buffer. I make my edits, and hit :q on the buffer, and I'm left with . . . NERDTree. This is annoying.

I could use :qa to close all buffers, and exit vim, but I'm used to the :q trope. So I'm wondering if there's a way to detect that the only remaining buffer is NERDTree, and "unify" the two buffers, for purposes of :q

Edit

Ask and ye shall receive: https://github.com/scrooloose/nerdtree/issues#issue/21

Vim Solutions


Solution 1 - Vim

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

Solution 2 - Vim

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.

Solution 3 - Vim

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!).

Solution 4 - Vim

You could :cabbrv q qa but I'd advise against that because you'll forget about it when you actually want q.

Solution 5 - Vim

I like to do this: cmap bq :bufdo q<CR> to close all buffers with two keystrokes in command mode.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser67416View Question on Stackoverflow
Solution 1 - VimAndrewView Answer on Stackoverflow
Solution 2 - VimblueyedView Answer on Stackoverflow
Solution 3 - VimMichał MarczykView Answer on Stackoverflow
Solution 4 - VimRandy MorrisView Answer on Stackoverflow
Solution 5 - VimPierre-Antoine LaFayetteView Answer on Stackoverflow