2015-06-19 39 views
8

在vim脚本中,可以嵌入一些python代码,只要vim使用+python功能构建即可。通用:在vim中的python命令?

function! IcecreamInitialize() 
python << EOF 
class StrawberryIcecream: 
    def __call__(self): 
     print('EAT ME') 
EOF 
endfunction 

但是,有些人用+python3代替了vim。这为vim插件带来了一些兼容性问题。是否有一个通用命令调用计算机上安装的任何python版本?

+3

简短的答案是否定的。 Thne较长的答案是你可以抽出一些它,通过测试哪个版本的Python可用,设置一个变量'py'到'python'或'python3',然后用'exec py调用它。 'print(“吃我”)''。是的,我从来没有说过这很好。 – lcd047

回答

1

“heredoc”(<< EOF)语法仅限于脚本:py:perl等)命令;你不能用普通字符串来使用它们。在Vim中使用续行有点痛苦。

因此,我会将Python代码放在​​一个单独的文件中,并将其传递给:py:py3命令。

let mycode = join(readfile(expand('~/mycode.py')), "\n") 

if has('python') 
    execute 'py ' . mycode 
elseif has('python3') 
    execute 'py3 ' . mycode 
else 
    echoe 'Your mother was a hamster' 
endif 

而且mycode.py脚本:

import sys 
import vim 
print('This is mycode', sys.version) 

vim.command(':echo "Hello"') 
print(vim.eval('42')) 

通过Python 2:

('This is mycode', '2.7.10 (default, May 26 2015, 04:16:29) \n[GCC 5.1.0]') 
Hello 
42 

而且在Python 3:

This is mycode 3.4.3 (default, Mar 25 2015, 17:13:50) 
[GCC 4.9.2 20150304 (prerelease)] 
Hello 
42 
3

这个片段可以决定哪个Python版本我们正在使用和切换到它(Python代表安装的版本)。

if has('python') 
    command! -nargs=1 Python python <args> 
elseif has('python3') 
    command! -nargs=1 Python python3 <args> 
else 
    echo "Error: Requires Vim compiled with +python or +python3" 
    finish 
endif 

要加载Python代码,我们首先弄清楚它的位置(这里的同一目录Vim脚本下):

execute "Python import sys" 
execute "Python sys.path.append(r'" . expand("<sfile>:p:h") . "')" 

然后检查Python模块可用。如果没有,重新加载它:

Python << EOF 
if 'yourModuleName' not in sys.modules: 
    import yourModuleName 
else: 
    import imp 
    # Reload python module to avoid errors when updating plugin 
    yourModuleName = imp.reload(yourModuleName) 
EOF 

两种方式来调用它:
1.

" call the whole module 
execute "Python yourModuleName" 

" call a function from that module 
execute "Python yourModuleName.aMethod()" 

2.

" Call a method using map 
vnoremap <leader> c :Python yourModuleName.aMethod()<cr> 

" Call a module or method using Vim function 
vnoremap <leader> c :<c-u> <SID>yourFunctionName(visualmode())<cr> 
function! s:YourFunctionName(someName) 
    Python YourFunctionName.aMethod(a:someName) 
    Python YourFunctionName 
endfunction