Is there a configuration I can add to a .vimrc file which will cause vim to run a command when a file is closed?

For instance, suppose I'm editing a file that is under version control. Once I'm done editing I would like a command to commit my changes to be run immediately before vim fully closes without having to run it separately after saving/quiting the file.

I'm curious about this as I have a tendency to forget to commit my changes.

Alternatively and if it is not possible to do what I'm asking, is it possible to configure an internal vim :command that will run the commit from with vim before I close the file?

  • It's not in vimrc however you could use shell &&. I use it like this: vim a.c && gcc a.c -Wall -Werror -pedantic && ./a.out which opens file, compiles after closing and runs it. You can create a shell script to simplify it. – Dominik Dosoudil Oct 19 '17 at 10:27

Though it is not a good idea to commit changes immediately after editing and quitting the file, you can try vim auto commands.

augroup autocom
    "executes the command on quit
     autocmd VimLeave *.cpp !your_command

    "execute the command on write
    autocmd BufWritePost,FileWritePost *.cpp !your_commad
augroup END

Auto-commit on exit sounds like a bad idea. You're essentially encouraging your own bad practices.

To commit from within vim you'd do it the same way you execute any other command:

 :!git commit -m "look ma I remembered to commit" my_dir/my_file.c

After running:


to save it ofc


Why not create your own command ? I m not already familliar with it but it must look like in your vimrc :

command Wc w | Gcommit

And then after editing your file, type :Wc

Wc "custom name for Write commit
Gcommit " it s a command that exist from the excellent vim plugin 'fugitive' written by tpope
| "(pipe) allow you to add a second command
w " write

The vcscommand.vim - CVS/SVN/SVK/git/hg/bzr integration plugin provides a :VCSCommit command.

To hook into when a file is closed, you can use an :autocmd on the BufDelete event.

But I agree with Nanzikambe that this is a bad idea, and you should work on improving your practices instead. For example, there are plugins that can show the working copy dirty state in Vim's statusline, and several blog posts explain how to add such an indicator to your shell's prompt.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.