Vim undo: undo changes after file write

25,904

There's persistent undo option in vim, :h persistent-undo
Note: It was introduced in VIM 7.3 version, so for earlier versions, it will not work.

It can be turned on by placing following text in your .vimrc:

if has('persistent_undo')      "check if your vim version supports it
  set undofile                 "turn on the feature  
  set undodir=$HOME/.vim/undo  "directory where the undo files will be stored
  endif     

Note: Before enabling this option, whatever that was lost, remains lost.
After enabling the option, you will be able to do subsequent undo/redo on whatever was added/deleted after enabling the option.

Share:
25,904
brokenfoot
Author by

brokenfoot

Full stack developer programming in C/C++, python, bash LinkedIn Blog Github

Updated on September 24, 2020

Comments

  • brokenfoot
    brokenfoot over 3 years

    In my code on vim, I did a lot of changes and then did a ZZ (save and exit). But then I realized I didn't need those changes. Is there a way I can get back to the state before doing those changes using from some buffer where that data still might be stored. I haven't made any changes after the save & exit.

  • Searene
    Searene almost 7 years
    Notice that you have to make sure the directory exists to make it work.
  • ka3ak
    ka3ak over 5 years
    I'm not sure why this answer was accepted. I have the same situation as asked in the question, but I still don't understand how it solves the problem. The setting seems to work only for new files/changes.
  • Miron Veryanskiy
    Miron Veryanskiy about 5 years
    You can make sure the directory exists by adding a statement silent !mkdir -p ~/.vim/undo inside the if-block. This solution assumes you have write permissions to create the directory ~/.vim/undo.