Vim: sourcing based on a string

Just :source works for me:

% export MYPATH='a/b/c'
% mkdir -p $MYPATH
% export MYFILE='temp.vim'
% cat > $MYPATH/$MYFILE
echo 'hello world'
^D
% vim
:source $MYPATH/$MYFILE
hello world

If you want to have some vim scripts automatically sourced though, just stick them in your ~/.vim/plugin/ directory, and they'll be loaded for you, without having to do it manually.

From :help expand-environment-var (which I got by doing :help environment and tab completing to the first likely result)

             *:set_env* *expand-env* *expand-environment-var*
    Environment variables in specific string options will be expanded.  If the
    environment variable exists the '$' and the following environment variable
    name is replaced with its value.  If it does not exist the '$' and the name
    are not modified.  Any non-id character (not a letter, digit or '_') may
    follow the environment variable name.  That character and what follows is
    appended to the value of the environment variable.  Examples: >
       :set term=$TERM.new
       :set path=/usr/$INCLUDE,$HOME/include,.
    When adding or removing a string from an option with ":set opt-=val" or ":set
    opt+=val" the expansion is done before the adding or removing.

I tend to find vim's built in help more useful than anything else, but it does take a while to get the knack of knowing what to look for.


You can build up a string and then use the execute command:

exec "source " . $HOME . "/.vim/myscript_" . l:foo . ".vim"

(The l:foo here is an example of using a local variable from within a function.)


Edit:

But in fact exec is overkill in this specific case. As rampion shows here, the OPs task can be done directly with:

source $HOME/.vim/myscript_$FOO.vim

Although vim does not let us wrap the variable names neatly in ${...} like we could in the shell, in this case we are lucky that HOME is terminated by the / and FOO by the .

In general, exec would be needed if you wanted to follow one of the variables by a non-terminating character. For example:

exec "source " . $BAR . "_script.vim"

would insert the BAR variable, while the following would try to find a variable called BAR_script:

source $BAR_script.vim       " Possibly not what you wanted!

Use shellescape() for safety

When adding a variable to a string to be executed, we should really use shellescape() to escape strange chars (for example spaces in filenames).

For example, these are safer versions of the above:

exec "source " . shellescape($HOME . "/.vim/myscript_" . l:foo) . ".vim"

exec "source " . shellescape($BAR) . "_script.vim"

Tags:

Vim