A simple example of writing the vim plug-in using Python

Source: Internet
Author: User
This article mainly introduces a simple tutorial on compiling the vim plug-in using Python. An example of getting the reddit homepage information and displaying it in the buffer zone is provided in this article. For more information, see the Vim plug-in. the vim script file defines functions, ING, syntax rules, and commands, which can be used for Operation windows, buffering, and rows. Generally, a plug-in contains command definitions and event hooks. When using Python to compile the vim plug-in, the function is written outside VimL. although VimL is fast to learn, Python is more flexible. for example, you can use urllib/httplib/simplejson to access some Web services, this is why many plug-ins that need to access Web services are written using VimL + Python.


Before writing the plug-in, you must confirm that Vim supports Python and use the following command to determine whether the plug-in is supported:

The code is as follows:

Vim -- version | grep + python


Next, we will use a simple example to learn how to compile the Vim plug-in Python. this plug-in is used to obtain the Reddit homepage information and display it on the current buffer.

First, create a vimmit. Vim file in vim. First, we need to determine whether Python is supported. if not, the following message is displayed:

if !has('python')  echo "Error: Required vim compiled with +python"  finishendif

The above code is written in VimL. it will check whether Vim supports Python.


The main function of Reddit () written in Python is as follows:


" 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

Run the following command to save the file:

The code is as follows:

: Source vimmit. vim

Then call the plug-in:

The code is as follows:

: Call Reddit ()

This command is not easy to use, so we define another command:

The code is as follows:

Command! -Nargs = 0 Reddit call Reddit ()

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


Questions about function parameters:

Q: How do I access parameters in a function?

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 a variable number parameter to replace a specific parameter name, which can be accessed by location or named parameter, such as: (arg1, arg2 ,...)

Q: How to call the Vim command in Python?

The code is as follows:

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

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

The global variable uses a prefix such as g:. before defining a global variable, check whether the variable has been defined:

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

Then you can access this variable in Python using the following code:

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

You can assign a value to a global variable using the following method:

let g:reddit_apicall_timeout=60

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.