2011-02-12 60 views
37

在我的vim插件目前Vimscript中,我有两个文件:如何获得路径正在执行

myplugin/plugin.vim 
myplugin/plugin_helpers.py 

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

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

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

+0

源相对于路径当前脚本:`执行'源'。展开(':p:h')。 '/ another.vim'` – 2015-06-25 08:44:44

回答

53
" 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仓库。

32

发现:

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

它帮助其他人。确保在最高级别范围内执行此操作。如果你试图在一个函数中运行它,你最终会得到函数名,而不是包含该函数的文件的路径。 – 2012-02-12 21:54:38

+3

我很惊讶在互联网上找到这些信息有多困难,谢谢! – 2013-01-15 06:53:22

+1

`:p`为绝对路径。 `:p:h`代表脚本所在的目录。 – Zenexer 2013-05-10 12:56:57

7

值得一提的是,上述解决方案只能在一个函数之外使用。

这将不会得到预期的结果:

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