Open Source Software Scripting in Vim

By Juliet Kemp (Send Email)
Posted Aug 9, 2010

More about Vim and open source software

I've been using the open source editor Vim for an alarming number of years now, but I only very recently encountered its scripting capabilities. Here I'll look at writing a quick script in Vim's built-in scripting language. You can also use another scripting language if you prefer.


Vimscript is function-based. Here's an example of a function to put in your ~/.vimrc that puts a single text underline (a row of dashes) under the current line. Note that function names must start with a capital letter to distinguish them from built-in functions.

function! SingleUnderline()

The first line copies (:t, a synonym for :copy) the current line (.) to the line below it. The second line substitutes - for all characters in the new line, using the substitute function. In a function, you don't need to use : to call a built-in function.

Next, you must be able to call the function. Start up Vim, write a line, hit ESC, then type

:call SingleUnderline()

(Vim will tab-complete function names for you.) The current line should now be underlined.

However, that's a lot of typing for a short function! Instead, you can set up a mapping, again in your ~/.vimrc:

nmap ,u :call SingleUnderline()<CR>
imap ,u <ESC>:call SingleUnderline()<CR>o

The first line maps ,u to the SingleUnderline() command in Normal mode; the second deals with calling it from Insert mode, then returning to Insert mode afterwards on a newline underneath.

This is a fairly simple example, but Vim functions can get about as complex as you like. Check out the list of built-in functions by type to help you construct your own functions; there's also a bunch of scripting tips on the Vim wiki.


Follow ServerWatch on Twitter

Page 1 of 1

Comment and Contribute

Your name/nickname

Your email

(Maximum characters: 1200). You have characters left.