Commandline git diff that highlights exactly what is changed

Inpired by this great post on how to use the meld diff tool to get a nice GUI view of git diffs, I started looking for a way to get a similarly good result on the command line. That is, a diff that does not just show the whole lines that are changed, but that highlights the actually changed parts of each lineHere I document what I found. 

It turned out I could even get something better, than meld, in that I can view both the removed and added part in the same view (color coded with red/green) which my brain find much easier to interpret.

So, to the steps.

First I specify that git should use some external tool for it's diffs, by editing my ~/.gitconfig file and adds this to the bottom:

[diff]
    external = git-wdiff
Then, I go on and create that tool, "git-wdiff", in /usr/local/bin/git-wdiff, and put this text into it:

#!/bin/bash
wdiff -n $2 $5|colordiff|sed -r 's/(\{\+|\+\}|\[\-|\-\])//'|less
You'll need to install wdiff and colordiff (available in ubuntu repos).

What it does is:

  • wdiff produces a syntax where each deleted chunk of word(s) is surrounded with "[-" and "-]", and each added chunk with "{+" and "+}". (the "-n" flag is to prevent diff chunks to span over newlines, which will cause problems to colordiff).
  • colordiff gives nice red/green (depending on your terminal color sheme) coloring of this output
  • the sed part removes those [- ]- and {+ +} parts, so that you only have the color coding left.
  • less just adds a nice pager, for easy scrolling.
  • See the results below:

EDIT: [http://chem-bla-ics.blogspot.se/ Egon Willighagen] hinted me at another way to do this, where you don't even need colordiff, but can do the coloring directly with wdiff, by using it's facility for adding arbitrary start and end sequences around the changed words. Then the command in /bin/git-wdiff would become:

#!/bin/bash
diff -u $2 $5 | wdiff -n -d -w $'\033[30;31m' -x $'\033[0m' -y $'\033[30;32m' -z $'\033[0m' | less
The codes for the colors might need some tweaking to fit your terminal's color scheme. (More info about that [http://en.wikipedia.org/wiki/ANSI_escape_code#Colors here] ).

Tags: