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
"first tutorial hello world
imap &
python << EOF
#start the function
def pythonHelloWorld():
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 &
press the & in insert mode to execute the command :python pythonHelloWordl(), notice the
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():
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"]
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