Trying to solve a colleague's problem when editing Edje files, I pushed myself into learning how to do scripting inside Vim.
Scripting wasn't ever my choice for reasonably complex editing tasks since I refused to learn Yet Another Scripting Language just because my favorite editor wanted me to. But, for the sake of all lazy guys like me, Vim started to add python support, and python was a must learn bullet in my language listing.
However, not everything are flowers and the entry point must be configured using common vim script. Well, at least until vim supports python from its core, which - I believe - is not far from possible, since python integration has been voted as top priority for a long time.
To successfully import your python script inside vim context, one can wrap it into a vim function in an external file. Let's call it
" Title-ize sentences using python str methods function! PyMakeTitle() " the ! erases previous definitions python << END " here-document (bash-style), read 'till given word import vim w = vim.current.window b = vim.current.buffer line, col = w.cursor line -= 1 b[line] = b[line].title() # str.title() method END endfunction
:source extras.vim command to load it, one can call this function by typing
:call PyMakeTitle(). Remember repeating the
:source step every time the script gets updated.
The net effect of this function is to turn all initial word letters in the current line into capitals. It proved me to be useful when editing a large LaTeX document where all section titles were small letters only.
If it comes to be a very useful function, you may map it to a key-stroke by using
:nmap :call PyMakeTitle()<CR> inside your vimrc script.
A more complex example accessing internal vim properties. Ok, it's a bit useless, but it demonstrates well such features.
" Auto Documentation (example code) function! PyCreateDoc() python << END import vim name = vim.eval("expand(\"<cword>\")") # expand word under cursor ts = int(vim.eval("&ts")) # tab space property il = int(vim.eval("indent(\".\")")) # indentation on current line w = vim.current.window l, c = w.cursor docstr = '%s# @brief %s - write description' % (' ' * il, name) b = vim.current.buffer b[l-1:l-1] = [ docstr ] print 'Indent set is %d, cursor at (%d, %d)' % (ts, l, c) END endfunction
With the cursor over a function name, type
:call PyCreateDoc() and watch it insert a line above containing doxygen-like formatting.
For more examples, there is an excellent material at vim's online help (see
:h python). Furthermore, there are some plugins being made using only python, take a look at Omni Completion for Python (pythoncomplete.vim) for a good reference on the power of using python inside vim.
Happy Easter Vim'ing!