首页 > 编程 > Python > 正文

使用Python编写vim插件的简单示例

2020-02-23 00:46:15
字体:
来源:转载
供稿:网友

 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: Required vim compiled with +python"  finishendif

上面这段代码就是用 VimL 编写的,它将检查 Vim 是否支持 Python。


下面是用 Python 编写的 Reddit() 主函数:

 

" Vim comments start with a double quote." Function definition is VimL. We can mix VimL and Python in" function definition.function! Reddit() " We start the python code like the next line. python << EOF# the vim module contains everything we need to interface with vim from# python. We need urllib2 for the web service consumer.import vim, urllib2# we need json for parsing the responseimport json # we define a timeout that we'll use in the API call. We don't want# users to wait much.TIMEOUT = 20URL = "http://reddit.com/.json" try:  # Get the posts and parse the json response  response = urllib2.urlopen(URL, None, TIMEOUT).read()  json_response = json.loads(response)   posts = json_response.get("data", "").get("children", "")   # vim.current.buffer is the current buffer. It's list-like object.  # each line is an item in the list. We can loop through them delete  # them, alter them etc.  # Here we delete all lines in the current buffer  del vim.current.buffer[:]   # Here we append some lines above. Aesthetics.  vim.current.buffer[0] = 80*"-"   for post in posts:    # In the next few lines, we get the post details    post_data = post.get("data", {})    up = post_data.get("ups", 0)    down = post_data.get("downs", 0)    title = post_data.get("title", "NO TITLE").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")     # And here we append line by line to the buffer.    # First the upvotes    vim.current.buffer.append("↑ %s"%up)    # Then the title and the url    vim.current.buffer.append("  %s [%s]"%(title, url,))    # Then the downvotes and number of comments    vim.current.buffer.append("↓ %s  | comments: %s [%s]"%(down, comments, permalink,))    # And last we append some "-" for visual appeal.    vim.current.buffer.append(80*"-") except Exception, e:  print e EOF" Here the python code is closed. We can continue writing VimL or python again.endfunction            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表