32

Undo is nice to have in Vim. But sometimes, at a known good point, I want to erase my undo history - to be able to use u to undo individual changes, but only back to a certain point. (For instance, this might be when I last committed.)

One way to accomplish this would be to close and reopen the file - the undo history starts clean at that point. But that's a hassle.

In the past, I accomplished this with :edit!. But in Vim 7.3, that doesn't discard the undo history.

Is there another way to do this, apart from closing the file?

Nathan Long
  • 27,435

6 Answers6

16
:set undoreload=0 | edit

should do what you're asking for.

n.r.
  • 103
Steven
  • 176
9

The old :edit! behaviour in a one-liner:

:exe "set ul=-1 | e! | set ul=" . &ul
Aldrik
  • 926
6

Benoit's function didn't work for me, but I found something similar in the vim manual, here:

http://www.polarhome.com/vim/manual/v73/undo.html#undo-remarks

I slapped it into a function, added to my vimrc and it seems to be working fine on vim 7.3:

" A function to clear the undo history
function! <SID>ForgetUndo()
    let old_undolevels = &undolevels
    set undolevels=-1
    exe "normal a \<BS>\<Esc>"
    let &undolevels = old_undolevels
    unlet old_undolevels
endfunction
command -nargs=0 ClearUndo call <SID>ForgetUndo()

This can be used with :ClearUndo.

Nathan Long
  • 27,435
Nycto
  • 161
5

Probably:

:let old_ul=&ul
:set ul=-1
:let &ul=old_ul
:unlet old_ul

('ul' is alias for 'undolevels').

Benoit
  • 7,113
4

" Clear undo history (:w to clear the undo file if presented)
command! -bar UndoClear exe "set ul=-1 | m-1 | let &ul=" . &ul

  • When you set 'undolevels' to -1 the undo information is not immediately cleared, this happens at the next change, i.e. m-1, which doesn't actually change your text.
  • When 'undofile' is on, :w to clear the undo file, or chain like UndoClear|w.
Bohr
  • 544
1

In a script:

function! <SID>ForgetUndo
     let old_ul = &ul
     set ul=-1
     let &ul = old_ul
     unlet old_ul
endfunction
command -nargs=0 Reset call <SID>ForgetUndo()

Then use :Reset to call it.

Benoit
  • 7,113