Reputation: 4429
I would like to open NERDTree at vim startup with a specific directory root depending on an environment variable.
Set environment variables will correctly be expanded, like $HOME
. The documentation states undefined variables will expand to an empty string.
So this one works correctly with NERD_TREE_ROOT
set to an existing directory. But will not if it is undefined. Instead $NERD_TREE_ROOT
will be used like a string.
autocmd VimEnter * NERDTree $HOME/$NERD_TREE_ROOT
How can I use undefined environment variables correctly as empty string?
EDIT: To clarify a bit. This is what I wanted to avoid:
if empty($NERD_TREE_ROOT)
autocmd VimEnter * NERDTree $HOME
else
autocmd VimEnter * NERDTree $HOME/$NERD_TREE_ROOT
endif
If that is not possible it will do though.
Upvotes: 6
Views: 7379
Reputation: 53614
What you observe has nothing to do with eval or expressions: echo eval('$HOME/$NERD_TREE_ROOT')
results in -2147483648
just like echo 0/0
because both variables when performing a numeric operation turn out to be zeros. The expansion of $HOME
is performed by vim due to presence of -complete=dir
in :NERDTree
command definition. This is rather unexpected and, by the way, is the third type of expansion: :echo expand('$HOME/$NERD_TREE_ROOT')
results in $HOME/$NERD_TREE_ROOT
while :echo expand('$HOME/$HOME')
results in /home/zyx//home/zyx
. I do not see any way to fix this, but you can always do
execute 'autocmd VimEnter * NERDTree '.fnameescape($HOME.'/'.$NERD_TREE_ROOT)
. It is the only case when expansion works as described in the doc because it is the only way when there are any expressions.
Upvotes: 5
Reputation: 161674
Test whether it is empty before autocmd
:
if !empty($NERD_TREE_ROOT)
autocmd VimEnter * NERDTree $HOME/$NERD_TREE_ROOT
endif
Upvotes: 9