merlin2011
merlin2011

Reputation: 75555

How can I cancel vim recording that has already started, so that it does not overwrite my previous recorded macro?

I accidentally hit qq instead of @q, and my vim is now recording into register q. If I type q again, it will overwrite the previously recorded macro.

Is there a way to either

  1. Cancel the recording so that the previous macro is not overwritten or
  2. Restore the previous macro without re-recording it from scratch?

Upvotes: 11

Views: 5148

Answers (3)

Ingo Karkat
Ingo Karkat

Reputation: 172540

Here is a mapping that aborts the current macro recording and restores the original register contents. Just use q! instead of q to end the macro recording.

" q!            Abort macro recording without changing the current one.
function! s:AbortMacroRecording()
    " We don't know which register is being recorded, so save them all and find
    " the one by comparing all values.
    let l:registers = split('abcdefghijklmnopqrstuvwxyz', '\zs')
    let l:savedRegisters = map(copy(l:registers), 'getreg(v:val)')

    " Abort macro recording.
    normal! q

    for l:idx in range(len(l:registers))
        let l:reg = l:registers[l:idx]
        let l:contents = l:savedRegisters[l:idx]
        if getreg(l:reg) !=# l:contents
            call setreg(l:reg, l:contents)
            echo printf('Aborted recording into register %s; macro is: %s', l:reg, strtrans(l:contents))
            return
        endif
    endfor

    echomsg "Couldn't detect recorded register"
endfunction
nnoremap <silent> q! :<C-u>call <SID>AbortMacroRecording()<CR>

Upvotes: 2

merlin2011
merlin2011

Reputation: 75555

I just found a less direct way of doing the thing same thing too, also based on the observation that the macro is not recorded until the second q.

I simply use "qp to paste the macro somewhere, and then use "qyy to yank it back in after I cancel the recording.

Upvotes: 3

rampion
rampion

Reputation: 89053

You can back the macro up into a different register:

:let @a=@q

Then the previous macro will be stored in register a, and available to be run as @a.

Upvotes: 13

Related Questions