使用 Python 编写 vim 插件
使用 Python 编写 vim 插件 - 技术翻译 - 开源中国社区
code {margin: 0;padding: 0;white-space: pre;border: none;background: transparent;}
.TextContent pre code{background-color: transparent;border: none;}
.TextContent ol,.TextContent ul {margin:20px 0 20px 20px;list-style-position: inside;}
.TextContent ol{list-style-type:decimal;margin: 0.5em 0 0.5em 1.5em;}
.TextContent ul{list-style-type:disc;margin: 0.5em 0 0.5em 1.5em;}
.TextContent img{max-width: 980px;}
.links{margin-top:1em;padding:1.25em 0;color:#666;}
.links a, .copyright a {color:#666;}
.links p{margin: 0; padding: 0;}
.copyright{padding:1.25em 0; border-top: 1px solid #AAA;color:#666;}
-->
使用 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: 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网站找到一些有用的资料。
本文地址:http://www.oschina.net/translate/how-to-write-vim-plugins-with-python
原文地址:http://brainacle.com/how-to-write-vim-plugins-with-python.html
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们
使用 Python 编写 vim 插件的更多相关文章
- python开发vim插件
[python开发vim插件] 按如下方式使用python开发vim插件,注意调用时使用的是exec. 但在函数中嵌入python代码更为简便,如下: python如何传递参数给python: 代码头 ...
- 使用python制作ArcGIS插件(2)代码编写
使用python制作ArcGIS插件(2)代码编写 by 李远祥 上一章节已经介绍了如何去搭建AddIn的界面,接下来要实现具体的功能,则到了具体的编程环节.由于使用的是python语言进行编程,则开 ...
- vim 插件管理
1 进入自己的vim mkdir ./bundle/vundle 2 在vimrc同级中执行 git clone https://github.com/gmarik/vundle.git ./bund ...
- 【转载】跟我一起学习VIM - vim插件
目录 写在前面:Life Changing Editor 什么是VIM 为什么选VIM 为什么选其它 为什么犹豫选择它们 VIM >= SUM(现代编辑器) 如何学习VIM 一秒钟变记事本 VI ...
- 跟我一起学习VIM - vim插件合集
2016-06-14 15:04 13333人阅读 评论(0) 收藏 举报 分类: Linux(104) 目录(?)[+] 前两天同事让我在小组内部分享一下VIM,于是我花了一点时间写了个简短的教 ...
- 多语言编程必备的十大 Vim 插件
原文地址:http://www.linuxeden.com/a/58769 使用这 10 个 Vim 插件,可以让你在写代码或运维时,感觉更棒. 我使用 Vim 文本编辑器大约 20 年了.有一段时间 ...
- 基于python编写的天气抓取程序
以前一直使用中国天气网的天气预报组件都挺好,可是自从他们升级组件后数据加载变得非常不稳定,因为JS的阻塞常常导致网站打开速度很慢.为了解决这个问题决定现学现用python编写一个抓取程序,每天定时抓取 ...
- 使用pathogen管理Vim插件并托管到Github
参照文章[1][2]的办法,将vim打造成一个Python开发环境.文章中使用的是 pathogen + git 来管理 Vim 插件的.对这种方式还不太明白的同学可以参考[3]中的介绍.pathog ...
- [译]Python编写虚拟解释器
使用Python编写虚拟机解释器 一.实验说明 1. 环境登录 无需密码自动登录,系统用户名shiyanlou,密码shiyanlou 2. 环境介绍 本实验环境采用带桌面的Ubuntu Linux环 ...
随机推荐
- 设计模式_CallBack
一.基本概念 if you call me, i will call back 什么是回调函数 回调函数(callback Function),顾名思义,用于回调的函数. 回调函数只是一个功能片段, ...
- 3.2 Zend_Db_Select
10.4. Zend_Db_Select 你能够使用该对象和它的对应方法构建一个select查询语句,然后生成 字符串符用来传送给zend_db_adapter进行查询或者读取结果. 你也能够在你的查 ...
- flink on yarn部分源码解析 (FLIP-6 new mode)
我们在https://www.cnblogs.com/dongxiao-yang/p/9403427.html文章里分析了flink提交single job到yarn集群上的代码,flink在1.5版 ...
- JAVA工具类 UUID
UUID:通用惟一识别:Universally Unique Identifier: 在一台机器上生成的数字,它保证对在同一时空中的所有机器都是唯一的. GUID是一个128位长的数字,一般用16进制 ...
- IntelliJ IDEA代码编码区提示库源不匹配字节码解决办法
在使用IntelliJ IDEA进行开发时,可能会在代码编辑区出现此提示:library source does not match the bytecode for class HelloWorld ...
- 跟着百度学PHP[14]-PDO-优化驱动
使用方法设置预定义变量 PDO的方法/属性 PDO::beginTransaction — Initiates a transaction PDO::commit — Commits a transa ...
- libubox
lbubox是openwrt的一个核心库,封装了一系列基础实用功能,主要提供事件循环,二进制格式处理,linux链表实现和一些JSON辅助处理. 它的目的是以动态链接库方式来提供可重用的通用功能,给其 ...
- iOS学习笔记9 - 组件库介绍1
总算成功开发完了第一个较大的功能(即时通信).毕竟不可能什么东西都从轮子开始造,于是用到了一些组件,这里简单列举一下吧. 1. FMDB 作为一种文件型的数据存储方式,SQLite在iOS开发中自然也 ...
- 【原创】jpgraph中文乱码问题的解决
php jpgraph库非常强大,可以在后台生成图片 后台生成在需要导出图表型报告的时候非常有用,当然,前端的可视化还是要用highcharts/echarts/anycharts等类库 比较麻烦的是 ...
- php安装redis扩展初始化失败解决办法
错误信息如下: PHP Warning: PHP Startup: redis: Unable to initialize module Module compiled with module API ...