1

Sometimes I accidentally type ma instead of 'a and overwrite the mark I had at a instead of jumping there.

I know that by default vim has no way to undo an ma, but how can I add this functionality?

I want to be able to undo an accidental mark overwrite.

0

2 Answers 2

2

Here's some Vimscript that achieves your goal. To undo mark a, type <leader>ma.

There's various ways this could be tweaked/polished, but it should be a good starting point for a more robust solution.

nnoremap m :call UndoableMark()<CR>
nnoremap <leader>m :call UndoMark()<CR>

function! UndoableMark() abort
    let mark = nr2char(getchar())
    if mark =~ '\a'
        try
            execute 'let s:save_mark_' . mark . ' = getpos("''' . mark . '")'
        catch
        endtry
    endif
    execute 'normal! m' . mark
endfunction

function! UndoMark() abort
    let mark = nr2char(getchar())
    execute 'call setpos("''' . mark . '", s:save_mark_' . mark . ')'
endfunction
1

I am not sure this is a solution, as this might have too many nasty side effects. But one way to reset lost marks, is to re-read the viminfo file.

So after you have accidentally pressed ma, you can issue :rviminfo! to re-read the viminfo file. The ! causes it to overwrite all marks, registers, command-line histories, search history... from the current session (so this solution might not work all the time).

In fact, it should be possible to edit the viminfo file, just keeping the marks section, save it as a temporary file and then using :rviminfo! temp_viminfo_with_marks to just restore the marks for each particular file.