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