Better colors for moved text in Git

Posted on . Reading time: 2 mins. Tags: git.

If you move a block of text/code around, and then you run git diff, you will see that the moved text is displayed like any other change. If you are using the default colors, the old location will show in red and the new one in green. So, we can't quickly tell if that change only involves moving that block around, or if in addition to the displacement something has actually changed inside the block.

Well, Git has a setting to change that behaviour: color-moved. According to the documentation, at the date of this article, there are 6 different modes. I recommend trying them out and see which one you like the most. With the couple of examples I tried I couldn't appreciate a difference between plain and zebra, so I think I'll stick to zebra as I liked it more than the others.

I must say that I got very confused reading that the default behaviour is not the default mode, but the no mode.

If you don't know how to set this setting, you have two ways. One is running the command git config --global diff.colormoved "zebra". The other is manually editing the config file. If you have a .gitconfig file on your home directory or on your repository, add the following lines:

[diff]
  colormoved = "zebra"

Another setting related to moving code that is very useful is color-modev-ws. Citing the documentation:

This configures how white spaces are ignored when performing the move detection for --color-moved.

What does that mean? Well, it is not rare that when moving a block of code we change its indentation. Maybe the block was inside a top level function (one indentation level) and now it's inside a method inside a class (two indentation levels). If you set this setting to allow-indentation-change, the diff will be more "clever" and figure out that this is still only a block displacement and not a regular text modification. So, it will apply the right colors on the diff according to your color-moved setting.

This post was inspired by matklad's post Git Things, where they briefly mention both settings explained above.

Happy coding!