Use Python to develop a vim plug-in and experience sharing _python

Source: Internet
Author: User
Tags stmt python script in python

Vim has a variety of powerful plug-ins, not only because of the scripting language that it provides to write plug-ins, but also because of its good interface implementation, which supports the writing of plug-ins in languages such as Python viml. When vim compiles with +python features and uses python2.x to write plug-ins, it +python3 supports python3.x, which you can use vim --version to view the compilation features of Vim.

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

Execute Python command in vim

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

You can only execute a single statement, it's useless, isn't it? So there is a more powerful interface, the syntax is as follows:

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

So we can execute the contents of the Python script {scripts}. {Endmarker} is a tag symbol that 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 use :source path_to_script/script_demo.vim to load the script, and then we can :call Foo() run the Python script, and the whole process looks like this:

In addition, we can put the Python script in a separate. py file, and then run the pyf[ile] {file} program in the Python file, and note that all the 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 rows the current buffer of vim has, and then get the last line of content, what do you do with Python?

So vim provides a Python module, and interestingly the module name is called Vim, which we can use 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 your own script to run the witness miracle! The above code appears vim.current.buffer , you must have guessed it from the name of the meaning of it, but let's have a detailed look at it:

Constants in the VIM module

Vim.buffers: A list object used to access the buffers in vim, you 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: A list object used to access windows in Vim, and the basic phase of operations 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 global (g:) variables or vim (V:) variables.

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

But Vim does not stop here, but it Stronger than Stronger ! Because we can use VIM's powerful command set in Python, we can write some common batch plug-ins in Python and look at 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 function del (n) above to delete the contents of the first n rows of the current buffer (just an example, don't do it in reality!). The eval and command functions are used above, as follows:

Two main methods in the VIM module

vim.command(str): Executes the command str (ex-mode, command-mode command) in Vim, and returns none of the values, such as:

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

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

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

vim.eval(str): Using Vim's internal interpreter to compute the contents of STR, the return value can be a string, a dictionary, or a list, such as a value that calculates 12+12:

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

The settlement result is returned 24.

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 "..." instead of a named parameter to define a function that can receive any number of arguments, but this can only be accessed by location.

The Vim module also provides a 异常处理对象vim.error simple example of a Vim.error exception when an error occurs when using a VIM module:

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

The objects provided by the Vim module

Here you can basically use Python to do basic operations on buffers, such as deleting rows or adding content to a specified line. Adding content to the buffer is not pythoner, however, because you have to use command to invoke Vim's i/i/a/a command. Fortunately there is a more scientific way to do this using the objects provided by the Vim module, and look at 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 comment content at the end of the current buffer. " Demo What's the matter with the buffer object?

Buffer Object

The VIM module provides a buffer object that lets us manipulate the buffer, which has two read-only property name and Number,name as the name of the current buffer file (contains an absolute path) and number is the quantity of the buffer. There is also a bool attribute valid that identifies whether the relevant buffer is erased.

There are several ways to buffer objects:

B.append (STR): Inserts a new row below the current line, with Str;b.append (STR, n): Inserts a new row below the nth line, and the content is str;b.append (list)
B.append (list, n): Inserting multiple rows into a buffer; B.range (s,e): Returns a range对象 representation of the contents of S to e in the buffer.

Note When you add a new line of STR using append, str must not contain a newline character "\ n". The Str end can have "\ n", but it will be ignored.

The range method of the Buffer object returns a Range object that represents the portion of the buffer content, what about the Range object and the method? In fact, the Range object and the buffer object are basically the same on the operation, except that the Range object operates on the specified range. The Range object has two properties, start and end, which are the starting and ending 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 manipulating it only through the properties of the Window object because it does not provide a method or other interface to operate. The read-only property has buffer, number, tabpage, and so on, read and write properties have cursor, height, width, valid and so on. Help can be viewed specifically: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.