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

gfx*_*onk 53 vim

在我的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存储库中脚本的符号链接.

  • 谢谢!这个问题已经得到了很好的回答,但我现在就拿这个问题,因为额外的信息可能很有用. (2认同)

gfx*_*onk 36

找到了:

let s:current_file=expand("<sfile>")
Run Code Online (Sandbox Code Playgroud)

  • 包括它可以帮助其他人.确保在顶级范围内执行此操作.如果您尝试在函数内部运行它,您最终将获得函数名称而不是包含该函数的文件的路径. (18认同)
  • 我很惊讶在互联网上找到这些信息是多么困难,多亏了一大堆! (3认同)
  • `<sfile>:p`表示绝对路径.`<sfile>:p:h`表示脚本所在的目录. (2认同)
  • 另请注意:您可能希望将其包含在`resolve()`中,因为`<sfile>`可能是符号链接. (2认同)

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)