Thanks everyone for reading along. I hope you’ve enjoyed reading these
tips as much as I’ve enjoyed writing them.
For the last installment, I wanted to share a very cool feature in VIM
that I am just beginning to learn how to use. VIM provides support for
Perl, Python and Ruby so that you can use these languages to create
functions in VIM.
I’m most familiar with Python myself, so here are a couple of examples.
In VIM, try the following:
:python print "Hello world"
You’ll see ‘Hello world’ show up in the status line at the bottom of the
screen. Cool, but not all that handy (though you can use this as a
quick calculator, e.g. :py print 256 * 8 ).
To actually get Python to do something interesting with the contents of
your editor, you can define a VIM function that uses Python to do the
heavy lifting.
Here’s how:
:function! PySort()
python << EOF
import vim
b = vim.buffers[0]
x = b[:]
x.sort()
b[:] = x
EOF
endfunction
The :function! line begins a function definition. VIM has its own
internal scripting language, which is swell and all, but if you already
have familiarity with one of the other supported languages, you can use
that language to get a jump start on seriously tricking out VIM.
The line:
python << EOF
tells VIM that we’re defining a block of Python code. The block will
end with the line “EOF”. The enclosed lines are pure Python.
First, we import the vim module:
import vim
Now we have access to that module’s components, like the buffers[]
list. Just like in normal Python, buffers[] is zero-indexed, so
buffers[0] is the first buffer.
Next, we copy the contents of b as a list into the variable x:
x = b[:]
Then we sort that list alphabetically:
x.sort()
Then we replace the current buffer with the sorted context of x:
b[:] = x
And voila – you can now sort the current buffer alphabetically by
calling the PySort() function:
:call PySort()
This is just a trivial example, but hopefully it gives you some ideas of
what can be done with Python (or Perl, or Ruby) inside of VIM.
To get more information about using scripts in VIM, try the following
help commands in VIM:
:help python-vim
:help perl
:help perl-using
:help ruby-vim
Thank you all for reading. Anyone interested in exploring any of the
topics discussed in this or previous tips should feel free to contact me.
Happy VIMming!
