您的位置:首页 > 编程语言 > Python开发

使用 Python 编写 vim 插件

2012-10-18 00:00 549 查看
http://lib.open-open.com/view/open1330228856906.htmlhttp://vimdoc.sourceforge.net/htmldoc/if_pyth.html#python-vimvim 中输入 命令 python import vim在vim 的python 解释器中 引入 vim 当前的运行状态vim 模块两个 函数command 执行vim命令 eval 获得一个vim 的 状态值 例如 参数 值 a:0 buffers current 当前操作对象 属性 window buffer等window 当前窗口 vim map 设置 快捷键例如:map a=strftime("%c")将F2 映射成 在当前位置的后面插入 当前时间 的命令

在本地的 ~/.vimrc 文件可以配置 插件函数快捷键

例子:

vim 补全 单词的插件

在当前工程目录下面 有多个文件夹, 每个文件夹 有 多个 xxx.as 文件, 需要 在插入模式下 按下 ctrl + a 不全 当前光标所在位置的单词;

函数简单的返回第一个匹配的单词。

函数如下: 在ubuntu 12.04 系统, ~/.vim/plugin/文件夹中 新建 xxx.vim 放置下面的代码

function! CompleteAsWord()

if !exists("g:findMatches")

let g:findMatch = []

endif

python << EOF

import vim

import os

import re

word = re.compile('\w+')

cw = vim.current.window

p = cw.cursor

#find CurWord row col lastCol

def tranverse(cur, newPat):

f = os.listdir(cur)

ret = []

for i in f:

n = os.path.join(cur, i)

if os.path.isdir(n):

ret += tranverse(n, newPat)

elif n.find('.as') != -1 and n.find('swp') == -1:

li = open(n).readlines()

for l in li:

ws = newPat.findall(l)

if len(ws) > 0:

return ws

return ret

lastWord = word.findall(vim.current.buffer[p[0]-1])

if len(lastWord) > 0:

lastWord = lastWord[-1]

newPat = re.compile("%s\w+"%(lastWord))

mat = tranverse('.', newPat)

cw = vim.current.window

p = cw.cursor

if len(mat) > 0:

curLine = vim.current.buffer[p[0]-1]

vim.current.buffer[p[0]-1] = curLine[:p[1]-len(lastWord)+1]+mat[0]+curLine[p[1]+1:]

cw.cursor = (p[0], len(vim.current.buffer[p[0]-1]))

vim.command('let g:findMatch = ["%s", "%s"]'%(lastWord, mat[0]))

EOF

endfunction

#搞定了 函数之后 需要 在插入模式 map一下功能键

在 ~/.vimrc 文件中加入

imap <C-A> <Esc>:call CompleteAsWord()<CR>a

意思是插入模式 中 ctrl+a 键 映射的功能就是

esc 退出插入模式, 调用函数 回车 a 插入光标移到行最后

http://vimdoc.sourceforge.net/htmldoc/map.html#{rhs}

http://vimdoc.sourceforge.net/htmldoc/if_pyth.html

http://vimdoc.sourceforge.net/htmldoc/if_pyth.html#python-vim

http://vimdoc.sourceforge.net/htmldoc/eval.html#expression
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: