Vim’s expression register and macros

The video below shows a little trick using the expression register.
First you need to know that in Vim you cannot only paste register values in normal mode. It is also possible in insert mode using <C-r> and the register name.
So <C-r>” insert the default unnamed register in insert mode. This also works in command line mode. The next thing to know is the expression register ‘=’. When inserting this, Vim does not insert the register value directly as with other registers. Instead Vim shows an equal sign and enters a special command prompt at the bottom. Here you can type any expression including Vimscript functions. When hitting <CR> Vim evaluates this expression and replaces the equal sign place holder in your file with the result.

What I’m showing in the video is the following: qqvt=yA <C-r>=<C-r>”<CR>j0q

| keystrokes | description                                     |
| qq         | start recording and store macro in register 'q' |
| vt=y       | visual select till '=' and yank the selection   |
| A <C-r>=   | append at the and of line, insert ' ' and       |
|            | insert the expression register                  |
| <C-r>"<CR> | paste what we have yanked before in the         |
|            | command prompt and hit <CR>                     |
| j0q        | go one line down, goto start of line and        |
|            | stop recording                                  |

Now we can replay the macro using: 22@q
This replays the recored macro 22 times. Note, that the macro replaying will stop when the search operation “t=” fails. This way we don’t need to count the number of lines. We just need a number that is huge enough and 22 is handy to type 😉

See “:h registers” in Vim help for an overview about the available registers.

0 Responses to “Vim’s expression register and macros”

  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: