diff --git a/chardiff_test.go b/chardiff_test.go index 540e15a..a4fa5ab 100644 --- a/chardiff_test.go +++ b/chardiff_test.go @@ -1,6 +1,7 @@ package diff_test import ( + "bytes" "strings" "testing" @@ -396,3 +397,91 @@ func joinSegments(segs []diff.Segment) string { return sb.String() } + +func TestWordDiff(t *testing.T) { + tests := []struct { + name string + removed []byte + added []byte + wantAllUnchanged bool + wantHasChanged bool + }{ + { + name: "identical lines - all segments unchanged", + removed: []byte("return foo\n"), + added: []byte("return foo\n"), + wantAllUnchanged: true, + }, + { + name: "changed word - only the word is highlighted", + removed: []byte("return foo\n"), + added: []byte("return bar\n"), + wantHasChanged: true, + }, + { + name: "completely different lines", + removed: []byte("abc def\n"), + added: []byte("xyz qrs\n"), + wantHasChanged: true, + }, + { + name: "empty removed", + removed: []byte(""), + added: []byte("new content\n"), + wantHasChanged: true, + }, + { + name: "invalid UTF-8 falls back to whole-line", + removed: []byte("\xff\xfe old\n"), + added: []byte("new content\n"), + wantHasChanged: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + result := diff.WordDiff(tt.removed, tt.added) + + assertJoinInvariant(t, result, tt.removed, tt.added) + + if tt.wantAllUnchanged { + assertNoneChanged(t, result.Removed, "removed") + assertNoneChanged(t, result.Added, "added") + } + + if tt.wantHasChanged { + if !anyChanged(result.Removed) && !anyChanged(result.Added) { + t.Error("WordDiff on differing inputs should produce at least one Changed segment") + } + } + }) + } +} + +func FuzzWordDiff(f *testing.F) { + f.Add([]byte("return foo\n"), []byte("return bar\n")) + f.Add([]byte("hello world\n"), []byte("hello earth\n")) + f.Add([]byte(""), []byte("")) + + f.Fuzz(func(t *testing.T, removed, added []byte) { + got := diff.WordDiff(removed, added) + + var rConcat []byte + for _, s := range got.Removed { + rConcat = append(rConcat, s.Text...) + } + + if !bytes.Equal(rConcat, removed) { + t.Fatalf("Removed concat %q != input %q", rConcat, removed) + } + + var aConcat []byte + for _, s := range got.Added { + aConcat = append(aConcat, s.Text...) + } + + if !bytes.Equal(aConcat, added) { + t.Fatalf("Added concat %q != input %q", aConcat, added) + } + }) +} diff --git a/chars.go b/chars.go index b373850..b4798dd 100644 --- a/chars.go +++ b/chars.go @@ -2,6 +2,7 @@ package diff import ( "bytes" + "unicode" "unicode/utf8" ) @@ -125,6 +126,252 @@ func CharDiff(removed, added []byte, opts ...Option) InlineChange { return InlineChange{Removed: removedSegs, Added: addedSegs} } +// tokenize splits b into word and delimiter tokens. +// Words are maximal runs of Unicode letters, digits, and underscores. +// Every other rune is an individual delimiter token. +// Tokens are subslices of b — no allocation beyond the slice header list. +func tokenize(b []byte) [][]byte { + var tokens [][]byte + + i := 0 + for i < len(b) { + r, sz := utf8.DecodeRune(b[i:]) + if unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' { + start := i + for i < len(b) { + r, sz = utf8.DecodeRune(b[i:]) + if !unicode.IsLetter(r) && !unicode.IsDigit(r) && r != '_' { + break + } + + i += sz + } + + tokens = append(tokens, b[start:i]) + } else { + tokens = append(tokens, b[i:i+sz]) + i += sz + } + } + + return tokens +} + +// tokenOp is a single edit operation produced during word-token LCS backtracking. +type tokenOp struct { + tok []byte + kind byte // 'e' equal, 'd' delete, 'i' insert +} + +// wordLCSSegments builds the LCS table for token slices and returns Segment-based sides. +// It is the word-token analogue of lcsSegments: tokens replace runes, bytes.Equal +// replaces rune equality, and each token's bytes are appended to the backing buffers. +// rCap and aCap must equal the byte lengths of the removed and added core inputs so +// the backing buffers never reallocate. +func wordLCSSegments(old, newToks [][]byte, rCap, aCap int) sides { + m, n := len(old), len(newToks) + + dp := make([]int, (m+1)*(n+1)) + + stride := n + 1 + for i := 1; i <= m; i++ { + for j := 1; j <= n; j++ { + if bytes.Equal(old[i-1], newToks[j-1]) { + dp[i*stride+j] = dp[(i-1)*stride+(j-1)] + 1 + } else { + dp[i*stride+j] = max(dp[(i-1)*stride+j], dp[i*stride+(j-1)]) + } + } + } + + ops := make([]tokenOp, 0, m+n) + + i, j := m, n + for i > 0 || j > 0 { + switch { + case i > 0 && j > 0 && bytes.Equal(old[i-1], newToks[j-1]): + ops = append(ops, tokenOp{tok: old[i-1], kind: 'e'}) + i-- + j-- + case j > 0 && (i == 0 || dp[i*stride+(j-1)] >= dp[(i-1)*stride+j]): + ops = append(ops, tokenOp{tok: newToks[j-1], kind: 'i'}) + j-- + default: + ops = append(ops, tokenOp{tok: old[i-1], kind: 'd'}) + i-- + } + } + + for l, r := 0, len(ops)-1; l < r; l, r = l+1, r-1 { + ops[l], ops[r] = ops[r], ops[l] + } + + return mergeTokenSegments(ops, rCap, aCap) +} + +// mergeTokenSegments merges consecutive same-kind token ops into Segment runs. +// rCap and aCap are the byte capacities for the removed and added backing buffers; +// they must equal the byte lengths of the respective core inputs so the buffers +// never reallocate, keeping all segment Text subslices valid. +func mergeTokenSegments(ops []tokenOp, rCap, aCap int) sides { + removedBacking := make([]byte, 0, rCap) + addedBacking := make([]byte, 0, aCap) + removedSegs := make([]Segment, 0, segmentInitCap) + addedSegs := make([]Segment, 0, segmentInitCap) + + for _, o := range ops { + nb := len(o.tok) + + switch o.kind { + case 'e': + removedBacking = append(removedBacking, o.tok...) + + if len(removedSegs) > 0 && !removedSegs[len(removedSegs)-1].Changed { + last := &removedSegs[len(removedSegs)-1] + last.Text = last.Text[:len(last.Text)+nb] + } else { + removedSegs = append( + removedSegs, + Segment{Text: removedBacking[len(removedBacking)-nb:], Changed: false}, + ) + } + + addedBacking = append(addedBacking, o.tok...) + + if len(addedSegs) > 0 && !addedSegs[len(addedSegs)-1].Changed { + last := &addedSegs[len(addedSegs)-1] + last.Text = last.Text[:len(last.Text)+nb] + } else { + addedSegs = append(addedSegs, Segment{Text: addedBacking[len(addedBacking)-nb:], Changed: false}) + } + + case 'd': + removedBacking = append(removedBacking, o.tok...) + + if len(removedSegs) > 0 && removedSegs[len(removedSegs)-1].Changed { + last := &removedSegs[len(removedSegs)-1] + last.Text = last.Text[:len(last.Text)+nb] + } else { + removedSegs = append(removedSegs, Segment{Text: removedBacking[len(removedBacking)-nb:], Changed: true}) + } + + case 'i': + addedBacking = append(addedBacking, o.tok...) + + if len(addedSegs) > 0 && addedSegs[len(addedSegs)-1].Changed { + last := &addedSegs[len(addedSegs)-1] + last.Text = last.Text[:len(last.Text)+nb] + } else { + addedSegs = append(addedSegs, Segment{Text: addedBacking[len(addedBacking)-nb:], Changed: true}) + } + + default: + // op.kind is always 'e', 'd', or 'i' — wordLCSSegments is the only producer. + } + } + + if len(removedSegs) == 0 { + removedSegs = append(removedSegs, Segment{Text: []byte{}, Changed: false}) + } + + if len(addedSegs) == 0 { + addedSegs = append(addedSegs, Segment{Text: []byte{}, Changed: false}) + } + + return sides{removed: removedSegs, added: addedSegs} +} + +// WordDiff computes word-level diff segments for a removed/added line pair. +// It tokenises each line into words (maximal runs of Unicode letters, digits, +// and underscores) and delimiters (all other runes, individually), then runs +// an LCS on the token slices. Changed segments cover whole words or delimiter +// sequences, producing wider, cleaner highlights than [CharDiff] for prose or +// code identifiers. +// +// The same guards as [CharDiff] apply: +// - Identical inputs return all-unchanged segments. +// - Trailing newlines are stripped before diffing and reattached afterwards; +// a trailing newline is never placed inside a Changed segment. +// - Invalid UTF-8 returns a whole-line Changed segment. +// - Either side exceeding 500 tokens returns a whole-line Changed segment. +// - If the similarity ratio (2*equalBytes / totalBytes) is below the threshold +// set by [WithSimilarityThreshold] (default 0.5), a whole-line Changed +// segment is returned. +// +// The concatenation of segment Text fields on each side always equals the +// original input byte-for-byte. +func WordDiff(removed, added []byte, opts ...Option) InlineChange { + cfg := applyOptions(opts) + + if bytes.Equal(removed, added) { + return InlineChange{ + Removed: []Segment{{Text: bytes.Clone(removed), Changed: false}}, + Added: []Segment{{Text: bytes.Clone(added), Changed: false}}, + } + } + + removedNL := len(removed) > 0 && removed[len(removed)-1] == '\n' + addedNL := len(added) > 0 && added[len(added)-1] == '\n' + + removedCore := removed + if removedNL { + removedCore = removed[:len(removed)-1] + } + + addedCore := added + if addedNL { + addedCore = added[:len(added)-1] + } + + if !utf8.Valid(removedCore) || !utf8.Valid(addedCore) { + return fallback(removed, added) + } + + oldToks := tokenize(removedCore) + newToks := tokenize(addedCore) + + if len(oldToks) > 500 || len(newToks) > 500 { + return fallback(removed, added) + } + + segs := wordLCSSegments(oldToks, newToks, len(removedCore), len(addedCore)) + + // Similarity ratio gate using byte counts for consistency with CharDiff. + totalBytes := len(removedCore) + len(addedCore) + if totalBytes > 0 { + equalBytes := 0 + + for _, seg := range segs.removed { + if !seg.Changed { + equalBytes += len(seg.Text) + } + } + + ratio := float64(similarityRatioScale*equalBytes) / float64(totalBytes) + if ratio < cfg.similarityThreshold { + var rSegs []Segment + if len(removedCore) > 0 { + rSegs = []Segment{{Text: bytes.Clone(removedCore), Changed: true}} + } + + var aSegs []Segment + if len(addedCore) > 0 { + aSegs = []Segment{{Text: bytes.Clone(addedCore), Changed: true}} + } + + return InlineChange{ + Removed: reattachNL(rSegs, removedNL), + Added: reattachNL(aSegs, addedNL), + } + } + } + + return InlineChange{ + Removed: reattachNL(segs.removed, removedNL), + Added: reattachNL(segs.added, addedNL), + } +} + // fallback returns a single Changed segment per side (whole-line fallback). // Copies the input slices to avoid aliasing the caller's memory. func fallback(removed, added []byte) InlineChange { diff --git a/diff.go b/diff.go index a324f28..4a0d394 100644 --- a/diff.go +++ b/diff.go @@ -58,6 +58,68 @@ type Line struct { Kind LineKind } +// LinePair groups a contiguous block of removed lines with the immediately +// following block of added lines. Either field may be nil if the change is +// a pure insertion or pure deletion. +// +// LinePair is produced by [Pairs] and is intended for downstream consumers +// (e.g. custom renderers) that need to perform per-pair operations such as +// intraline diff highlighting. +type LinePair struct { + Removed []Line + Added []Line +} + +// Pairs groups the KindRemoved and KindAdded lines from a structured diff into +// LinePair values. Each LinePair holds one contiguous block of removed lines +// and/or the immediately following block of added lines. KindContext and +// KindHeader lines are skipped. +// +// The input is typically the slice returned by [Lines]. Pairs returns nil if +// lines contains no KindRemoved or KindAdded lines. +// +// The Removed and Added slices in each LinePair are subslices of the input; +// callers must not modify the input slice or the Line values within it after +// calling Pairs. +func Pairs(lines []Line) []LinePair { + var result []LinePair + + i := 0 + for i < len(lines) { + kind := lines[i].Kind + if kind != KindRemoved && kind != KindAdded { + i++ + continue + } + + // Collect contiguous removed block. + start := i + for i < len(lines) && lines[i].Kind == KindRemoved { + i++ + } + + removed := lines[start:i] + if len(removed) == 0 { + removed = nil + } + + // Collect immediately following added block. + start = i + for i < len(lines) && lines[i].Kind == KindAdded { + i++ + } + + added := lines[start:i] + if len(added) == 0 { + added = nil + } + + result = append(result, LinePair{Removed: removed, Added: added}) + } + + return result +} + // pair is a pair of line indexes, one for each side of the diff. type pair struct{ x, y int } @@ -279,6 +341,57 @@ func trimPrefixSuffix(x, y [][]byte) trimResult { } } +// compact post-processes grouped diff lines, shifting change blocks to semantic +// boundaries. For each contiguous block of KindRemoved (or KindAdded) lines, if +// the last line in the block has the same content as the KindContext line +// immediately following it, the block shifts down by one: the first line of the +// block is re-classified as KindContext and the formerly-context line is +// re-classified as the changed kind. This repeats until stable. +// +// compact never moves changes across hunk boundaries (KindHeader lines act as +// natural stops since the inner loop only shifts when the next line is KindContext). +func compact(lines []Line) []Line { + result := make([]Line, len(lines)) + copy(result, lines) + + for { + shifted := false + + i := 0 + for i < len(result) { + kind := result[i].Kind + if kind != KindRemoved && kind != KindAdded { + i++ + continue + } + // Find end of contiguous block of this kind. + j := i + 1 + for j < len(result) && result[j].Kind == kind { + j++ + } + // j is the index of the first line after the block. + // Shift down when last line in block == first context line after it. + if j < len(result) && result[j].Kind == KindContext && + bytes.Equal(result[j-1].Content, result[j].Content) { + result[i].Kind = KindContext + result[j].Kind = kind + shifted = true + i++ // advance past the newly-Context line; the freshly-reclassified j will be found on next scan + + continue + } + + i = j + } + + if !shifted { + break + } + } + + return result +} + // computeLines computes structured diff lines for old and newText (assumed non-equal). func computeLines(oldName string, old []byte, newName string, newText []byte, cfg config) []Line { x := splitLines(old) @@ -298,21 +411,25 @@ func computeLines(oldName string, old []byte, newName string, newText []byte, cf if isDisjoint(tr.oldTrimmed, tr.newTrimmed) { // Fast-path: no common lines — emit one hunk with all removals then all additions. - result := make([]Line, 0, diffHeaders+1+len(tr.oldTrimmed)+len(tr.newTrimmed)) - result = append(result, headers...) + body := make([]Line, 0, 1+len(tr.oldTrimmed)+len(tr.newTrimmed)) - result = append(result, chunkHeader( + body = append(body, chunkHeader( pair{tr.prefix, tr.prefix}, pair{len(tr.oldTrimmed), len(tr.newTrimmed)}, )) for _, s := range tr.oldTrimmed { - result = append(result, Line{Kind: KindRemoved, Content: s}) + body = append(body, Line{Kind: KindRemoved, Content: s}) } for _, s := range tr.newTrimmed { - result = append(result, Line{Kind: KindAdded, Content: s}) + body = append(body, Line{Kind: KindAdded, Content: s}) } + body = compact(body) + result := make([]Line, 0, diffHeaders+len(body)) + result = append(result, headers...) + result = append(result, body...) + return result } @@ -326,6 +443,7 @@ func computeLines(oldName string, old []byte, newName string, newText []byte, cf } hunks := groupIntoHunks(pairs, x, y, cfg.contextLines) + hunks = compact(hunks) result := make([]Line, 0, diffHeaders+len(hunks)) result = append(result, headers...) result = append(result, hunks...) diff --git a/diff_test.go b/diff_test.go index c2fa077..7c4e2de 100644 --- a/diff_test.go +++ b/diff_test.go @@ -70,6 +70,50 @@ func TestLines(t *testing.T) { {Kind: diff.KindRemoved, Content: []byte("old line\n")}, }, }, + { + name: "compact shifts duplicate removal to second occurrence", + oldName: "want", newName: "got", + old: []byte("a\na\nb\n"), + newText: []byte("a\nb\n"), + want: []diff.Line{ + {Kind: diff.KindHeader, Content: []byte("diff want got\n")}, + {Kind: diff.KindHeader, Content: []byte("--- want\n")}, + {Kind: diff.KindHeader, Content: []byte("+++ got\n")}, + {Kind: diff.KindHeader, Content: []byte("@@ -1,3 +1,2 @@\n")}, + {Kind: diff.KindContext, Content: []byte("a\n")}, + {Kind: diff.KindRemoved, Content: []byte("a\n")}, + {Kind: diff.KindContext, Content: []byte("b\n")}, + }, + }, + { + name: "compact shifts duplicate addition to second occurrence", + oldName: "want", newName: "got", + old: []byte("a\nb\n"), + newText: []byte("a\na\nb\n"), + want: []diff.Line{ + {Kind: diff.KindHeader, Content: []byte("diff want got\n")}, + {Kind: diff.KindHeader, Content: []byte("--- want\n")}, + {Kind: diff.KindHeader, Content: []byte("+++ got\n")}, + {Kind: diff.KindHeader, Content: []byte("@@ -1,2 +1,3 @@\n")}, + {Kind: diff.KindContext, Content: []byte("a\n")}, + {Kind: diff.KindAdded, Content: []byte("a\n")}, + {Kind: diff.KindContext, Content: []byte("b\n")}, + }, + }, + { + name: "compact does not shift block at end of hunk with no following context", + oldName: "want", newName: "got", + old: []byte("a\nb\n"), + newText: []byte("a\n"), + want: []diff.Line{ + {Kind: diff.KindHeader, Content: []byte("diff want got\n")}, + {Kind: diff.KindHeader, Content: []byte("--- want\n")}, + {Kind: diff.KindHeader, Content: []byte("+++ got\n")}, + {Kind: diff.KindHeader, Content: []byte("@@ -1,2 +1,1 @@\n")}, + {Kind: diff.KindContext, Content: []byte("a\n")}, + {Kind: diff.KindRemoved, Content: []byte("b\n")}, + }, + }, } for _, tt := range tests { @@ -432,6 +476,170 @@ func TestDisjointFastPath(t *testing.T) { } } +// TestPairs verifies that Pairs groups consecutive removed/added blocks correctly. +func TestPairs(t *testing.T) { + tests := []struct { + name string + lines []diff.Line + want []diff.LinePair + }{ + { + name: "nil input returns nil", + lines: nil, + want: nil, + }, + { + name: "only context lines returns nil", + lines: []diff.Line{ + {Kind: diff.KindContext, Content: []byte("unchanged\n")}, + }, + want: nil, + }, + { + name: "removed followed by added forms one pair", + lines: []diff.Line{ + {Kind: diff.KindContext, Content: []byte("ctx\n")}, + {Kind: diff.KindRemoved, Content: []byte("old\n")}, + {Kind: diff.KindAdded, Content: []byte("new\n")}, + {Kind: diff.KindContext, Content: []byte("ctx2\n")}, + }, + want: []diff.LinePair{ + { + Removed: []diff.Line{{Kind: diff.KindRemoved, Content: []byte("old\n")}}, + Added: []diff.Line{{Kind: diff.KindAdded, Content: []byte("new\n")}}, + }, + }, + }, + { + name: "removed-only block has nil Added", + lines: []diff.Line{ + {Kind: diff.KindRemoved, Content: []byte("gone\n")}, + {Kind: diff.KindContext, Content: []byte("ctx\n")}, + }, + want: []diff.LinePair{ + { + Removed: []diff.Line{{Kind: diff.KindRemoved, Content: []byte("gone\n")}}, + Added: nil, + }, + }, + }, + { + name: "added-only block has nil Removed", + lines: []diff.Line{ + {Kind: diff.KindContext, Content: []byte("ctx\n")}, + {Kind: diff.KindAdded, Content: []byte("new\n")}, + }, + want: []diff.LinePair{ + { + Removed: nil, + Added: []diff.Line{{Kind: diff.KindAdded, Content: []byte("new\n")}}, + }, + }, + }, + { + name: "two separate change blocks produce two pairs", + lines: []diff.Line{ + {Kind: diff.KindRemoved, Content: []byte("a\n")}, + {Kind: diff.KindAdded, Content: []byte("b\n")}, + {Kind: diff.KindContext, Content: []byte("ctx\n")}, + {Kind: diff.KindRemoved, Content: []byte("c\n")}, + {Kind: diff.KindAdded, Content: []byte("d\n")}, + }, + want: []diff.LinePair{ + { + Removed: []diff.Line{{Kind: diff.KindRemoved, Content: []byte("a\n")}}, + Added: []diff.Line{{Kind: diff.KindAdded, Content: []byte("b\n")}}, + }, + { + Removed: []diff.Line{{Kind: diff.KindRemoved, Content: []byte("c\n")}}, + Added: []diff.Line{{Kind: diff.KindAdded, Content: []byte("d\n")}}, + }, + }, + }, + { + name: "header lines are skipped", + lines: []diff.Line{ + {Kind: diff.KindHeader, Content: []byte("@@ -1,1 +1,1 @@\n")}, + {Kind: diff.KindRemoved, Content: []byte("x\n")}, + {Kind: diff.KindAdded, Content: []byte("y\n")}, + }, + want: []diff.LinePair{ + { + Removed: []diff.Line{{Kind: diff.KindRemoved, Content: []byte("x\n")}}, + Added: []diff.Line{{Kind: diff.KindAdded, Content: []byte("y\n")}}, + }, + }, + }, + { + name: "added block before removed block produces two pairs", + lines: []diff.Line{ + {Kind: diff.KindAdded, Content: []byte("new\n")}, + {Kind: diff.KindContext, Content: []byte("ctx\n")}, + {Kind: diff.KindRemoved, Content: []byte("old\n")}, + }, + want: []diff.LinePair{ + { + Removed: nil, + Added: []diff.Line{{Kind: diff.KindAdded, Content: []byte("new\n")}}, + }, + { + Removed: []diff.Line{{Kind: diff.KindRemoved, Content: []byte("old\n")}}, + Added: nil, + }, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := diff.Pairs(tt.lines) + if len(got) != len(tt.want) { + t.Fatalf("Pairs() returned %d pairs, want %d\ngot: %#v\nwant: %#v", + len(got), len(tt.want), got, tt.want) + } + + for i, p := range got { + assertLinePair(t, i, p, tt.want[i]) + } + }) + } +} + +// assertLinePair verifies that a single LinePair matches the expected pair. +func assertLinePair(t *testing.T, i int, got, want diff.LinePair) { + t.Helper() + + if len(got.Removed) != len(want.Removed) { + t.Errorf("pair[%d].Removed len = %d, want %d", i, len(got.Removed), len(want.Removed)) + return + } + + if len(got.Added) != len(want.Added) { + t.Errorf("pair[%d].Added len = %d, want %d", i, len(got.Added), len(want.Added)) + return + } + + for j, line := range got.Removed { + if line.Kind != want.Removed[j].Kind { + t.Errorf("pair[%d].Removed[%d].Kind = %v, want %v", i, j, line.Kind, want.Removed[j].Kind) + } + + if !bytes.Equal(line.Content, want.Removed[j].Content) { + t.Errorf("pair[%d].Removed[%d].Content = %q, want %q", i, j, line.Content, want.Removed[j].Content) + } + } + + for j, line := range got.Added { + if line.Kind != want.Added[j].Kind { + t.Errorf("pair[%d].Added[%d].Kind = %v, want %v", i, j, line.Kind, want.Added[j].Kind) + } + + if !bytes.Equal(line.Content, want.Added[j].Content) { + t.Errorf("pair[%d].Added[%d].Content = %q, want %q", i, j, line.Content, want.Added[j].Content) + } + } +} + func clean(text []byte) []byte { text = bytes.ReplaceAll(text, []byte("$\n"), []byte("\n")) text = bytes.TrimSuffix(text, []byte("^D\n"))