Friday, May 6, 2011

Vim: sourcing based on a string

I can't seem to find an answer to this in any of the numerous Vim scripting tutorials online. What I want to do is construct a file name of a script from environment variables and then source it. And I want to do it in Vim.

If I were to do it in a shell I'd do something like this:

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

How do I do it in Vim?

From stackoverflow
  • You can use the execute command:

    :exec ":source " . $HOME . "/.vim/myscript_" . l:foo . ".vim"
    
  • 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.

    Magnus : Yes, I know that works, but your script path differs in a very specific way; you don't concatenate anything to your environment variables!
    joeytwiddle : (+1) Although Magnus originally said "environment variables" I thought he meant "vim variables". rampion's solution does work for me with environment variables and concatenation. :source $HOME/.vim/myscript_$FOO.vim

0 comments:

Post a Comment