0

I'm trying to create a simple function in vim which lets me map <leader>b, <leader>n, and <leader>0 to execute a function that checks if a nerd tree is open then cycle tabs and do :NerdTreeFind if not then only cycle tabs. but I couldn't seem to make it work and it returns E121: Undefined variable: CR

here is the script

function! CheckNerdTree(tab)
    if exists("g:NERDTree") && g:NERDTree.IsOpen()
        execute a:tab<CR>:NERDTreeFind<CR><C-w>l<CR>
    else
        execute a:tab<CR>
    endif
endfunction


noremap <leader>0 :call CheckNerdTree(":tablast")
noremap <leader>n :call CheckNerdTree(":tabnext")
noremap <leader>b :call CheckNerdTree(":tabprev")

I'm pretty new to vim scripting and haven't really 100% understand how it works, any help would be appreciated. Thanks

  • Aside: you probably want nnoremap for normal mode. – D. Ben Knoble May 18 at 18:02
0

The execute command takes a string as an argument. Further, it is used to execute Ex commands. Finally, Ex-commands may be « executed » (in the programmatic sense, not the vimscript sense!) by simply calling them.

So we can simplify to

execute a:tab
NERDTreeFind
wincmd l

And

execute a:tab

Don’t forget the <CR>s at the end of the mapping

  • I recommend Steve Losh’s Learn Vimscript the Hard Way for beginners. – D. Ben Knoble May 18 at 18:01
  • wow thankyou!, adding your solution and changing the noremaps into noremap <silent><leader>0 :call CheckNerdTree(":tablast")<cr> makes it perfect! – millenito May 18 at 19:22
  • @millenito happy to help :) – D. Ben Knoble May 18 at 19:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.