13

我有两个关于理解那些 vim 脚本的问题。请提供一些帮助,

问题1:我下载了一个.vim插件,并尝试阅读这个插件,如何理解下面的变量定义?第一行我能理解,但第二行,我不知道“g:alternateExtensions_{'aspx.cs'}”是什么意思。

" E.g. let g:alternateExtensions_CPP = "inc,h,H,HPP,hpp" 
"      let g:alternateExtensions_{'aspx.cs'} = "aspx"

问题2:如何理解函数名前的“SID”,使用如下函数定义和函数调用。

function! <SID>AddAlternateExtensionMapping(extension, alternates)
//omit define body

call <SID>AddAlternateExtensionMapping('h',"c,cpp,cxx,cc,CC")
call <SID>AddAlternateExtensionMapping('H',"C,CPP,CXX,CC")

谢谢你的帮助。

4

2 回答 2

28
let g:alternateExtensions_{'aspx.cs'} = "aspx"

这是 Vimscript 表达式到变量名的内联扩展,这是一个相当晦涩的功能,自 Vim 版本 7 以来很少使用。详情请参阅:help curly-braces-names。它通常用于插入变量,而不是像这里 ( 'aspx.cs') 这样的字符串文字。此外,这会产生错误,因为变量名称中禁止使用句点。较新的插件会使用 List 或 Dictionary 变量,但在编写a.vim时这些数据类型不可用。


为了避免污染函数命名空间,插件内部函数应该是脚本本地的,即具有前缀s:。要从映射中调用这些,必须使用特殊<SID>前缀s:<SID>不是s:它。

一些插件作者也不完全理解 Vim 作用域实现的这种不幸和意外的复杂性,他们<SID>也将前缀放在函数名前面(这也有效)。虽然它稍微更正确并建议这样写:

" Define and invoke script-local function.
function! s:AddAlternateExtensionMapping(extension, alternates)
...
call s:AddAlternateExtensionMapping('h',"c,cpp,cxx,cc,CC")

" Only in a mapping, the special <SID> prefix is actually necessary.
nmap <Leader>a :call <SID>AddAlternateExtensionMapping('h',"c,cpp,cxx,cc,CC")
于 2013-05-27T07:38:34.757 回答
8

<SID>解释:help <SID>如下:

When defining a function in a script, "s:" can be prepended to the name to
make it local to the script.  But when a mapping is executed from outside of
the script, it doesn't know in which script the function was defined.  To
avoid this problem, use "<SID>" instead of "s:".  The same translation is done
as for mappings.  This makes it possible to define a call to the function in
a mapping.

When a local function is executed, it runs in the context of the script it was
defined in.  This means that new functions and mappings it defines can also
use "s:" or "<SID>" and it will use the same unique number as when the
function itself was defined.  Also, the "s:var" local script variables can be
used.

这个数字是你在左边看到的那个:scriptnames,IIRC。

于 2013-05-27T07:28:48.617 回答