Nerdtree: Is it possible to have it so that when nerd tree is activated and is shown on the side, activating it again will not hide it but bring focus to it?

Created on 23 Jul 2016  路  4Comments  路  Source: preservim/nerdtree

I am not really sure what this happens but it is really annoying. For example I activate nerdtree by control l map <C-l> :NERDTreeToggle<CR> mapped by this vimrc setting.

It shows up as normal and on the side and I can navigate through it with hjkl keys, I then press enter and the focus is on the file while the sidebar is still open which is good. However if I was to press my control + l mapping again, it won't bring focus to NerdTree sidebar but close it. Is it possible to fix this behaviour somehow?

Thank you for any help on this.

Most helpful comment

You can use an expression in your mapping. I'll show you my mapping as an example. I use the BufExplorer plugin also, and I don't want them both open at the same time, so I wrote the following mapping:

nnoremap <silent><expr> <leader>n bufname(winbufnr(0))=='[BufExplorer]' ? ":ToggleBufExplorer\<CR>:NERDTreeFocus\<CR>" : (winnr()==g:NERDTree.GetWinNum() ? ":NERDTreeClose\<CR>" : ":NERDTreeFocus\<CR>")

It works like so:

  • IF current window is BufExplorer,

    • ToggleBufExplorer (to close it)

    • NERDTreeFocus

  • ELSE IF current window is NERDTree

    • NERDTreeClose

  • ELSE

    • NERDTreeFocus

You could simplify this, removing the first IF block, to open or return to NERDTree if you're not in it, and close it if you are in NERDTree. (I think that's what you're asking for.)

nnoremap <silent><expr> <C-L> winnr()==g:NERDTree.GetWinNum() ? ":NERDTreeClose\<CR>" : ":NERDTreeFocus\<CR>"

All 4 comments

@nikitavoloboev, use the NERDTreeFocus command instead.

Thank you, this works. However is it possible to have it be hidden on a subsequent hotkey press? In my case it would be control+l.

You can use an expression in your mapping. I'll show you my mapping as an example. I use the BufExplorer plugin also, and I don't want them both open at the same time, so I wrote the following mapping:

nnoremap <silent><expr> <leader>n bufname(winbufnr(0))=='[BufExplorer]' ? ":ToggleBufExplorer\<CR>:NERDTreeFocus\<CR>" : (winnr()==g:NERDTree.GetWinNum() ? ":NERDTreeClose\<CR>" : ":NERDTreeFocus\<CR>")

It works like so:

  • IF current window is BufExplorer,

    • ToggleBufExplorer (to close it)

    • NERDTreeFocus

  • ELSE IF current window is NERDTree

    • NERDTreeClose

  • ELSE

    • NERDTreeFocus

You could simplify this, removing the first IF block, to open or return to NERDTree if you're not in it, and close it if you are in NERDTree. (I think that's what you're asking for.)

nnoremap <silent><expr> <C-L> winnr()==g:NERDTree.GetWinNum() ? ":NERDTreeClose\<CR>" : ":NERDTreeFocus\<CR>"

Thank you, that works perfectly.

Was this page helpful?
0 / 5 - 0 ratings