DiffCleanupSemantic reduces the number of edits by eliminating semantically trivial equalities.
(diffs []Diff)
| 604 | |
| 605 | // DiffCleanupSemantic reduces the number of edits by eliminating semantically trivial equalities. |
| 606 | func (dmp *DiffMatchPatch) DiffCleanupSemantic(diffs []Diff) []Diff { |
| 607 | changes := false |
| 608 | // Stack of indices where equalities are found. |
| 609 | equalities := make([]int, 0, len(diffs)) |
| 610 | |
| 611 | var lastequality string |
| 612 | // Always equal to diffs[equalities[equalitiesLength - 1]][1] |
| 613 | var pointer int // Index of current position. |
| 614 | // Number of characters that changed prior to the equality. |
| 615 | var lengthInsertions1, lengthDeletions1 int |
| 616 | // Number of characters that changed after the equality. |
| 617 | var lengthInsertions2, lengthDeletions2 int |
| 618 | |
| 619 | for pointer < len(diffs) { |
| 620 | if diffs[pointer].Type == DiffEqual { |
| 621 | // Equality found. |
| 622 | equalities = append(equalities, pointer) |
| 623 | lengthInsertions1 = lengthInsertions2 |
| 624 | lengthDeletions1 = lengthDeletions2 |
| 625 | lengthInsertions2 = 0 |
| 626 | lengthDeletions2 = 0 |
| 627 | lastequality = diffs[pointer].Text |
| 628 | } else { |
| 629 | // An insertion or deletion. |
| 630 | |
| 631 | if diffs[pointer].Type == DiffInsert { |
| 632 | lengthInsertions2 += utf8.RuneCountInString(diffs[pointer].Text) |
| 633 | } else { |
| 634 | lengthDeletions2 += utf8.RuneCountInString(diffs[pointer].Text) |
| 635 | } |
| 636 | // Eliminate an equality that is smaller or equal to the edits on both sides of it. |
| 637 | difference1 := int(math.Max(float64(lengthInsertions1), float64(lengthDeletions1))) |
| 638 | difference2 := int(math.Max(float64(lengthInsertions2), float64(lengthDeletions2))) |
| 639 | if utf8.RuneCountInString(lastequality) > 0 && |
| 640 | (utf8.RuneCountInString(lastequality) <= difference1) && |
| 641 | (utf8.RuneCountInString(lastequality) <= difference2) { |
| 642 | // Duplicate record. |
| 643 | insPoint := equalities[len(equalities)-1] |
| 644 | diffs = splice(diffs, insPoint, 0, Diff{DiffDelete, lastequality}) |
| 645 | |
| 646 | // Change second copy to insert. |
| 647 | diffs[insPoint+1].Type = DiffInsert |
| 648 | // Throw away the equality we just deleted. |
| 649 | equalities = equalities[:len(equalities)-1] |
| 650 | |
| 651 | if len(equalities) > 0 { |
| 652 | equalities = equalities[:len(equalities)-1] |
| 653 | } |
| 654 | pointer = -1 |
| 655 | if len(equalities) > 0 { |
| 656 | pointer = equalities[len(equalities)-1] |
| 657 | } |
| 658 | |
| 659 | lengthInsertions1 = 0 // Reset the counters. |
| 660 | lengthDeletions1 = 0 |
| 661 | lengthInsertions2 = 0 |
| 662 | lengthDeletions2 = 0 |
| 663 | lastequality = "" |