Within some run time files I would like to source a file relative to the $MYVIMRC file. My best efforts have lead me to this (which does not work):

source expand("$MYVIMRC:p:h") . "/vimrc/env.vim")
  • 1
    source doesn't work for "strings". :exe "source " . expand("$MYVIMRC:p:h") . "/vimrc/env.vim" might work, but I am not sure.
    – Maxim Kim
    Mar 21 '20 at 10:43

Your best effort:

source expand("$MYVIMRC:p:h") . "/vimrc/env.vim")

has issues:

  1. source command doesn't work with "strings"
  2. even if it worked with strings, you have strange last unbalanced )

You can try using :execute statement with composed source:

:exe "source " . fnamemodify("$MYVIMRC", ":p:h") . "/vimrc/env.vim"

Note that expand("$MYVIMRC:p:h") will not work as expected, but fnamemodify will.

Another option I personally use is:

source <sfile>:h/statusline.vim

where <sfile> when executing a ":source" command, is replaced with the file name of the sourced file.

  • expand("$MYVIMRC:p:h") result in a path ending with the literal ":p:h", so ":exe "source " . expand("$MYVIMRC:p:h") . "/vimrc/env.vim"" does not work Mar 21 '20 at 23:29
  • @run_the_race indeed. fnamemodify would fix this
    – Maxim Kim
    Mar 22 '20 at 7:12

A possible solution:

execute printf('source %s/vimrc/env.vim', fnamemodify($MYVIMRC, ':h'))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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