在我的vim插件中,我有两个文件:
myplugin/plugin.vim
myplugin/plugin_helpers.py
Run Code Online (Sandbox Code Playgroud)
我想从plugin.vim导入plugin_helpers(使用vim python支持),所以我相信我首先需要将我的插件目录放在python的sys.path上.
我如何(在vimscript中)获取当前正在执行的脚本的路径?在python中,这是__file__.在红宝石中,它是__FILE__.我通过谷歌搜索找不到任何类似的vim,可以这样做吗?
注意:我不是在寻找当前编辑的文件("%:p"和朋友).
Zen*_*xer 72
" Relative path of script file:
let s:path = expand('<sfile>')
" Absolute path of script file:
let s:path = expand('<sfile>:p')
" Absolute path of script file with symbolic links resolved:
let s:path = resolve(expand('<sfile>:p'))
" Folder in which script resides: (not safe for symlinks)
let s:path = expand('<sfile>:p:h')
" If you're using a symlink to your script, but your resources are in
" the same directory as the actual script, you'll need to do this:
" 1: Get the absolute path of the script
" 2: Resolve all symbolic links
" 3: Get the folder of the resolved absolute file
let s:path = fnamemodify(resolve(expand('<sfile>:p')), ':h')
Run Code Online (Sandbox Code Playgroud)
我经常使用最后一个因为我~/.vimrc是git存储库中脚本的符号链接.
gfx*_*onk 36
找到了:
let s:current_file=expand("<sfile>")
Run Code Online (Sandbox Code Playgroud)
edt*_*dev 11
值得一提的是,上述解决方案仅适用于功能之外.
这不会产生预期的结果:
function! MyFunction()
let s:current_file=expand('<sfile>:p:h')
echom s:current_file
endfunction
Run Code Online (Sandbox Code Playgroud)
但这会:
let s:current_file=expand('<sfile>')
function! MyFunction()
echom s:current_file
endfunction
Run Code Online (Sandbox Code Playgroud)
这是OP原始问题的完整解决方案:
let s:path = expand('<sfile>:p:h')
function! MyPythonFunction()
import sys
import os
script_path = vim.eval('s:path')
lib_path = os.path.join(script_path, '.')
sys.path.insert(0, lib_path)
import vim
import plugin_helpers
plugin_helpers.do_some_cool_stuff_here()
vim.command("badd %(result)s" % {'result':plugin_helpers.get_result()})
EOF
endfunction
Run Code Online (Sandbox Code Playgroud)