如何获取当前正在执行的vimscript的路径

时间:2011-02-12 06:52:34

标签: vim

在我的vim插件中,我有两个文件:

myplugin/plugin.vim
myplugin/plugin_helpers.py

我想从plugin.vim导入plugin_helpers(使用vim python支持),所以我相信我首先需要将我的插件目录放在python的sys.path上。

我如何(在vimscript中)获取当前正在执行的脚本的路径?在python中,这是__file__。在红宝石中,它是__FILE__。我通过谷歌搜索找不到任何类似的vim,可以吗?

注意:我不是在寻找当前已编辑的文件(“%:p”和朋友)。

3 个答案:

答案 0 :(得分:66)

" 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')

我经常使用最后一个,因为我的~/.vimrc是git存储库中脚本的符号链接。

答案 1 :(得分:33)

找到它:

let s:current_file=expand("<sfile>")

答案 2 :(得分:11)

值得一提的是,上述解决方案仅适用于函数之外。

这不会产生预期的结果:

function! MyFunction()
let s:current_file=expand('<sfile>:p:h')
echom s:current_file
endfunction

但这会:

let s:current_file=expand('<sfile>')
function! MyFunction()
echom s:current_file
endfunction

以下是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