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