Vim: How to synchronize NERDTree with current opened tab file path?
I use the following mapping to view the current buffer in NERDTree:
map <leader>r :NERDTreeFind<cr>
throw a % sign on the end like a boss
:NERDTree %
i have this in my .vimrc, it maps Ctrl+o to toggle nerdtree in the dir of the current buffer:
map <C-o> :NERDTreeToggle %<CR>
I found both the existing answers educational, and successfully combined the two so that the behavior is more like many people would expect from an IDE: Click on an open window/buffer, and have that file highlighted in the NERDTree. I put this in my ~/.vimrc:
autocmd BufEnter * if &modifiable | NERDTreeFind | wincmd p | endif
What this does:
autocmd BufEnter
- runs every time you focus on a buffer (including the NERDTree window)if &modifiable
- when you do click the NERDTree window, do nothing else (the NERDTree window is not modifiable)wincmd p
- NERDTreeFind leaves the cursor focused on the NERDTree; this switches back to the window you'd originally focused on
Note that this won't work on any other buffer that isn't modifiable -- but that's generally a good thing; otherwise (for example) any time you got :help
in vim, NERDTree would find and focus the directory where help files are stored--probably not something you want it to do.
That one-line solution worked great for me at first, but I soon found that it causes NERDTree to activate any time I opened a file--and as a result, it prevents NERDTree from ever being closed! If you don't want to use NERDTree full-time, put this in your .vimrc instead:
" returns true iff is NERDTree open/active
function! rc:isNTOpen()
return exists("t:NERDTreeBufName") && (bufwinnr(t:NERDTreeBufName) != -1)
endfunction
" calls NERDTreeFind iff NERDTree is active, current window contains a modifiable file, and we're not in vimdiff
function! rc:syncTree()
if &modifiable && rc:isNTOpen() && strlen(expand('%')) > 0 && !&diff
NERDTreeFind
wincmd p
endif
endfunction
autocmd BufEnter * call rc:syncTree()