Number8
Number8

Reputation: 12870

vim - how to use environment variable in autocommand

Win7x32 gvim 7.4

I want to call a batch file in response to the VimLeave event.
If my autocommand looks like this:

au VimLeave * !c:\users\Sauron\vimfiles\cleanSession.cmd

it works as expected.
I want to replace 'c:\users\Sauron' with '~' or '$HOME' or something similar, but have not gotten it to work. I have tried:

au VimLeave * !$HOME\vimfiles\cleanSession.cmd  
au VimLeave * !%HOME%\vimfiles\cleanSession.cmd  
au VimLeave * !~\vimfiles\cleanSession.cmd  

The '%' is expanded to the containing file's name.
$HOME doesn't get expanded. I have tried quoting the path, and not.
What am I overlooking?
Thanks --

Upvotes: 2

Views: 387

Answers (2)

Ingo Karkat
Ingo Karkat

Reputation: 172510

@lcd047's answer expands $HOME at autocommand definition; it's a bit more common to expand only at invocation. This also makes the command's syntax slightly more tolerable.

Additionally, fnameescape() is not the correct function; for :!, shellescape() (with the optional {special} argument) should be used:

au VimLeave * execute '!' . shellescape($HOME . '/vimfiles/cleanSession.cmd', 1)

Technically, escaping is only necessary if the path contains special characters, which is unlikely here, so you could also get away with:

au VimLeave * execute '!' . $HOME . '/vimfiles/cleanSession.cmd'

Upvotes: 1

lcd047
lcd047

Reputation: 5851

exec 'au VimLeave * !' . fnameescape($HOME . '/vimfiles/cleanSession.cmd')

Welcome to the wonderful world of Vim command mode syntax. :)

Upvotes: 1

Related Questions