Do calculations with the expression register
You can do calculations in both normal mode and insert mode.
Normal 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:
@=col('$')/2<CR>|
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:
@=col('$')/2.'|'
...but of course that's more bytes.
Insert mode
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 :help "=
.
Reusing expressions
The last expression you used is stored in the expression register, "=
. Typing @=<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:
foo
bar
baz
The function call line('.')
returns the current line number, so the job is easy. Entering this:
:s/^/\=line('.').' '/g<CR>
...yields the desired result:
1 foo
2 bar
3 baz
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 :help sub-replace-expression
.