vimvim-pluginnerdtreetagbar

How to open or close NERDTree and Tagbar with <leader>\?


I want <leader>\ to open or close NERDTree and Tagbar, under the following conditions:

  1. Only close both if NERDTree and Tagbar are both opened
  2. Open both if NERDTree and Tagbar are closed OR if one is already opened

So far, in VIMRC, I have:

nmap <leader>\ :NERDTreeToggle<CR> :TagbarToggle<CR>

Which doesn't exactly work, since if one is opened, and the other closed. It would open the one that was closed and close the one that was opened.

How can this be achieved?


Solution

  • You need to use a function that checks whether the plugin windows are open or not and then acts accordingly. This should work and will also jump back to the window that you started in:

    function! ToggleNERDTreeAndTagbar()
        let w:jumpbacktohere = 1
    
        " Detect which plugins are open
        if exists('t:NERDTreeBufName')
            let nerdtree_open = bufwinnr(t:NERDTreeBufName) != -1
        else
            let nerdtree_open = 0
        endif
        let tagbar_open = bufwinnr('__Tagbar__') != -1
    
        " Perform the appropriate action
        if nerdtree_open && tagbar_open
            NERDTreeClose
            TagbarClose
        elseif nerdtree_open
            TagbarOpen
        elseif tagbar_open
            NERDTree
        else
            NERDTree
            TagbarOpen
        endif
    
        " Jump back to the original window
        for window in range(1, winnr('$'))
            execute window . 'wincmd w'
            if exists('w:jumpbacktohere')
                unlet w:jumpbacktohere
                break
            endif
        endfor
    endfunction
    nnoremap <leader>\ :call ToggleNERDTreeAndTagbar()<CR>