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.


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.

| improve this answer | |

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'
            execute 'let s:save_mark_' . mark . ' = getpos("''' . mark . '")'
    execute 'normal! m' . mark

function! UndoMark() abort
    let mark = nr2char(getchar())
    execute 'call setpos("''' . mark . '", s:save_mark_' . mark . ')'
| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.