From 590367d5d52e9949d02aa0f5fcb3026bf7838a28 Mon Sep 17 00:00:00 2001 From: Yanhu007 Date: Wed, 15 Apr 2026 11:39:33 +0800 Subject: [PATCH] fix: preserve ANSI color across newlines in DiffPrettyText DiffPrettyText previously split insert/delete text on newlines and reset the color code before each newline. This caused the color to not visually extend across line breaks, making multi-line insertions and deletions appear only partially colored. Simplify to wrap the entire diff text in a single color escape sequence pair, which correctly maintains the color through newlines. Fixes #138 --- diffmatchpatch/diff.go | 27 ++++++--------------------- diffmatchpatch/diff_test.go | 2 +- 2 files changed, 7 insertions(+), 22 deletions(-) diff --git a/diffmatchpatch/diff.go b/diffmatchpatch/diff.go index 08c36e7..c70866b 100644 --- a/diffmatchpatch/diff.go +++ b/diffmatchpatch/diff.go @@ -1146,28 +1146,13 @@ func (dmp *DiffMatchPatch) DiffPrettyText(diffs []Diff) string { switch diff.Type { case DiffInsert: - lines := strings.Split(text, "\n") - for i, line := range lines { - _, _ = buff.WriteString("\x1b[32m") - _, _ = buff.WriteString(line) - if i < len(lines)-1 { - _, _ = buff.WriteString("\x1b[0m\n") - } else { - _, _ = buff.WriteString("\x1b[0m") - } - } - + _, _ = buff.WriteString("\x1b[32m") + _, _ = buff.WriteString(text) + _, _ = buff.WriteString("\x1b[0m") case DiffDelete: - lines := strings.Split(text, "\n") - for i, line := range lines { - _, _ = buff.WriteString("\x1b[31m") - _, _ = buff.WriteString(line) - if i < len(lines)-1 { - _, _ = buff.WriteString("\x1b[0m\n") - } else { - _, _ = buff.WriteString("\x1b[0m") - } - } + _, _ = buff.WriteString("\x1b[31m") + _, _ = buff.WriteString(text) + _, _ = buff.WriteString("\x1b[0m") case DiffEqual: _, _ = buff.WriteString(text) } diff --git a/diffmatchpatch/diff_test.go b/diffmatchpatch/diff_test.go index 2c43864..be18840 100644 --- a/diffmatchpatch/diff_test.go +++ b/diffmatchpatch/diff_test.go @@ -1042,7 +1042,7 @@ func TestDiffPrettyText(t *testing.T) { {Type: DiffEqual, Text: "\ni"}, }, - Expected: "a\n\x1b[31mb\x1b[0m\n\x1b[31mc\x1b[0m\n\x1b[31m\x1b[0mdef\x1b[32m\x1b[0m\n\x1b[32mg\x1b[0m\n\x1b[32mh\x1b[0m\ni", + Expected: "a\n\x1b[31mb\nc\n\x1b[0mdef\x1b[32m\ng\nh\x1b[0m\ni", }, } { actual := dmp.DiffPrettyText(tc.Diffs)