I have a Vim script that calls an external shell script and reads the output into the current buffer. It works fine in Unix systems. I'm trying to make the script OS-agnostic, so I want it to work for Windows users too. Here's the relevant line from the script:
:exe ":0r !$HOME/bin/shell_script"
According to Vim's docs, $HOME
should translate fine for Windows users too. Using gvim on Win XP in command mode, doing
:echo $HOME
does indeed produce "C:\Documents and Settings\my_user".
However, my Vim script (adjusted for backslashes) fails on the Windows machine with a message in the DOS cmd.exe window saying
$HOME\bin\shell_script" not found.
In other words, Vim appears not to be expanding the value of $HOME
before passing it to cmd.exe.
I can't use %APPDATA%
either because Vim interprets %
as the current file and pre/appends the file name to APPDATA
. Weird that Vim does expand %
but doesn't expand $HOME
.
How do I get $HOME
expanded correctly? Is it because I'm using exe
in the vim script?
You don't need !
to read a file.
:exe ":0r $HOME/bin/shell_script"
Or read type
command in windows(like cat
in linux):
:exe '0r !type "'. $HOME . '\bin\shell_script"'
Note:
type
is executed in windows shell, so you need \
(backslash) in path$HOME
contains space
s, you need "
(double-quote) to preserves the literal value of space
sTo clarify the answer given by kev:
On windows the $HOME variable do not expand properly when you escape to the console. For example, consider this code:
:e $HOME/myscript
This works because vim expands $HOME as normal. On the other hand this won't work:
:%! $HOME/myscript
Why? Because vim passes everything after !
to the underlying shell, which on Windows is cmd.exe
which does environment variables %LIKE_THIS%
. If you try to use that notation, vim will jump in and expand %
to the name of the current file - go figure.
How to get around it? Use exe
keyword:
:exe "%! ".$HOME."\myscript"
Let's analyze:
:exe
is a command that takes a string and evaluates it (think eval in most languages)
"!% "
the escape to shell command. Note that it is quoted so that exe can evaluate it. Also note how there is an extra space there so that when we append the home var it does not but right against it
.$HOME
the dot is a string concatenation symbol. The $HOME
is outside of the quotes but concatenated so that vim can expand it properly
."/myscript"
path to script and possible arguments (also quoted)
The important thing here is keeping $HOME
outside of the quote marks, otherwise it may not be properly expanded on Windows.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With