Here is the solution I chose:
function! IsSideBar(buf_nr)
" Return 1 if the buffer correspond to a side bar:
" - A terminal window
" - The quickfix window
" - The help
" - The NERDTree side bar
" - ...
let buf_name = bufname(a:buf_nr)
let buf_type = getbufvar(a:buf_nr, '&filetype')
let readonly = getbufvar(a:buf_nr, '&readonly')
let term_buffers = term_list()
if buf_type ==# 'qf'
" QuickFix, LocationList:
return 1
elseif buf_type ==# 'help'
" Help Window:
return 1
elseif buf_type ==# 'undotree'
return 1
elseif buf_type ==# 'tagbar'
return 1
elseif buf_type ==# 'nerdtree'
return 1
elseif index(term_buffers, a:buf_nr) >= 0
" echom 'Console'
return 1
else
return 0
endif
endfunction
function! LeaveSideBar()
" Go to a non side bar window
let loop = 0
while 1
let loop = loop + 1
let bufnr = bufnr('%')
if loop > 10
" Don't search for more than 10 windows
" To handle the case all the windows are 'side bars'
break
endif
if IsSideBar(bufnr)
wincmd w
else
break
endif
endwhile
endfunction
command! LeaveSideBar call LeaveSideBar()
function! NERDTreeExplore(...)
if a:0 == 0
NERDTree %:p:h
else
if isdirectory(a:1)
execute printf("NERDTree %s", a:1)
else
call LeaveSideBar()
execute printf("e %s", a:1)
endif
endif
endfunction
command! -nargs=* -complete=file E call NERDTreeExplore(<f-args>)
I have created a LeaveSideBar
command that moves the cursor outside of the side bars (NERDTree but also UndoTree, TagBar, QuickFix, Terminal, ...) and I have replaced the method that open buffer (:e
, :bn
) by custom variant (:E
, :Bn
) that call LeaveSideBar
first.
autocmd BufUnload nerdtree <your commands here>
, maybe. There are a lot of posts that deal with nerdtree specific buffers...maybe not this question exactly but similar enough to reveal some useful information.:bnext
...:nnoremap <silent> <leader>n :if &filetype != 'nerdtree' <bar> :bnext <bar> endif<cr>
and similar for:bprev
. (I use such mappings forbnext
/bprev
even without having a requirement like yours...it's quicker!)