71

If I'm working in a file, change to another buffer, and then change back, I have lost my undo history.

  1. vim File1.txt - make a bunch of changes & save.
  2. Open new buffer - :e test.txt
  3. Switch back to File1.txt - :b#
  4. Undo history is gone.

Any workarounds for this?

Matthias Braun
  • 32,039
  • 22
  • 142
  • 171
Brian
  • 3,571
  • 7
  • 44
  • 70
  • This has caught me unawares more than once. I suspect you're asking because `:sp test.txt` or `:tabe test.txt` won't work for you? – dash-tom-bang Apr 28 '10 at 18:54
  • Yes. I don't use tabs because I find that just having one vertical split is easiest to manage. If need be I'll do more splits, but the main issue is I'm constantly switching buffers and eventually want to go back to a previous buffer and undo something. If I know I'm going to be editing a file a lot and may need undo, then I try not to switch the buffer on that window - but sometimes I forget. – Brian Apr 28 '10 at 20:23

2 Answers2

85

You could :set hidden. This means that the buffer of the old file will only be hidden when you switch to the new file. When you switch back, you still have your undo history.

Rüdiger Hanke
  • 6,215
  • 2
  • 38
  • 45
  • 5
    the vim I love otherwise, sucks here a little bit :( The ":set hidden" option should be ON by default. – Tem Pora Dec 05 '14 at 13:44
70

You can also add persistent undo, this will have vim store your undo even through restart:

" Persistent undo
set undofile
set undodir=$HOME/.vim/undo

set undolevels=1000
set undoreload=10000

Edit - via @sanbor:

Don't forget to do mkdir ~/.vim/undo, otherwise vim won't do it for you.

jorgeh
  • 1,727
  • 20
  • 32
Aaron Jensen
  • 6,030
  • 1
  • 30
  • 40
  • 3
    Don't forget to do `mkdir ~/.vim/undo`, otherwise vim won't do it for you. Source: http://stackoverflow.com/questions/5700389/using-vims-persistent-undo – sanbor Jul 02 '15 at 14:36
  • 1
    @Patrick Because it's not better. I often do spontaneous changes in a file and save by habit only to soon wipe unproven rubbish with an Undo series. Digging up undos from before opening the file (~recent stable state) would be horrible! – bloody Apr 16 '20 at 23:12