vimtricks.wiki Concise Vim tricks, one at a time.

How do I remove accidental Enter keystrokes from a recorded macro?

Answer

:let @q = substitute(@q, '\n', '', 'g')

Explanation

A common macro failure mode is accidentally hitting <CR> while recording. That inserts newline keystrokes into the register and can make replay jump unpredictably or execute extra commands. Instead of re-recording from scratch, you can surgically clean the macro text in place by editing the register value with substitute().

How it works

  • @q is the raw content of register q (your macro)
  • substitute(@q, '\n', '', 'g') removes every newline character from that string
  • :let @q = ... writes the cleaned result back to the same macro register

Because macros are just register strings, this technique is deterministic and repeatable. It is particularly useful when the macro is long and re-recording would be expensive.

Example

Suppose @q accidentally contains an embedded newline while you intended one continuous command chain. Run:

:let @q = substitute(@q, '\n', '', 'g')

Now replay with @q and confirm behavior is linear again.

Tips

  • Inspect first with :echo string(@q) so hidden newline escapes are visible.
  • If you only want to drop a trailing <CR>, use slicing instead: :let @q = @q[:-2].
  • Apply the same pattern to other macro registers (@a, @b, etc.) by changing the register name.

Next

How do I paste the unnamed register after transforming it to uppercase?