使用 Python 編寫 vim 插件

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 映射成 在當前位置的後面插入 當前時間 的命令html

 

在本地的 ~/.vimrc 文件能夠配置 插件函數快捷鍵python

 

例子:express

vim 補全 單詞的插件ubuntu

在當前工程目錄下面 有多個文件夾, 每一個文件夾 有 多個 xxx.as 文件, 須要 在插入模式下 按下 ctrl + a 不全 當前光標所在位置的單詞;vim

函數簡單的返回第一個匹配的單詞。函數

函數以下: 在ubuntu 12.04 系統, ~/.vim/plugin/文件夾中 新建 xxx.vim 放置下面的代碼.net

 

function! CompleteAsWord() 插件

if !exists("g:findMatches")htm

    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 插入光標移到行最後
相關文章
相關標籤/搜索