A simple example of using Python to write a vim plug-in _python

Source: Internet
Author: User
Tags documentation eval function definition ibm developerworks


The Vim plug-in is a. Vim script file that defines functions, mappings, syntax rules, and commands that you can use to manipulate windows, buffers, and rows. A general plug-in contains the command definition and event hooks. When you write a vim plug-in using Python, the function is written using VIML, although VIML is quick to learn, Python is more flexible, for example, you can use Urllib/httplib/simplejson to access certain WEB services, which is why a lot of the need to visit The plug-ins that ask Web services are written using VIML + Python.




Before you start writing plug-ins, you need to make sure that Vim supports Python by identifying the following commands:


Copy Code code as follows:
Vim--version | grep +python






Let's go through a simple example to write a Vim plug-in in Python, which is used to get the Reddit home page information and display it on the current buffer.



First of all, in Vim, create a new Vimmit.vim file, we first need to determine whether to support Python, if you do not support the presentation message:


If!has (' python ')
  echo "error:required vim compiled with +python"
  finish
endif


The above code is written in Viml, and it checks to see if Vim supports Python.




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





" 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 = 20
URL = "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


Save the file with the following command


Copy Code code as follows:
: Source Vimmit.vim





Then call the plug-in:


Copy Code code as follows:
: Call Reddit ()





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





Copy Code code as follows:
command! -nargs=0 Reddit call Reddit ()





We defined the command: Reddit to call this function. The-nargs parameter declares how many parameters are in the command line.




Questions about function Parameters:



Q: How do I access parameters in a function?


function! Somename (Arg1, arg2, Arg3) "Get the" the "the" the "the", "the" the "the" the "argument" the Viml
 
  " Ent by position into VIML let
  secondarg=a:1
 
  "get" arguments in python
 
  python << EOF
  import vimfirst_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 by positional or named arguments, such as: (Arg1, arg2, ...)



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


Copy Code code as follows:
Vim.command ("[Vim-command-here]")





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



Global variables use a shape like g:. prefix, you should check whether the variable is defined before defining a global variable:


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


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


TIMEOUT = Vim.eval ("G:reddit_apicall_timeout")


You can reassign a global variable in the following ways:


Let g:reddit_apicall_timeout=60


For more information on using Python to write Vim Plug-ins, see the official documentation.




Note:



Once you've used VIML, you'll find that it's quite simple, and the code you write in Python can be implemented with it. Please refer to the Vim Python module documentation for details, which is an important reference.



In addition to the above documents, you can also find some useful information on the IBM Developerworks website.


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.