When Vim is started, it grabs many of the environment variables from the operating system (like PATH) and it also sets it own environment variables (like MYVIMRC).
How do I list or view all the environment variables that Vim understands, together with their respective values from inside Vim?
In Vimscript, there is not a direct way of getting the list of
currently defined environment variables. However, it is possible
to exploit Vim command-line completion feature to make one.
Consider possible completions for the following unfinished command:
It is not difficult to see that, according to Vimscript syntax,
the completions must be the names of the environment variables.
Pressing the
wildcharkey (Tab, by default) orCtrl+D will display all of them.
In order to get this list of completions from within a script, we need
to overcome its interactive nature. A possible trick that I propose
herein relies on a combination of features. The first of them is the
Ctrl+A command. In Command-line mode, this
shortcut triggers insertion of every available completion in front of
the cursor. The inserted completions are listed in alphabetical order
and separated with spaces.
If we could make Vim print those completions out right into the
command line, we would easily capture them by redirecting command
output with the
:redircommand. But all we need to achieve thatside effect is to quote the text inserted with Ctrl+A:
Quoting makes the rest of our
:echocommand a string literal thatcan be just printed out!
To edit the command line in this way, the user can type
:ec(analias for
:echo) followed by$, pressCtrl+A, type
', jump to the beginning of theline by pressing Ctrl+B, move the cursor over
the dollar sign by pressing ⇾ (the right arrow key) twice,
delete that
$, and, finally, insert'instead. The same sequenceof key presses can easily be reproduced non-interactively using the
:normalcommand.Putting all these pieces together, we obtain the following function:
For this approach to work, Vim must be compiled with the
+cmdline_complfeature.