zondag 20 mei 2007

python scripting in vim (1)

This is a short tutorial about writing vim scripts in python.
This tutorial is for everyone who likes vim and python.

Preperations:

To write vim scripts in python you need to have vim compiled with +python

Fedora/CentOS: vim-enhanced
Debian/Ubuntu: vim-python

Let's get started:

first a thing about how you can use python for vim-scripting,
you can set these things in your ~/.vimrc
  • autocmd FileType python [commands]
    Run commands when this type of file is edited
  • python [python code]
    Evaluate the python code given
  • python << EOF
    Read python code untill the EOF
  • pyfile [filename]
    Read python commands from a python file
  • map [keys] [command]
    Run the specified command when the key(s) are pressed
Simple start...

"first tutorial hello world
imap & :python pythonHelloWorld()
python << EOF

#start the function
def pythonHelloWorld():
import vim #so you can use the vim functions
buffer = vim.current.buffer #returns the current buffer
buffer[0] = "hello world"
#sets the first line of the buffer to "hello world"

EOF

What we have so far
a line starting with " is a comment in the .vimrc

imap & :python pythonHelloWorld()

press the & in insert mode to execute the command :python pythonHelloWordl(), notice the so you leave insert mode and go to the command mode.

python << EOF

everything between these lines will be read as python code


slightly improved version
We will improve the previous version so that we insert the "hello world" line before the current line, so we don't overwrite anything.

def pythonInsertHelloWorld():
import vim
buffer = vim.current.buffer
#returns the row and column of the current cursor
#position
(row, col) = vim.current.window.cursor
#python starts numbering from 0, vim from 1.
#insert line above current cursor position
#the argument must be a list, or it won't work
buffer[row-1:row-1] = ["hello world"]
EOF


and further...
this was the first really basic tutorial, more will follow soon, but you should have a start now.
If you have questions, see mistakes or have comments, please add your reaction.


see also:
about python scripting:http://www.tummy.com/Community/Presentations/vimpython-20070225/vim.html
in vim :help python
help about map: http://www.linux.com/article.pl?sid=06/06/08/1431210