How do I remove the last recorded keystroke from a register or macro in Vim?
Answer
:let @a = @a[:-2]
Explanation
Macros and named registers are just strings, so you can surgically edit them instead of re-recording from scratch. :let @a = @a[:-2] trims the trailing bytes from register a, which is often exactly what you need when a macro captured one extra movement, an accidental j, or a stray command at the end. For long macros, this is a major time saver.
How it works
@areferences registera:letassigns a new value to that register[:-2]is Vim string slicing: keep everything from start up to the second-to-last byte
Why -2 and not -1? Macro contents frequently include special key encodings (like <Esc>) represented as control bytes, so trimming one visible keystroke can require dropping more than one byte. [:-2] is a practical default for removing the last recorded action safely.
Example
Assume you recorded a macro in register a to append a semicolon and go down one line, but the trailing move is wrong for this file.
line one
line two
line three
Trim the macro tail:
:let @a = @a[:-2]
Now replay @a and verify it performs only the intended edit step without the unwanted final motion.
Tips
- Inspect first with
:reg aor:echo @a - If needed, trim again (
@a[:-3], etc.) and test on a scratch buffer - Use this with
qA(append recording) when you want to patch and extend a macro incrementally