可以编写一个通过Pygments pygmentize工具传递文件的git diff驱动程序.
首先,pygmentize在您的首选pygmentize设置(格式化程序/样式/过滤器)中定义一个包装器~/bin/pygmentize-term:
#!/bin/sh
exec pygmentize -f terminal256 -O bg=dark,style=trac "$@"
Run Code Online (Sandbox Code Playgroud)
然后,在以下位置定义一个通用的"diff with syntax highlighting"程序~/bin/hldiff:
#!/bin/bash
set -euo pipefail
# Diff two files with syntax highlighting using pygmentize.
# pygmentize-term should be a pygmentize wrapper with your preferred
# pygmentize settings (formatter / style / filters)
function prepare() {
local fn=$1
# Work around https://bitbucket.org/birkenfeld/pygments-main/issues/1437
if [[ "$fn" == /dev/null ]]
then
return
fi
local lexer
lexer=$(pygmentize -N "$fn")
#printf "Detected lexer of %q as %q\n" "$fn" "$lexer" 1>&2
if [[ "$lexer" == text ]]
then
expand "$fn" | pygmentize-term -g
else
expand "$fn" | pygmentize-term -l "$lexer"
fi
}
# Use colordiff (instead of diff --color=always) solely because it
# produces consistent formatting on a per-line basis, saving us from
# having to keep track of state across lines
diff=(colordiff --color=yes)
for arg in "$@"
do
if [[ $arg == -* ]]
then
diff+=("$arg")
else
exec {fd}< <(prepare "$arg")
diff+=(/dev/fd/$fd)
fi
done
sed=(
sed
# replace "all attributes off" (used by Pygmentize to turn off
# bold) with "normal intensity"
-e 's/\x1b\[00m/\x1b[22m/g'
# Replace colordiff's foreground colors with some dark background
# colors. You can customize them here.
-e 's/^\x1b\[0;36m/\x1b[0;36;48;5;23m/' # cyan
-e 's/^\x1b\[0;31m/\x1b[0;31;48;5;52m/' # red
-e 's/^\x1b\[0;32m/\x1b[0;32;48;5;22m/' # green
# Extend background color across the entire terminal window width
-e 's/\x1b\[0;0m$/\x1b\[K\x1b[0m/'
)
"${diff[@]}" | "${sed[@]}"
Run Code Online (Sandbox Code Playgroud)
可以使用上面的代码diff来获取具有语法突出显示的两个文件的差异.
要让git使用它,请为上面的内容定义一个git diff驱动程序包装器~/bin/git-hldiff-driver:
#!/bin/bash
set -euo pipefail
# Program suitable for GIT_EXTERNAL_DIFF, which will syntax-highlight differences.
hldiff -u "$2" "$5" || true
Run Code Online (Sandbox Code Playgroud)
您现在可以设置GIT_EXTERNAL_DIFF上面的包装器脚本来让git显示带有语法高亮的差异:
$ GIT_EXTERNAL_DIFF=~/bin/git-hldiff-driver git diff
Run Code Online (Sandbox Code Playgroud)
要git show使用它,您需要指定--ext-diff开关:
$ GIT_EXTERNAL_DIFF=~/bin/git-hldiff-driver git show --ext-diff
Run Code Online (Sandbox Code Playgroud)
请注意,默认情况下,git show它将通过pager(less)发送其输出,这将导致背景颜色无法正确显示,因此也添加--no-pager以防止这种情况.
代码语法突出显示不能直接在 git 中使用。\n“ Vive la git diff!
”中总结了可用的内容,其中包含以下实用程序:
$ git diff \xe2\x80\x90\xe2\x80\x90color-words\n# or\n$ git diff | ~/src/git/contrib/diff-hightlight/diff-highlight\n\nIt was the best of times,\n-it was the **blu**rst of times.\n+it was the **wo**rst of times.\nRun Code Online (Sandbox Code Playgroud)\n(该**xx**部分实际上是彩色的)
但这些亮点并不取决于语言本身。\n甚至像git
这样更复杂的扩展仍然是对差异块进行着色,而不是代码语法。diff-so-fancy
poke在评论中提到diff 工具Semanticmerge.com,它了解有关被比较文件的语言的更多信息:使用 git 查看其配置。
\n