How do I deal with vim buffers when switching git

2019-07-07 00:39发布

问题:

So, I've got a ton of files open in my vim buffer, and I'm working on a feature branch with git. Suddenly, I realize that I need to revert back to my master branch to make a quick fix.

After making my commits, I leave my vim session open and switch back over to the master branch. However, when I try and load the files I need from the buffer, I now get the message

Warning: File "<filename>" has changed since editing started

This makes complete since to me. The file in the buffer is from my feature branch, and now that I have switched back to master branch, there are understandably some deltas to deal with.

My question is, how is this situation dealt with on a professional level?

Thinking of solutions, I could just close all the buffers and re-open the files. However, I was hoping there is a "smart" way to do this. Is there a way to replace the files in the current vim buffer with their counterparts in the desired branch? Is there a way of maintaining multiple buffers, one per git branch?

Ultimately, I want to be able to switch between git branches, and have the open vim session just "know" which version of the file should currently reside in the buffer.

Part of this is that I am still learning about how vim buffers work, and have just started to use them extensively. So if I made any assumptions that don't hold, please correct me where appropriate.

回答1:

You can do a :bufdo e to force vim to reread all the open buffer from the filesystem.

bufdo is a way to apply a command to multiple buffers. (Similarly there is a tabdo if you are using tabs)

So it will replace the version of the old branch by the version of the new branch.

(Similar question & answer there : Git branching while files are opened )



回答2:

I would recommend you :set autoread in your ~/.vimrc:

When a file has been detected to have been changed outside of Vim and it has not been changed inside of Vim, automatically read it again.