Skip to content

Commit 65165c5

Browse files
committed
Escape Whitespace in DiffPrettyText
Displace escape sequence for whitespace characters in diffs.
1 parent 5b0b94c commit 65165c5

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

diffmatchpatch/diff.go

+26
Original file line numberDiff line numberDiff line change
@@ -1138,6 +1138,30 @@ func (dmp *DiffMatchPatch) DiffPrettyHtml(diffs []Diff) string {
11381138
return buff.String()
11391139
}
11401140

1141+
func escapeWhitespace(input string) string {
1142+
// Define a map of whitespace characters and their escaped versions
1143+
escapeMap := map[string]string{
1144+
"\n": "\\n",
1145+
"\t": "\\t",
1146+
"\r": "\\r",
1147+
" ": "\\s",
1148+
}
1149+
1150+
// Use a regular expression to match all whitespace characters
1151+
re := regexp.MustCompile(`\s`)
1152+
1153+
// Replace each whitespace character using the escapeMap
1154+
result := re.ReplaceAllStringFunc(input, func(match string) string {
1155+
escaped, exists := escapeMap[match]
1156+
if !exists {
1157+
escaped = fmt.Sprintf("\\x%x", match[0]) // Default escape for unknown whitespace
1158+
}
1159+
return escaped
1160+
})
1161+
1162+
return result
1163+
}
1164+
11411165
// DiffPrettyText converts a []Diff into a colored text report.
11421166
func (dmp *DiffMatchPatch) DiffPrettyText(diffs []Diff) string {
11431167
var buff bytes.Buffer
@@ -1146,10 +1170,12 @@ func (dmp *DiffMatchPatch) DiffPrettyText(diffs []Diff) string {
11461170

11471171
switch diff.Type {
11481172
case DiffInsert:
1173+
text = escapeWhitespace(text)
11491174
_, _ = buff.WriteString("\x1b[32m")
11501175
_, _ = buff.WriteString(text)
11511176
_, _ = buff.WriteString("\x1b[0m")
11521177
case DiffDelete:
1178+
text = escapeWhitespace(text)
11531179
_, _ = buff.WriteString("\x1b[31m")
11541180
_, _ = buff.WriteString(text)
11551181
_, _ = buff.WriteString("\x1b[0m")

diffmatchpatch/diff_test.go

+9
Original file line numberDiff line numberDiff line change
@@ -1031,6 +1031,15 @@ 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+
{DiffEqual, "a\n"},
1037+
{DiffDelete, "\n"},
1038+
{DiffInsert, "c\td e"},
1039+
},
1040+
1041+
Expected: "a\n\x1b[31m\\n\x1b[0m\x1b[32mc\\td\\se\x1b[0m",
1042+
},
10341043
} {
10351044
actual := dmp.DiffPrettyText(tc.Diffs)
10361045
assert.Equal(t, tc.Expected, actual, fmt.Sprintf("Test case #%d, %#v", i, tc))

0 commit comments

Comments
 (0)