如何让 git-diff 忽略所有空白更改但领先一个?

How to have git-diff ignore all whitespace-change but leading one?

another post中我发现非常整洁

git diff --color-words='[^[:space:]]|([[:alnum:]]|UTF_8_GUARD)+'

在将 git-diff 的输出压缩到基本内容的同时保持清晰可读方面做得很好(尤其是在添加 --word-diff=plain 以获取额外的 [-/-]{+/+} 周围 deletions/additions)。虽然此 确实 包含空格更改,但输出不会以任何明显的方式突出显示它们,例如当更改一行 代码的缩进时(这是一个严重的更改)将显示为具有较长缩进的行(之前或之后),但没有任何突出显示。

如何正确突出显示空格更改,可能是通过将空格替换为一些 unicode 字符,例如 ·,或更接近 [=21= 的字符] 的 {+ +} 等,但使用更智能的单词分隔?

到目前为止我能得到的最好的是

git diff --color-words='[[:space:]]|([[:alnum:]]|UTF_8_GUARD)+' --word-diff=plain

注意去掉[:space:]前面的^

我无法解决您的问题,但我担心 Git 可能对您不利。回想一下 --color-words=<regex>--word-diff=color--word-diff-regex=<regex> 的组合。 man git 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.

       Every non-overlapping match of the <regex> is considered a word.
       Anything between these matches is considered whitespace and
       ignored(!) for the purposes of finding differences. You may want
       to append |[^[:space:]] to your regular expression to make sure
       that it matches all non-whitespace characters. A match that
       contains a newline is silently truncated(!) at the newline.

       The regex can also be set via a diff driver or configuration
       option, see gitattributes(1) or git-config(1). Giving it
       explicitly overrides any diff driver or configuration setting.
       Diff drivers override configuration settings.

请注意中间段落的这一部分:“这些匹配项之间的任何内容都被视为空白并被忽略(!)以查找差异。" 所以,听起来 Git 试图在这里专门处理空白,这可能是个问题。

这是使用问题末尾建议的替代方法的替代方法:

git config --global core.pager 'less --raw-control-chars'

这样可以正确显示 unicode 符号,而不是一些奇怪的 <c3>ish 输出。将以下内容添加到您的 git 配置中:

[diff "txt"]
    textconv = unwhite.sh

并且缺少 global solution.gitattributes 类似

*.py diff=txt

最后,unwhite.sh

#!/bin/bash
awk 1 ORS='[7m\n[27m\n'  | sed -e 's/ /␣/g' -e 's/\t/→/g'

请注意 [ 之前有原始转义(awk 不支持 \e)字符,我显示 newline-indicating \n in inverted colors 以区别于文字 \ns。这可能无法复制粘贴,在这种情况下您可能需要手动插入它们。或者用 等 unicode 符号试试运气。

我偏离了原始的 unicode 符号,因为它们无法在 msys 上正确显示git。