Explanation Python write Vim plugin

Source: Internet
Author: User

The Vim plugin is a. Vim script file that defines functions, mappings, grammar rules, and commands that can be used to manipulate windows, buffers, and rows. Typically a plug-in contains command definitions and event hooks. When using Python to write Vim plug-ins, the outside of the function is written using VIML, although Viml learned quickly, but Python more flexible, such as the use of Urllib/httplib/simplejson to access some WEB services, which is why many need to visit The plugin for WEB services is written using VIML + Python.


Before you start writing a plugin, you need to confirm that Vim supports Python by following these commands:

Vim--version | grep +python



We then use a simple example to learn how to write a Vim plugin in Python, which is used to get Reddit home information and display it on the current buffer.

First, in Vim new Vimmit.vim file, we first need to determine whether to support Python, if not support to give the prompt message:

1234 if!has(‘python‘)   echo "Error: Required vim compiled with +python"  finish endif

The above code is written in Viml, which will check if Vim supports Python.


Here is the Reddit () main function written in Python:


1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 " 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 = 20URL ="Codego.net"  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

Save the file using the following command

: Source Vimmit.vim


Then call the plugin:

: Call Reddit ()


This command is not easy to use, so let's define a command:


command! -nargs=0 Reddit call Reddit ()


We define the command: Reddit to call this function. The-nargs parameter declares the number of arguments in the command line.


Questions about function Parameters:

Q: How do I access parameters in a function?

1234567891011121314 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")

You can use ... To handle a variable number of parameters to replace a specific parameter name, which can be accessed through a location or named parameter, such as: (Arg1, arg2, ...)

Q: How do I invoke the Vim command in Python?

Vim.command ("[Vim-command-here]")


Q: How do I define global variables and access them in VIML and Python?

Global variables use a shape such as G:. prefix, you should check that the variable is defined before defining the global variable:


123 if!exists("g:reddit_apicall_timeout")   let g:reddit_apicall_timeout=40endif

You then access the variable in Python by using the following code:

1 TIMEOUT =vim.eval("g:reddit_apicall_timeout")

The global variables can be re-assigned by the following methods:

1 let g:reddit_apicall_timeout=60

For more information on using Python to write a Vim plugin, see the official documentation.

Codego.net Code Excerpt

Explanation Python write Vim plugin

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.