0

Currently, I set the following keymap to my .vimrc:

nnoremap <C-z> :NERDTreeToggle ~/Dropbox/jupyter/<CR>

However, I sometimes want to trigger it with different directory, for example:

:NERDTreeToggle CURRENT_DIR

However, I tried the following command with the following answer, but it did not work.

:NERDTreeToggle getcwd()
:NERDTreeToggle pwd

How can I get the current directory to insert into the command-line mode?

2
  • 2
    Interactively, use the = expression register with control r
    – D. Ben Knoble
    Aug 1, 2018 at 21:58
  • 1
    @D.BenKnoble I just came back to this question to add that to my answer! Goodjob.
    – Rich
    Aug 2, 2018 at 5:29

3 Answers 3

3

The arguments you pass to a command are used as text, not as expressions, so unless a command specifically evaluates the expression in its implementation, passing an expression such as getcwd() won’t function how you’re hoping.

Instead, you can write a command where the expression is evaluated before being passed to the argument:

:execute 'NERDTreeToggle' getcwd()

You might need to add a bit more handling for paths that contain spaces to stop them being passed as separate arguments:

:execute 'NERDTreeToggle' escape(getcwd(), ' ')

Alternatively, you can use the expression register to add the result of a function directly. While in command-line mode press Ctrl-R= and then type your function getcwd() and press Enter.

1

Looks like

:NERDTreeToggle .

is doing what you're looking for -- several other commands work this way :sp, :e...

If you want to use getcwd(), you would have needed to play with :execute, or c_CTRL-R_= in that case. I prefer the later when I can (from mappings, or from the command-line e.g.).

nnoremap µ :NERDTreeToggle <c-r>=getcwd()<cr><cr>

Interactively, this means you'd have to type CTRL+R and conclude with ENTER, twice.

If your question was "the directory from the current file", interactively I usually type CTRL+R % CTRL-W (^W once or twice depending . is in the &isk list or not). In a mapping/script/..., instead of getcwd(), I call expand('%:h'), or expand('%:p:h') to have an absolute path.

0

getcwd(), so the command you want would be :NERDTreeToggle getcwd().

You just exchanged one character. pwd means print working directory. cwd means current working directory. That's why the function name is a bit different.

2
  • Sorry, it was a typo. As written in the linked answer, it is getcwd() but still did not work...
    – Blaszard
    Aug 1, 2018 at 18:15
  • But then the command works, the trouble is using it on the mapping?
    – Spidey
    Aug 2, 2018 at 10:40

Your Answer

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

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