GoByte Skills Episode 27 of 27, track Vim (3 of 3)

Vim macros: a register full of keystrokes

GoByte Skills #27: a Vim macro is just keystrokes in a register. Record once with qa, paste it as text, edit it, yank it back, then run it on every line. The only program whose bug report reads: it did exactly what I did.

Zoe is one of GoByte's characters. This post was drafted by AI agents in Zoe's voice, then fact checked, run and edited by the GoByte team.

Back to top

A macro is just keystrokes saved in a register, so you can record, edit as text and run it on every line. qa starts recording into register a, q stops, @a replays. Vim writes the register when q stops, not key by key: until then a holds its old contents, which is why a recursive macro starts with qaq to empty it. There is no macro language: the register holds the keys, and Vim feeds them back as if you typed them.

Animation for GoByte Skills #27: A recording is replayed down a list of lines.
Transcript

Keystrokes typed after qa edit the first name while register a stays empty, q writes them into the register in one go, and the register then replays down the list, turning each plain line into a JSON style entry.

Record on line 1, then replay on the rest:

qaI"<Esc>ea":<Esc>A,<Esc>jq
:2,$normal @a
before    after
ada 36    "ada": 36,
bob 41    "bob": 41,
cy 29     "cy": 29,

It is only text#

:put a pastes the register into the buffer:

I"^[ea":^[A,^[j

^[ is the Escape you pressed. Edit that line like any other (say :s/,/;/), then 0"ay$ yanks it back and the next @a runs the new version. Recording and yanking share the same registers, which is also the trap: a later "ayy overwrites your macro.

Two ways to run it#

  • 100@a replays until a motion fails. The trailing j fails on the last line and the replay stops, so overshooting the count is safe.
  • :2,$normal @a runs it once per line, with the cursor in the first column, and a failure only aborts that line.

The boundary#

  • A replay starts wherever the last one ended. Use keys that carry their own position (I, A, 0, f,) and avoid counts of l that assume a column.
  • The macro is blind. It runs the keys you typed, not the intent you had, so a line with a different shape gets the same keystrokes and a different result.
  • Mappings apply during replay too. Record with your real config, replay with the same one.

Rule of thumb#

Record on one line, replay on one more, look, then run it on the rest. A macro is a program you write by doing the job once, and the only program whose bug report reads "it did exactly what I did".

Report a mistake

Your product here? Partner with us

Back to top

Discussion

No comments yet. Signed in GoByte members with a verified e-mail can join. Community guidelines

Reading is open to everyone. Commenting and voting need a GoByte account with a verified e-mail.