Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One mapping to toggle NERDTree and open to current file when toggling on

Tags:

vim

nerdtree

I'm trying to find a way to have a normal mode mapping that can toggle NERDTree, but when toggling on, tell NERDTree to find the current file.

I know about NERDTreeToggle and NERDTreeFind, and what I'm looking to do is essentially a combination of those two commands.

Here's my use case:

  1. When NERDTree is not open, I can hit <C-\> and NERDTree will open to the current file.
  2. I can then hit <C-\> again and NERDTree will close.
like image 960
Josh Rieken Avatar asked Nov 01 '15 18:11

Josh Rieken


People also ask

How do you toggle NERDTree?

If you want to close NERDTree window make sure you are inside the NERDTree menu. You can switch windows by using ctrl+w then type :q to close NERDTree window so that you will be left with the window for editing your code.

How do I open a NERDTree file?

In NERDTree, press m to bring up the NERDTree Menu, and then you should see an option, labeled o , to open the current node with the system editor associated with that file or directory.

How do I switch between vim and NERDTree?

I normally switch screen in vim using ctrl+h or ctrl+l to switch between NerdTree and vim main window. Vim8 got :term command to bring up terminal which is great!


3 Answers

The first answer didn't work for me so I came up with this:

function MyNerdToggle()
    if &filetype == 'nerdtree'
        :NERDTreeToggle
    else
        :NERDTreeFind
    endif
endfunction

nnoremap <C-\> :call MyNerdToggle()<CR>
like image 125
Lewis R Avatar answered Sep 21 '22 22:09

Lewis R


This will do exactly what you want:

nnoremap <silent> <expr> <C-\> g:NERDTree.IsOpen() ? "\:NERDTreeClose<CR>" : bufexists(expand('%')) ? "\:NERDTreeFind<CR>" : "\:NERDTree<CR>"
like image 39
AdUki Avatar answered Sep 19 '22 22:09

AdUki


function! NerdTreeToggleFind()
    if exists("g:NERDTree") && g:NERDTree.IsOpen()
        NERDTreeClose
    elseif filereadable(expand('%'))
        NERDTreeFind
    else
        NERDTree
    endif
endfunction

nnoremap <C-\> :call NerdTreeToggleFind()<CR>
like image 43
hiqsol Avatar answered Sep 20 '22 22:09

hiqsol