Do calculations with the expression register
You can do calculations in both normal mode and insert mode.
In normal mode, if you type
@= your cursor will move to the command line, where you can enter any expression. When you press enter, the result of the expression will be executed as normal mode commands.
For example, suppose you want to go to the middle column of the current line. The function call
col('$') returns the number of columns in the line, so we can accomplish what by typing the following:
When you press enter, the cursor returns to the buffer and vim waits for an operator (like
|) as though you had just entered a number. Alternatively, you could have entered this:
...but of course that's more bytes.
You can use the expression register in insert mode, too, by pressing
<Ctrl-r>= instead of
@=. It works the same in normal mode, except the result of the expression you enter will be executed in insert mode. For example, if you typed
<Ctrl-r>=col('$')<CR>, the number of columns in the current line would be inserted at the cursor as though you had typed it.
For more information on the expression register, type
The last expression you used is stored in the expression register,
@=<CR> in normal mode or
<Ctrl-r>=<CR> in insert mode will evaluate the expression again, allowing you to use them much like macros.
Do calculations in substitutions
You can evaluate expressions when doing regular expression substitutions, too. All you have to do is begin your substitution with
\=. For example, suppose you wanted to number the lines in this file:
The function call
line('.') returns the current line number, so the job is easy. Entering this:
...yields the desired result:
To use captured groups in such an expression you can use the
submatch() function, where e.g.
submatch(0) is equivalent to
\0 in an ordinary substitution,
submatch(1) is equivalent to
\1, etc. This eats up a lot of keystrokes, unfortunately.
For more information on expression substitution, type