使用 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网站找到一些有用的资料

本文中的所有译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们

使用 Python 编写 vim 插件的更多相关文章

  1. python开发vim插件

    [python开发vim插件] 按如下方式使用python开发vim插件,注意调用时使用的是exec. 但在函数中嵌入python代码更为简便,如下: python如何传递参数给python: 代码头 ...

  2. 使用python制作ArcGIS插件(2)代码编写

    使用python制作ArcGIS插件(2)代码编写 by 李远祥 上一章节已经介绍了如何去搭建AddIn的界面,接下来要实现具体的功能,则到了具体的编程环节.由于使用的是python语言进行编程,则开 ...

  3. vim 插件管理

    1 进入自己的vim mkdir ./bundle/vundle 2 在vimrc同级中执行 git clone https://github.com/gmarik/vundle.git ./bund ...

  4. 【转载】跟我一起学习VIM - vim插件

    目录 写在前面:Life Changing Editor 什么是VIM 为什么选VIM 为什么选其它 为什么犹豫选择它们 VIM >= SUM(现代编辑器) 如何学习VIM 一秒钟变记事本 VI ...

  5. 跟我一起学习VIM - vim插件合集

    2016-06-14 15:04 13333人阅读 评论(0) 收藏 举报 分类: Linux(104)  目录(?)[+]  前两天同事让我在小组内部分享一下VIM,于是我花了一点时间写了个简短的教 ...

  6. 多语言编程必备的十大 Vim 插件

    原文地址:http://www.linuxeden.com/a/58769 使用这 10 个 Vim 插件,可以让你在写代码或运维时,感觉更棒. 我使用 Vim 文本编辑器大约 20 年了.有一段时间 ...

  7. 基于python编写的天气抓取程序

    以前一直使用中国天气网的天气预报组件都挺好,可是自从他们升级组件后数据加载变得非常不稳定,因为JS的阻塞常常导致网站打开速度很慢.为了解决这个问题决定现学现用python编写一个抓取程序,每天定时抓取 ...

  8. 使用pathogen管理Vim插件并托管到Github

    参照文章[1][2]的办法,将vim打造成一个Python开发环境.文章中使用的是 pathogen + git 来管理 Vim 插件的.对这种方式还不太明白的同学可以参考[3]中的介绍.pathog ...

  9. [译]Python编写虚拟解释器

    使用Python编写虚拟机解释器 一.实验说明 1. 环境登录 无需密码自动登录,系统用户名shiyanlou,密码shiyanlou 2. 环境介绍 本实验环境采用带桌面的Ubuntu Linux环 ...

随机推荐

  1. Tomcat启动时报 java.lang.OutOfMemoryError: Java heap space

    见效的解决方法如下:   在myeclipse中修改jvm启动的参数 打开Myeclipse -->windows-->preference-->myeclipse->serv ...

  2. apue.h文件找不到的解决办法

    参考:http://blog.csdn.net/nihaotoyou/article/details/16827675 1.首先到该书的官网下载源代码:http://www.apuebook.com/ ...

  3. 【网络爬虫】Httpclient4.X中使用HTTPS的方法采集12306网站

    HttpClient请求https的实例: package train; import java.io.IOException; import java.security.NoSuchAlgorith ...

  4. JVM Specification 9th Edition (2) Chapter 1. Introduction

    Chapter 1. Introduction 翻译太累了,我就这样的看英文吧. 内容列表 1.1. A Bit of History 1.2. The Java Virtual Machine 1. ...

  5. Spring的核心机制——依赖注入(Dependency Inject)

    Spring不仅提供对象,还提供对象的属性值,而不是由使用该对象的程序所提供的. Java应用是由一些相互协作的对象所组成的,在Spring中这种相互协作的关系就叫依赖关系. 如果A组件调用了B组件的 ...

  6. UVALive 3942 Remember the Word 字典树+dp

    /** 题目:UVALive 3942 Remember the Word 链接:https://vjudge.net/problem/UVALive-3942 题意:给定一个字符串(长度最多3e5) ...

  7. Xcode模拟iPhone教程!

    iOS 开发者常常会使用模拟器来进行调试,当然这就少不了Mac电脑中的Xcode软件了,今天PC6小编就给大家带来在Mac系统下如何快速启动iOS模拟器的使用教程: 一.如何启动iOS模拟器 1.在L ...

  8. yum 安装出错--"Couldn't resolve host 'mirrors.aliyun.com'"

    1.yum 安装出错 [root@iz25m0z7ik3z ~]#yum install mysql [root@iZ25m0z7ik3Z ~]#yum install mysql Loaded pl ...

  9. Unity3D脚本:C#计时类脚本

    Unity3D脚本:C#计时类脚本  unity3D更多资源教程免费下载,群153442627using UnityEngine;using System.Collections;/// <su ...

  10. Hourrank 21 Tree Isomorphism 树hash

    https://www.hackerrank.com/contests/hourrank-21/challenges/tree-isomorphism 题目大意: 给出一棵树, 求有多少本质不同的子树 ...