使用Python编写vim插件的简单示例
Vim插件是一个.vim的脚本文件,定义了函数、映射、语法规则和命令,可用于操作窗口、缓冲以及行。一般一个插件包含了命令定义和事件钩子。当使用Python编写vim插件时,函数外面是使用VimL编写,尽管VimL学起来很快,但Python更加灵活,例如可以用urllib/httplib/simplejson来访问某些Web服务,这也是为什么很多需要访问Web服务的插件都是使用VimL+Python编写的原因。
在开始编写插件之前,你需要确认Vim支持Python,通过以下命令来判别:
vim--version|grep+python
接下来我们通过一个简单的例子来学习用Python编写Vim插件,该插件用来获取Reddit首页信息并显示在当前缓冲区上。
首先在Vim新建vimmit.vim文件,我们首先需要判断是否支持Python,如果不支持给出提示信息:
if!has('python')
echo"Error:Requiredvimcompiledwith+python"
finish
endif
上面这段代码就是用VimL编写的,它将检查Vim是否支持Python。
下面是用Python编写的Reddit()主函数:
"Vimcommentsstartwithadoublequote.
"FunctiondefinitionisVimL.WecanmixVimLandPythonin
"functiondefinition.
function!Reddit()
"Westartthepythoncodelikethenextline.
python<<EOF
#thevimmodulecontainseverythingweneedtointerfacewithvimfrom
#python.Weneedurllib2forthewebserviceconsumer.
importvim,urllib2
#weneedjsonforparsingtheresponse
importjson
#wedefineatimeoutthatwe'lluseintheAPIcall.Wedon'twant
#userstowaitmuch.
TIMEOUT=20
URL="http://reddit.com/.json"
try:
#Getthepostsandparsethejsonresponse
response=urllib2.urlopen(URL,None,TIMEOUT).read()
json_response=json.loads(response)
posts=json_response.get("data","").get("children","")
#vim.current.bufferisthecurrentbuffer.It'slist-likeobject.
#eachlineisaniteminthelist.Wecanloopthroughthemdelete
#them,alterthemetc.
#Herewedeletealllinesinthecurrentbuffer
delvim.current.buffer[:]
#Hereweappendsomelinesabove.Aesthetics.
vim.current.buffer[0]=80*"-"
forpostinposts:
#Inthenextfewlines,wegetthepostdetails
post_data=post.get("data",{})
up=post_data.get("ups",0)
down=post_data.get("downs",0)
title=post_data.get("title","NOTITLE").encode("utf-8")
score=post_data.get("score",0)
permalink=post_data.get("permalink").encode("utf-8")
url=post_data.get("url").encode("utf-8")
comments=post_data.get("num_comments")
#Andhereweappendlinebylinetothebuffer.
#Firsttheupvotes
vim.current.buffer.append("↑%s"%up)
#Thenthetitleandtheurl
vim.current.buffer.append("%s[%s]"%(title,url,))
#Thenthedownvotesandnumberofcomments
vim.current.buffer.append("↓%s|comments:%s[%s]"%(down,comments,permalink,))
#Andlastweappendsome"-"forvisualappeal.
vim.current.buffer.append(80*"-")
exceptException,e:
printe
EOF
"Herethepythoncodeisclosed.WecancontinuewritingVimLorpythonagain.
endfunction
使用如下命令保存文件
:sourcevimmit.vim
然后调用该插件:
:callReddit()
这个命令用起来不那么方便,因此我们再定义一个命令:
command!-nargs=0RedditcallReddit()
我们定义了命令:Reddit来调用这个函数。-nargs参数声明命令行中有多少个参数。
关于函数参数的问题:
问:如何访问函数中的参数?
function!SomeName(arg1,arg2,arg3)
"GetthefirstargumentbynameinVimL
letfirstarg=a:arg1
"GetthesecondargumentbypositioninViml
letsecondarg=a:1
"Gettheargumentsinpython
python<<EOF
importvim
first_argument=vim.eval("a:arg1")#orvim.eval("a:0")
second_argument=vim.eval("a:arg2")#orvim.eval("a:1")
你可以使用...来处理可变个数参数来替换特定的参数名,可通过位置或者命名参数来访问,如:(arg1,arg2,...)
问:如何在Python中调用Vim命令?
vim.command("[vim-command-here]")
问:如何定义全局变量,并在VimL和Python中访问?
全局变量使用形如g:.的前缀,定义全局变量前应该检查该变量是否已定义:
if!exists("g:reddit_apicall_timeout")
letg:reddit_apicall_timeout=40
endif
然后你通过下面代码在Python中访问这个变量:
TIMEOUT=vim.eval("g:reddit_apicall_timeout")
可通过下面的方法来对全局变量进行重新赋值:
letg:reddit_apicall_timeout=60
更多关于使用Python编写Vim插件的说明请看官方文档。
备注:
一旦你用过VimL,就会发现它挺简单的,你用python写的代码也可以用它来实现。详细请参考vimpython模块文档,这是一份重要的参考资料。
除了上述文档,你也可以在IBMdeveloperWorks网站找到一些有用的资料。