DiffCleanupSemanticLossless looks for single edits surrounded on both sides by equalities which can be shifted sideways to align the edit to a word boundary. E.g: The c at c ame. -> The cat came.
(diffs []Diff)
| 772 | // DiffCleanupSemanticLossless looks for single edits surrounded on both sides by equalities which can be shifted sideways to align the edit to a word boundary. |
| 773 | // E.g: The c<ins>at c</ins>ame. -> The <ins>cat </ins>came. |
| 774 | func (dmp *DiffMatchPatch) DiffCleanupSemanticLossless(diffs []Diff) []Diff { |
| 775 | pointer := 1 |
| 776 | |
| 777 | // Intentionally ignore the first and last element (don't need checking). |
| 778 | for pointer < len(diffs)-1 { |
| 779 | if diffs[pointer-1].Type == DiffEqual && |
| 780 | diffs[pointer+1].Type == DiffEqual { |
| 781 | |
| 782 | // This is a single edit surrounded by equalities. |
| 783 | equality1 := diffs[pointer-1].Text |
| 784 | edit := diffs[pointer].Text |
| 785 | equality2 := diffs[pointer+1].Text |
| 786 | |
| 787 | // First, shift the edit as far left as possible. |
| 788 | commonOffset := dmp.DiffCommonSuffix(equality1, edit) |
| 789 | if commonOffset > 0 { |
| 790 | commonString := edit[len(edit)-commonOffset:] |
| 791 | equality1 = equality1[0 : len(equality1)-commonOffset] |
| 792 | edit = commonString + edit[:len(edit)-commonOffset] |
| 793 | equality2 = commonString + equality2 |
| 794 | } |
| 795 | |
| 796 | // Second, step character by character right, looking for the best fit. |
| 797 | bestEquality1 := equality1 |
| 798 | bestEdit := edit |
| 799 | bestEquality2 := equality2 |
| 800 | bestScore := diffCleanupSemanticScore(equality1, edit) + |
| 801 | diffCleanupSemanticScore(edit, equality2) |
| 802 | |
| 803 | for len(edit) != 0 && len(equality2) != 0 { |
| 804 | _, sz := utf8.DecodeRuneInString(edit) |
| 805 | if len(equality2) < sz || edit[:sz] != equality2[:sz] { |
| 806 | break |
| 807 | } |
| 808 | equality1 += edit[:sz] |
| 809 | edit = edit[sz:] + equality2[:sz] |
| 810 | equality2 = equality2[sz:] |
| 811 | score := diffCleanupSemanticScore(equality1, edit) + |
| 812 | diffCleanupSemanticScore(edit, equality2) |
| 813 | // The >= encourages trailing rather than leading whitespace on edits. |
| 814 | if score >= bestScore { |
| 815 | bestScore = score |
| 816 | bestEquality1 = equality1 |
| 817 | bestEdit = edit |
| 818 | bestEquality2 = equality2 |
| 819 | } |
| 820 | } |
| 821 | |
| 822 | if diffs[pointer-1].Text != bestEquality1 { |
| 823 | // We have an improvement, save it back to the diff. |
| 824 | if len(bestEquality1) != 0 { |
| 825 | diffs[pointer-1].Text = bestEquality1 |
| 826 | } else { |
| 827 | diffs = splice(diffs, pointer-1, 1) |
| 828 | pointer-- |
| 829 | } |
| 830 | |
| 831 | diffs[pointer].Text = bestEdit |