Saturday, February 27, 2016

Better Git Diff Word Colorization

I recently spent some time dialing in the colorization of my git diffs. Modern versions of the git command-line client will colorize diffs by default — but it still doesn't highlight the specific changed words or characters within the changed lines, like some of the fancier diff tools do (vimdiff, github, etc).

The diff-highlight script, a perl script from the "contrib" subtree of the git source repo, highlights the changed characters nicely. Several other blog posts (such as at The Unix Toolbox and at Viget) do a good job of describing how to install this script, and what it gets you. Here's the TLDR:

Installing Diff-Highlight

Download the diff-highlight script, make it executable, and put it on your path:

wget https://raw.githubusercontent.com/git/git/master/contrib/diff-highlight/diff-highlight
chmod +x diff-highlight
sudo mv diff-highlight /usr/local/bin/.

Update your git configuration to use it, adding the following to your ~/.gitconfig file:

[pager]
    diff = diff-highlight | less
    log = diff-highlight | less
    show = diff-highlight | less

By default now, git diff will highlight the characters of lines that differ just by a few characters by reversing the background and foreground colors of the differing characters (ie colorize the removed characters with a red background, and colorize the added characters with a green background). That's okay, but with the light color-scheme I like to use for my terminals, it still looks a little... ugly.

The Pretty Stick

Adding the following settings to your ~/.gitconfig will make it look much more pretty:

[color "diff-highlight"]
    oldNormal = red
    oldHighlight = 88 224
    newNormal = green
    newHighlight = 28 193

The numbers are XTerm 256 color numbers (foreground first, and then the optional background color second). For reference, Wikipedia has a nice XTerm color chart; and there's a really cool VIM plugin you can use to explore custom xterm colors, if you have a different aesthetic.

No comments:

Post a Comment