How to use undefined environment variables in .vimrc correctly?

I would like to open NERDTree when starting vim with a specific directory root depending on the environment variable.

Set environment variables that will be correctly extended, for example $HOME . the documentation states that undefined variables will expand to an empty string .

So this works correctly with NERD_TREE_ROOT installed in an existing directory. But it will not be if it is undefined. Instead, $NERD_TREE_ROOT will be used as a string.

 autocmd VimEnter * NERDTree $HOME/$NERD_TREE_ROOT 

How can I correctly use undefined environment variables as an empty string?

EDIT: 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 this is not possible, it will be done.

+4
source share
2 answers

What you are observing has nothing to do with eval or expressions: echo eval('$HOME/$NERD_TREE_ROOT') leads to -2147483648 in the same way as echo 0/0 , because both variables turn out to be zeros when performing a numerical operation . The $HOME extension is performed by vim due to the -complete=dir definition in :NERDTree . This is quite unexpected and, by the way, is the third type of extension:: :echo expand('$HOME/$NERD_TREE_ROOT') leads to $HOME/$NERD_TREE_ROOT , and :echo expand('$HOME/$HOME') leads to /home/zyx//home/zyx . I see no way to fix this, but you can always do

 execute 'autocmd VimEnter * NERDTree '.fnameescape($HOME.'/'.$NERD_TREE_ROOT) 

. This is the only case where the extension works as described in the document, because it is the only way when there are any expressions.

+5
source

Check if it is empty before autocmd :

 if !empty($NERD_TREE_ROOT) autocmd VimEnter * NERDTree $HOME/$NERD_TREE_ROOT endif 
+4
source

Source: https://habr.com/ru/post/1398980/


All Articles