GuidesOpen Source Software Scripting in Vim

Open Source Software Scripting in Vim

ServerWatch content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

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.

Get even more out of the open source software editor, Vim, by taking advantage of its scripting capabilities.

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()
imap ,u :call SingleUnderline()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.

Juliet Kemp has been messing around with Linux systems, for financial reward and otherwise, for about a decade. She is also the author of “Linux System Administration Recipes: A Problem-Solution Approach” (Apress, 2009).

Follow ServerWatch on Twitter

Get the Free Newsletter!

Subscribe to Daily Tech Insider for top news, trends & analysis

Latest Posts

Related Stories