1

How do I write a function that executes the :NERDTree commands? Note: I am using neovim but i'm assuming the vimscript syntax is the same

here is my code

nmap <expr> <C-n> Toggle()

func Toggle()
  if g:open == 0
    let g:open += 1
    execute g:NERDTreeCWD
  else
    let g:open -= 1
    execute g:NERDTreeClose
endfunc
2
  • You don't need execute because you don't do evaluation. And you need (). So: g:NERDTreeCWD() and g:NERDTreeClose(). Commented Nov 15, 2019 at 1:29
  • And you dont need g: for functions, only for variables (see help :g). So: NERDTreeCWD() Commented Nov 15, 2019 at 2:15

1 Answer 1

2

The NERDTree commands are custom Ex commands, so you invoke them (interactively) via :NERDTreeCWD followed by Enter. In a Vimscript, you can drop the : prefix.

Maybe part of the confusion (also seen in the comments) arises from the fact that the NERDTree commands are implemented by global functions with the same name:

:verbose command NERDTreeCWD
    Name              Args Address Complete    Definition
|   NERDTreeCWD       0                        call NERDTreeCWD()

So you could also bypass the custom function and call NERDTreeCWD() directly, but this would make you depend on implementation details of the plugin, and is therefore discouraged.

Implementing NERDTree toggling

Are you aware that the plugin already has a :NERDTreeToggle command?

Also, you don't need to define your own flag variable (g:open) - just reuse the one from the plugin (exposed via the g:NERDTree.IsOpen() function). Yes, this makes you depend on plugin details (but this looks like a public API, not internal implementation, so it should be far more stable) - it's still better than trying to reinvent the wheel. (Your global flag would have problems with multiple tab pages - each could have a NERDTree active or not.)

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much for the useful info. What I should have explained earlier is that i'm trying to workaround a problem with :NERDTreeToggle where the command opens a second unwanted tree of the parent dir that lingers after toggling. The idea was to use NERDTreeCWD because it does not spawn the unwanted parent tree. I tried using call NERDTreeCWD() however I get this error E523: Not allowed here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.