Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download
Views: 39537
1
/**
2
* Diff Match and Patch
3
*
4
* Copyright 2006 Google Inc.
5
* http://code.google.com/p/google-diff-match-patch/
6
*
7
* Licensed under the Apache License, Version 2.0 (the "License");
8
* you may not use this file except in compliance with the License.
9
* You may obtain a copy of the License at
10
*
11
* http://www.apache.org/licenses/LICENSE-2.0
12
*
13
* Unless required by applicable law or agreed to in writing, software
14
* distributed under the License is distributed on an "AS IS" BASIS,
15
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
* See the License for the specific language governing permissions and
17
* limitations under the License.
18
*/
19
20
/**
21
* @fileoverview Computes the difference between two texts to create a patch.
22
* Applies the patch onto another text, allowing for errors.
23
* @author [email protected] (Neil Fraser)
24
*/
25
26
/**
27
* Class containing the diff, match and patch methods.
28
* @constructor
29
*/
30
function diff_match_patch() {
31
32
// Defaults.
33
// Redefine these in your program to override the defaults.
34
35
// Number of seconds to map a diff before giving up (0 for infinity).
36
this.Diff_Timeout = 1.0;
37
// Cost of an empty edit operation in terms of edit characters.
38
this.Diff_EditCost = 4;
39
// At what point is no match declared (0.0 = perfection, 1.0 = very loose).
40
this.Match_Threshold = 0.5;
41
// How far to search for a match (0 = exact location, 1000+ = broad match).
42
// A match this many characters away from the expected location will add
43
// 1.0 to the score (0.0 is a perfect match).
44
this.Match_Distance = 1000;
45
// When deleting a large block of text (over ~64 characters), how close do
46
// the contents have to be to match the expected contents. (0.0 = perfection,
47
// 1.0 = very loose). Note that Match_Threshold controls how closely the
48
// end points of a delete need to match.
49
this.Patch_DeleteThreshold = 0.5;
50
// Chunk size for context length.
51
this.Patch_Margin = 4;
52
53
// The number of bits in an int.
54
this.Match_MaxBits = 32;
55
}
56
57
58
// DIFF FUNCTIONS
59
60
61
/**
62
* The data structure representing a diff is an array of tuples:
63
* [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']]
64
* which means: delete 'Hello', add 'Goodbye' and keep ' world.'
65
*/
66
var DIFF_DELETE = -1;
67
var DIFF_INSERT = 1;
68
var DIFF_EQUAL = 0;
69
70
/** @typedef {{0: number, 1: string}} */
71
diff_match_patch.Diff;
72
73
74
/**
75
* Find the differences between two texts. Simplifies the problem by stripping
76
* any common prefix or suffix off the texts before diffing.
77
* @param {string} text1 Old string to be diffed.
78
* @param {string} text2 New string to be diffed.
79
* @param {boolean=} opt_checklines Optional speedup flag. If present and false,
80
* then don't run a line-level diff first to identify the changed areas.
81
* Defaults to true, which does a faster, slightly less optimal diff.
82
* @param {number} opt_deadline Optional time when the diff should be complete
83
* by. Used internally for recursive calls. Users should set DiffTimeout
84
* instead.
85
* @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.
86
*/
87
diff_match_patch.prototype.diff_main = function(text1, text2, opt_checklines,
88
opt_deadline) {
89
//console.log("diff_main", opt_deadline);
90
// Set a deadline by which time the diff must be complete.
91
if (typeof opt_deadline == 'undefined') {
92
if (this.Diff_Timeout <= 0) {
93
opt_deadline = Number.MAX_VALUE;
94
} else {
95
opt_deadline = (new Date).getTime() + this.Diff_Timeout * 1000;
96
}
97
}
98
var deadline = opt_deadline;
99
100
// Check for null inputs.
101
if (text1 == null || text2 == null) {
102
throw new Error('Null input. (diff_main)');
103
}
104
105
// Check for equality (speedup).
106
if (text1 == text2) {
107
if (text1) {
108
return [[DIFF_EQUAL, text1]];
109
}
110
return [];
111
}
112
113
if (typeof opt_checklines == 'undefined') {
114
opt_checklines = true;
115
}
116
var checklines = opt_checklines;
117
118
// Trim off common prefix (speedup).
119
var commonlength = this.diff_commonPrefix(text1, text2);
120
var commonprefix = text1.substring(0, commonlength);
121
text1 = text1.substring(commonlength);
122
text2 = text2.substring(commonlength);
123
124
// Trim off common suffix (speedup).
125
commonlength = this.diff_commonSuffix(text1, text2);
126
var commonsuffix = text1.substring(text1.length - commonlength);
127
text1 = text1.substring(0, text1.length - commonlength);
128
text2 = text2.substring(0, text2.length - commonlength);
129
130
// Compute the diff on the middle block.
131
//console.log("Compute the diff on the middle block...");
132
var diffs = this.diff_compute_(text1, text2, checklines, deadline);
133
//console.log("Compute the diff on the middle block... (done)");
134
135
// Restore the prefix and suffix.
136
if (commonprefix) {
137
diffs.unshift([DIFF_EQUAL, commonprefix]);
138
}
139
if (commonsuffix) {
140
diffs.push([DIFF_EQUAL, commonsuffix]);
141
}
142
this.diff_cleanupMerge(diffs);
143
return diffs;
144
};
145
146
147
/**
148
* Find the differences between two texts. Assumes that the texts do not
149
* have any common prefix or suffix.
150
* @param {string} text1 Old string to be diffed.
151
* @param {string} text2 New string to be diffed.
152
* @param {boolean} checklines Speedup flag. If false, then don't run a
153
* line-level diff first to identify the changed areas.
154
* If true, then run a faster, slightly less optimal diff.
155
* @param {number} deadline Time when the diff should be complete by.
156
* @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.
157
* @private
158
*/
159
diff_match_patch.prototype.diff_compute_ = function(text1, text2, checklines,
160
deadline) {
161
var diffs;
162
163
if (!text1) {
164
// Just add some text (speedup).
165
//console.log("Just add some text (speedup).");
166
return [[DIFF_INSERT, text2]];
167
}
168
169
if (!text2) {
170
// Just delete some text (speedup).
171
//console.log("Just delete some text (speedup).");
172
return [[DIFF_DELETE, text1]];
173
}
174
175
var tr = deadline - new Date();
176
if (tr < 0) {
177
//console.log("Out of time in diff_compute_ -- bailing");
178
// Out of time, so bail with trivial diff
179
return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]];
180
}
181
182
var longtext = text1.length > text2.length ? text1 : text2;
183
var shorttext = text1.length > text2.length ? text2 : text1;
184
var i = longtext.indexOf(shorttext);
185
if (i != -1) {
186
// Shorter text is inside the longer text (speedup).
187
diffs = [[DIFF_INSERT, longtext.substring(0, i)],
188
[DIFF_EQUAL, shorttext],
189
[DIFF_INSERT, longtext.substring(i + shorttext.length)]];
190
// Swap insertions for deletions if diff is reversed.
191
if (text1.length > text2.length) {
192
diffs[0][0] = diffs[2][0] = DIFF_DELETE;
193
}
194
return diffs;
195
}
196
197
if (shorttext.length == 1) {
198
// Single character string.
199
// After the previous speedup, the character can't be an equality.
200
return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]];
201
}
202
203
// Check to see if the problem can be split in two.
204
//console.log("Check to see if the problem can be split in two.");
205
var hm = this.diff_halfMatch_(text1, text2, deadline);
206
tr = deadline - new Date();
207
if (tr < 0) {
208
//console.log("Out of time in diff_halfMatch_ -- bailing");
209
// Out of time, so bail with trivial diff
210
return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]];
211
}
212
if (hm) {
213
// A half-match was found, sort out the return data.
214
//console.log("A half-match was found, sort out the return data.");
215
var text1_a = hm[0];
216
var text1_b = hm[1];
217
var text2_a = hm[2];
218
var text2_b = hm[3];
219
var mid_common = hm[4];
220
// Send both pairs off for separate processing.
221
//console.log("Send both pairs off for separate processing.");
222
var diffs_a = this.diff_main(text1_a, text2_a, checklines, deadline);
223
var diffs_b = this.diff_main(text1_b, text2_b, checklines, deadline);
224
// Merge the results.
225
return diffs_a.concat([[DIFF_EQUAL, mid_common]], diffs_b);
226
}
227
228
if (checklines && text1.length > 100 && text2.length > 100) {
229
return this.diff_lineMode_(text1, text2, deadline);
230
}
231
232
return this.diff_bisect_(text1, text2, deadline);
233
};
234
235
236
/**
237
* Do a quick line-level diff on both strings, then rediff the parts for
238
* greater accuracy.
239
* This speedup can produce non-minimal diffs.
240
* @param {string} text1 Old string to be diffed.
241
* @param {string} text2 New string to be diffed.
242
* @param {number} deadline Time when the diff should be complete by.
243
* @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.
244
* @private
245
*/
246
diff_match_patch.prototype.diff_lineMode_ = function(text1, text2, deadline) {
247
// Scan the text on a line-by-line basis first.
248
var a = this.diff_linesToChars_(text1, text2);
249
text1 = a.chars1;
250
text2 = a.chars2;
251
var linearray = a.lineArray;
252
253
var diffs = this.diff_main(text1, text2, false, deadline);
254
255
// Convert the diff back to original text.
256
this.diff_charsToLines_(diffs, linearray);
257
// Eliminate freak matches (e.g. blank lines)
258
this.diff_cleanupSemantic(diffs);
259
260
// Rediff any replacement blocks, this time character-by-character.
261
// Add a dummy entry at the end.
262
diffs.push([DIFF_EQUAL, '']);
263
var pointer = 0;
264
var count_delete = 0;
265
var count_insert = 0;
266
var text_delete = '';
267
var text_insert = '';
268
while (pointer < diffs.length) {
269
switch (diffs[pointer][0]) {
270
case DIFF_INSERT:
271
count_insert++;
272
text_insert += diffs[pointer][1];
273
break;
274
case DIFF_DELETE:
275
count_delete++;
276
text_delete += diffs[pointer][1];
277
break;
278
case DIFF_EQUAL:
279
// Upon reaching an equality, check for prior redundancies.
280
if (count_delete >= 1 && count_insert >= 1) {
281
// Delete the offending records and add the merged ones.
282
diffs.splice(pointer - count_delete - count_insert,
283
count_delete + count_insert);
284
pointer = pointer - count_delete - count_insert;
285
var a = this.diff_main(text_delete, text_insert, false, deadline);
286
for (var j = a.length - 1; j >= 0; j--) {
287
diffs.splice(pointer, 0, a[j]);
288
}
289
pointer = pointer + a.length;
290
}
291
count_insert = 0;
292
count_delete = 0;
293
text_delete = '';
294
text_insert = '';
295
break;
296
}
297
pointer++;
298
}
299
diffs.pop(); // Remove the dummy entry at the end.
300
301
return diffs;
302
};
303
304
305
/**
306
* Find the 'middle snake' of a diff, split the problem in two
307
* and return the recursively constructed diff.
308
* See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations.
309
* @param {string} text1 Old string to be diffed.
310
* @param {string} text2 New string to be diffed.
311
* @param {number} deadline Time at which to bail if not yet complete.
312
* @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.
313
* @private
314
*/
315
diff_match_patch.prototype.diff_bisect_ = function(text1, text2, deadline) {
316
//console.log("diff_biset_");
317
// Cache the text lengths to prevent multiple calls.
318
var text1_length = text1.length;
319
var text2_length = text2.length;
320
var max_d = Math.ceil((text1_length + text2_length) / 2);
321
var v_offset = max_d;
322
var v_length = 2 * max_d;
323
var v1 = new Array(v_length);
324
var v2 = new Array(v_length);
325
// Setting all elements to -1 is faster in Chrome & Firefox than mixing
326
// integers and undefined.
327
for (var x = 0; x < v_length; x++) {
328
v1[x] = -1;
329
v2[x] = -1;
330
}
331
v1[v_offset + 1] = 0;
332
v2[v_offset + 1] = 0;
333
var delta = text1_length - text2_length;
334
// If the total number of characters is odd, then the front path will collide
335
// with the reverse path.
336
var front = (delta % 2 != 0);
337
// Offsets for start and end of k loop.
338
// Prevents mapping of space beyond the grid.
339
var k1start = 0;
340
var k1end = 0;
341
var k2start = 0;
342
var k2end = 0;
343
for (var d = 0; d < max_d; d++) {
344
// Bail out if deadline is reached.
345
if ((new Date()).getTime() > deadline) {
346
break;
347
}
348
349
// Walk the front path one step.
350
//console.log("Walk the front path one step.");
351
for (var k1 = -d + k1start; k1 <= d - k1end; k1 += 2) {
352
var k1_offset = v_offset + k1;
353
var x1;
354
if (k1 == -d || (k1 != d && v1[k1_offset - 1] < v1[k1_offset + 1])) {
355
x1 = v1[k1_offset + 1];
356
} else {
357
x1 = v1[k1_offset - 1] + 1;
358
}
359
var y1 = x1 - k1;
360
while (x1 < text1_length && y1 < text2_length &&
361
text1.charAt(x1) == text2.charAt(y1)) {
362
x1++;
363
y1++;
364
}
365
v1[k1_offset] = x1;
366
if (x1 > text1_length) {
367
// Ran off the right of the graph.
368
k1end += 2;
369
} else if (y1 > text2_length) {
370
// Ran off the bottom of the graph.
371
k1start += 2;
372
} else if (front) {
373
var k2_offset = v_offset + delta - k1;
374
if (k2_offset >= 0 && k2_offset < v_length && v2[k2_offset] != -1) {
375
// Mirror x2 onto top-left coordinate system.
376
var x2 = text1_length - v2[k2_offset];
377
if (x1 >= x2) {
378
// Overlap detected.
379
return this.diff_bisectSplit_(text1, text2, x1, y1, deadline);
380
}
381
}
382
}
383
}
384
385
// Walk the reverse path one step.
386
for (var k2 = -d + k2start; k2 <= d - k2end; k2 += 2) {
387
var k2_offset = v_offset + k2;
388
var x2;
389
if (k2 == -d || (k2 != d && v2[k2_offset - 1] < v2[k2_offset + 1])) {
390
x2 = v2[k2_offset + 1];
391
} else {
392
x2 = v2[k2_offset - 1] + 1;
393
}
394
var y2 = x2 - k2;
395
while (x2 < text1_length && y2 < text2_length &&
396
text1.charAt(text1_length - x2 - 1) ==
397
text2.charAt(text2_length - y2 - 1)) {
398
x2++;
399
y2++;
400
}
401
v2[k2_offset] = x2;
402
if (x2 > text1_length) {
403
// Ran off the left of the graph.
404
k2end += 2;
405
} else if (y2 > text2_length) {
406
// Ran off the top of the graph.
407
k2start += 2;
408
} else if (!front) {
409
var k1_offset = v_offset + delta - k2;
410
if (k1_offset >= 0 && k1_offset < v_length && v1[k1_offset] != -1) {
411
var x1 = v1[k1_offset];
412
var y1 = v_offset + x1 - k1_offset;
413
// Mirror x2 onto top-left coordinate system.
414
x2 = text1_length - x2;
415
if (x1 >= x2) {
416
// Overlap detected.
417
return this.diff_bisectSplit_(text1, text2, x1, y1, deadline);
418
}
419
}
420
}
421
}
422
}
423
// Diff took too long and hit the deadline or
424
// number of diffs equals number of characters, no commonality at all.
425
return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]];
426
};
427
428
429
/**
430
* Given the location of the 'middle snake', split the diff in two parts
431
* and recurse.
432
* @param {string} text1 Old string to be diffed.
433
* @param {string} text2 New string to be diffed.
434
* @param {number} x Index of split point in text1.
435
* @param {number} y Index of split point in text2.
436
* @param {number} deadline Time at which to bail if not yet complete.
437
* @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.
438
* @private
439
*/
440
diff_match_patch.prototype.diff_bisectSplit_ = function(text1, text2, x, y,
441
deadline) {
442
var text1a = text1.substring(0, x);
443
var text2a = text2.substring(0, y);
444
var text1b = text1.substring(x);
445
var text2b = text2.substring(y);
446
447
// Compute both diffs serially.
448
var diffs = this.diff_main(text1a, text2a, false, deadline);
449
var diffsb = this.diff_main(text1b, text2b, false, deadline);
450
451
return diffs.concat(diffsb);
452
};
453
454
455
/**
456
* Split two texts into an array of strings. Reduce the texts to a string of
457
* hashes where each Unicode character represents one line.
458
* @param {string} text1 First string.
459
* @param {string} text2 Second string.
460
* @return {{chars1: string, chars2: string, lineArray: !Array.<string>}}
461
* An object containing the encoded text1, the encoded text2 and
462
* the array of unique strings.
463
* The zeroth element of the array of unique strings is intentionally blank.
464
* @private
465
*/
466
diff_match_patch.prototype.diff_linesToChars_ = function(text1, text2) {
467
var lineArray = []; // e.g. lineArray[4] == 'Hello\n'
468
var lineHash = {}; // e.g. lineHash['Hello\n'] == 4
469
470
// '\x00' is a valid character, but various debuggers don't like it.
471
// So we'll insert a junk entry to avoid generating a null character.
472
lineArray[0] = '';
473
474
/**
475
* Split a text into an array of strings. Reduce the texts to a string of
476
* hashes where each Unicode character represents one line.
477
* Modifies linearray and linehash through being a closure.
478
* @param {string} text String to encode.
479
* @return {string} Encoded string.
480
* @private
481
*/
482
function diff_linesToCharsMunge_(text) {
483
var chars = '';
484
// Walk the text, pulling out a substring for each line.
485
// text.split('\n') would would temporarily double our memory footprint.
486
// Modifying text would create many large strings to garbage collect.
487
var lineStart = 0;
488
var lineEnd = -1;
489
// Keeping our own length variable is faster than looking it up.
490
var lineArrayLength = lineArray.length;
491
while (lineEnd < text.length - 1) {
492
lineEnd = text.indexOf('\n', lineStart);
493
if (lineEnd == -1) {
494
lineEnd = text.length - 1;
495
}
496
var line = text.substring(lineStart, lineEnd + 1);
497
lineStart = lineEnd + 1;
498
499
if (lineHash.hasOwnProperty ? lineHash.hasOwnProperty(line) :
500
(lineHash[line] !== undefined)) {
501
chars += String.fromCharCode(lineHash[line]);
502
} else {
503
chars += String.fromCharCode(lineArrayLength);
504
lineHash[line] = lineArrayLength;
505
lineArray[lineArrayLength++] = line;
506
}
507
}
508
return chars;
509
}
510
511
var chars1 = diff_linesToCharsMunge_(text1);
512
var chars2 = diff_linesToCharsMunge_(text2);
513
return {chars1: chars1, chars2: chars2, lineArray: lineArray};
514
};
515
516
517
/**
518
* Rehydrate the text in a diff from a string of line hashes to real lines of
519
* text.
520
* @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
521
* @param {!Array.<string>} lineArray Array of unique strings.
522
* @private
523
*/
524
diff_match_patch.prototype.diff_charsToLines_ = function(diffs, lineArray) {
525
for (var x = 0; x < diffs.length; x++) {
526
var chars = diffs[x][1];
527
var text = [];
528
for (var y = 0; y < chars.length; y++) {
529
text[y] = lineArray[chars.charCodeAt(y)];
530
}
531
diffs[x][1] = text.join('');
532
}
533
};
534
535
536
/**
537
* Determine the common prefix of two strings.
538
* @param {string} text1 First string.
539
* @param {string} text2 Second string.
540
* @return {number} The number of characters common to the start of each
541
* string.
542
*/
543
diff_match_patch.prototype.diff_commonPrefix = function(text1, text2) {
544
// Quick check for common null cases.
545
if (!text1 || !text2 || text1.charAt(0) != text2.charAt(0)) {
546
return 0;
547
}
548
// Binary search.
549
// Performance analysis: http://neil.fraser.name/news/2007/10/09/
550
var pointermin = 0;
551
var pointermax = Math.min(text1.length, text2.length);
552
var pointermid = pointermax;
553
var pointerstart = 0;
554
while (pointermin < pointermid) {
555
if (text1.substring(pointerstart, pointermid) ==
556
text2.substring(pointerstart, pointermid)) {
557
pointermin = pointermid;
558
pointerstart = pointermin;
559
} else {
560
pointermax = pointermid;
561
}
562
pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin);
563
}
564
return pointermid;
565
};
566
567
568
/**
569
* Determine the common suffix of two strings.
570
* @param {string} text1 First string.
571
* @param {string} text2 Second string.
572
* @return {number} The number of characters common to the end of each string.
573
*/
574
diff_match_patch.prototype.diff_commonSuffix = function(text1, text2) {
575
// Quick check for common null cases.
576
if (!text1 || !text2 ||
577
text1.charAt(text1.length - 1) != text2.charAt(text2.length - 1)) {
578
return 0;
579
}
580
// Binary search.
581
// Performance analysis: http://neil.fraser.name/news/2007/10/09/
582
var pointermin = 0;
583
var pointermax = Math.min(text1.length, text2.length);
584
var pointermid = pointermax;
585
var pointerend = 0;
586
while (pointermin < pointermid) {
587
if (text1.substring(text1.length - pointermid, text1.length - pointerend) ==
588
text2.substring(text2.length - pointermid, text2.length - pointerend)) {
589
pointermin = pointermid;
590
pointerend = pointermin;
591
} else {
592
pointermax = pointermid;
593
}
594
pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin);
595
}
596
return pointermid;
597
};
598
599
600
/**
601
* Determine if the suffix of one string is the prefix of another.
602
* @param {string} text1 First string.
603
* @param {string} text2 Second string.
604
* @return {number} The number of characters common to the end of the first
605
* string and the start of the second string.
606
* @private
607
*/
608
diff_match_patch.prototype.diff_commonOverlap_ = function(text1, text2) {
609
// Cache the text lengths to prevent multiple calls.
610
var text1_length = text1.length;
611
var text2_length = text2.length;
612
// Eliminate the null case.
613
if (text1_length == 0 || text2_length == 0) {
614
return 0;
615
}
616
// Truncate the longer string.
617
if (text1_length > text2_length) {
618
text1 = text1.substring(text1_length - text2_length);
619
} else if (text1_length < text2_length) {
620
text2 = text2.substring(0, text1_length);
621
}
622
var text_length = Math.min(text1_length, text2_length);
623
// Quick check for the worst case.
624
if (text1 == text2) {
625
return text_length;
626
}
627
628
// Start by looking for a single character match
629
// and increase length until no match is found.
630
// Performance analysis: http://neil.fraser.name/news/2010/11/04/
631
var best = 0;
632
var length = 1;
633
while (true) {
634
var pattern = text1.substring(text_length - length);
635
var found = text2.indexOf(pattern);
636
if (found == -1) {
637
return best;
638
}
639
length += found;
640
if (found == 0 || text1.substring(text_length - length) ==
641
text2.substring(0, length)) {
642
best = length;
643
length++;
644
}
645
}
646
};
647
648
649
/**
650
* Do the two texts share a substring which is at least half the length of the
651
* longer text?
652
* This speedup can produce non-minimal diffs.
653
* @param {string} text1 First string.
654
* @param {string} text2 Second string.
655
* @return {Array.<string>} Five element Array, containing the prefix of
656
* text1, the suffix of text1, the prefix of text2, the suffix of
657
* text2 and the common middle. Or null if there was no match.
658
* @private
659
*/
660
diff_match_patch.prototype.diff_halfMatch_ = function(text1, text2, deadline) {
661
if (this.Diff_Timeout <= 0) {
662
// Don't risk returning a non-optimal diff if we have unlimited time.
663
return null;
664
}
665
var longtext = text1.length > text2.length ? text1 : text2;
666
var shorttext = text1.length > text2.length ? text2 : text1;
667
if (longtext.length < 4 || shorttext.length * 2 < longtext.length) {
668
return null; // Pointless.
669
}
670
var dmp = this; // 'this' becomes 'window' in a closure.
671
672
/**
673
* Does a substring of shorttext exist within longtext such that the substring
674
* is at least half the length of longtext?
675
* Closure, but does not reference any external variables.
676
* @param {string} longtext Longer string.
677
* @param {string} shorttext Shorter string.
678
* @param {number} i Start index of quarter length substring within longtext.
679
* @return {Array.<string>} Five element Array, containing the prefix of
680
* longtext, the suffix of longtext, the prefix of shorttext, the suffix
681
* of shorttext and the common middle. Or null if there was no match.
682
* @private
683
*/
684
function diff_halfMatchI_(longtext, shorttext, i) {
685
// Start with a 1/4 length substring at position i as a seed.
686
var seed = longtext.substring(i, i + Math.floor(longtext.length / 4));
687
var j = -1;
688
var best_common = '';
689
var best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b;
690
//console.log("start while....");
691
var tr;
692
var k = 0;
693
while ((j = shorttext.indexOf(seed, j + 1)) != -1) {
694
k += 1;
695
if (k % 100 === 0) {
696
tr = deadline - new Date();
697
//console.log("while time left ", deadline, tr);
698
if (tr < 0) {
699
//console.log("exit while early");
700
return null;
701
}
702
}
703
var prefixLength = dmp.diff_commonPrefix(longtext.substring(i),
704
shorttext.substring(j));
705
var suffixLength = dmp.diff_commonSuffix(longtext.substring(0, i),
706
shorttext.substring(0, j));
707
if (best_common.length < suffixLength + prefixLength) {
708
best_common = shorttext.substring(j - suffixLength, j) +
709
shorttext.substring(j, j + prefixLength);
710
best_longtext_a = longtext.substring(0, i - suffixLength);
711
best_longtext_b = longtext.substring(i + prefixLength);
712
best_shorttext_a = shorttext.substring(0, j - suffixLength);
713
best_shorttext_b = shorttext.substring(j + prefixLength);
714
}
715
}
716
if (best_common.length * 2 >= longtext.length) {
717
return [best_longtext_a, best_longtext_b,
718
best_shorttext_a, best_shorttext_b, best_common];
719
} else {
720
return null;
721
}
722
}
723
724
// First check if the second quarter is the seed for a half-match.
725
var hm1 = diff_halfMatchI_(longtext, shorttext,
726
Math.ceil(longtext.length / 4));
727
// Check again based on the third quarter.
728
var hm2 = diff_halfMatchI_(longtext, shorttext,
729
Math.ceil(longtext.length / 2));
730
var hm;
731
if (!hm1 && !hm2) {
732
return null;
733
} else if (!hm2) {
734
hm = hm1;
735
} else if (!hm1) {
736
hm = hm2;
737
} else {
738
// Both matched. Select the longest.
739
hm = hm1[4].length > hm2[4].length ? hm1 : hm2;
740
}
741
742
// A half-match was found, sort out the return data.
743
var text1_a, text1_b, text2_a, text2_b;
744
if (text1.length > text2.length) {
745
text1_a = hm[0];
746
text1_b = hm[1];
747
text2_a = hm[2];
748
text2_b = hm[3];
749
} else {
750
text2_a = hm[0];
751
text2_b = hm[1];
752
text1_a = hm[2];
753
text1_b = hm[3];
754
}
755
var mid_common = hm[4];
756
return [text1_a, text1_b, text2_a, text2_b, mid_common];
757
};
758
759
760
/**
761
* Reduce the number of edits by eliminating semantically trivial equalities.
762
* @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
763
*/
764
diff_match_patch.prototype.diff_cleanupSemantic = function(diffs) {
765
var changes = false;
766
var equalities = []; // Stack of indices where equalities are found.
767
var equalitiesLength = 0; // Keeping our own length var is faster in JS.
768
/** @type {?string} */
769
var lastequality = null;
770
// Always equal to diffs[equalities[equalitiesLength - 1]][1]
771
var pointer = 0; // Index of current position.
772
// Number of characters that changed prior to the equality.
773
var length_insertions1 = 0;
774
var length_deletions1 = 0;
775
// Number of characters that changed after the equality.
776
var length_insertions2 = 0;
777
var length_deletions2 = 0;
778
while (pointer < diffs.length) {
779
if (diffs[pointer][0] == DIFF_EQUAL) { // Equality found.
780
equalities[equalitiesLength++] = pointer;
781
length_insertions1 = length_insertions2;
782
length_deletions1 = length_deletions2;
783
length_insertions2 = 0;
784
length_deletions2 = 0;
785
lastequality = diffs[pointer][1];
786
} else { // An insertion or deletion.
787
if (diffs[pointer][0] == DIFF_INSERT) {
788
length_insertions2 += diffs[pointer][1].length;
789
} else {
790
length_deletions2 += diffs[pointer][1].length;
791
}
792
// Eliminate an equality that is smaller or equal to the edits on both
793
// sides of it.
794
if (lastequality && (lastequality.length <=
795
Math.max(length_insertions1, length_deletions1)) &&
796
(lastequality.length <= Math.max(length_insertions2,
797
length_deletions2))) {
798
// Duplicate record.
799
diffs.splice(equalities[equalitiesLength - 1], 0,
800
[DIFF_DELETE, lastequality]);
801
// Change second copy to insert.
802
diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT;
803
// Throw away the equality we just deleted.
804
equalitiesLength--;
805
// Throw away the previous equality (it needs to be reevaluated).
806
equalitiesLength--;
807
pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1;
808
length_insertions1 = 0; // Reset the counters.
809
length_deletions1 = 0;
810
length_insertions2 = 0;
811
length_deletions2 = 0;
812
lastequality = null;
813
changes = true;
814
}
815
}
816
pointer++;
817
}
818
819
// Normalize the diff.
820
if (changes) {
821
this.diff_cleanupMerge(diffs);
822
}
823
this.diff_cleanupSemanticLossless(diffs);
824
825
// Find any overlaps between deletions and insertions.
826
// e.g: <del>abcxxx</del><ins>xxxdef</ins>
827
// -> <del>abc</del>xxx<ins>def</ins>
828
// e.g: <del>xxxabc</del><ins>defxxx</ins>
829
// -> <ins>def</ins>xxx<del>abc</del>
830
// Only extract an overlap if it is as big as the edit ahead or behind it.
831
pointer = 1;
832
while (pointer < diffs.length) {
833
if (diffs[pointer - 1][0] == DIFF_DELETE &&
834
diffs[pointer][0] == DIFF_INSERT) {
835
var deletion = diffs[pointer - 1][1];
836
var insertion = diffs[pointer][1];
837
var overlap_length1 = this.diff_commonOverlap_(deletion, insertion);
838
var overlap_length2 = this.diff_commonOverlap_(insertion, deletion);
839
if (overlap_length1 >= overlap_length2) {
840
if (overlap_length1 >= deletion.length / 2 ||
841
overlap_length1 >= insertion.length / 2) {
842
// Overlap found. Insert an equality and trim the surrounding edits.
843
diffs.splice(pointer, 0,
844
[DIFF_EQUAL, insertion.substring(0, overlap_length1)]);
845
diffs[pointer - 1][1] =
846
deletion.substring(0, deletion.length - overlap_length1);
847
diffs[pointer + 1][1] = insertion.substring(overlap_length1);
848
pointer++;
849
}
850
} else {
851
if (overlap_length2 >= deletion.length / 2 ||
852
overlap_length2 >= insertion.length / 2) {
853
// Reverse overlap found.
854
// Insert an equality and swap and trim the surrounding edits.
855
diffs.splice(pointer, 0,
856
[DIFF_EQUAL, deletion.substring(0, overlap_length2)]);
857
diffs[pointer - 1][0] = DIFF_INSERT;
858
diffs[pointer - 1][1] =
859
insertion.substring(0, insertion.length - overlap_length2);
860
diffs[pointer + 1][0] = DIFF_DELETE;
861
diffs[pointer + 1][1] =
862
deletion.substring(overlap_length2);
863
pointer++;
864
}
865
}
866
pointer++;
867
}
868
pointer++;
869
}
870
};
871
872
873
/**
874
* Look for single edits surrounded on both sides by equalities
875
* which can be shifted sideways to align the edit to a word boundary.
876
* e.g: The c<ins>at c</ins>ame. -> The <ins>cat </ins>came.
877
* @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
878
*/
879
diff_match_patch.prototype.diff_cleanupSemanticLossless = function(diffs) {
880
/**
881
* Given two strings, compute a score representing whether the internal
882
* boundary falls on logical boundaries.
883
* Scores range from 6 (best) to 0 (worst).
884
* Closure, but does not reference any external variables.
885
* @param {string} one First string.
886
* @param {string} two Second string.
887
* @return {number} The score.
888
* @private
889
*/
890
function diff_cleanupSemanticScore_(one, two) {
891
if (!one || !two) {
892
// Edges are the best.
893
return 6;
894
}
895
896
// Each port of this function behaves slightly differently due to
897
// subtle differences in each language's definition of things like
898
// 'whitespace'. Since this function's purpose is largely cosmetic,
899
// the choice has been made to use each language's native features
900
// rather than force total conformity.
901
var char1 = one.charAt(one.length - 1);
902
var char2 = two.charAt(0);
903
var nonAlphaNumeric1 = char1.match(diff_match_patch.nonAlphaNumericRegex_);
904
var nonAlphaNumeric2 = char2.match(diff_match_patch.nonAlphaNumericRegex_);
905
var whitespace1 = nonAlphaNumeric1 &&
906
char1.match(diff_match_patch.whitespaceRegex_);
907
var whitespace2 = nonAlphaNumeric2 &&
908
char2.match(diff_match_patch.whitespaceRegex_);
909
var lineBreak1 = whitespace1 &&
910
char1.match(diff_match_patch.linebreakRegex_);
911
var lineBreak2 = whitespace2 &&
912
char2.match(diff_match_patch.linebreakRegex_);
913
var blankLine1 = lineBreak1 &&
914
one.match(diff_match_patch.blanklineEndRegex_);
915
var blankLine2 = lineBreak2 &&
916
two.match(diff_match_patch.blanklineStartRegex_);
917
918
if (blankLine1 || blankLine2) {
919
// Five points for blank lines.
920
return 5;
921
} else if (lineBreak1 || lineBreak2) {
922
// Four points for line breaks.
923
return 4;
924
} else if (nonAlphaNumeric1 && !whitespace1 && whitespace2) {
925
// Three points for end of sentences.
926
return 3;
927
} else if (whitespace1 || whitespace2) {
928
// Two points for whitespace.
929
return 2;
930
} else if (nonAlphaNumeric1 || nonAlphaNumeric2) {
931
// One point for non-alphanumeric.
932
return 1;
933
}
934
return 0;
935
}
936
937
var pointer = 1;
938
// Intentionally ignore the first and last element (don't need checking).
939
while (pointer < diffs.length - 1) {
940
if (diffs[pointer - 1][0] == DIFF_EQUAL &&
941
diffs[pointer + 1][0] == DIFF_EQUAL) {
942
// This is a single edit surrounded by equalities.
943
var equality1 = diffs[pointer - 1][1];
944
var edit = diffs[pointer][1];
945
var equality2 = diffs[pointer + 1][1];
946
947
// First, shift the edit as far left as possible.
948
var commonOffset = this.diff_commonSuffix(equality1, edit);
949
if (commonOffset) {
950
var commonString = edit.substring(edit.length - commonOffset);
951
equality1 = equality1.substring(0, equality1.length - commonOffset);
952
edit = commonString + edit.substring(0, edit.length - commonOffset);
953
equality2 = commonString + equality2;
954
}
955
956
// Second, step character by character right, looking for the best fit.
957
var bestEquality1 = equality1;
958
var bestEdit = edit;
959
var bestEquality2 = equality2;
960
var bestScore = diff_cleanupSemanticScore_(equality1, edit) +
961
diff_cleanupSemanticScore_(edit, equality2);
962
while (edit.charAt(0) === equality2.charAt(0)) {
963
equality1 += edit.charAt(0);
964
edit = edit.substring(1) + equality2.charAt(0);
965
equality2 = equality2.substring(1);
966
var score = diff_cleanupSemanticScore_(equality1, edit) +
967
diff_cleanupSemanticScore_(edit, equality2);
968
// The >= encourages trailing rather than leading whitespace on edits.
969
if (score >= bestScore) {
970
bestScore = score;
971
bestEquality1 = equality1;
972
bestEdit = edit;
973
bestEquality2 = equality2;
974
}
975
}
976
977
if (diffs[pointer - 1][1] != bestEquality1) {
978
// We have an improvement, save it back to the diff.
979
if (bestEquality1) {
980
diffs[pointer - 1][1] = bestEquality1;
981
} else {
982
diffs.splice(pointer - 1, 1);
983
pointer--;
984
}
985
diffs[pointer][1] = bestEdit;
986
if (bestEquality2) {
987
diffs[pointer + 1][1] = bestEquality2;
988
} else {
989
diffs.splice(pointer + 1, 1);
990
pointer--;
991
}
992
}
993
}
994
pointer++;
995
}
996
};
997
998
// Define some regex patterns for matching boundaries.
999
diff_match_patch.nonAlphaNumericRegex_ = /[^a-zA-Z0-9]/;
1000
diff_match_patch.whitespaceRegex_ = /\s/;
1001
diff_match_patch.linebreakRegex_ = /[\r\n]/;
1002
diff_match_patch.blanklineEndRegex_ = /\n\r?\n$/;
1003
diff_match_patch.blanklineStartRegex_ = /^\r?\n\r?\n/;
1004
1005
/**
1006
* Reduce the number of edits by eliminating operationally trivial equalities.
1007
* @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
1008
*/
1009
diff_match_patch.prototype.diff_cleanupEfficiency = function(diffs) {
1010
var changes = false;
1011
var equalities = []; // Stack of indices where equalities are found.
1012
var equalitiesLength = 0; // Keeping our own length var is faster in JS.
1013
/** @type {?string} */
1014
var lastequality = null;
1015
// Always equal to diffs[equalities[equalitiesLength - 1]][1]
1016
var pointer = 0; // Index of current position.
1017
// Is there an insertion operation before the last equality.
1018
var pre_ins = false;
1019
// Is there a deletion operation before the last equality.
1020
var pre_del = false;
1021
// Is there an insertion operation after the last equality.
1022
var post_ins = false;
1023
// Is there a deletion operation after the last equality.
1024
var post_del = false;
1025
while (pointer < diffs.length) {
1026
if (diffs[pointer][0] == DIFF_EQUAL) { // Equality found.
1027
if (diffs[pointer][1].length < this.Diff_EditCost &&
1028
(post_ins || post_del)) {
1029
// Candidate found.
1030
equalities[equalitiesLength++] = pointer;
1031
pre_ins = post_ins;
1032
pre_del = post_del;
1033
lastequality = diffs[pointer][1];
1034
} else {
1035
// Not a candidate, and can never become one.
1036
equalitiesLength = 0;
1037
lastequality = null;
1038
}
1039
post_ins = post_del = false;
1040
} else { // An insertion or deletion.
1041
if (diffs[pointer][0] == DIFF_DELETE) {
1042
post_del = true;
1043
} else {
1044
post_ins = true;
1045
}
1046
/*
1047
* Five types to be split:
1048
* <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del>
1049
* <ins>A</ins>X<ins>C</ins><del>D</del>
1050
* <ins>A</ins><del>B</del>X<ins>C</ins>
1051
* <ins>A</del>X<ins>C</ins><del>D</del>
1052
* <ins>A</ins><del>B</del>X<del>C</del>
1053
*/
1054
if (lastequality && ((pre_ins && pre_del && post_ins && post_del) ||
1055
((lastequality.length < this.Diff_EditCost / 2) &&
1056
(pre_ins + pre_del + post_ins + post_del) == 3))) {
1057
// Duplicate record.
1058
diffs.splice(equalities[equalitiesLength - 1], 0,
1059
[DIFF_DELETE, lastequality]);
1060
// Change second copy to insert.
1061
diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT;
1062
equalitiesLength--; // Throw away the equality we just deleted;
1063
lastequality = null;
1064
if (pre_ins && pre_del) {
1065
// No changes made which could affect previous entry, keep going.
1066
post_ins = post_del = true;
1067
equalitiesLength = 0;
1068
} else {
1069
equalitiesLength--; // Throw away the previous equality.
1070
pointer = equalitiesLength > 0 ?
1071
equalities[equalitiesLength - 1] : -1;
1072
post_ins = post_del = false;
1073
}
1074
changes = true;
1075
}
1076
}
1077
pointer++;
1078
}
1079
1080
if (changes) {
1081
this.diff_cleanupMerge(diffs);
1082
}
1083
};
1084
1085
1086
/**
1087
* Reorder and merge like edit sections. Merge equalities.
1088
* Any edit section can move as long as it doesn't cross an equality.
1089
* @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
1090
*/
1091
diff_match_patch.prototype.diff_cleanupMerge = function(diffs) {
1092
diffs.push([DIFF_EQUAL, '']); // Add a dummy entry at the end.
1093
var pointer = 0;
1094
var count_delete = 0;
1095
var count_insert = 0;
1096
var text_delete = '';
1097
var text_insert = '';
1098
var commonlength;
1099
while (pointer < diffs.length) {
1100
switch (diffs[pointer][0]) {
1101
case DIFF_INSERT:
1102
count_insert++;
1103
text_insert += diffs[pointer][1];
1104
pointer++;
1105
break;
1106
case DIFF_DELETE:
1107
count_delete++;
1108
text_delete += diffs[pointer][1];
1109
pointer++;
1110
break;
1111
case DIFF_EQUAL:
1112
// Upon reaching an equality, check for prior redundancies.
1113
if (count_delete + count_insert > 1) {
1114
if (count_delete !== 0 && count_insert !== 0) {
1115
// Factor out any common prefixies.
1116
commonlength = this.diff_commonPrefix(text_insert, text_delete);
1117
if (commonlength !== 0) {
1118
if ((pointer - count_delete - count_insert) > 0 &&
1119
diffs[pointer - count_delete - count_insert - 1][0] ==
1120
DIFF_EQUAL) {
1121
diffs[pointer - count_delete - count_insert - 1][1] +=
1122
text_insert.substring(0, commonlength);
1123
} else {
1124
diffs.splice(0, 0, [DIFF_EQUAL,
1125
text_insert.substring(0, commonlength)]);
1126
pointer++;
1127
}
1128
text_insert = text_insert.substring(commonlength);
1129
text_delete = text_delete.substring(commonlength);
1130
}
1131
// Factor out any common suffixies.
1132
commonlength = this.diff_commonSuffix(text_insert, text_delete);
1133
if (commonlength !== 0) {
1134
diffs[pointer][1] = text_insert.substring(text_insert.length -
1135
commonlength) + diffs[pointer][1];
1136
text_insert = text_insert.substring(0, text_insert.length -
1137
commonlength);
1138
text_delete = text_delete.substring(0, text_delete.length -
1139
commonlength);
1140
}
1141
}
1142
// Delete the offending records and add the merged ones.
1143
if (count_delete === 0) {
1144
diffs.splice(pointer - count_insert,
1145
count_delete + count_insert, [DIFF_INSERT, text_insert]);
1146
} else if (count_insert === 0) {
1147
diffs.splice(pointer - count_delete,
1148
count_delete + count_insert, [DIFF_DELETE, text_delete]);
1149
} else {
1150
diffs.splice(pointer - count_delete - count_insert,
1151
count_delete + count_insert, [DIFF_DELETE, text_delete],
1152
[DIFF_INSERT, text_insert]);
1153
}
1154
pointer = pointer - count_delete - count_insert +
1155
(count_delete ? 1 : 0) + (count_insert ? 1 : 0) + 1;
1156
} else if (pointer !== 0 && diffs[pointer - 1][0] == DIFF_EQUAL) {
1157
// Merge this equality with the previous one.
1158
diffs[pointer - 1][1] += diffs[pointer][1];
1159
diffs.splice(pointer, 1);
1160
} else {
1161
pointer++;
1162
}
1163
count_insert = 0;
1164
count_delete = 0;
1165
text_delete = '';
1166
text_insert = '';
1167
break;
1168
}
1169
}
1170
if (diffs[diffs.length - 1][1] === '') {
1171
diffs.pop(); // Remove the dummy entry at the end.
1172
}
1173
1174
// Second pass: look for single edits surrounded on both sides by equalities
1175
// which can be shifted sideways to eliminate an equality.
1176
// e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC
1177
var changes = false;
1178
pointer = 1;
1179
// Intentionally ignore the first and last element (don't need checking).
1180
while (pointer < diffs.length - 1) {
1181
if (diffs[pointer - 1][0] == DIFF_EQUAL &&
1182
diffs[pointer + 1][0] == DIFF_EQUAL) {
1183
// This is a single edit surrounded by equalities.
1184
if (diffs[pointer][1].substring(diffs[pointer][1].length -
1185
diffs[pointer - 1][1].length) == diffs[pointer - 1][1]) {
1186
// Shift the edit over the previous equality.
1187
diffs[pointer][1] = diffs[pointer - 1][1] +
1188
diffs[pointer][1].substring(0, diffs[pointer][1].length -
1189
diffs[pointer - 1][1].length);
1190
diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1];
1191
diffs.splice(pointer - 1, 1);
1192
changes = true;
1193
} else if (diffs[pointer][1].substring(0, diffs[pointer + 1][1].length) ==
1194
diffs[pointer + 1][1]) {
1195
// Shift the edit over the next equality.
1196
diffs[pointer - 1][1] += diffs[pointer + 1][1];
1197
diffs[pointer][1] =
1198
diffs[pointer][1].substring(diffs[pointer + 1][1].length) +
1199
diffs[pointer + 1][1];
1200
diffs.splice(pointer + 1, 1);
1201
changes = true;
1202
}
1203
}
1204
pointer++;
1205
}
1206
// If shifts were made, the diff needs reordering and another shift sweep.
1207
if (changes) {
1208
this.diff_cleanupMerge(diffs);
1209
}
1210
};
1211
1212
1213
/**
1214
* loc is a location in text1, compute and return the equivalent location in
1215
* text2.
1216
* e.g. 'The cat' vs 'The big cat', 1->1, 5->8
1217
* @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
1218
* @param {number} loc Location within text1.
1219
* @return {number} Location within text2.
1220
*/
1221
diff_match_patch.prototype.diff_xIndex = function(diffs, loc) {
1222
var chars1 = 0;
1223
var chars2 = 0;
1224
var last_chars1 = 0;
1225
var last_chars2 = 0;
1226
var x;
1227
for (x = 0; x < diffs.length; x++) {
1228
if (diffs[x][0] !== DIFF_INSERT) { // Equality or deletion.
1229
chars1 += diffs[x][1].length;
1230
}
1231
if (diffs[x][0] !== DIFF_DELETE) { // Equality or insertion.
1232
chars2 += diffs[x][1].length;
1233
}
1234
if (chars1 > loc) { // Overshot the location.
1235
break;
1236
}
1237
last_chars1 = chars1;
1238
last_chars2 = chars2;
1239
}
1240
// Was the location was deleted?
1241
if (diffs.length != x && diffs[x][0] === DIFF_DELETE) {
1242
return last_chars2;
1243
}
1244
// Add the remaining character length.
1245
return last_chars2 + (loc - last_chars1);
1246
};
1247
1248
1249
/**
1250
* Convert a diff array into a pretty HTML report.
1251
* @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
1252
* @return {string} HTML representation.
1253
*/
1254
diff_match_patch.prototype.diff_prettyHtml = function(diffs) {
1255
var html = [];
1256
var pattern_amp = /&/g;
1257
var pattern_lt = /</g;
1258
var pattern_gt = />/g;
1259
var pattern_para = /\n/g;
1260
for (var x = 0; x < diffs.length; x++) {
1261
var op = diffs[x][0]; // Operation (insert, delete, equal)
1262
var data = diffs[x][1]; // Text of change.
1263
var text = data.replace(pattern_amp, '&amp;').replace(pattern_lt, '&lt;')
1264
.replace(pattern_gt, '&gt;').replace(pattern_para, '&para;<br>');
1265
switch (op) {
1266
case DIFF_INSERT:
1267
html[x] = '<ins style="background:#e6ffe6;">' + text + '</ins>';
1268
break;
1269
case DIFF_DELETE:
1270
html[x] = '<del style="background:#ffe6e6;">' + text + '</del>';
1271
break;
1272
case DIFF_EQUAL:
1273
html[x] = '<span>' + text + '</span>';
1274
break;
1275
}
1276
}
1277
return html.join('');
1278
};
1279
1280
1281
/**
1282
* Compute and return the source text (all equalities and deletions).
1283
* @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
1284
* @return {string} Source text.
1285
*/
1286
diff_match_patch.prototype.diff_text1 = function(diffs) {
1287
var text = [];
1288
for (var x = 0; x < diffs.length; x++) {
1289
if (diffs[x][0] !== DIFF_INSERT) {
1290
text[x] = diffs[x][1];
1291
}
1292
}
1293
return text.join('');
1294
};
1295
1296
1297
/**
1298
* Compute and return the destination text (all equalities and insertions).
1299
* @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
1300
* @return {string} Destination text.
1301
*/
1302
diff_match_patch.prototype.diff_text2 = function(diffs) {
1303
var text = [];
1304
for (var x = 0; x < diffs.length; x++) {
1305
if (diffs[x][0] !== DIFF_DELETE) {
1306
text[x] = diffs[x][1];
1307
}
1308
}
1309
return text.join('');
1310
};
1311
1312
1313
/**
1314
* Compute the Levenshtein distance; the number of inserted, deleted or
1315
* substituted characters.
1316
* @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
1317
* @return {number} Number of changes.
1318
*/
1319
diff_match_patch.prototype.diff_levenshtein = function(diffs) {
1320
var levenshtein = 0;
1321
var insertions = 0;
1322
var deletions = 0;
1323
for (var x = 0; x < diffs.length; x++) {
1324
var op = diffs[x][0];
1325
var data = diffs[x][1];
1326
switch (op) {
1327
case DIFF_INSERT:
1328
insertions += data.length;
1329
break;
1330
case DIFF_DELETE:
1331
deletions += data.length;
1332
break;
1333
case DIFF_EQUAL:
1334
// A deletion and an insertion is one substitution.
1335
levenshtein += Math.max(insertions, deletions);
1336
insertions = 0;
1337
deletions = 0;
1338
break;
1339
}
1340
}
1341
levenshtein += Math.max(insertions, deletions);
1342
return levenshtein;
1343
};
1344
1345
1346
/**
1347
* Crush the diff into an encoded string which describes the operations
1348
* required to transform text1 into text2.
1349
* E.g. =3\t-2\t+ing -> Keep 3 chars, delete 2 chars, insert 'ing'.
1350
* Operations are tab-separated. Inserted text is escaped using %xx notation.
1351
* @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
1352
* @return {string} Delta text.
1353
*/
1354
diff_match_patch.prototype.diff_toDelta = function(diffs) {
1355
var text = [];
1356
for (var x = 0; x < diffs.length; x++) {
1357
switch (diffs[x][0]) {
1358
case DIFF_INSERT:
1359
text[x] = '+' + encodeURI(diffs[x][1]);
1360
break;
1361
case DIFF_DELETE:
1362
text[x] = '-' + diffs[x][1].length;
1363
break;
1364
case DIFF_EQUAL:
1365
text[x] = '=' + diffs[x][1].length;
1366
break;
1367
}
1368
}
1369
return text.join('\t').replace(/%20/g, ' ');
1370
};
1371
1372
1373
/**
1374
* Given the original text1, and an encoded string which describes the
1375
* operations required to transform text1 into text2, compute the full diff.
1376
* @param {string} text1 Source string for the diff.
1377
* @param {string} delta Delta text.
1378
* @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.
1379
* @throws {!Error} If invalid input.
1380
*/
1381
diff_match_patch.prototype.diff_fromDelta = function(text1, delta) {
1382
var diffs = [];
1383
var diffsLength = 0; // Keeping our own length var is faster in JS.
1384
var pointer = 0; // Cursor in text1
1385
var tokens = delta.split(/\t/g);
1386
for (var x = 0; x < tokens.length; x++) {
1387
// Each token begins with a one character parameter which specifies the
1388
// operation of this token (delete, insert, equality).
1389
var param = tokens[x].substring(1);
1390
switch (tokens[x].charAt(0)) {
1391
case '+':
1392
try {
1393
diffs[diffsLength++] = [DIFF_INSERT, decodeURI(param)];
1394
} catch (ex) {
1395
// Malformed URI sequence.
1396
throw new Error('Illegal escape in diff_fromDelta: ' + param);
1397
}
1398
break;
1399
case '-':
1400
// Fall through.
1401
case '=':
1402
var n = parseInt(param, 10);
1403
if (isNaN(n) || n < 0) {
1404
throw new Error('Invalid number in diff_fromDelta: ' + param);
1405
}
1406
var text = text1.substring(pointer, pointer += n);
1407
if (tokens[x].charAt(0) == '=') {
1408
diffs[diffsLength++] = [DIFF_EQUAL, text];
1409
} else {
1410
diffs[diffsLength++] = [DIFF_DELETE, text];
1411
}
1412
break;
1413
default:
1414
// Blank tokens are ok (from a trailing \t).
1415
// Anything else is an error.
1416
if (tokens[x]) {
1417
throw new Error('Invalid diff operation in diff_fromDelta: ' +
1418
tokens[x]);
1419
}
1420
}
1421
}
1422
if (pointer != text1.length) {
1423
throw new Error('Delta length (' + pointer +
1424
') does not equal source text length (' + text1.length + ').');
1425
}
1426
return diffs;
1427
};
1428
1429
1430
// MATCH FUNCTIONS
1431
1432
1433
/**
1434
* Locate the best instance of 'pattern' in 'text' near 'loc'.
1435
* @param {string} text The text to search.
1436
* @param {string} pattern The pattern to search for.
1437
* @param {number} loc The location to search around.
1438
* @return {number} Best match index or -1.
1439
*/
1440
diff_match_patch.prototype.match_main = function(text, pattern, loc) {
1441
// Check for null inputs.
1442
if (text == null || pattern == null || loc == null) {
1443
throw new Error('Null input. (match_main)');
1444
}
1445
1446
loc = Math.max(0, Math.min(loc, text.length));
1447
if (text == pattern) {
1448
// Shortcut (potentially not guaranteed by the algorithm)
1449
return 0;
1450
} else if (!text.length) {
1451
// Nothing to match.
1452
return -1;
1453
} else if (text.substring(loc, loc + pattern.length) == pattern) {
1454
// Perfect match at the perfect spot! (Includes case of null pattern)
1455
return loc;
1456
} else {
1457
// Do a fuzzy compare.
1458
return this.match_bitap_(text, pattern, loc);
1459
}
1460
};
1461
1462
1463
/**
1464
* Locate the best instance of 'pattern' in 'text' near 'loc' using the
1465
* Bitap algorithm.
1466
* @param {string} text The text to search.
1467
* @param {string} pattern The pattern to search for.
1468
* @param {number} loc The location to search around.
1469
* @return {number} Best match index or -1.
1470
* @private
1471
*/
1472
diff_match_patch.prototype.match_bitap_ = function(text, pattern, loc) {
1473
if (pattern.length > this.Match_MaxBits) {
1474
throw new Error('Pattern too long for this browser.');
1475
}
1476
1477
// Initialise the alphabet.
1478
var s = this.match_alphabet_(pattern);
1479
1480
var dmp = this; // 'this' becomes 'window' in a closure.
1481
1482
/**
1483
* Compute and return the score for a match with e errors and x location.
1484
* Accesses loc and pattern through being a closure.
1485
* @param {number} e Number of errors in match.
1486
* @param {number} x Location of match.
1487
* @return {number} Overall score for match (0.0 = good, 1.0 = bad).
1488
* @private
1489
*/
1490
function match_bitapScore_(e, x) {
1491
var accuracy = e / pattern.length;
1492
var proximity = Math.abs(loc - x);
1493
if (!dmp.Match_Distance) {
1494
// Dodge divide by zero error.
1495
return proximity ? 1.0 : accuracy;
1496
}
1497
return accuracy + (proximity / dmp.Match_Distance);
1498
}
1499
1500
// Highest score beyond which we give up.
1501
var score_threshold = this.Match_Threshold;
1502
// Is there a nearby exact match? (speedup)
1503
var best_loc = text.indexOf(pattern, loc);
1504
if (best_loc != -1) {
1505
score_threshold = Math.min(match_bitapScore_(0, best_loc), score_threshold);
1506
// What about in the other direction? (speedup)
1507
best_loc = text.lastIndexOf(pattern, loc + pattern.length);
1508
if (best_loc != -1) {
1509
score_threshold =
1510
Math.min(match_bitapScore_(0, best_loc), score_threshold);
1511
}
1512
}
1513
1514
// Initialise the bit arrays.
1515
var matchmask = 1 << (pattern.length - 1);
1516
best_loc = -1;
1517
1518
var bin_min, bin_mid;
1519
var bin_max = pattern.length + text.length;
1520
var last_rd;
1521
for (var d = 0; d < pattern.length; d++) {
1522
// Scan for the best match; each iteration allows for one more error.
1523
// Run a binary search to determine how far from 'loc' we can stray at this
1524
// error level.
1525
bin_min = 0;
1526
bin_mid = bin_max;
1527
while (bin_min < bin_mid) {
1528
if (match_bitapScore_(d, loc + bin_mid) <= score_threshold) {
1529
bin_min = bin_mid;
1530
} else {
1531
bin_max = bin_mid;
1532
}
1533
bin_mid = Math.floor((bin_max - bin_min) / 2 + bin_min);
1534
}
1535
// Use the result from this iteration as the maximum for the next.
1536
bin_max = bin_mid;
1537
var start = Math.max(1, loc - bin_mid + 1);
1538
var finish = Math.min(loc + bin_mid, text.length) + pattern.length;
1539
1540
var rd = Array(finish + 2);
1541
rd[finish + 1] = (1 << d) - 1;
1542
for (var j = finish; j >= start; j--) {
1543
// The alphabet (s) is a sparse hash, so the following line generates
1544
// warnings.
1545
var charMatch = s[text.charAt(j - 1)];
1546
if (d === 0) { // First pass: exact match.
1547
rd[j] = ((rd[j + 1] << 1) | 1) & charMatch;
1548
} else { // Subsequent passes: fuzzy match.
1549
rd[j] = (((rd[j + 1] << 1) | 1) & charMatch) |
1550
(((last_rd[j + 1] | last_rd[j]) << 1) | 1) |
1551
last_rd[j + 1];
1552
}
1553
if (rd[j] & matchmask) {
1554
var score = match_bitapScore_(d, j - 1);
1555
// This match will almost certainly be better than any existing match.
1556
// But check anyway.
1557
if (score <= score_threshold) {
1558
// Told you so.
1559
score_threshold = score;
1560
best_loc = j - 1;
1561
if (best_loc > loc) {
1562
// When passing loc, don't exceed our current distance from loc.
1563
start = Math.max(1, 2 * loc - best_loc);
1564
} else {
1565
// Already passed loc, downhill from here on in.
1566
break;
1567
}
1568
}
1569
}
1570
}
1571
// No hope for a (better) match at greater error levels.
1572
if (match_bitapScore_(d + 1, loc) > score_threshold) {
1573
break;
1574
}
1575
last_rd = rd;
1576
}
1577
return best_loc;
1578
};
1579
1580
1581
/**
1582
* Initialise the alphabet for the Bitap algorithm.
1583
* @param {string} pattern The text to encode.
1584
* @return {!Object} Hash of character locations.
1585
* @private
1586
*/
1587
diff_match_patch.prototype.match_alphabet_ = function(pattern) {
1588
var s = {};
1589
for (var i = 0; i < pattern.length; i++) {
1590
s[pattern.charAt(i)] = 0;
1591
}
1592
for (var i = 0; i < pattern.length; i++) {
1593
s[pattern.charAt(i)] |= 1 << (pattern.length - i - 1);
1594
}
1595
return s;
1596
};
1597
1598
1599
// PATCH FUNCTIONS
1600
1601
1602
/**
1603
* Increase the context until it is unique,
1604
* but don't let the pattern expand beyond Match_MaxBits.
1605
* @param {!diff_match_patch.patch_obj} patch The patch to grow.
1606
* @param {string} text Source text.
1607
* @private
1608
*/
1609
diff_match_patch.prototype.patch_addContext_ = function(patch, text) {
1610
if (text.length == 0) {
1611
return;
1612
}
1613
var pattern = text.substring(patch.start2, patch.start2 + patch.length1);
1614
var padding = 0;
1615
1616
// Look for the first and last matches of pattern in text. If two different
1617
// matches are found, increase the pattern length.
1618
while (text.indexOf(pattern) != text.lastIndexOf(pattern) &&
1619
pattern.length < this.Match_MaxBits - this.Patch_Margin -
1620
this.Patch_Margin) {
1621
padding += this.Patch_Margin;
1622
pattern = text.substring(patch.start2 - padding,
1623
patch.start2 + patch.length1 + padding);
1624
}
1625
// Add one chunk for good luck.
1626
padding += this.Patch_Margin;
1627
1628
// Add the prefix.
1629
var prefix = text.substring(patch.start2 - padding, patch.start2);
1630
if (prefix) {
1631
patch.diffs.unshift([DIFF_EQUAL, prefix]);
1632
}
1633
// Add the suffix.
1634
var suffix = text.substring(patch.start2 + patch.length1,
1635
patch.start2 + patch.length1 + padding);
1636
if (suffix) {
1637
patch.diffs.push([DIFF_EQUAL, suffix]);
1638
}
1639
1640
// Roll back the start points.
1641
patch.start1 -= prefix.length;
1642
patch.start2 -= prefix.length;
1643
// Extend the lengths.
1644
patch.length1 += prefix.length + suffix.length;
1645
patch.length2 += prefix.length + suffix.length;
1646
};
1647
1648
1649
/**
1650
* Compute a list of patches to turn text1 into text2.
1651
* Use diffs if provided, otherwise compute it ourselves.
1652
* There are four ways to call this function, depending on what data is
1653
* available to the caller:
1654
* Method 1:
1655
* a = text1, b = text2
1656
* Method 2:
1657
* a = diffs
1658
* Method 3 (optimal):
1659
* a = text1, b = diffs
1660
* Method 4 (deprecated, use method 3):
1661
* a = text1, b = text2, c = diffs
1662
*
1663
* @param {string|!Array.<!diff_match_patch.Diff>} a text1 (methods 1,3,4) or
1664
* Array of diff tuples for text1 to text2 (method 2).
1665
* @param {string|!Array.<!diff_match_patch.Diff>} opt_b text2 (methods 1,4) or
1666
* Array of diff tuples for text1 to text2 (method 3) or undefined (method 2).
1667
* @param {string|!Array.<!diff_match_patch.Diff>} opt_c Array of diff tuples
1668
* for text1 to text2 (method 4) or undefined (methods 1,2,3).
1669
* @return {!Array.<!diff_match_patch.patch_obj>} Array of Patch objects.
1670
*/
1671
diff_match_patch.prototype.patch_make = function(a, opt_b, opt_c) {
1672
//console.log("patch_make");
1673
var text1, diffs;
1674
if (typeof a == 'string' && typeof opt_b == 'string' &&
1675
typeof opt_c == 'undefined') {
1676
// Method 1: text1, text2
1677
// Compute diffs from text1 and text2.
1678
text1 = /** @type {string} */(a);
1679
diffs = this.diff_main(text1, /** @type {string} */(opt_b), true);
1680
if (diffs.length > 2) {
1681
this.diff_cleanupSemantic(diffs);
1682
this.diff_cleanupEfficiency(diffs);
1683
}
1684
} else if (a && typeof a == 'object' && typeof opt_b == 'undefined' &&
1685
typeof opt_c == 'undefined') {
1686
// Method 2: diffs
1687
// Compute text1 from diffs.
1688
diffs = /** @type {!Array.<!diff_match_patch.Diff>} */(a);
1689
text1 = this.diff_text1(diffs);
1690
} else if (typeof a == 'string' && opt_b && typeof opt_b == 'object' &&
1691
typeof opt_c == 'undefined') {
1692
// Method 3: text1, diffs
1693
text1 = /** @type {string} */(a);
1694
diffs = /** @type {!Array.<!diff_match_patch.Diff>} */(opt_b);
1695
} else if (typeof a == 'string' && typeof opt_b == 'string' &&
1696
opt_c && typeof opt_c == 'object') {
1697
// Method 4: text1, text2, diffs
1698
// text2 is not used.
1699
text1 = /** @type {string} */(a);
1700
diffs = /** @type {!Array.<!diff_match_patch.Diff>} */(opt_c);
1701
} else {
1702
throw new Error('Unknown call format to patch_make.');
1703
}
1704
1705
if (diffs.length === 0) {
1706
return []; // Get rid of the null case.
1707
}
1708
var patches = [];
1709
var patch = new diff_match_patch.patch_obj();
1710
var patchDiffLength = 0; // Keeping our own length var is faster in JS.
1711
var char_count1 = 0; // Number of characters into the text1 string.
1712
var char_count2 = 0; // Number of characters into the text2 string.
1713
// Start with text1 (prepatch_text) and apply the diffs until we arrive at
1714
// text2 (postpatch_text). We recreate the patches one by one to determine
1715
// context info.
1716
var prepatch_text = text1;
1717
var postpatch_text = text1;
1718
for (var x = 0; x < diffs.length; x++) {
1719
var diff_type = diffs[x][0];
1720
var diff_text = diffs[x][1];
1721
1722
if (!patchDiffLength && diff_type !== DIFF_EQUAL) {
1723
// A new patch starts here.
1724
patch.start1 = char_count1;
1725
patch.start2 = char_count2;
1726
}
1727
1728
switch (diff_type) {
1729
case DIFF_INSERT:
1730
patch.diffs[patchDiffLength++] = diffs[x];
1731
patch.length2 += diff_text.length;
1732
postpatch_text = postpatch_text.substring(0, char_count2) + diff_text +
1733
postpatch_text.substring(char_count2);
1734
break;
1735
case DIFF_DELETE:
1736
patch.length1 += diff_text.length;
1737
patch.diffs[patchDiffLength++] = diffs[x];
1738
postpatch_text = postpatch_text.substring(0, char_count2) +
1739
postpatch_text.substring(char_count2 +
1740
diff_text.length);
1741
break;
1742
case DIFF_EQUAL:
1743
if (diff_text.length <= 2 * this.Patch_Margin &&
1744
patchDiffLength && diffs.length != x + 1) {
1745
// Small equality inside a patch.
1746
patch.diffs[patchDiffLength++] = diffs[x];
1747
patch.length1 += diff_text.length;
1748
patch.length2 += diff_text.length;
1749
} else if (diff_text.length >= 2 * this.Patch_Margin) {
1750
// Time for a new patch.
1751
if (patchDiffLength) {
1752
this.patch_addContext_(patch, prepatch_text);
1753
patches.push(patch);
1754
patch = new diff_match_patch.patch_obj();
1755
patchDiffLength = 0;
1756
// Unlike Unidiff, our patch lists have a rolling context.
1757
// http://code.google.com/p/google-diff-match-patch/wiki/Unidiff
1758
// Update prepatch text & pos to reflect the application of the
1759
// just completed patch.
1760
prepatch_text = postpatch_text;
1761
char_count1 = char_count2;
1762
}
1763
}
1764
break;
1765
}
1766
1767
// Update the current character count.
1768
if (diff_type !== DIFF_INSERT) {
1769
char_count1 += diff_text.length;
1770
}
1771
if (diff_type !== DIFF_DELETE) {
1772
char_count2 += diff_text.length;
1773
}
1774
}
1775
// Pick up the leftover patch if not empty.
1776
if (patchDiffLength) {
1777
this.patch_addContext_(patch, prepatch_text);
1778
patches.push(patch);
1779
}
1780
1781
return patches;
1782
};
1783
1784
1785
/**
1786
* Given an array of patches, return another array that is identical.
1787
* @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects.
1788
* @return {!Array.<!diff_match_patch.patch_obj>} Array of Patch objects.
1789
*/
1790
diff_match_patch.prototype.patch_deepCopy = function(patches) {
1791
// Making deep copies is hard in JavaScript.
1792
var patchesCopy = [];
1793
for (var x = 0; x < patches.length; x++) {
1794
var patch = patches[x];
1795
var patchCopy = new diff_match_patch.patch_obj();
1796
patchCopy.diffs = [];
1797
for (var y = 0; y < patch.diffs.length; y++) {
1798
patchCopy.diffs[y] = patch.diffs[y].slice();
1799
}
1800
patchCopy.start1 = patch.start1;
1801
patchCopy.start2 = patch.start2;
1802
patchCopy.length1 = patch.length1;
1803
patchCopy.length2 = patch.length2;
1804
patchesCopy[x] = patchCopy;
1805
}
1806
return patchesCopy;
1807
};
1808
1809
1810
/**
1811
* Merge a set of patches onto the text. Return a patched text, as well
1812
* as a list of true/false values indicating which patches were applied.
1813
* @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects.
1814
* @param {string} text Old text.
1815
* @return {!Array.<string|!Array.<boolean>>} Two element Array, containing the
1816
* new text and an array of boolean values.
1817
*/
1818
diff_match_patch.prototype.patch_apply = function(patches, text) {
1819
if (patches.length == 0) {
1820
return [text, []];
1821
}
1822
1823
// Deep copy the patches so that no changes are made to originals.
1824
patches = this.patch_deepCopy(patches);
1825
1826
var nullPadding = this.patch_addPadding(patches);
1827
text = nullPadding + text + nullPadding;
1828
1829
this.patch_splitMax(patches);
1830
// delta keeps track of the offset between the expected and actual location
1831
// of the previous patch. If there are patches expected at positions 10 and
1832
// 20, but the first patch was found at 12, delta is 2 and the second patch
1833
// has an effective expected position of 22.
1834
var delta = 0;
1835
var results = [];
1836
for (var x = 0; x < patches.length; x++) {
1837
var expected_loc = patches[x].start2 + delta;
1838
var text1 = this.diff_text1(patches[x].diffs);
1839
var start_loc;
1840
var end_loc = -1;
1841
if (text1.length > this.Match_MaxBits) {
1842
// patch_splitMax will only provide an oversized pattern in the case of
1843
// a monster delete.
1844
start_loc = this.match_main(text, text1.substring(0, this.Match_MaxBits),
1845
expected_loc);
1846
if (start_loc != -1) {
1847
end_loc = this.match_main(text,
1848
text1.substring(text1.length - this.Match_MaxBits),
1849
expected_loc + text1.length - this.Match_MaxBits);
1850
if (end_loc == -1 || start_loc >= end_loc) {
1851
// Can't find valid trailing context. Drop this patch.
1852
start_loc = -1;
1853
}
1854
}
1855
} else {
1856
start_loc = this.match_main(text, text1, expected_loc);
1857
}
1858
if (start_loc == -1) {
1859
// No match found. :(
1860
results[x] = false;
1861
// Subtract the delta for this failed patch from subsequent patches.
1862
delta -= patches[x].length2 - patches[x].length1;
1863
} else {
1864
// Found a match. :)
1865
results[x] = true;
1866
delta = start_loc - expected_loc;
1867
var text2;
1868
if (end_loc == -1) {
1869
text2 = text.substring(start_loc, start_loc + text1.length);
1870
} else {
1871
text2 = text.substring(start_loc, end_loc + this.Match_MaxBits);
1872
}
1873
if (text1 == text2) {
1874
// Perfect match, just shove the replacement text in.
1875
text = text.substring(0, start_loc) +
1876
this.diff_text2(patches[x].diffs) +
1877
text.substring(start_loc + text1.length);
1878
} else {
1879
// Imperfect match. Run a diff to get a framework of equivalent
1880
// indices.
1881
var diffs = this.diff_main(text1, text2, false);
1882
if (text1.length > this.Match_MaxBits &&
1883
this.diff_levenshtein(diffs) / text1.length >
1884
this.Patch_DeleteThreshold) {
1885
// The end points match, but the content is unacceptably bad.
1886
results[x] = false;
1887
} else {
1888
this.diff_cleanupSemanticLossless(diffs);
1889
var index1 = 0;
1890
var index2;
1891
for (var y = 0; y < patches[x].diffs.length; y++) {
1892
var mod = patches[x].diffs[y];
1893
if (mod[0] !== DIFF_EQUAL) {
1894
index2 = this.diff_xIndex(diffs, index1);
1895
}
1896
if (mod[0] === DIFF_INSERT) { // Insertion
1897
text = text.substring(0, start_loc + index2) + mod[1] +
1898
text.substring(start_loc + index2);
1899
} else if (mod[0] === DIFF_DELETE) { // Deletion
1900
text = text.substring(0, start_loc + index2) +
1901
text.substring(start_loc + this.diff_xIndex(diffs,
1902
index1 + mod[1].length));
1903
}
1904
if (mod[0] !== DIFF_DELETE) {
1905
index1 += mod[1].length;
1906
}
1907
}
1908
}
1909
}
1910
}
1911
}
1912
// Strip the padding off.
1913
text = text.substring(nullPadding.length, text.length - nullPadding.length);
1914
return [text, results];
1915
};
1916
1917
1918
/**
1919
* Add some padding on text start and end so that edges can match something.
1920
* Intended to be called only from within patch_apply.
1921
* @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects.
1922
* @return {string} The padding string added to each side.
1923
*/
1924
diff_match_patch.prototype.patch_addPadding = function(patches) {
1925
var paddingLength = this.Patch_Margin;
1926
var nullPadding = '';
1927
for (var x = 1; x <= paddingLength; x++) {
1928
nullPadding += String.fromCharCode(x);
1929
}
1930
1931
// Bump all the patches forward.
1932
for (var x = 0; x < patches.length; x++) {
1933
patches[x].start1 += paddingLength;
1934
patches[x].start2 += paddingLength;
1935
}
1936
1937
// Add some padding on start of first diff.
1938
var patch = patches[0];
1939
var diffs = patch.diffs;
1940
if (diffs.length == 0 || diffs[0][0] != DIFF_EQUAL) {
1941
// Add nullPadding equality.
1942
diffs.unshift([DIFF_EQUAL, nullPadding]);
1943
patch.start1 -= paddingLength; // Should be 0.
1944
patch.start2 -= paddingLength; // Should be 0.
1945
patch.length1 += paddingLength;
1946
patch.length2 += paddingLength;
1947
} else if (paddingLength > diffs[0][1].length) {
1948
// Grow first equality.
1949
var extraLength = paddingLength - diffs[0][1].length;
1950
diffs[0][1] = nullPadding.substring(diffs[0][1].length) + diffs[0][1];
1951
patch.start1 -= extraLength;
1952
patch.start2 -= extraLength;
1953
patch.length1 += extraLength;
1954
patch.length2 += extraLength;
1955
}
1956
1957
// Add some padding on end of last diff.
1958
patch = patches[patches.length - 1];
1959
diffs = patch.diffs;
1960
if (diffs.length == 0 || diffs[diffs.length - 1][0] != DIFF_EQUAL) {
1961
// Add nullPadding equality.
1962
diffs.push([DIFF_EQUAL, nullPadding]);
1963
patch.length1 += paddingLength;
1964
patch.length2 += paddingLength;
1965
} else if (paddingLength > diffs[diffs.length - 1][1].length) {
1966
// Grow last equality.
1967
var extraLength = paddingLength - diffs[diffs.length - 1][1].length;
1968
diffs[diffs.length - 1][1] += nullPadding.substring(0, extraLength);
1969
patch.length1 += extraLength;
1970
patch.length2 += extraLength;
1971
}
1972
1973
return nullPadding;
1974
};
1975
1976
1977
/**
1978
* Look through the patches and break up any which are longer than the maximum
1979
* limit of the match algorithm.
1980
* Intended to be called only from within patch_apply.
1981
* @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects.
1982
*/
1983
diff_match_patch.prototype.patch_splitMax = function(patches) {
1984
var patch_size = this.Match_MaxBits;
1985
for (var x = 0; x < patches.length; x++) {
1986
if (patches[x].length1 <= patch_size) {
1987
continue;
1988
}
1989
var bigpatch = patches[x];
1990
// Remove the big old patch.
1991
patches.splice(x--, 1);
1992
var start1 = bigpatch.start1;
1993
var start2 = bigpatch.start2;
1994
var precontext = '';
1995
while (bigpatch.diffs.length !== 0) {
1996
// Create one of several smaller patches.
1997
var patch = new diff_match_patch.patch_obj();
1998
var empty = true;
1999
patch.start1 = start1 - precontext.length;
2000
patch.start2 = start2 - precontext.length;
2001
if (precontext !== '') {
2002
patch.length1 = patch.length2 = precontext.length;
2003
patch.diffs.push([DIFF_EQUAL, precontext]);
2004
}
2005
while (bigpatch.diffs.length !== 0 &&
2006
patch.length1 < patch_size - this.Patch_Margin) {
2007
var diff_type = bigpatch.diffs[0][0];
2008
var diff_text = bigpatch.diffs[0][1];
2009
if (diff_type === DIFF_INSERT) {
2010
// Insertions are harmless.
2011
patch.length2 += diff_text.length;
2012
start2 += diff_text.length;
2013
patch.diffs.push(bigpatch.diffs.shift());
2014
empty = false;
2015
} else if (diff_type === DIFF_DELETE && patch.diffs.length == 1 &&
2016
patch.diffs[0][0] == DIFF_EQUAL &&
2017
diff_text.length > 2 * patch_size) {
2018
// This is a large deletion. Let it pass in one chunk.
2019
patch.length1 += diff_text.length;
2020
start1 += diff_text.length;
2021
empty = false;
2022
patch.diffs.push([diff_type, diff_text]);
2023
bigpatch.diffs.shift();
2024
} else {
2025
// Deletion or equality. Only take as much as we can stomach.
2026
diff_text = diff_text.substring(0,
2027
patch_size - patch.length1 - this.Patch_Margin);
2028
patch.length1 += diff_text.length;
2029
start1 += diff_text.length;
2030
if (diff_type === DIFF_EQUAL) {
2031
patch.length2 += diff_text.length;
2032
start2 += diff_text.length;
2033
} else {
2034
empty = false;
2035
}
2036
patch.diffs.push([diff_type, diff_text]);
2037
if (diff_text == bigpatch.diffs[0][1]) {
2038
bigpatch.diffs.shift();
2039
} else {
2040
bigpatch.diffs[0][1] =
2041
bigpatch.diffs[0][1].substring(diff_text.length);
2042
}
2043
}
2044
}
2045
// Compute the head context for the next patch.
2046
precontext = this.diff_text2(patch.diffs);
2047
precontext =
2048
precontext.substring(precontext.length - this.Patch_Margin);
2049
// Append the end context for this patch.
2050
var postcontext = this.diff_text1(bigpatch.diffs)
2051
.substring(0, this.Patch_Margin);
2052
if (postcontext !== '') {
2053
patch.length1 += postcontext.length;
2054
patch.length2 += postcontext.length;
2055
if (patch.diffs.length !== 0 &&
2056
patch.diffs[patch.diffs.length - 1][0] === DIFF_EQUAL) {
2057
patch.diffs[patch.diffs.length - 1][1] += postcontext;
2058
} else {
2059
patch.diffs.push([DIFF_EQUAL, postcontext]);
2060
}
2061
}
2062
if (!empty) {
2063
patches.splice(++x, 0, patch);
2064
}
2065
}
2066
}
2067
};
2068
2069
2070
/**
2071
* Take a list of patches and return a textual representation.
2072
* @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects.
2073
* @return {string} Text representation of patches.
2074
*/
2075
diff_match_patch.prototype.patch_toText = function(patches) {
2076
var text = [];
2077
for (var x = 0; x < patches.length; x++) {
2078
text[x] = patches[x];
2079
}
2080
return text.join('');
2081
};
2082
2083
2084
/**
2085
* Parse a textual representation of patches and return a list of Patch objects.
2086
* @param {string} textline Text representation of patches.
2087
* @return {!Array.<!diff_match_patch.patch_obj>} Array of Patch objects.
2088
* @throws {!Error} If invalid input.
2089
*/
2090
diff_match_patch.prototype.patch_fromText = function(textline) {
2091
var patches = [];
2092
if (!textline) {
2093
return patches;
2094
}
2095
var text = textline.split('\n');
2096
var textPointer = 0;
2097
var patchHeader = /^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$/;
2098
while (textPointer < text.length) {
2099
var m = text[textPointer].match(patchHeader);
2100
if (!m) {
2101
throw new Error('Invalid patch string: ' + text[textPointer]);
2102
}
2103
var patch = new diff_match_patch.patch_obj();
2104
patches.push(patch);
2105
patch.start1 = parseInt(m[1], 10);
2106
if (m[2] === '') {
2107
patch.start1--;
2108
patch.length1 = 1;
2109
} else if (m[2] == '0') {
2110
patch.length1 = 0;
2111
} else {
2112
patch.start1--;
2113
patch.length1 = parseInt(m[2], 10);
2114
}
2115
2116
patch.start2 = parseInt(m[3], 10);
2117
if (m[4] === '') {
2118
patch.start2--;
2119
patch.length2 = 1;
2120
} else if (m[4] == '0') {
2121
patch.length2 = 0;
2122
} else {
2123
patch.start2--;
2124
patch.length2 = parseInt(m[4], 10);
2125
}
2126
textPointer++;
2127
2128
while (textPointer < text.length) {
2129
var sign = text[textPointer].charAt(0);
2130
try {
2131
var line = decodeURI(text[textPointer].substring(1));
2132
} catch (ex) {
2133
// Malformed URI sequence.
2134
throw new Error('Illegal escape in patch_fromText: ' + line);
2135
}
2136
if (sign == '-') {
2137
// Deletion.
2138
patch.diffs.push([DIFF_DELETE, line]);
2139
} else if (sign == '+') {
2140
// Insertion.
2141
patch.diffs.push([DIFF_INSERT, line]);
2142
} else if (sign == ' ') {
2143
// Minor equality.
2144
patch.diffs.push([DIFF_EQUAL, line]);
2145
} else if (sign == '@') {
2146
// Start of next patch.
2147
break;
2148
} else if (sign === '') {
2149
// Blank line? Whatever.
2150
} else {
2151
// WTF?
2152
throw new Error('Invalid patch mode "' + sign + '" in: ' + line);
2153
}
2154
textPointer++;
2155
}
2156
}
2157
return patches;
2158
};
2159
2160
2161
/**
2162
* Class representing one patch operation.
2163
* @constructor
2164
*/
2165
diff_match_patch.patch_obj = function() {
2166
/** @type {!Array.<!diff_match_patch.Diff>} */
2167
this.diffs = [];
2168
/** @type {?number} */
2169
this.start1 = null;
2170
/** @type {?number} */
2171
this.start2 = null;
2172
/** @type {number} */
2173
this.length1 = 0;
2174
/** @type {number} */
2175
this.length2 = 0;
2176
};
2177
2178
2179
/**
2180
* Emmulate GNU diff's format.
2181
* Header: @@ -382,8 +481,9 @@
2182
* Indicies are printed as 1-based, not 0-based.
2183
* @return {string} The GNU diff string.
2184
*/
2185
diff_match_patch.patch_obj.prototype.toString = function() {
2186
var coords1, coords2;
2187
if (this.length1 === 0) {
2188
coords1 = this.start1 + ',0';
2189
} else if (this.length1 == 1) {
2190
coords1 = this.start1 + 1;
2191
} else {
2192
coords1 = (this.start1 + 1) + ',' + this.length1;
2193
}
2194
if (this.length2 === 0) {
2195
coords2 = this.start2 + ',0';
2196
} else if (this.length2 == 1) {
2197
coords2 = this.start2 + 1;
2198
} else {
2199
coords2 = (this.start2 + 1) + ',' + this.length2;
2200
}
2201
var text = ['@@ -' + coords1 + ' +' + coords2 + ' @@\n'];
2202
var op;
2203
// Escape the body of the patch with %xx notation.
2204
for (var x = 0; x < this.diffs.length; x++) {
2205
switch (this.diffs[x][0]) {
2206
case DIFF_INSERT:
2207
op = '+';
2208
break;
2209
case DIFF_DELETE:
2210
op = '-';
2211
break;
2212
case DIFF_EQUAL:
2213
op = ' ';
2214
break;
2215
}
2216
text[x + 1] = op + encodeURI(this.diffs[x][1]) + '\n';
2217
}
2218
return text.join('').replace(/%20/g, ' ');
2219
};
2220
2221
2222
// Export these global variables so that they survive Google's JS compiler.
2223
// In a browser, 'this' will be 'window'.
2224
// Users of node.js should 'require' the uncompressed version since Google's
2225
// JS compiler may break the following exports for non-browser environments.
2226
this['diff_match_patch'] = diff_match_patch;
2227
this['DIFF_DELETE'] = DIFF_DELETE;
2228
this['DIFF_INSERT'] = DIFF_INSERT;
2229
this['DIFF_EQUAL'] = DIFF_EQUAL;
2230
2231