diff --git a/diffmatchpatch/dmp.go b/diffmatchpatch/dmp.go index 4607452..0350978 100644 --- a/diffmatchpatch/dmp.go +++ b/diffmatchpatch/dmp.go @@ -1412,6 +1412,29 @@ func (dmp *DiffMatchPatch) DiffPrettyHtml(diffs []Diff) string { return buff.String() } +// DiffPrettyText converts a []Diff into a colored text report. +func (dmp *DiffMatchPatch) DiffPrettyText(diffs []Diff) string { + var buff bytes.Buffer + for _, diff := range diffs { + text := diff.Text + + switch diff.Type { + case DiffInsert: + _, _ = buff.WriteString("\x1b[32m") + _, _ = buff.WriteString(text) + _, _ = buff.WriteString("\x1b[0m") + case DiffDelete: + _, _ = buff.WriteString("\x1b[31m") + _, _ = buff.WriteString(text) + _, _ = buff.WriteString("\x1b[0m") + case DiffEqual: + _, _ = buff.WriteString(text) + } + } + + return buff.String() +} + // DiffText1 computes and returns the source text (all equalities and deletions). func (dmp *DiffMatchPatch) DiffText1(diffs []Diff) string { //StringBuilder text = new StringBuilder() diff --git a/diffmatchpatch/dmp_test.go b/diffmatchpatch/dmp_test.go index c727e8a..ee4766b 100644 --- a/diffmatchpatch/dmp_test.go +++ b/diffmatchpatch/dmp_test.go @@ -746,6 +746,17 @@ func Test_diffPrettyHtml(t *testing.T) { dmp.DiffPrettyHtml(diffs)) } +func Test_diffPrettyText(t *testing.T) { + dmp := New() + // Pretty print. + diffs := []Diff{ + Diff{DiffEqual, "a\n"}, + Diff{DiffDelete, "b"}, + Diff{DiffInsert, "c&d"}} + assert.Equal(t, "a\n\x1b[31mb\x1b[0m\x1b[32mc&d\x1b[0m", + dmp.DiffPrettyText(diffs)) +} + func Test_diffText(t *testing.T) { dmp := New() // Compute the source and destination texts.