34

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.

Philip Kirkbride
  • 21,381
  • 38
  • 125
  • 225
brokenfoot
  • 11,083
  • 10
  • 59
  • 80

1 Answers1

60

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 the 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 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.

gerrard00
  • 1,628
  • 14
  • 17
brokenfoot
  • 11,083
  • 10
  • 59
  • 80
  • 8
    Notice that you have to make sure the directory exists to make it work. – Searene Jun 22 '17 at 00:08
  • 1
    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. – ka3ak Sep 05 '18 at 15:07
  • 1
    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`. – Miron Veryanskiy Apr 03 '19 at 21:24