Vim: sourcing based on a string

后端 未结 2 1880
情书的邮戳
情书的邮戳 2021-01-17 08:44

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 varia

2条回答
  •  不知归路
    2021-01-17 09:17

    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"
    

提交回复
热议问题