Skip to content

Commit 4ebce9c

Browse files
committed
fix: colored display for diffs with newlines
1 parent facec63 commit 4ebce9c

File tree

2 files changed

+32
-6
lines changed

2 files changed

+32
-6
lines changed

diffmatchpatch/diff.go

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1151,13 +1151,28 @@ func (dmp *DiffMatchPatch) DiffPrettyText(diffs []Diff) string {
11511151

11521152
switch diff.Type {
11531153
case DiffInsert:
1154-
_, _ = buff.WriteString("\x1b[32m")
1155-
_, _ = buff.WriteString(text)
1156-
_, _ = buff.WriteString("\x1b[0m")
1154+
lines := strings.Split(text, "\n")
1155+
for i, line := range lines {
1156+
_, _ = buff.WriteString("\x1b[32m")
1157+
_, _ = buff.WriteString(line)
1158+
if i < len(lines)-1 {
1159+
_, _ = buff.WriteString("\x1b[0m\n")
1160+
} else {
1161+
_, _ = buff.WriteString("\x1b[0m")
1162+
}
1163+
}
1164+
11571165
case DiffDelete:
1158-
_, _ = buff.WriteString("\x1b[31m")
1159-
_, _ = buff.WriteString(text)
1160-
_, _ = buff.WriteString("\x1b[0m")
1166+
lines := strings.Split(text, "\n")
1167+
for i, line := range lines {
1168+
_, _ = buff.WriteString("\x1b[31m")
1169+
_, _ = buff.WriteString(line)
1170+
if i < len(lines)-1 {
1171+
_, _ = buff.WriteString("\x1b[0m\n")
1172+
} else {
1173+
_, _ = buff.WriteString("\x1b[0m")
1174+
}
1175+
}
11611176
case DiffEqual:
11621177
_, _ = buff.WriteString(text)
11631178
}

diffmatchpatch/diff_test.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1033,6 +1033,17 @@ func TestDiffPrettyText(t *testing.T) {
10331033

10341034
Expected: "a\n\x1b[31m<B>b</B>\x1b[0m\x1b[32mc&d\x1b[0m",
10351035
},
1036+
{
1037+
Diffs: []Diff{
1038+
{Type: DiffEqual, Text: "a\n"},
1039+
{Type: DiffDelete, Text: "b\nc\n"},
1040+
{Type: DiffEqual, Text: "def"},
1041+
{Type: DiffInsert, Text: "\ng\nh"},
1042+
{Type: DiffEqual, Text: "\ni"},
1043+
},
1044+
1045+
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",
1046+
},
10361047
} {
10371048
actual := dmp.DiffPrettyText(tc.Diffs)
10381049
assert.Equal(t, tc.Expected, actual, fmt.Sprintf("Test case #%d, %#v", i, tc))

0 commit comments

Comments
 (0)