Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git - Color words excluding {}

Tags:

git

regex

I am using git with --color-words to view my diff. In my diff, it shows that I removed

<b>{{ljcount}}</b>&nbsp;&nbsp;&nbsp;Changes

And that I added:

<b>{{skills_limits}}</b>&nbsp;&nbsp;&nbsp;Changes

This is larger than what I would like it to be (I want the word boundary to be at the {}). I tried playing around with --word-diff-regex, but I couldn't find a regex to make it work. How can I achieve this result?

like image 464
Casebash Avatar asked Dec 13 '11 00:12

Casebash


3 Answers

From git help diff:

   --word-diff-regex=<regex>
       Use <regex> to decide what a word is, instead of considering runs of non-whitespace to be a word. Also implies
       --word-diff unless it was already enabled.

The following expression will make a word be any string of characters and underscore, or any non-whitespace character.

$ git diff --color-words --word-diff-regex='\\w+|[^[:space:]]'
like image 118
holygeek Avatar answered Nov 19 '22 19:11

holygeek


Since you already use --color-words, you don't need to supply --word-diff-regex separately, the first option accepts a regex:

--color-words[=<regex>]

Equivalent to --word-diff=color plus --word-diff-regex=<regex> (if a regex was specified).

A regex that works particularly well for me is:

$ git diff --color-words='\w+|.'
like image 38
arekolek Avatar answered Nov 19 '22 18:11

arekolek


If you are using --color-words[=<regex>], make sure to use Git 2.32 (Q2 2021) or more recent: the word-diff mode has been taught to work better with a word regexp that can match an empty string.

See commit 0324e8f (04 May 2021) by Phillip Wood (phillipwood).
(Merged by Junio C Hamano -- gitster -- in commit 65c1891, 14 May 2021)

word diff: handle zero length matches

Signed-off-by: Phillip Wood

If find_word_boundaries() encounters a zero length match (which can be caused by matching a newline or using '*' instead of '+' in the regex) we stop splitting the input into words which generates an inaccurate diff.
To fix this increment the start point when there is a zero length match and try a new match.
This is safe as posix regular expressions always return the longest available match so a zero length match means there are no longer matches available from the current position.

Commit bf82940 ("color-words: enable REG_NEWLINE to help user", 2009-01-17, Git v1.6.2-rc0 -- merge) prevented matching newlines in negated character classes but it is still possible for the user to have an explicit newline match in the regex which could cause a zero length match.

One could argue that having explicit newline matches or using '*' rather than '+' are user errors but it seems to be better to work round them than produce inaccurate diffs.

like image 1
VonC Avatar answered Nov 19 '22 18:11

VonC