PatchAddContext increases the context until it is unique, but doesn't let the pattern expand beyond MatchMaxBits.
(patch Patch, text string)
| 107 | |
| 108 | // PatchAddContext increases the context until it is unique, but doesn't let the pattern expand beyond MatchMaxBits. |
| 109 | func (dmp *DiffMatchPatch) PatchAddContext(patch Patch, text string) Patch { |
| 110 | if len(text) == 0 { |
| 111 | return patch |
| 112 | } |
| 113 | |
| 114 | pattern := text[patch.Start2 : patch.Start2+patch.Length1] |
| 115 | padding := 0 |
| 116 | |
| 117 | // Look for the first and last matches of pattern in text. If two different matches are found, increase the pattern length. |
| 118 | for strings.Index(text, pattern) != strings.LastIndex(text, pattern) && |
| 119 | len(pattern) < dmp.MatchMaxBits-2*dmp.PatchMargin { |
| 120 | padding += dmp.PatchMargin |
| 121 | maxStart := max(0, patch.Start2-padding) |
| 122 | minEnd := min(len(text), patch.Start2+patch.Length1+padding) |
| 123 | pattern = text[maxStart:minEnd] |
| 124 | } |
| 125 | // Add one chunk for good luck. |
| 126 | padding += dmp.PatchMargin |
| 127 | |
| 128 | // Add the prefix. |
| 129 | // rune-safety: align prefix start to nearest rune boundary so the slice |
| 130 | // never produces an invalid-UTF-8 string when the surrounding text contains |
| 131 | // multi-byte characters. |
| 132 | prefixStart := alignRuneStart(text, max(0, patch.Start2-padding)) |
| 133 | prefix := text[prefixStart:patch.Start2] |
| 134 | if len(prefix) != 0 { |
| 135 | patch.diffs = append([]Diff{Diff{DiffEqual, prefix}}, patch.diffs...) |
| 136 | } |
| 137 | // Add the suffix. |
| 138 | // rune-safety: round suffix end forward to the next rune boundary. Rounding |
| 139 | // back would shorten the context, and PatchAddPadding would then treat the |
| 140 | // patch as touching the end of the text. |
| 141 | suffixEnd := alignRuneEnd(text, min(len(text), patch.Start2+patch.Length1+padding)) |
| 142 | suffix := text[patch.Start2+patch.Length1 : suffixEnd] |
| 143 | if len(suffix) != 0 { |
| 144 | patch.diffs = append(patch.diffs, Diff{DiffEqual, suffix}) |
| 145 | } |
| 146 | |
| 147 | // Roll back the start points. |
| 148 | patch.Start1 -= len(prefix) |
| 149 | patch.Start2 -= len(prefix) |
| 150 | // Extend the lengths. |
| 151 | patch.Length1 += len(prefix) + len(suffix) |
| 152 | patch.Length2 += len(prefix) + len(suffix) |
| 153 | |
| 154 | return patch |
| 155 | } |
| 156 | |
| 157 | // PatchMake computes a list of patches. |
| 158 | func (dmp *DiffMatchPatch) PatchMake(opt ...interface{}) []Patch { |