How to use --color-words with git add --patch?
I recently solved this issue, but it requires modifying a Perl script in git. That's easy and requires no special skill, however.
This solution requires that your git configuration use colorization for screen output, because that's the only circumstance under which git will show a word-based diff.
- Copy
git-add--interactive
from your installation to somewhere in yourPATH
environment variable and rename itgit-add--interactive-words
. - Edit a line about half way down to change*
@colored = run_cmd_pipe("git", @diff_cmd, qw(--color --), $path);
to
@colored = run_cmd_pipe("git", @diff_cmd, qw(--color --color-words --), $path);
- You can now run
git add-interactive--words
to do the equivalent ofgit add --interactive
with colorized word-based diff. - However, combining
git add --patch
with that is awkward because you need to pass the new script the right parameters. Fortunately, you can create an alias to the magic words in your.gitconfig
:
[alias]
iaddpw = add--interactive-words --patch=stage --
which means git iaddpw
runs the equivalent of git add --interactive --patch
with colorized word-based diff.
*- For Git 2.18, this command is:
my @display_cmd = ("git", @diff_cmd, qw(--color --), $path);
Building off of what VonC said:
Starting with Git 2.9, you can use this command to color words during add --patch
:
git -c interactive.diffFilter="git diff --color-words" add -p
This sets the interactive.diffFilter
variable for the call to add -p
without affecting further calls. For me this is ideal because I usually want to run add -p
normally, but sometimes want to run it with --color-words
.
You can easily add an alias for this command like so:
git config --global alias.addcw '-c interactive.diffFilter="git diff --color-words" add -p'
Taking cue from VonC's answer. Here are detailed steps to use --interactive
option introduced in git 2.9.
Add diff-highlight to your PATH.
On Ubuntu, diff-highlight
comes with git and can be found in /usr/share/git/diff-highlight/diff-highlight
.
Otherwise, you can download and set it up manually.
cd ~/bin
curl -LO "https://raw.githubusercontent.com/git/git/master/contrib/diff-highlight/diff-highlight"
chmod u+x diff-highlight
Restart your shell, if necessary.
Then configure Git to filter your diffs whenever it's showing them in a pager:
git config --global pager.log 'diff-highlight | less'
git config --global pager.show 'diff-highlight | less'
git config --global pager.diff 'diff-highlight | less'
git config --global interactive.diffFilter diff-highlight
This will put an extra emphasis on the changed part of a line, which is almost same as --word-diff
.
The advantage is you get word diff every where, like git log --patch
or git add -p
.