Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show trailing whitespace and line endings in removed lines in diff output

Tags:

git

git-diff

Currently when doing git diff with --color option enabled git shows line endings such as ^M and trailing whitespaces only in added lines. Is it possible to make git show these also in removed lines?

like image 476
user1042840 Avatar asked Nov 02 '22 14:11

user1042840


1 Answers

It's not the prettiest workaround, but you can create a shell alias to make it bearable. Sadly, if you mix tabs and spaces on the output, it does not render correctly in the terminal. This appears to be an issue with Gnome terminal (you'll notice the same behavior with the lines added in the diff as well).

Here's the command you want:

git diff --color | \
sed 's/^\(\x1B\[31m-.*[^ \t]\)\([ \t]\+\)\(\x1B\[m\)$/\1\x1B[41m\2\3/g'

Or more conveniently, add this to your .bashrc:

alias coloreol="sed 's/^\(\x1B\[31m-.*[^ \t]\)\([ \t]\+\)\(\x1B\[m\)$/\1\x1B[41m\2\3/g'"

That way you can type git diff --color|coloreol at the shell prompt.

Essentially, it matches the ANSI red color code, a minus sign followed by anything up to a non-whitespace character. It then matches one or more whitespace characters until it encounters the ANSI reset flag. Sed will insert an ANSI red-invert code between the whitespace and the end of the line.

I've broken down the reg ex for you so that you can modify it to your needs:

The first part, broken down into three groups:

Match the start of the line and ANSI code for red: 
   ^\(\x1B\[31m
          -.*[^ \t]  <-- Followed by the hyphen, anything, then a non-whitespace character
    \)
 Now match one or more space or tab characters for group 2.
 \([ \t]\+\)
 Finally the ANSI reset code and EOL for group 3
 \(\x1B\[m\)$

We then replace it with:

 \1  \x1B[41m  \2  \3

That is, the first match, the invert-red ANSI code (\x1B[41m), followed by the whitespace and ANSI reset.

like image 86
Kunal Avatar answered Nov 15 '22 05:11

Kunal