tldr: The title pretty much summarizes the entirety of the question

I am trying to make my configuration more adaptable to different machines so that I can use git to keep them in sync between my personal windows, linux, and work machines. right now my .vimrc/init.vim passes absolute literal paths to the source key word and it works fine, but say I want to do something like this...

if has('win32')
   let prefix = $HOME . '/AppData/Local/nvim'
   let prefix = $HOME . '/.config/nvim'

source prefix . '/vim-plug/plugins.vim'

This doesn't work because the source keyword interprets everything literally. So how can I make it expand the variables?

Here are some things i've tried

source exec expand(prefix) . '/rest/of/path'

source <exec> expand(prefix) . '/rest/of/path'

source <exec> prefix . '/rest/of/path'

exec source prefix . '/rest/of/path'

and many other variations

As I have been unsuccessful in finding an answer in a search engine, I've resorted to guessing different variations of this which is tedious and unproductive. So does anyone know how to make this work?


2 Answers 2


:h expand() your string with environment variable, concatenate it the rest and use :h :execute to source it:

:execute "source " . expand(prefix) . "/whatever.vim"
  • No need for expand() around prefix, it will already be evaluated since we're in an expression here.
    – adamency
    Nov 5, 2023 at 23:58

You can also assign a value for the path to a self defined environment variable (prefix: $, without $ it is a normal variable) and then use that environment variable, e.g.:

let $file_path = prefix . '/rest/of/path'
source $file_path

I don't know the reason, why Vim doesn't source a normal variable, but an environment variable.

  • It's because :source is an ex commands and does not expect an expression Oct 17, 2023 at 7:44

Your Answer

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

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