Is there any way to hook saving in Vim up to commiting in git?

I am new to the world of Vim, and I want to make it so that every time I save a file it is commited to version control. Is this possible?


Solution 1:

I use a vim autocommand which I place in my .vimrc. The command first does a crude check that we're working in a git directory (by checking existence of a .git directory, either in the current directory or using git rev-parse), then uses git -a -m % so that only files that have previously been added are staged and committed.

autocmd BufWritePost * execute '! if [ -d .git ] || git rev-parse --git-dir > /dev/null 2>&1 ; then git add % ; git commit -m %; fi'

Solution 2:

You could use Vim's autocommands:

:autocmd BufWritePost * execute '!git add % && git commit -m %'

That's untested but it should add the file and commit it with the filename as commit message.
You want BufWritePost as this is triggered after the file is written. I'd imagine there are a lot of irksome or unsafe edge cases though.