How to cancel recording a macro in Vim?

9

3

Imagine I had recorded a macro and then I've occasionally started recording a macro into the same register. Can I interrupt the recording so that the original macro is preserved in the register?

I know that I can do :let @b=@a to copy the macro from register a to register b and thus preserve it but maybe there is a more straightforward way?

Alexey

Posted 2013-10-28T13:38:05.723

Reputation: 263

Answers

7

When you record a macro, the register is emptied first and filled as you go so it's very unlikely that there exists a built-in way to save your previous macro while you are halfway through another recording. A way that doesn't involve writing a wrapper around q, that is.

I and a lot of people use a temporary register (@q, for example) for all our one-off recordings. Maybe you should, too.

romainl

Posted 2013-10-28T13:38:05.723

Reputation: 19 227

1Perhaps this behavior changed, I tested it with vim 7.4 and the register is available until I press q the second time. So :let @b=@a is imho the best answer so far. – Trendfischer – 2016-07-07T13:34:52.860

I like qm because I remember it with the mnemonic req*ord macro*. – Walf – 2018-07-03T00:46:46.470

3:let @b=@q definitely works, so it's not true that the register is cleared when you start recording a macro. And I do use q register for one-off macros. And it's most likely that I can occasionally override it. – Alexey – 2013-10-28T20:24:28.623

The register is cleared on the first keypress. Will you do the :let @b=@q dance every time you want to record a one off macro? That's what I was hinting at with my "wrapper" idea: write a short mapping that backs up @q each time you hit qq. It's very easy. But there's no built-in "record and backup" command. – romainl – 2013-10-28T21:27:06.133

6

As noted by @Trendfischer in his comment, the current behavior of vim is not (anymore?) to empty the register on the first press of q.

Now, if you picked the wrong register, here is what you can do:

  • do not quit the recording mode (for now),
  • create an empty line,
  • paste the register you are overwriting (if you're recording in the q register, it's "qp),
  • now quit the recording mode (q)
  • select the line you pasted above (without end of line mark: 0v$h; don't use V)
  • yank it in the register you have overwritten ("qy if you're using the q register; again: don't use the line wise copy Y).
  • now you have your old macro back in the register and you can restart the recording of your new macro in the correct register.

Of course, with a bit of effort, you can rescue both the old and the new macro (but you have to start the process before pressing the second time the q): just paste what you have recorded and yank in the "new"/"right" register.

a.l.e

Posted 2013-10-28T13:38:05.723

Reputation: 196