How to use Windows environment variables in Vim script? How to use Windows environment variables in Vim script? windows windows

How to use Windows environment variables in 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:

  • 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


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.


You probably need something like the expand function. For example:

:echo expand("$HOME/hello")/home/amir/hello

You can find out more info about expand() with :help expand.