Clear undo history in Vim

2 minute read 2019-07-13 Ashkan Kiani -

The Answer

" Clear undo history
function! ClearUndo()
  let save_cursor = getpos(".")
  " Inspired by: https://superuser.com/a/688962/301551
  " Disable undo level, move line 0 to ., move it back, clear modified, restore undo
  " Resets position to 0, though
  exe "setl ul=-1 | 0m. | m0 | set nomodified | set ul=".&ul
  " Fix the cursor messed up by the above.
  call setpos(".", save_cursor)
endfunction

The Question

I'm making an interface for a program whereby I make a virtual file and use BufReadCmd to create the content, kind of like vidir for directories, netrw for network directories, and tar.vim for .tar* files (vim can view tar files, by the way).

When I create this virtual file, it starts with an undo history back to a blank file, but I didn't like that. I wanted it to appear as if the file always existed, which meant clearing the undo list. It turns out Vim doesn't support this natively, so I went searching.

After reading this superuser thread, I found a few snippets, but they actually didn't work great for me. When you set undolist=-1, it will clear the undo history on the next edit, which meant triggering an edit.

This particular answer this superuser answer was intriguing, but, unfortunately, :m-1 isn't effective in my version of Neovim. Perhaps it's smart enough to not update the edit list for invalid edits. So that left me with the end result.

Many of the answers recommended e!, but edit! has side effects, which I wanted to avoid. 0m. and m0 is a no-op except for the cursor position, which we can easily reset.


published in programming and tagged vim , snippets and neovim