Chris Frederick

Git Tip of the Day: --color-words

September 04, 2013

I’ve always felt that Git’s default diff output left something to be desired, especially when it was applied to Markdown text files (like the ones used to generate this blog). Line-by-line diffs aren’t very helpful if every line represents a paragraph of text.

I was thus pleasantly surprised to stumble across this blog post, which—among other things—explains how to generate word-by-word diffs that wrap nicely. The first step is to configure the default Git pager to wrap lines using one of the following commands.

git config --global core.pager less -r
git config --global core.pager "less -+\$LESS -FRX"

The second step is to tell Git to generate a (colored!) word-by-word diff with the --color-words option.

git diff --color-words

And that’s all there is to it! Note that --color-words is technically equivalent to --word-diff=color, so if you’re interested in reading about the other available options to --word-diff you can check out the git-diff man page.

As helpful as this technique is, there is one caveat to keep in mind: as far as I can tell the --color-words option only works with the git-diff and git-log commands. If you happen to use git add -p to stage individual changes—like I do—you are stuck with the default line-by-line diff output of git-add. That’s really only a minor inconvenience, though, because you can still call git diff --color-words just before git add -p to get a nicely-formatted overview of your changes before you stage them.

I hope you found this tip to be as helpful as I did!