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 插件的说明请看官方文档。

时间: 2024-07-31 22:44:35

python编辑写vim脚本例子的相关文章

utf-8-在linux环境下,用vim写.py脚本时,print中文

问题描述 在linux环境下,用vim写.py脚本时,print中文 我在linux环境下,用vim写.py脚本时,print中文时,运行不成功,查了查网友说要加# -*- coding:utf-8 -*-,但不是说#后的无效吗 ?这是什么意思呢 解决方案 一些解释器,使用注释来添加私有的功能 这样的好处是,这些功能是非标准的,因为写在注释里面,用不兼容的解释器执行,直接忽略掉,而不会丢出错误来.保证了兼容性的同时,实现了额外的功能扩展. 很多语言都用了类似的技术,比如ie浏览器解释html有自

Python批量按比例缩小图片脚本分享

  这篇文章主要介绍了Python批量按比例缩小图片脚本分享,本文直接给出实现代码,需要的朋友可以参考下 图片太大了,上百张图用photoshop改太慢,就想到用python写个简单的批处理.功能简单就是把原图按比例缩小 代码如下: # -*- coding: cp936 -*- import Image import glob, os #图片批处理 def timage(): for files in glob.glob('D:1*.JPG'): filepath,filename = os.

完善坛子工具库之--python版memcached遍历脚本

今天看到robbin大哥用ruby写了一个遍历memcached的脚本,由于自己不用ruby就鳴发了用python也写一个的想法,说做就做,虽然功能上没有ruby版的强憾,不过也可以凑合用一下. 这个python版本还可以继续优化.代码如下: import socket, StringIO ''''' @author: ahuaxuan @date: 2008-10-22 ''' class mcstats(object): def __init__(self, address, port):

Python复制目录结构脚本代码分享_python

引言 有个需要,需要把某个目录下的目录结构进行复制,不要文件,当目录结构很少的时候可以手工去建立,当目录结构复杂,目录层次很深,目录很多的时候,这个时候要是还是手动去建立的话,实在不是一种好的方法,弄不好会死人的.写一个python脚本来处理吧. 首先了解 写python脚本前,先了解几个东西 复制代码 代码如下: #!/usr/bin/python 这个东西写过脚本的人都知道,用来标明该脚本的执行器,类似的还有 复制代码 代码如下: #!/bin/bash       通过bash来执行 #!

python中多线程的一个例子总是报错大家帮忙看看

问题描述 python中多线程的一个例子总是报错大家帮忙看看 解决方案 http://bbs.csdn.net/topics/390614709 解决方案二: ...找到原因了是t2里的args函数名没写对.............,还是谢谢各位了

unix-Solaris 10 写一个脚本,在atc用户下,调用该脚本,执行poweroff命令

问题描述 Solaris 10 写一个脚本,在atc用户下,调用该脚本,执行poweroff命令 Solaris 10 写一个脚本,在atc用户下,调用该脚本,执行poweroff命令 解决方案 实现一个脚本,然后atc用户执行 解决方案二: 实现一个脚本,然后atc用户执行

JSP中读文件和写文件的例子

js 读文件的例子***************************************************<%@ page contentType="text/html;charset=gb2312"%><%//变量声明\java.lang.String strFileName; //文件名java.io.File objFile; //文件对象java.io.FileReader objFileReader; //读文件对象char[] chrBuff

性能测试-LR12打不开VS上用C#写的脚本

问题描述 LR12打不开VS上用C#写的脚本 性能测试-LR12打不开VS上用C#写的脚本-lr性能测试结果分析"> 做了个C/S的性能测试,但是用LR12打开脚本的时候,报这个错误,用LR11打开却可以,请问各位大神,这个肿么破? 解决方案 http://bbs.51testing.com/thread-1044655-1-1.html

数据库服务器-如何写一个脚本把数据库中包含”伊利“两个字的数据全查出来?

问题描述 如何写一个脚本把数据库中包含"伊利"两个字的数据全查出来? 之前有一个"伊利"的项目,现在新的项目要复用他的数据库,但是数据库中的数据不能 出现"伊利"两个字的数据,如何写一个脚本把包含"伊利"的数据全查出来呢?求指导,万分感谢 .