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.
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.
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@areplays until a motion fails. The trailingjfails on the last line and the replay stops, so overshooting the count is safe.:2,$normal @aruns 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 oflthat 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".
Your product here? Partner with us
Back to topDiscussion
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.