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()
3I find this very usefull, and i went to my .vimrc. I wanted to use some other binding to make it easier to me to remember. And i found out that there is already a binding for this with NERDTree
<Leader>f
– benzen – 2015-02-18T18:16:44.1871Awesome! Example what I was looking for. – mawaldne – 2015-04-28T02:32:12.213
Can you elaborate on this? – jterm – 2017-08-14T17:50:16.380
If you are using this amazing vimrc (not mine), it is mapped to ,nf: https://github.com/amix/vimrc
– alpha_989 – 2017-11-21T15:34:20.013What key is
<leader>
? – stillanoob – 2018-07-28T07:15:31.803@stillanoob,
<leader>
defaults to backslash\
but @alpha_989 and many of us remap it to comma,
which one can do withlet mapleader = ','
in the .vimrc – krry – 2019-02-27T19:49:47.977