Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Windows environment variables in Vim script?

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?

like image 859
Nick Coleman Avatar asked Feb 19 '12 03:02

Nick Coleman


2 Answers

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:

  • the type is executed in windows shell, so you need \(backslash) in path
  • if $HOME contains spaces, you need "(double-quote) to preserves the literal value of spaces
like image 125
kev Avatar answered Oct 15 '22 11:10

kev


To 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.

like image 35
Tuxmentat Avatar answered Oct 15 '22 12:10

Tuxmentat