When refactoring I sometimes do too much at once—all little steps, but I forget to commit after each little change.

Of course in many cases a commit after each change would be too much, but if each individual change were initially made as a separate commit, it would be very easy to git rebase them to combine them into logical, atomic changes.

Is there a way to convert each point in Vim's multiple undo history into a separate git commit?

  • 2
    Why don't use git add -p? Using this command someone can selectively stage modifications; edit, split into smaller hunks and commit them.
    – dNitro
    Sep 28 '16 at 10:13
  • 2
    @dNitro, good answer for most people, but I'm already familiar with that. It's not quite so useful when you end up modifying every line of the file so the whole thing is considered as one "hunk." Of course you can remove lines by editing the hunk manually, but then there are the cases when you change a line and then change the same line again.
    – Wildcard
    Sep 28 '16 at 19:56

Here's a quick and dirty function that does what you request:

function! UndoCommits(steps)
    for i in range(a:steps)

    for i in range(a:steps)
        execute printf('!silent git commit -am "%s"', "undo-commit" . i)
    execute printf('!silent git commit -am "%s"', "final-undo-commit")

Call with :call UndoCommits({N}) where {N} is the number of undo steps back you want to go.

The function simply undoes the requested number of times, and then redoes the changes one at a time, making a commit between each change.

Personally, I think I'd just do this manually — I guess a compromise might be to create a mapping that just performs the save-and-commit, and then run this mapping by hand at the relevant parts of the undolist.


I would recommend one of the undo tree visualizer plugins:

With them, you can easily revisit previous editing states. You can them (temporarily) restore them (one by one, starting with the oldest relevant), and git commit them, until you arrive back at the original.

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.