7

I am trying to retrieve the value of $MYVIMRC in my init.lua but I am coming up short because I don't understand what $MYVIMRC actually is.

It is not a global variable, is it?

None of these work:

vim.g.$MYVIMRC
vim.g.MYVIMRC
vim.g.myvimrc

What is $MYVIMRC and how can I access it from Lua?

1

2 Answers 2

9

$MYVIMRC is an environment variable that Vim adds to the current environment.

Environment variables are usually inherited by child processes from their parent process. For example, you can see $MYVIMRC in a shell that is a child process of Vim:

:!printenv | grep MYVIMRC

(I use this form rather than just :!echo "$MYVIMRC" to "prove" that the value is not inserted before the command is sent to the shell.)

I don't use lua in Vim but I know you can examine environment variables with os.getenv() so, for instance, this will print the expected value:

:lua print(os.getenv("MYVIMRC"))

In other words, you don't need any special Vim API to get the value.

1
  • Thank you for taking the time to provide both the explanation and the Lua code! The $ should have been a clue that it's an environment variable that is simply available in vim.
    – severin
    Jul 3, 2021 at 9:19
11

This is already answered but I just wanted to add another way to access environment variables in lua using vim API.

vim.env.whatever -- will give you the value of whatever
vim.env.test = "test msg" -- sets env variable test to value "test msg"

I believe this way is more readable and more pleasant to script than using os.getenv

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.