Vim 插件是一個 .vim 的腳本文件,定義了函數(shù)、映射、語法規(guī)則和命令,可用于操作窗口、緩沖以及行。一般一個插件包含了命令定義和事件鉤子。當(dāng)使用 Python 編寫 vim 插件時,函數(shù)外面是使用 VimL 編寫,盡管 VimL 學(xué)起來很快,但 Python 更加靈活,例如可以用 urllib/httplib/simplejson 來訪問某些 Web 服務(wù),這也是為什么很多需要訪問 Web 服務(wù)的插件都是使用 VimL + Python 編寫的原因。
在開始編寫插件之前,你需要確認(rèn) Vim 支持 Python,通過以下命令來判別:
代碼如下:vim --version | grep +python
接下來我們通過一個簡單的例子來學(xué)習(xí)用 Python 編寫 Vim 插件,該插件用來獲取 Reddit 首頁信息并顯示在當(dāng)前緩沖區(qū)上。
首先在 Vim 新建 vimmit.vim 文件,我們首先需要判斷是否支持 Python,如果不支持給出提示信息:
if !has('python') echo "Error: Required vim compiled with +python" finishendif
上面這段代碼就是用 VimL 編寫的,它將檢查 Vim 是否支持 Python。
下面是用 Python 編寫的 Reddit() 主函數(shù):
" 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 responseimport json # we define a timeout that we'll use in the API call. We don't want# users to wait much.TIMEOUT = 20URL = "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
新聞熱點(diǎn)
疑難解答
圖片精選