Use Python to develop vim plugins and share experiences

Source: Internet
Author: User
Vim has a variety of powerful plugins, not only thanks to the scripting language VIML it provides for writing plugins, but also thanks to its good interface implementation, which supports writing plugins in languages such as Python. When Vim is compiled with +pythonfeature, you can write a plug-in using python2.x. +python3Python3.x is supported, you can use vim --versionTo view the compilation characteristics of Vim.

To use the Python interface, you can use it :h python to view the help documentation provided by VIM, a simple introduction to this article. We all know that in vim you can execute a bash command, just :!command so you can execute a python statement in vim? Of course, VIM is so powerful! Isn't it, right?!

Execute Python command in vim

You can use it in vim py[thon] {stmt} to execute the python statement {stmt}, which you can :python print "Hello World!" verify.

You can only execute a single statement, no use, right? So there are more powerful interfaces, the syntax is as follows:

Py[thon] << {endmarker}
{Script}
{Endmarker}

This allows us to execute the contents of the Python script, {script}. {Endmarker} is a marker symbol and can be anything, but {Endmarker} cannot have any white space characters after it. Look at a simple example, assuming the following code is saved as Script_demo.vim:

function! Foo()
python << EOF
class Foo_demo:
def __init__(self):
print 'Foo_demo init'
Foo_demo()
EOF
endfunction

So in vim we first load the :source path_to_script/script_demo.vim script, then we can :call Foo() run the Python script, the whole process:

In addition, we can put the Python script in a separate. py file, and then use it pyf[ile] {file} to run the program in the Python file, note that all parameters behind Pyf[ile] are considered to be the name of a file.

VIM Module

We can already execute Python commands in vim, but how does Python get some of the information in vim? For example, I want to know how many lines of vim are in the current buffer, and then get the contents of the last line, what do you do with Python?

So vim provides a Python module, and interestingly, the module name is called Vim, and we can use it to get all the information in the Vim editor. The above problem can be solved with the following Python script:

function! Bar()
python << EOF
import vim
cur_buf = vim.current.buffer
print "Lines: {0}".format(len(cur_buf))
print "Contents: {0}".format(cur_buf[-1])
EOF
endfunction

You can load the script yourself and run the witness miracle! The above code appears vim.current.buffer , presumably you have guessed the meaning of it from the name, but let's look at it in detail:

Constants in the VIM module

Vim.buffers: The list object used to access the buffer in Vim can do the following:

:py b = vim.buffers[i]    # Indexing (read-only)
:py b in vim.buffers # Membership test
:py n = len(vim.buffers) # Number of elements
:py for b in vim.buffers: # Iterating over buffer list

Vim.windows: The list object used to access the window in Vim, and the basic phase of the operation supported by Vim.buffers.

Vim.current: A variety of information used to access the current location in Vim, such as:

Vim.current.line
Vim.current.buffer
Vim.current.window
Vim.current.tabpage
Vim.current.range

Vim.vvars: A dictionary-like object used to store either the Global (g:) variable or the VIM (V:) variable.

There are some other constants that are not described here. Note that the constants here are not real constants, and you can assign them again. However, we should avoid doing this because it will lose the value referenced by that constant. So far we've been able to get data from vim and then manipulate it with Python, which seems perfect.

But Vim doesn't stop there, it does Stronger than Stronger ! Because we can use VIM's powerful command set in Python, we can write some common batch plugins in Python, and see the following simple example:

function! Del(number)
python << EOF
import vim
num = vim.eval("a:number")
vim.command("normal gg{0}dd".format(num))
vim.command("w")
EOF
endfunction

You can call the above function del (n) to delete the contents of the top n rows of the current buffer (just an example, don't do it in the real world!). The eval and command functions are used as follows:

Two main methods in the VIM module

vim.command(str): Executes the command in Vim str (ex-mode, Command mode command), the return value is None, for example:

:py vim.command("%s/aaa/bbb/g")

You can also use vim.command("normal "+str) the command in normal mode, for example, to delete the contents of the current line with the following command:

:py vim.command("normal "+'dd')

vim.eval(str): Use the interpreter inside the vim to calculate the contents of STR, the return value can be a string, a dictionary, or a list, such as the value of the computed 12+12:

:py print vim.eval("12+12")

The settlement result 24 is returned.

The previous Del function also provides a number parameter, which can be used in VIML let arg=a:number and used in Python vim.eval("a:number") . It can also be accessed by parameter location, such as Let arg=a:0 or Vim.eval ("a:0"). We can use the "..." instead of a named parameter to define a function that can receive any number of arguments, but it can only be accessed by location.

The Vim module also provides a 异常处理对象vim.error simple example of a Vim.error exception that will be triggered when an error occurs when using the Vim module, as follows:

try:
vim.command("put a")
except vim.error:
# nothing in register a

Objects provided by the Vim module

Here you can basically use Python to perform basic operations on the buffer, such as deleting a row or adding content to a specified line. However, adding content in the buffer is not pythoner, because you have to use command to invoke Vim's i/i/a/a command. Fortunately there is a more scientific way, that is, using the objects provided by the Vim module to operate, see the following simple example:

function! Append()
python << EOF
import vim
cur_buf = vim.current.buffer
lens = len(cur_buf)
cur_buf.append('" Demo', lens)
EOF
endfunction

The APPEND function adds the comment content at the end of the current buffer " Demo , what is the buffer object for a while?

Buffer Object

The VIM module provides a buffer object that allows us to manipulate the buffer, which has two read-only properties name and Number,name for the current buffer file (containing the absolute path) and number for the buffer. There is also a bool property, valid, that identifies whether the associated buffer is erased.

Buffer objects are available in the following ways:

B.append (STR): Inserts a new row below the current line with the contents of Str;b.append (str, n): Inserts a new line below the nth line, with the contents of Str;b.append (list)
B.append (list, N): Inserts multiple lines into the buffer; B.range (s,e): Returns a range对象 content that represents the S-to-e line in the buffer.

Note When you use append to add a new row str, you must not include the newline character "\ n" in Str. STR can have "\ n" at the end, but it will be ignored.

The range method of the Buffer object returns a Range object to represent the portion of the buffer content, and then the Range object has those properties and methods? In fact, the Range object and the buffer object are basically the same, except that the Range object operates on the specified area. The Range object has two properties, start and end, which are the start and end rows of the Range object. Its methods are R.append (str), R.append (str, n) and R.append (list), R.append (list, n).

We can vim.windows get the Window object in vim by using the properties of the Window object, because it does not provide a method or other interface to manipulate it. The read-only attribute has buffer, number, tabpage, and so on, reading and writing properties are cursor, height, width, valid and so on. You can see Help for details:h python-window

  • 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.