我想打电话与脚本范围(声明的函数s:在一个执行的Vim脚本),没有硬编码%d在call <SNR>%d_function()或通过修改自己的插件文件曝光功能的全局命名空间.如何以<SNR>编程方式检索其父脚本或脚本编号?
您可以<SNR>通过解析输出来检索脚本:scriptnames.以下函数将对脚本的完整文件名或其片段执行此操作(只要它唯一标识您想要的文件名).
func! GetScriptNumber(script_name)
" Return the <SNR> of a script.
"
" Args:
" script_name : (str) The name of a sourced script.
"
" Return:
" (int) The <SNR> of the script; if the script isn't found, -1.
redir => scriptnames
silent! scriptnames
redir END
for script in split(l:scriptnames, "\n")
if l:script =~ a:script_name
return str2nr(split(l:script, ":")[0])
endif
endfor
return -1
endfunc
Run Code Online (Sandbox Code Playgroud)
例如,如果需要调用在名为的脚本中foo定义的函数,则可以使用:s:bar.vim
call eval(printf("<SNR>%d_foo()", GetScriptNumber("bar.vim")))
Run Code Online (Sandbox Code Playgroud)