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


Posted in Python onApril 17, 2015

 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"
  finish
endif

上面这段代码就是用 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 response
import json
 
# we define a timeout that we'll use in the API call. We don't want
# users to wait much.
TIMEOUT = 20
URL = "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

使用如下命令保存文件
 

:source vimmit.vim

然后调用该插件:
 

:call Reddit()

这个命令用起来不那么方便,因此我们再定义一个命令:

command! -nargs=0 Reddit call Reddit()

我们定义了命令:Reddit来调用这个函数。-nargs 参数声明命令行中有多少个参数。

关于函数参数的问题:

问:如何访问函数中的参数?
 

function! SomeName(arg1, arg2, arg3)
  " Get the first argument by name in VimL
  let firstarg=a:arg1
 
  " Get the second argument by position in Viml
  let secondarg=a:1
 
  " Get the arguments in python
 
  python << EOF
  import vim
 
  first_argument = vim.eval("a:arg1") #or vim.eval("a:0")
  second_argument = vim.eval("a:arg2") #or vim.eval("a:1")

你可以使用 ... 来处理可变个数参数来替换特定的参数名,可通过位置或者命名参数来访问,如:(arg1, arg2, ...)

问:如何在 Python 中调用 Vim 命令?
 

vim.command("[vim-command-here]")

问:如何定义全局变量,并在 VimL 和 Python 中访问?

全局变量使用形如 g:. 的前缀,定义全局变量前应该检查该变量是否已定义:
 

if !exists("g:reddit_apicall_timeout")
  let g:reddit_apicall_timeout=40
endif

然后你通过下面代码在 Python 中访问这个变量:
 

TIMEOUT = vim.eval("g:reddit_apicall_timeout")

可通过下面的方法来对全局变量进行重新赋值:
 

let g:reddit_apicall_timeout=60

更多关于使用 Python 编写 Vim 插件的说明请看官方文档。

备注:

一旦你用过VimL,就会发现它挺简单的,你用python写的代码也可以用它来实现。详细请参考vim python模块文档,这是一份重要的参考资料。

除了上述文档,你也可以在IBM developerWorks网站找到一些有用的资料。

Python 相关文章推荐
python实现随机密码字典生成器示例
Apr 09 Python
介绍Python中几个常用的类方法
Apr 08 Python
Python中字符串的格式化方法小结
May 03 Python
python list转矩阵的实例讲解
Aug 04 Python
python3 读取Excel表格中的数据
Oct 16 Python
python后端接收前端回传的文件方法
Jan 02 Python
Python-ElasticSearch搜索查询的讲解
Feb 25 Python
Django学习笔记之为Model添加Action
Apr 30 Python
使用Python自动生成HTML的方法示例
Aug 06 Python
PyCharm 专业版安装图文教程
Feb 20 Python
Pytorch转keras的有效方法,以FlowNet为例讲解
May 26 Python
Python本地及虚拟解释器配置过程解析
Oct 13 Python
用Python登录Gmail并发送Gmail邮件的教程
Apr 17 #Python
基于Python实现的百度贴吧网络爬虫实例
Apr 17 #Python
python中dir函数用法分析
Apr 17 #Python
python传递参数方式小结
Apr 17 #Python
使用70行Python代码实现一个递归下降解析器的教程
Apr 17 #Python
python类继承与子类实例初始化用法分析
Apr 17 #Python
python中split方法用法分析
Apr 17 #Python
You might like
PHP基础之运算符的使用方法
2013/04/28 PHP
php实现cookie加密的方法
2015/03/10 PHP
Zend Framework上传文件重命名的实现方法
2016/11/25 PHP
建议大家看下JavaScript重要知识更新
2007/07/08 Javascript
jQuery DOM操作小结与实例
2010/01/07 Javascript
js控制div弹出层实现方法
2015/05/11 Javascript
浅谈JavaScript中的对象及Promise对象的实现
2015/11/15 Javascript
基于jQuery实现带动画效果超炫酷的弹出对话框(附源码下载)
2016/02/22 Javascript
纯js代码制作的网页时钟特效【附实例】
2016/03/30 Javascript
javascript运算符语法全面概述
2016/07/14 Javascript
jQuery+CSS3实现四种应用广泛的导航条制作实例详解
2016/09/17 Javascript
详解百度百科目录导航树小插件
2017/01/08 Javascript
jQuery的三种bind/One/Live/On事件绑定使用方法
2017/02/23 Javascript
jQuery阻止移动端遮罩层后页面滚动
2017/03/15 Javascript
slideToggle+slideup实现手机端折叠菜单效果
2017/05/25 Javascript
JS跨浏览器解析XML应用过程详解
2020/10/16 Javascript
详解javascript脚本何时会被执行
2021/02/05 Javascript
python使用urllib模块开发的多线程豆瓣小站mp3下载器
2014/01/16 Python
Python去除列表中重复元素的方法
2015/03/20 Python
python实现手机通讯录搜索功能
2018/02/22 Python
对Python 除法负数取商的取整方式详解
2018/12/12 Python
Django实现跨域请求过程详解
2019/07/25 Python
Ubuntu18.04安装 PyCharm并使用 Anaconda 管理的Python环境
2020/04/08 Python
css3背景图片透明叠加属性cross-fade简介及用法实例
2013/01/08 HTML / CSS
Brasty波兰:香水、化妆品、手表网上商店
2019/04/15 全球购物
德国亚马逊官方网站:Amazon.de
2020/11/15 全球购物
计算机大学生的自我评价
2013/10/15 职场文书
吸烟检讨书2000字
2014/02/13 职场文书
点菜员岗位职责范本
2014/02/14 职场文书
清明节扫墓活动方案
2014/03/02 职场文书
《欢乐的泼水节》教学反思
2014/04/22 职场文书
大学生应聘求职信
2014/05/26 职场文书
经济贸易专业自荐信
2014/06/11 职场文书
纪念一二九运动演讲稿
2014/09/16 职场文书
幼儿园秋季开学通知
2015/07/16 职场文书
Python集合的基础操作
2021/11/01 Python