Macros and Registers

Vim's registers explained one by one, from the yank register to the expression register, then recording, editing and running macros across lines and files.

By The Dark DebuggerUpdated 20 min read

Registers are Vim's clipboards, and macros are recorded keystrokes stored in those same registers. This article covers every kind of register you'll meet, how to use them in Insert mode and on the command line, and then macros: recording, replaying over ranges and files, recursion, and editing a macro as plain text. It assumes the Ex commands and :normal from Ex Commands, Ranges, and :global and the buffer and argument-list material from Buffers, Windows, and Tabs.

Why this matters

You've been handed a CSV export of users and need SQL INSERT statements to seed a test database. Each line needs a prefix, quotes around three of the four fields, and a suffix. :s can do part of it, but the quoting logic makes the pattern ugly and hard to get right. Doing it by hand is fine for five lines and miserable for five hundred.

A macro is the middle ground: you do the edit once, by hand, while Vim records the keys, then replay it on every other line. Understanding registers is what makes macros reliable, and it also fixes the everyday annoyance of "I yanked something, deleted a line, and now p pastes the wrong thing".

The keystroke notation follows Vim's help: <Esc>, <CR> (Enter), <C-r> (Ctrl-R).

What a register is

A register is a named slot that holds text. Every yank, delete and change writes to one or more registers, and every put reads from one. You choose a register by typing " and its name before the command: "ayy yanks the line into register a, "ap puts it.

:registers (or :reg) shows the contents. Give it names to see only those. After yanking line 2 of an nginx upstream block and then deleting line 4:

upstream checkout {
    server 10.20.1.11:8080;
    server 10.20.1.12:8080;
    server 10.20.1.13:8080;
}
:reg "01
Type Name Content
  l  ""       server 10.20.1.13:8080;^J
  l  "0       server 10.20.1.11:8080;^J
  l  "1       server 10.20.1.13:8080;^J

Type is c for characterwise text, l for whole lines and b for a block. ^J is the newline at the end of a linewise register. The next sections go through each kind of register.

The unnamed register and the yank register

"" (the unnamed register) is what plain p uses, and it holds the text of the last yank or delete. That's the source of the classic surprise: in the example above, p after the dd puts the deleted .13 line, not the .11 line you yanked.

Register "0 (the yank register) only changes when you yank. Deletes never touch it. After the delete, "0p still put the yanked line:

    server 10.20.1.11:8080;
    server 10.20.1.12:8080;
}
    server 10.20.1.11:8080;

Remember "0p as "paste what I yanked, whatever I deleted since".

Numbered registers and the small-delete register

Deletes and changes of one line or more go into "1, and the previous contents shift down to "2, "3, up to "9. Deletes within a line go to "- (the small delete register) instead. I deleted three lines with dd three times, then } with dw:

Type Name Content
  l  "1       server 10.20.1.13:8080;^J
  l  "2       server 10.20.1.12:8080;^J
  l  "3       server 10.20.1.11:8080;^J
  c  "-   }

That makes "1 to "9 an undo history for deletions. There is a nice trick to browse it: "1p puts the most recent delete; if it's not the one you want, u then . repeats the put with the next register ("2p), and so on. On a file where I had deleted alpha, beta and gamma (in that order), the line below end went gamma, then beta after u., then alpha after another u..

Named registers: a to z, and appending with A to Z

The 26 named registers are yours. Nothing writes to them unless you say so, which makes them the place for text you want to keep while you do other things: "ayy, move around, delete freely, "ap.

Naming the register in uppercase appends to it instead of replacing it. Combined with :global, that collects lines from all over a file. Gathering the errors of a log into register a:

:call setreg('a', [])
:g/ERROR/y A

setreg('a', []) empties the register and marks it linewise; :y A then appends each matching line. G and "ap pasted the three errors at the bottom of the log:

2026-11-09 10:42:14 ERROR [db] deadlock detected on table orders
2026-11-09 10:42:05 ERROR [payment] provider timeout after 30000ms order=88412
2026-11-09 10:42:09 ERROR [payment] provider timeout after 30000ms order=88415
2026-11-09 10:42:14 ERROR [db] deadlock detected on table orders

The first line is the original last line of the log; the next three came from the register. The common shortcut for clearing a register, qaq (record an empty macro into a), leaves it empty but characterwise, and appending lines to that produced an extra blank line before the first error when I pasted. The setreg() form avoids it.

The black hole register "_

Text deleted into "_ goes nowhere, and every other register is left alone. Use it when you want to delete something without losing what you're about to paste:

primary = db-primary.internal
obsolete line
replica = PLACEHOLDER
gg$yiW      yank the hostname on line 1
j"_dd       delete the obsolete line into the black hole
$viWp       replace PLACEHOLDER with the yanked hostname
primary = db-primary.internal
replica = db-primary.internal

With a plain dd instead of "_dd, the deleted line became the unnamed register, and viWp replaced PLACEHOLDER with obsolete line on a line of its own.

The clipboard registers "+ and "*

"+ is the system clipboard (Ctrl+C / Ctrl+V in other programs) and "* the X11 primary selection (middle-click paste on Linux; on Windows and macOS both are the clipboard). They only work if your Vim was built with clipboard support. Check first:

vim --version | grep -o '[+-]clipboard'
-clipboard

The Vim package in my Ubuntu 24.04 lab is built without it, and it fails quietly: "+yy followed by :reg "+ showed the line in the unnamed register and nothing in "+. On Ubuntu, the vim-gtk3 package provides a terminal Vim with +clipboard. On WSL there is no X11 clipboard by default; a common workaround is piping a range to Windows with :'<,'>w !clip.exe, which I did not run here because it writes to the Windows host's clipboard.

With a clipboard-enabled build, set clipboard=unnamedplus makes every plain yank and put use "+, so Vim and other programs share one clipboard. I couldn't test that setting in the lab for the reason above.

Read-only registers: . % : /

Vim fills four registers for you, and you can only read them. After searching for deploying, adding a line with Go and echo "done", and writing the file with :w:

:reg .%:/
Type Name Content
  c  ".   echo "done"
  c  ":   w
  c  "%   deploy.sh
  c  "/   deploying
RegisterHolds
".the text you last inserted
"%the current file name
":the last command-line command (@: repeats it)
"/the last search pattern
"#the alternate file name

@: is worth remembering on its own: it repeats the last Ex command, and @@ repeats it again after that.

The expression register "=

"= evaluates a Vim expression and uses the result as text. In Insert mode, <C-r>= opens a prompt; type an expression and Enter, and the result is inserted. Filling in a cache TTL without reaching for a calculator:

cache_ttl_seconds =
released =
ggA<C-r>=60*60*24<CR><Esc>       compute one day in seconds
j$"=strftime("%F")<CR>p          put today's date after "released ="
cache_ttl_seconds = 86400
released = 2026-11-09

In Normal mode, "= followed by an expression and <CR> makes the result available to the next p, which is what the second line does.

Registers while typing: <C-r>

In Insert mode and on the command line, <C-r> followed by a register name inserts that register's contents: <C-r>0 the last yank, <C-r>a register a, <C-r>/ the last search, <C-r>% the file name. On the command line, <C-r><C-w> inserts the word under the cursor, which makes renaming a variable quick:

retry_count = 3
max_retry_count = 5
log("retry_count=%d", retry_count)
gg                                          cursor on retry_count
:%s/\<<C-r><C-w>\>/retry_limit/g<CR>        the command line shows :%s/\<retry_count\>/retry_limit/g
retry_limit = 3
max_retry_count = 5
log("retry_limit=%d", retry_limit)

max_retry_count is untouched thanks to the \< and \> word boundaries.

Recording and playing a macro

KeysAction
q{a-z}start recording into a register (the status line shows recording @q)
qstop recording
@{a-z}play the macro
@@play the last played macro again
5@qplay it five times
q{A-Z}record more keys onto the end of an existing macro

A first macro: quote each host name and add a comma, to turn a list into JSON array items.

web-01
web-02
web-03
api-01
api-02
qq          start recording into register q
0           start of the line, whatever column the cursor was on
i"<Esc>     opening quote
A",<Esc>    closing quote and comma at the end
j           move to the next line, ready for the next run
q           stop recording
100@q       play it "100 times"
"web-01",
"web-02",
"web-03",
"api-01",
"api-02",

100@q didn't run 100 times. On the last line, j failed, and a macro stops at the first command that fails. That makes an over-sized count a safe way of saying "until the end".

A macro is just text in a register

:reg q
Type Name Content
  c  "q   0i"^[A",^[j

^[ is how Vim displays the Escape key. Recording into q overwrites whatever register q held, and yanking into q overwrites the macro. Keep macros in a register you don't use for text, and q is popular for exactly that reason.

Making macros that survive the next line

A macro replays keys literally, so it works on the next line only if the next line is similar enough for the same keys to make sense. Rules that make a macro robust:

  1. Start from a known position. 0, ^, gg, or a search. Never assume the cursor is where it was when you recorded.
  2. Move by meaning, not by count. f,, t", w, e, /pattern<CR> adapt to different line contents; 7l does not.
  3. End where the next run should start, usually with j or a search, so counts and recursion work.
  4. Try it once with @q before running it on everything. u undoes a whole macro run.

Running a macro on many lines

A count replays the macro one run after another. For "every line in this range", :normal is often better, because it runs the macro once per line with the cursor at the start of that line, and a failure on one line doesn't stop the others:

:2,$normal @q
:'<,'>normal @q
:g/^web-/normal @q

The first form runs on line 2 to the end, the second on a Visual selection, the third only on lines matching a pattern. Because :normal positions the cursor for you, a macro used this way doesn't need the trailing j.

Recursive macros

A macro that calls itself at the end keeps going until something fails. It's an alternative to counts when you don't know how many matches there are. The register must be empty while you record, so the recursive call does nothing during recording:

qqq                 record nothing into q: empties it
qq0i-<Space><Esc>j@qq  the macro: bullet, next line, call itself
@q                  run it from line 2
- web-01
- web-02
- web-03
- api-01
- api-02

Line 1 was edited while recording; @q then ran through to the last line, where j failed and ended the recursion.

Recursion combines well with a search. With set nowrapscan, a search that reaches the end of the file fails instead of wrapping, which stops the macro cleanly. Converting only the web hosts in this list into nginx server lines:

# checkout upstream hosts
web-01
api-01
web-02
web-03
api-02
:set nowrapscan<CR>
gg
qqq
qq/^web-<CR>Iserver<Space><Esc>A:8080;<Esc>@qq
@q
# checkout upstream hosts
server web-01:8080;
api-01
server web-02:8080;
server web-03:8080;
api-02

The header line matters: a search from line 1 never matches line 1 itself, so a web host on the first line would be skipped.

Editing a macro as text

Re-recording a long macro to fix one key is tedious. Since it's text in a register, edit it as text. I recorded the quoting macro but forgot the comma (A"<Esc> instead of A",<Esc>):

Type Name Content
  c  "q   0i"^[A"^[j

The fix, step by step:

uu              undo the two changes the recording made to line 1
G:put q<CR>     put the macro on a new last line: 0i"^[A"^[j
$h              cursor on the second ^[ (Escape is one character)
i,<Esc>         insert the comma: 0i"^[A",^[j
0"qy$           yank the line back into q, without the newline
dd              delete the scratch line
:%normal @q<CR> run the fixed macro on every line
"web-01",
"web-02",
"web-03",
"api-01",
"api-02",

Two details matter. First, uu: recording changed line 1 twice (the opening quote and the closing quote are separate changes), so one u leaves a stray quote behind. Second, y$ instead of yy; see Common mistakes.

For short macros, :let is quicker. In a double-quoted string, \<Esc> becomes a real Escape:

:let @q = "0i\"\<Esc>A\",\<Esc>j"

And to add keys to the end of a macro, record in uppercase: qQjq appends a j to macro q.

A real job: CSV to SQL INSERT statements

id,email,name,plan
101,ana@example.com,Ana Lima,pro
102,raj.patel@example.org,Raj Patel,free
103,mei@example.net,Mei Chen,team
104,siobhan@example.ie,Siobhan O'Neill,pro
105,tom@example.com,Tom Berg,free

Look at the data before recording. O'Neill contains a single quote, which would end the SQL string early. SQL escapes it by doubling, so do that first for the whole file:

:%s/'/''/g

Then record on the first data row:

2G                                                  first data row
qq                                                  record into q
0IINSERT INTO users (id, email, name, plan) VALUES (<Esc>
f,a '<Esc>                                          after the id: ", '"
f,i'<Esc>la '<Esc>                                  close the email, open the name
f,i'<Esc>la '<Esc>                                  close the name, open the plan
A');<Esc>                                           close the plan and the statement
j                                                   next row
q                                                   stop
:3,$normal @q<CR>                                   every remaining row
:1d<CR>                                             drop the header
INSERT INTO users (id, email, name, plan) VALUES (101, 'ana@example.com', 'Ana Lima', 'pro');
INSERT INTO users (id, email, name, plan) VALUES (102, 'raj.patel@example.org', 'Raj Patel', 'free');
INSERT INTO users (id, email, name, plan) VALUES (103, 'mei@example.net', 'Mei Chen', 'team');
INSERT INTO users (id, email, name, plan) VALUES (104, 'siobhan@example.ie', 'Siobhan O''Neill', 'pro');
INSERT INTO users (id, email, name, plan) VALUES (105, 'tom@example.com', 'Tom Berg', 'free');

Every movement inside the macro is f, (to the next comma) or A (to the end), so it works whatever the length of each field. It would break on a field that contains a comma, as would any naive CSV handling; for real exports with quoted fields, use a CSV-aware tool.

Macros across files with :argdo

Three scripts need set -euo pipefail added after the shebang line:

==> scripts/backup.sh <==
#!/usr/bin/env bash
echo "backup: starting"

Open them all, record the edit in the first one, undo it there, and replay it in every file:

vim scripts/*.sh
qa ggjOset -euo pipefail<Esc> q      record: line 2, open a line above it, type
u                                    undo, so the first file isn't edited twice
:argdo execute "normal @a" | update<CR>
"scripts/backup.sh" 3L, 62B written
"scripts/restart-worker.sh" 3L, 70B written
"scripts/rotate-logs.sh" 3L, 67B written
==> scripts/backup.sh <==
#!/usr/bin/env bash
set -euo pipefail
echo "backup: starting"

(The spaces in the recording line are for readability; don't type them.) The execute "…" wrapper is required, and so is ggjO rather than the more obvious ggo. Both are explained in the next section.

Where you'll use this

  • Reshaping data: CSV to SQL or JSON, log lines to a table, a list of names to a config block. Record once, :normal @q over the range.
  • Repetitive refactors that :s can't express: wrapping arguments, reordering fields, edits that need several cursor movements per line.
  • Batch edits across files: :argdo execute "normal @q" | update for a header, a license line or a renamed import in every file of a project.
  • Keeping text around while you work: named registers for snippets you'll paste several times, "0p after deletes, "_d when the unnamed register must survive.
  • Typing less: <C-r>= for arithmetic, <C-r><C-w> for the word under the cursor in a :s command, <C-r>% for the file name.

Common mistakes

:normal @a | update eats the | update

My first attempt at the :argdo example was :argdo normal @a | update. Vim printed:

E353: Nothing in register "

and none of the files was written. :normal takes the rest of the line as keystrokes, so after running @a it went on to type |, a space, u (undo!), p (put from an empty register: E353), and so on. Wrap the keys in execute, which ends at the |: :argdo execute "normal @a" | update.

The recorded o added a comment character

My first recording used ggo to open a line below the shebang. In the shell script it produced:

#!/usr/bin/env bash
#set -euo pipefail

The sh file type treats # as a comment leader, and formatoptions contains o, which continues comments when you open a line with o or O from a comment line:

  formatoptions=croql  comments=:#

The shebang counts as a comment. Recording ggjO (open a line above line 2, which is not a comment) avoids it.

"qyy adds a newline to the macro

Yanking an edited macro back with yy makes it linewise, with a newline at the end:

Type Name Content
  l  "q   0i"^[A",^[j^J

^J is a newline, which in Normal mode moves down a line. Every run of the macro now moves down two lines. gg3@q on the host list quoted lines 1, 3 and 5 and skipped the others:

"web-01",
web-02
"web-03",
api-01
"api-02",

Yank with 0"qy$ (to the end of the line, without the newline).

Recording a recursive macro without clearing the register first

If q still holds an old macro when you record qq…@qq, the @q near the end runs the old macro during recording. With dd left in q from earlier, recording the bullet macro deleted web-02 as a side effect:

- web-01
web-03
api-01
api-02

Always start a recursive recording with qqq.

Expecting "+ to reach the system clipboard

On a -clipboard build, "+yy and "+p silently behave like the unnamed register. Check vim --version before debugging anything else.

Summary

  • "" holds the last yank or delete; "0 the last yank only, so "0p survives deletes.
  • Line deletes rotate through "1…"9; small deletes go to "-. "1pu.u. walks back through deleted text.
  • "a…"z are yours; uppercase appends. :call setreg('a', []) then :g/pat/y A collects matching lines.
  • "_ discards; "+/"* are the clipboard (only with +clipboard); . % : / are read-only; "= evaluates an expression. <C-r>{reg} inserts any of them while typing.
  • Record with q{reg}, play with @{reg}, @@ and counts. A macro stops at the first failing command, so 100@q means "until it fails".
  • Robust macros start from a known position, move with f, t, w or searches, and end where the next run starts. :{range}normal @q and :g/pat/normal @q apply them per line.
  • Macros are text: :put q, edit, 0"qy$; or :let @q = "…\<Esc>…"; qQ appends.
  • Across files: :argdo execute "normal @q" | update, never normal @q | update.

Exercises

Exercise 1: Paste what you yankedeasy

In this upstream block, you want to replace the two down servers with a copy of the healthy one. You yank line 2, delete lines 3 and 4 with jdddd, and press P. What do you get, why, and what should you have pressed?

upstream checkout {
    server 10.20.1.11:8080;
    server 10.20.1.99:8080 down;
    server 10.20.1.98:8080 down;
}
Show Solution

2Gyyjdddd followed by P put back the last deleted line:

upstream checkout {
    server 10.20.1.11:8080;
    server 10.20.1.98:8080 down;
}

The deletes overwrote the unnamed register. The yank register still had the healthy line, so "0P instead of P gives:

upstream checkout {
    server 10.20.1.11:8080;
    server 10.20.1.11:8080;
}
Exercise 2: Let Vim do the arithmeticeasy

A file contains max_body_bytes = (with a trailing space). Fill in 25 MiB in bytes without working it out yourself.

Show Solution
A<C-r>=25*1024*1024<CR><Esc>
max_body_bytes = 26214400
Exercise 3: CSV to JSON linesmedium

Turn this CSV into one JSON object per line, with a comma after every object except the last:

id,email,plan
101,ana@example.com,pro
102,raj.patel@example.org,free
103,mei@example.net,team

Target: {"id": 101, "email": "ana@example.com", "plan": "pro"},

Hint

s replaces the character under the cursor, which is a quick way to swap a comma for a longer separator.

Show Solution
:1d<CR>
qq0i{"id":<Space><Esc>f,s,<Space>"email":<Space>"<Esc>f,s",<Space>"plan":<Space>"<Esc>A"},<Esc>jq
:2,$normal @q<CR>
:$s/,$//<CR>
{"id": 101, "email": "ana@example.com", "plan": "pro"},
{"id": 102, "email": "raj.patel@example.org", "plan": "free"},
{"id": 103, "email": "mei@example.net", "plan": "team"}

The last command removes the trailing comma from the final object. The id stays unquoted because it's a number.

Exercise 4: A recursive macro that knows when to stopmedium

In the # checkout upstream hosts list from the recursion section, convert only the web- lines into server web-NN:8080; using a recursive macro, without counting the matches and without touching the api- lines.

Show Solution
:set nowrapscan<CR>
gg
qqq
qq/^web-<CR>Iserver<Space><Esc>A:8080;<Esc>@qq
@q
# checkout upstream hosts
server web-01:8080;
api-01
server web-02:8080;
server web-03:8080;
api-02

Without nowrapscan, the search would wrap to the top and keep going until it found no web- line at all, which happens to work here because converted lines no longer match. With a pattern that still matches after the edit, the macro would never run out of matches. nowrapscan makes the end of the file a hard stop.

Exercise 5: Fix a macro without re-recording ithard

You recorded qq0i"<Esc>A",<Esc>q on line 1 of the host list, forgetting the j, so 5@q keeps editing the same line. Add the missing j to the macro without retyping it, then quote the remaining lines.

Show Solution
qQjq             record in uppercase: appends "j" to register q (and moves to line 2)
:2,$normal @q<CR>
"web-01",
"web-02",
"web-03",
"api-01",
"api-02",

:let @q .= 'j' does the same from the command line. :normal runs the macro once per line, so the extra j doesn't cause lines to be skipped.


Tested with: Vim 9.1 (Ubuntu 24.04 package 9.1.0016, -clipboard) on Ubuntu 24.04 (WSL2), November 2026, started as vim -u DEFAULTS. Macros were recorded by sending real keystrokes, either replayed with vim -s or typed into Vim running under tmux (for everything involving undo); :reg listings are screen captures. The clipboard workaround with clip.exe was not run. The | update and comment-leader mistakes both happened on my first attempt at the :argdo example.

Was this page helpful?
The Dark Debugger

Written by The Dark Debugger

Engineer documenting the things that took me too long to learn, so they take you less time. Every Vim tutorial here is tested end to end before publishing.