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

2

6

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?

Katheykathi answered 8/7, 2011 at 11:53 Comment(1)
I do not use NERDTree or Tagbar, so this is only supposition, but I expect they both declare a global variable while they are open. You could therefore write a function to perform the commands you wish based on the existence of these variables. Then map the function call to <leader>\.Unbolt
S
15

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>
Similitude answered 8/7, 2011 at 13:19 Comment(3)
Oooh lovely! Works perfectly. And thanks for the "jump back to the original window feature". Was also what I was looking forKatheykathi
How did you discover the name of the Tagbar window?Sizzler
Well, I wrote Tagbar, so I naturally knew it. But you can also get the name of the current buffer (which is what I'm using here, not the name of the window) with :echo bufname('%').Similitude
K
-1

hmm... this works for me in vimrc

The toggle option checks if the window already exists, so no custom function needed (@JanLarres or one of the contributors) must have added it to TagBar :D

" NERDTree
map <leader>n :NERDTreeToggle<CR>

" TagBar
map <leader>t :TagbarToggle<CR>
Katharina answered 23/4, 2014 at 12:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.