2013-05-27 62 views
4

我有關於理解那些Vim腳本2點的問題。請給予一些幫助,如何理解這些Vim腳本

問題1: 我下載a.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") 

感謝您的幫助。

回答

3

<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之一。

+0

好的,有用的信息,謝謝 – gladman

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

即一個內聯展開一個Vimscript中表達的成變量名,從Vim版本7.見:help curly-braces-names對於細節很少使用一個相當模糊的功能。它通常用於內插一個變量,而不是像這樣的字符串文字('aspx.cs')。此外,這裏會產生一個錯誤,因爲週期在變量名中是被禁止的。較新的插件會使用一個List或Dictionary變量,但這些數據類型在編寫a.vim時不可用。


爲了避免污染函數命名空間,插件,內部功能應該是腳本的地方,即有前綴s:。要從映射中調用這些映射,必須使用前綴<SID>而不是s:,因爲<SID>在內部被轉換爲保留腳本ID的東西,而純粹的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") 
+0

偉大的;-)我明白了;謝謝。 – gladman

+0

嗨Ingo,謝謝你的回答,一如既往非常翔實。你對A.vim插件有什麼建議或者選擇嗎? – skeept

+0

優秀的答案,謝謝。 –