2

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
  • 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
    Commented Mar 21, 2020 at 10:43

2 Answers 2

3

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.

3
  • 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 Commented Mar 21, 2020 at 23:29
  • @run_the_race indeed. fnamemodify would fix this
    – Maxim Kim
    Commented Mar 22, 2020 at 7:12
  • I had to do fnamemodify(expand("$MYVIMRC"), ":p:h") to get this to work ... or fnamemodify($MYVIMRC, ":p:h")
    – rrauenza
    Commented Oct 19, 2023 at 22:54
2

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 and acknowledge you have read our privacy policy.

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