Five Minute Vimscript

This article is intended so that you can learn the basics of vimscript as quickly as possible. You might even be able to consider this to be a cheat sheet.

You should probably already know how to program before reading this.

Vim’s built in documentation is excellent. Try :h <searchterm> to read more inside Vim. You can start a REPL inside Vim by issuing the command gQ in normal mode if you want to play around with Vimscript.

Note: Examples may contain tokens resembling <token>. These are meant to be replaced completely, including the < and the >. Vimscript does use < and > as comparison operators.

Variables

let is used to set a variable.

unlet is used to unset a variable.

unlet! unsets a variable and surpresses the error if it doesn’t exist.

By default, a variable is scoped globally if it is initially defined outside a function or it is local to the function it was initialized in in. You can explicitly scope variables by prepending a specific prefix to their name:

Functions

Define a function with the function keyword. If you want to overwrite a function, use function! instead. Functions can be defined in a specific scope, just like variables.

Note:Functions names must start with a capital letter.

function!<Name>(arg1, arg2, etc)<function body>endfunction

delfunction <function> deletes a function.

call <function> executes a function and is required unless the call is part of an expression.

Example: Create global function Foobar forcefully (with !). including ... as the last arg creates variable length arg list. To fetch the first value from ..., use a:1. To get the second value, use a:2 and so on. a:0 is special and contains the number of arguments held in ....

There’s a special way to call functions, and that is on a range of lines from a buffer. Calling a function this way looks like 1,3call Foobar(). A function called with a range is executed once for every line in the range. In this case, Foobar is called three times total.

If you add the keyword range after the argument list, the function will only be called once. Two special variables will be available within the scope of the function: a:firstline and a:lastline. These variables contain the start and end line numbers for the range on the function call.

Example: Create buffer function RangeSize forcefully which will print out the size of the range it is called with.

function!b:RangeSize() range
echo a:lastline -a:firstline
endfunction

Classes

Vim doesn’t have classes built in, but you can get rudimentary class-like functionality by leveraging the Dictionary object. In order to define a method on a class, use the dict keyword in the function definition to expose the internal dictionary as self.