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

 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
vim编写python、python编写viml脚本、python编写vim插件、企业文化 编写示例、python代码示例,以便于您获取更多的相关知识。

时间: 2024-07-28 19:38:57

使用Python编写vim插件的简单示例_python的相关文章

使用Python的Scrapy框架编写web爬虫的简单示例_python

 在这个教材中,我们假定你已经安装了Scrapy.假如你没有安装,你可以参考这个安装指南. 我们将会用开放目录项目(dmoz)作为我们例子去抓取. 这个教材将会带你走过下面这几个方面:     创造一个新的Scrapy项目     定义您将提取的Item     编写一个蜘蛛去抓取网站并提取Items.     编写一个Item Pipeline用来存储提出出来的Items Scrapy由Python写成.假如你刚刚接触Python这门语言,你可能想要了解这门语言起,怎么最好的利用这门语言.假如

使用python开发vim插件及心得分享_python

vim有各种强大的插件,这不仅归功于其提供的用来编写插件的脚本语言vimL,还得益于它良好的接口实现,从而支持python等语言编写插件.当vim编译时带有+python特性时就能使用python2.x编写插件,+python3则支持python3.x,可以使用vim --version来查看vim的编译特性. 要使用python接口,可以用:h python来查看vim提供的帮助文档,本文做一个简单的介绍.我们都知道在vim里可以执行bash命令,只需要:!command即可,那么vim里可以

用map函数来完成Python并行任务的简单示例_python

众所周知,Python的并行处理能力很不理想.我认为如果不考虑线程和GIL的标准参数(它们大多是合法的),其原因不是因为技术不到位,而是我们的使用方法不恰当.大多数关于Python线程和多进程的教材虽然都很出色,但是内容繁琐冗长.它们的确在开篇铺陈了许多有用信息,但往往都不会涉及真正能提高日常工作的部分. 经典例子 DDG上以"Python threading tutorial (Python线程教程)"为关键字的热门搜索结果表明:几乎每篇文章中给出的例子都是相同的类+队列. 事实上,

python采用requests库模拟登录和抓取数据的简单示例_python

如果你还在为python的各种urllib和urlibs,cookielib 头疼,或者还还在为python模拟登录和抓取数据而抓狂,那么来看看我们推荐的requests,python采集数据模拟登录必备利器! 这也是python推荐的HTTP客户端库: 本文就以一个模拟登录的例子来加以说明,至于采集大家就请自行发挥吧. 代码很简单,主要是展现python的requests库的简单至极,代码如下: s = requests.session() data = {'user':'用户名','pass

使用Python编写Linux系统守护进程实例_python

守护进程(daemon)是指在UNIX或其他多任务操作系统中在后台执行的电脑程序,并不会接受电脑用户的直接操控.此类程序会被以进程的形式初始化.通常,守护进程没有任何存在的父进程(即PPID=1),且在UNIX系统进程层级中直接位于init之下.守护进程程序通常通过如下方法使自己成为守护进程:对一个子进程调用fork,然后使其父进程立即终止,使得这个子进程能在init下运行.–维基百科 守护进程区别于普通用户登陆系统后运行的进程,它是直接由系统初始化,和系统用户没有关系,而用户开启的进程依存与用

从Python程序中访问Java类的简单示例_python

from jnius import autoclass >>> Stack = autoclass('java.util.Stack') >>> stack = Stack() >>> stack.push('hello') >>> stack.push('world') >>> stack.pop() 'world' >>> stack.pop() 'hello' 上面的代码中,我们使用 auto

Python装饰器decorator的简单示例

  1,闭包(closure) 闭包是Python所支持的一种特性,它让在非global scope定义的函数可以引用其外围空间中的变量,这些外围空间中被引用的变量叫做这个函数的环境变量.环境变量和这个非全局函数一起构成了闭包.  代码如下   def outer(x):     y = [1,2,3]     def inner():         print x         print y     return inner x = 5    #这个x没有被引用 f = outer(2)

python实现绘制树枝简单示例_python

python是解释型语言,本文介绍了Python下利用turtle实现绘图功能的示例,本例所示为Python绘制一个树枝,具体实现代码如下:      python是解释型语言,本文介绍了Python下利用turtle实现绘图功能的示例,本例所示为Python绘制一个树枝,具体实现代码如下: import turtle def branch(length,level): if level<=0: return turtle.forward(length) turtle.left(45) bran

jquery插件制作简单示例说明_jquery

一.先从一个简单的实例,不需要带参数的一个方法开始 复制代码 代码如下: //创建一个匿名函数 (function($){ //给jQuery附加一个新的方法(详细见备注1) $.fn.extend({ //插件的名字 MyFirstName: function() { //迭代当前匹配元素集合 return this.each(function() { var obj = $(this); //自己的代码 }); } }); )(jQuery); 备注1:理解$.fn.extend和$.ext