Question

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

Was it helpful?

Solution

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

OTHER TIPS

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

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

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

@MrD's answer works well for me, I'm using vim 8.1 from brew on macOS.

autocmd bufenter * if (winnr("$") == 1 && exists("b:NERDTreeType") && b:NERDTreeType == "primary") | q | endif 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top