Vim:基于字符串的采购 [英] Vim: sourcing based on a string

查看:26
本文介绍了Vim:基于字符串的采购的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法在众多在线 Vim 脚本教程中找到答案.我想要做的是从环境变量构造一个脚本的文件名,然后源它.我想在 Vim 中做到这一点.

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.

如果我要在 shell 中执行此操作,我会执行以下操作:

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

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

我如何在 Vim 中执行此操作?

How do I do it in Vim?

推荐答案

你可以建立一个字符串然后使用execute命令:

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

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

(这里的 l:foo 是一个在函数内使用局部变量的例子.)

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

但实际上 exec 在这种特定情况下是矫枉过正的.正如rampion 此处所示,可以直接完成OPs任务与:

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

虽然 vim 不允许我们像在 shell 中那样将变量名整齐地包裹在 ${...} 中,但在这种情况下,我们很幸运 HOME/ 终止,FOO 终止.

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 .

通常,如果您想在变量之一后跟一个非终止字符,则需要 exec .例如:

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"

将插入 BAR 变量,而以下将尝试查找名为 BAR_script 的变量:

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!

为了安全使用 shellescape()

在要执行的字符串中添加变量时,我们真的应该使用 shellescape() 来转义奇怪的字符(例如文件名中的空格).

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"

这篇关于Vim:基于字符串的采购的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆