loading...
Cover image for How to color the moved code in git
Cloud(x);

How to color the moved code in git

navarroaxel profile image Axel Navarro ・2 min read

We already know that we can customize the diff output colors, but git is able to detect moved blocks of code and style them differently from the usual removed/added lines!

The moved block

We can use the argument --color-moved to color moved code for any command that generates a diff: git diff, git log -p, git show...

git diff --color-moved --

We can also set this in the .gitconfig file:

git config --global diff.colormoved default
git diff --

Block of moved text

By default, git detects a block of moved text of at least 20 alphanumeric characters 👀. That's why the 3 and 4 is not "moved code" for git.

The moved line

If we want to color any line moved we can use the plain mode:

git diff --color-moved=plain --

Line moved

The blue lines show the blocks that were moved verbatim, while the red and green lines show the corrected typos. But git thinks this mode is not very useful in a review to determine if a block of code was moved without permutation. 🧐

Ignoring the white spaces

We can ignore indentation of moved code using --color-moved-ws=allow-indentation-change:

git config --global diff.colormovedws allow-indentation-change
git diff --

Moved code with indentation

Dimming the moved code

If we set the dimmed_zebra mode 🦓 the moved blocks of code won't take our attention like the added or removed lines:

git config --global diff.colormoved dimmed-zebra
git diff --

Dimmed moved code

What about delta?

Delta is a diff viewer that makes the visualization of the moved lines of code even better 🤩. After install, just need to set it to be git's pager:

git config --global core.pager delta
git config --global delta.line-numbers true
# git config --global delta.side-by-side true
git diff --

The delta moved code

The --color-moved support was added in the new version 0.4.0, you can learn more of Delta here.

Posted on by:

navarroaxel profile

Axel Navarro

@navarroaxel

IT solutions builder. JavaScript is my thing, Linux is my passion. Rocker 4ever!

Cloud(x);

We believe the traditional technology delivery model is outdated, so we rebooted it.

Discussion

markdown guide