PatchAddContext increases the context until it is unique, but doesn't let the pattern expand beyond MatchMaxBits.
(patch Patch, text string)
| 72 | |
| 73 | // PatchAddContext increases the context until it is unique, but doesn't let the pattern expand beyond MatchMaxBits. |
| 74 | func (dmp *DiffMatchPatch) PatchAddContext(patch Patch, text string) Patch { |
| 75 | if len(text) == 0 { |
| 76 | return patch |
| 77 | } |
| 78 | |
| 79 | pattern := text[patch.Start2 : patch.Start2+patch.Length1] |
| 80 | padding := 0 |
| 81 | |
| 82 | // Look for the first and last matches of pattern in text. If two different matches are found, increase the pattern length. |
| 83 | for strings.Index(text, pattern) != strings.LastIndex(text, pattern) && |
| 84 | len(pattern) < dmp.MatchMaxBits-2*dmp.PatchMargin { |
| 85 | padding += dmp.PatchMargin |
| 86 | maxStart := max(0, patch.Start2-padding) |
| 87 | minEnd := min(len(text), patch.Start2+patch.Length1+padding) |
| 88 | pattern = text[maxStart:minEnd] |
| 89 | } |
| 90 | // Add one chunk for good luck. |
| 91 | padding += dmp.PatchMargin |
| 92 | |
| 93 | // Add the prefix. |
| 94 | prefix := text[max(0, patch.Start2-padding):patch.Start2] |
| 95 | if len(prefix) != 0 { |
| 96 | patch.diffs = append([]Diff{Diff{DiffEqual, prefix}}, patch.diffs...) |
| 97 | } |
| 98 | // Add the suffix. |
| 99 | suffix := text[patch.Start2+patch.Length1 : min(len(text), patch.Start2+patch.Length1+padding)] |
| 100 | if len(suffix) != 0 { |
| 101 | patch.diffs = append(patch.diffs, Diff{DiffEqual, suffix}) |
| 102 | } |
| 103 | |
| 104 | // Roll back the start points. |
| 105 | patch.Start1 -= len(prefix) |
| 106 | patch.Start2 -= len(prefix) |
| 107 | // Extend the lengths. |
| 108 | patch.Length1 += len(prefix) + len(suffix) |
| 109 | patch.Length2 += len(prefix) + len(suffix) |
| 110 | |
| 111 | return patch |
| 112 | } |
| 113 | |
| 114 | // PatchMake computes a list of patches. |
| 115 | func (dmp *DiffMatchPatch) PatchMake(opt ...interface{}) []Patch { |