Skip to content

Commit 08e5792

Browse files
committed
fix : Stop breaking surrogate pairs in toText()/fromText()
1 parent 116615b commit 08e5792

File tree

1 file changed

+42
-2
lines changed

1 file changed

+42
-2
lines changed

javascript/diff_match_patch_uncompressed.js

+42-2
Original file line numberDiff line numberDiff line change
@@ -2215,6 +2215,46 @@ diff_match_patch.prototype.patch_splitMax = function(patches) {
22152215
}
22162216
};
22172217

2218+
diff_match_patch.prototype.diffs_joinSurrogatePairs = function(diffs) {
2219+
var lastEnd;
2220+
var overwrittenDiffsCounter = 0;
2221+
2222+
for (var x = 0 ; x < diffs.length ; x++) {
2223+
var thisDiff = diffs[x];
2224+
var thisTop = thisDiff[1][0];
2225+
var thisEnd = thisDiff[1][thisDiff[1].length - 1];
2226+
2227+
if (0 === thisDiff[1].length) {
2228+
continue;
2229+
}
2230+
2231+
// trap a trailing high-surrogate so we can
2232+
// distribute it to the successive edits
2233+
if (thisEnd && this.isHighSurrogate(thisEnd)) {
2234+
lastEnd = thisEnd;
2235+
thisDiff[1] = thisDiff[1].slice(0, -1);
2236+
}
2237+
2238+
if (lastEnd && thisTop && this.isHighSurrogate(lastEnd) && this.isLowSurrogate(thisTop)) {
2239+
thisDiff[1] = lastEnd + thisDiff[1];
2240+
}
2241+
2242+
if (0 === thisDiff[1].length) {
2243+
continue;
2244+
}
2245+
2246+
diffs[overwrittenDiffsCounter] = thisDiff;
2247+
overwrittenDiffsCounter ++;
2248+
}
2249+
2250+
return diffs.splice(0, overwrittenDiffsCounter)
2251+
}
2252+
2253+
diff_match_patch.prototype.patch_joinSurrogatePairs = function(patch) {
2254+
patch.diffs = this.diffs_joinSurrogatePairs(patch.diffs)
2255+
return patch
2256+
}
2257+
22182258

22192259
/**
22202260
* Take a list of patches and return a textual representation.
@@ -2224,7 +2264,7 @@ diff_match_patch.prototype.patch_splitMax = function(patches) {
22242264
diff_match_patch.prototype.patch_toText = function(patches) {
22252265
var text = [];
22262266
for (var x = 0; x < patches.length; x++) {
2227-
text[x] = patches[x];
2267+
text[x] = this.patch_joinSurrogatePairs(patches[x]);
22282268
}
22292269
return text.join('');
22302270
};
@@ -2277,7 +2317,7 @@ diff_match_patch.prototype.patch_fromText = function(textline) {
22772317
while (textPointer < text.length) {
22782318
var sign = text[textPointer].charAt(0);
22792319
try {
2280-
var line = decodeURI(text[textPointer].substring(1));
2320+
var line = this.decodeURI(text[textPointer].substring(1));
22812321
} catch (ex) {
22822322
// Malformed URI sequence.
22832323
throw new Error('Illegal escape in patch_fromText: ' + line);

0 commit comments

Comments
 (0)