Skip to content

Commit feac906

Browse files
authored
Merge pull request #139 from michaelcheah/fix_newline_diffs_colored_text
Fix colored display for diffs with newlines
2 parents 5b0b94c + 4ebce9c commit feac906

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
@@ -1146,13 +1146,28 @@ func (dmp *DiffMatchPatch) DiffPrettyText(diffs []Diff) string {
11461146

11471147
switch diff.Type {
11481148
case DiffInsert:
1149-
_, _ = buff.WriteString("\x1b[32m")
1150-
_, _ = buff.WriteString(text)
1151-
_, _ = buff.WriteString("\x1b[0m")
1149+
lines := strings.Split(text, "\n")
1150+
for i, line := range lines {
1151+
_, _ = buff.WriteString("\x1b[32m")
1152+
_, _ = buff.WriteString(line)
1153+
if i < len(lines)-1 {
1154+
_, _ = buff.WriteString("\x1b[0m\n")
1155+
} else {
1156+
_, _ = buff.WriteString("\x1b[0m")
1157+
}
1158+
}
1159+
11521160
case DiffDelete:
1153-
_, _ = buff.WriteString("\x1b[31m")
1154-
_, _ = buff.WriteString(text)
1155-
_, _ = buff.WriteString("\x1b[0m")
1161+
lines := strings.Split(text, "\n")
1162+
for i, line := range lines {
1163+
_, _ = buff.WriteString("\x1b[31m")
1164+
_, _ = buff.WriteString(line)
1165+
if i < len(lines)-1 {
1166+
_, _ = buff.WriteString("\x1b[0m\n")
1167+
} else {
1168+
_, _ = buff.WriteString("\x1b[0m")
1169+
}
1170+
}
11561171
case DiffEqual:
11571172
_, _ = buff.WriteString(text)
11581173
}

diffmatchpatch/diff_test.go

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

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

0 commit comments

Comments
 (0)