-
Notifications
You must be signed in to change notification settings - Fork 1
/
diff_match_patch.java
2072 lines (1934 loc) · 71.8 KB
/
diff_match_patch.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Diff Match and Patch
*
* Copyright 2006 Google Inc.
* http://code.google.com/p/google-diff-match-patch/
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Stack;
import java.util.ListIterator;
import java.util.regex.*;
import java.net.URLEncoder;
import java.net.URLDecoder;
import java.io.UnsupportedEncodingException;
/*
* Functions for diff, match and patch.
* Computes the difference between two texts to create a patch.
* Applies the patch onto another text, allowing for errors.
*
* @author fraser@google.com (Neil Fraser)
*/
/**
* Class containing the diff, match and patch methods.
* Also contains the behaviour settings.
*/
public class diff_match_patch {
// Defaults.
// Set these on your diff_match_patch instance to override the defaults.
// Number of seconds to map a diff before giving up. (0 for infinity)
public float Diff_Timeout = 1.0f;
// Cost of an empty edit operation in terms of edit characters.
public short Diff_EditCost = 4;
// The size beyond which the double-ended diff activates.
// Double-ending is twice as fast, but less accurate.
public short Diff_DualThreshold = 32;
// Tweak the relative importance (0.0 = accuracy, 1.0 = proximity)
public float Match_Balance = 0.5f;
// At what point is no match declared (0.0 = perfection, 1.0 = very loose)
public float Match_Threshold = 0.5f;
// The min and max cutoffs used when computing text lengths.
public int Match_MinLength = 100;
public int Match_MaxLength = 1000;
// Chunk size for context length.
public short Patch_Margin = 4;
// The number of bits in an int.
private int Match_MaxBits = 32;
// DIFF FUNCTIONS
/**-
* The data structure representing a diff is a Linked list of Diff objects:
* {Diff(Operation.DELETE, "Hello"), Diff(Operation.INSERT, "Goodbye"),
* Diff(Operation.EQUAL, " world.")}
* which means: delete "Hello", add "Goodbye" and keep " world."
*/
public enum Operation {
DELETE, INSERT, EQUAL
}
/**
* Find the differences between two texts.
* Run a faster slightly less optimal diff
* This method allows the 'checklines' of diff_main() to be optional.
* Most of the time checklines is wanted, so default to true.
* @param text1 Old string to be diffed
* @param text2 New string to be diffed
* @return Linked List of Diff objects
*/
public LinkedList<Diff> diff_main(String text1, String text2) {
return diff_main(text1, text2, true);
}
/**
* Find the differences between two texts. Simplifies the problem by
* stripping any common prefix or suffix off the texts before diffing.
* @param text1 Old string to be diffed
* @param text2 New string to be diffed
* @param checklines Speedup flag. If false, then don't run a
* line-level diff first to identify the changed areas.
* If true, then run a faster slightly less optimal diff
* @return Linked List of Diff objects
*/
public LinkedList<Diff> diff_main(String text1, String text2,
boolean checklines) {
// Check for equality (speedup)
LinkedList<Diff> diffs;
if (text1.equals(text2)) {
diffs = new LinkedList<Diff>();
diffs.add(new Diff(Operation.EQUAL, text1));
return diffs;
}
// Trim off common prefix (speedup)
int commonlength = diff_commonPrefix(text1, text2);
String commonprefix = text1.substring(0, commonlength);
text1 = text1.substring(commonlength);
text2 = text2.substring(commonlength);
// Trim off common suffix (speedup)
commonlength = diff_commonSuffix(text1, text2);
String commonsuffix = text1.substring(text1.length() - commonlength);
text1 = text1.substring(0, text1.length() - commonlength);
text2 = text2.substring(0, text2.length() - commonlength);
// Compute the diff on the middle block
diffs = diff_compute(text1, text2, checklines);
// Restore the prefix and suffix
if (commonprefix.length() != 0) {
diffs.addFirst(new Diff(Operation.EQUAL, commonprefix));
}
if (commonsuffix.length() != 0) {
diffs.addLast(new Diff(Operation.EQUAL, commonsuffix));
}
diff_cleanupMerge(diffs);
return diffs;
}
/**
* Find the differences between two texts.
* @param text1 Old string to be diffed
* @param text2 New string to be diffed
* @param checklines Speedup flag. If false, then don't run a
* line-level diff first to identify the changed areas.
* If true, then run a faster slightly less optimal diff
* @return Linked List of Diff objects
*/
public LinkedList<Diff> diff_compute(String text1, String text2,
boolean checklines) {
LinkedList<Diff> diffs = new LinkedList<Diff>();
if (text1.length() == 0) {
// Just add some text (speedup)
diffs.add(new Diff(Operation.INSERT, text2));
return diffs;
}
if (text2.length() == 0) {
// Just delete some text (speedup)
diffs.add(new Diff(Operation.DELETE, text1));
return diffs;
}
String longtext = text1.length() > text2.length() ? text1 : text2;
String shorttext = text1.length() > text2.length() ? text2 : text1;
int i = longtext.indexOf(shorttext);
if (i != -1) {
// Shorter text is inside the longer text (speedup)
Operation op = (text1.length() > text2.length()) ?
Operation.DELETE : Operation.INSERT;
diffs.add(new Diff(op, longtext.substring(0, i)));
diffs.add(new Diff(Operation.EQUAL, shorttext));
diffs.add(new Diff(op, longtext.substring(i + shorttext.length())));
return diffs;
}
longtext = shorttext = null; // Garbage collect
// Check to see if the problem can be split in two.
String[] hm = diff_halfMatch(text1, text2);
if (hm != null) {
// A half-match was found, sort out the return data.
String text1_a = hm[0];
String text1_b = hm[1];
String text2_a = hm[2];
String text2_b = hm[3];
String mid_common = hm[4];
// Send both pairs off for separate processing.
LinkedList<Diff> diffs_a = diff_main(text1_a, text2_a, checklines);
LinkedList<Diff> diffs_b = diff_main(text1_b, text2_b, checklines);
// Merge the results.
diffs = diffs_a;
diffs.add(new Diff(Operation.EQUAL, mid_common));
diffs.addAll(diffs_b);
return diffs;
}
// Perform a real diff.
if (checklines && text1.length() + text2.length() < 250) {
checklines = false; // Too trivial for the overhead.
}
ArrayList<String> linearray = null;
if (checklines) {
// Scan the text on a line-by-line basis first.
Object b[] = diff_linesToChars(text1, text2);
text1 = (String) b[0];
text2 = (String) b[1];
linearray = (ArrayList<String>) b[2];
}
diffs = diff_map(text1, text2);
if (diffs == null) {
// No acceptable result.
diffs = new LinkedList<Diff>();
diffs.add(new Diff(Operation.DELETE, text1));
diffs.add(new Diff(Operation.INSERT, text2));
}
if (checklines) {
// Convert the diff back to original text.
diff_charsToLines(diffs, linearray);
// Eliminate freak matches (e.g. blank lines)
diff_cleanupSemantic(diffs);
// Rediff any replacement blocks, this time character-by-character.
// Add a dummy entry at the end.
diffs.add(new Diff(Operation.EQUAL, ""));
int count_delete = 0;
int count_insert = 0;
String text_delete = "";
String text_insert = "";
ListIterator<Diff> pointer = diffs.listIterator();
Diff thisDiff = pointer.next();
while (thisDiff != null) {
if (thisDiff.operation == Operation.INSERT) {
count_insert++;
text_insert += thisDiff.text;
} else if (thisDiff.operation == Operation.DELETE) {
count_delete++;
text_delete += thisDiff.text;
} else {
// Upon reaching an equality, check for prior redundancies.
if (count_delete >= 1 && count_insert >= 1) {
// Delete the offending records and add the merged ones.
pointer.previous();
for (int j = 0; j < count_delete + count_insert; j++) {
pointer.previous();
pointer.remove();
}
for (Diff newDiff : diff_main(text_delete, text_insert, false)) {
pointer.add(newDiff);
}
}
count_insert = 0;
count_delete = 0;
text_delete = "";
text_insert = "";
}
thisDiff = pointer.hasNext() ? pointer.next() : null;
}
diffs.removeLast(); // Remove the dummy entry at the end.
}
return diffs;
}
/**
* Split two texts into a list of strings. Reduce the texts to a string of
* hashes where each Unicode character represents one line.
* @param text1 First string
* @param text2 Second string
* @return Three element Object array, containing the encoded text1, the
* encoded text2 and the List of unique strings. The zeroth element
* of the List of unique strings is intentionally blank.
*/
protected Object[] diff_linesToChars(String text1, String text2) {
List<String> linearray = new ArrayList<String>();
Map<String, Integer> linehash = new HashMap<String, Integer>();
// e.g. linearray[4] == "Hello\n"
// e.g. linehash.get("Hello\n") == 4
// "\x00" is a valid character, but various debuggers don't like it.
// So we'll insert a junk entry to avoid generating a null character.
linearray.add("");
String chars1 = diff_linesToCharsMunge(text1, linearray, linehash);
String chars2 = diff_linesToCharsMunge(text2, linearray, linehash);
return new Object[]{chars1, chars2, linearray};
}
/**
* Split a text into a list of strings. Reduce the texts to a string of
* hashes where each Unicode character represents one line.
* @param text String to encode
* @param linearray List of unique strings
* @param linehash Map of strings to indices
* @return Encoded string
*/
private String diff_linesToCharsMunge(String text, List<String> linearray,
Map<String, Integer> linehash) {
int i;
String line;
String chars = "";
// text.split('\n') would work fine, but would temporarily double our
// memory footprint for minimal speed improvement.
while (text.length() != 0) {
i = text.indexOf('\n');
if (i == -1) {
i = text.length() - 1;
}
line = text.substring(0, i + 1);
text = text.substring(i + 1);
if (linehash.containsKey(line)) {
chars += String.valueOf((char) (int) linehash.get(line));
} else {
linearray.add(line);
linehash.put(line, linearray.size() - 1);
chars += String.valueOf((char) (linearray.size() - 1));
}
}
return chars;
}
/**
* Rehydrate the text in a diff from a string of line hashes to real lines of
* text.
* @param diffs LinkedList of Diff objects
* @param linearray List of unique strings
*/
protected void diff_charsToLines(LinkedList<Diff> diffs,
List<String> linearray) {
StringBuilder text;
for (Diff diff : diffs) {
text = new StringBuilder();
for (int y = 0; y < diff.text.length(); y++) {
text.append(linearray.get(diff.text.charAt(y)));
}
diff.text = text.toString();
}
}
/**
* Explore the intersection points between the two texts.
* @param text1 Old string to be diffed
* @param text2 New string to be diffed
* @return LinkedList of Diff objects or null if no diff available
*/
protected LinkedList<Diff> diff_map(String text1, String text2) {
long ms_end = System.currentTimeMillis() + (long) (Diff_Timeout * 1000);
int max_d = text1.length() + text2.length() - 1;
boolean doubleEnd = Diff_DualThreshold * 2 < max_d;
List<Set<String>> v_map1 = new ArrayList<Set<String>>();
List<Set<String>> v_map2 = new ArrayList<Set<String>>();
Map<Integer, Integer> v1 = new HashMap<Integer, Integer>();
Map<Integer, Integer> v2 = new HashMap<Integer, Integer>();
v1.put(1, 0);
v2.put(1, 0);
int x, y;
String footstep = ""; // Used to track overlapping paths.
Map<String, Integer> footsteps = new HashMap<String, Integer>();
boolean done = false;
// If the total number of characters is odd, then the front path will
// collide with the reverse path.
boolean front = ((text1.length() + text2.length()) % 2 == 1);
for (int d = 0; d < max_d; d++) {
// Bail out if timeout reached.
if (Diff_Timeout > 0 && System.currentTimeMillis() > ms_end) {
return null;
}
// Walk the front path one step.
v_map1.add(new HashSet<String>()); // Adds at index 'd'.
for (int k = -d; k <= d; k += 2) {
if (k == -d || k != d && v1.get(k - 1) < v1.get(k + 1)) {
x = v1.get(k + 1);
} else {
x = v1.get(k - 1) + 1;
}
y = x - k;
if (doubleEnd) {
footstep = x + "," + y;
if (front && (footsteps.containsKey(footstep))) {
done = true;
}
if (!front) {
footsteps.put(footstep, d);
}
}
while (!done && x < text1.length() && y < text2.length()
&& text1.charAt(x) == text2.charAt(y)) {
x++;
y++;
if (doubleEnd) {
footstep = x + "," + y;
if (front && (footsteps.containsKey(footstep))) {
done = true;
}
if (!front) {
footsteps.put(footstep, d);
}
}
}
v1.put(k, x);
v_map1.get(d).add(x + "," + y);
if (x == text1.length() && y == text2.length()) {
// Reached the end in single-path mode.
return diff_path1(v_map1, text1, text2);
} else if (done) {
// Front path ran over reverse path.
v_map2 = v_map2.subList(0, footsteps.get(footstep) + 1);
LinkedList<Diff> a = diff_path1(v_map1, text1.substring(0, x),
text2.substring(0, y));
a.addAll(diff_path2(v_map2, text1.substring(x), text2.substring(y)));
return a;
}
}
if (doubleEnd) {
// Walk the reverse path one step.
v_map2.add(new HashSet<String>()); // Adds at index 'd'.
for (int k = -d; k <= d; k += 2) {
if (k == -d || k != d && v2.get(k - 1) < v2.get(k + 1)) {
x = v2.get(k + 1);
} else {
x = v2.get(k - 1) + 1;
}
y = x - k;
footstep = (text1.length() - x) + "," + (text2.length() - y);
if (!front && (footsteps.containsKey(footstep))) {
done = true;
}
if (front) {
footsteps.put(footstep, d);
}
while (!done && x < text1.length() && y < text2.length()
&& text1.charAt(text1.length() - x - 1)
== text2.charAt(text2.length() - y - 1)) {
x++;
y++;
footstep = (text1.length() - x) + "," + (text2.length() - y);
if (!front && (footsteps.containsKey(footstep))) {
done = true;
}
if (front) {
footsteps.put(footstep, d);
}
}
v2.put(k, x);
v_map2.get(d).add(x + "," + y);
if (done) {
// Reverse path ran over front path.
v_map1 = v_map1.subList(0, footsteps.get(footstep) + 1);
LinkedList<Diff> a
= diff_path1(v_map1, text1.substring(0, text1.length() - x),
text2.substring(0, text2.length() - y));
a.addAll(diff_path2(v_map2, text1.substring(text1.length() - x),
text2.substring(text2.length() - y)));
return a;
}
}
}
}
// Number of diffs equals number of characters, no commonality at all.
return null;
}
/**
* Work from the middle back to the start to determine the path.
* @param v_map List of path sets.
* @param text1 Old string fragment to be diffed
* @param text2 New string fragment to be diffed
* @return LinkedList of Diff objects
*/
protected LinkedList<Diff> diff_path1(List<Set<String>> v_map,
String text1, String text2) {
LinkedList<Diff> path = new LinkedList<Diff>();
int x = text1.length();
int y = text2.length();
Operation last_op = null;
for (int d = v_map.size() - 2; d >= 0; d--) {
while (true) {
if (v_map.get(d).contains((x - 1) + "," + y)) {
x--;
if (last_op == Operation.DELETE) {
path.getFirst().text = text1.charAt(x) + path.getFirst().text;
} else {
path.addFirst(new Diff(Operation.DELETE,
text1.substring(x, x + 1)));
}
last_op = Operation.DELETE;
break;
} else if (v_map.get(d).contains(x + "," + (y - 1))) {
y--;
if (last_op == Operation.INSERT) {
path.getFirst().text = text2.charAt(y) + path.getFirst().text;
} else {
path.addFirst(new Diff(Operation.INSERT,
text2.substring(y, y + 1)));
}
last_op = Operation.INSERT;
break;
} else {
x--;
y--;
assert (text1.charAt(x) == text2.charAt(y))
: "No diagonal. Can't happen. (diff_path1)";
if (last_op == Operation.EQUAL) {
path.getFirst().text = text1.charAt(x) + path.getFirst().text;
} else {
path.addFirst(new Diff(Operation.EQUAL, text1.substring(x, x + 1)));
}
last_op = Operation.EQUAL;
}
}
}
return path;
}
/**
* Work from the middle back to the end to determine the path.
* @param v_map List of path sets.
* @param text1 Old string fragment to be diffed
* @param text2 New string fragment to be diffed
* @return LinkedList of Diff objects
*/
protected LinkedList<Diff> diff_path2(List<Set<String>> v_map,
String text1, String text2) {
LinkedList<Diff> path = new LinkedList<Diff>();
int x = text1.length();
int y = text2.length();
Operation last_op = null;
for (int d = v_map.size() - 2; d >= 0; d--) {
while (true) {
if (v_map.get(d).contains((x - 1) + "," + y)) {
x--;
if (last_op == Operation.DELETE) {
path.getLast().text += text1.charAt(text1.length() - x - 1);
} else {
path.addLast(new Diff(Operation.DELETE,
text1.substring(text1.length() - x - 1, text1.length() - x)));
}
last_op = Operation.DELETE;
break;
} else if (v_map.get(d).contains(x + "," + (y - 1))) {
y--;
if (last_op == Operation.INSERT) {
path.getLast().text += text2.charAt(text2.length() - y - 1);
} else {
path.addLast(new Diff(Operation.INSERT,
text2.substring(text2.length() - y - 1, text2.length() - y)));
}
last_op = Operation.INSERT;
break;
} else {
x--;
y--;
assert (text1.charAt(text1.length() - x - 1)
== text2.charAt(text2.length() - y - 1))
: "No diagonal. Can't happen. (diff_path2)";
if (last_op == Operation.EQUAL) {
path.getLast().text += text1.charAt(text1.length() - x - 1);
} else {
path.addLast(new Diff(Operation.EQUAL,
text1.substring(text1.length() - x - 1, text1.length() - x)));
}
last_op = Operation.EQUAL;
}
}
}
return path;
}
/**
* Trim off common prefix
* @param text1 First string
* @param text2 Second string
* @return The number of characters common to the start of each string.
*/
public int diff_commonPrefix(String text1, String text2) {
// Quick check for common null cases.
if (text1.length() == 0 || text2.length() == 0 ||
text1.charAt(0) != text2.charAt(0)) {
return 0;
}
// Binary search.
int pointermin = 0;
int pointermax = Math.min(text1.length(), text2.length());
int pointermid = pointermax;
int pointerstart = 0;
while (pointermin < pointermid) {
if (text1.regionMatches(pointerstart, text2, pointerstart,
pointermid - pointerstart)) {
pointermin = pointermid;
pointerstart = pointermin;
} else {
pointermax = pointermid;
}
pointermid = (pointermax - pointermin) / 2 + pointermin;
}
return pointermid;
}
/**
* Trim off common suffix
* @param text1 First string
* @param text2 Second string
* @return The number of characters common to the end of each string.
*/
public int diff_commonSuffix(String text1, String text2) {
// Quick check for common null cases.
if (text1.length() == 0 || text2.length() == 0 ||
text1.charAt(text1.length() - 1) != text2.charAt(text2.length() - 1)) {
return 0;
}
// Binary search.
int pointermin = 0;
int pointermax = Math.min(text1.length(), text2.length());
int pointermid = pointermax;
int pointerend = 0;
while (pointermin < pointermid) {
if (text1.regionMatches(text1.length() - pointermid, text2,
text2.length() - pointermid,
pointermid - pointerend)) {
pointermin = pointermid;
pointerend = pointermin;
} else {
pointermax = pointermid;
}
pointermid = (pointermax - pointermin) / 2 + pointermin;
}
return pointermid;
}
/**
* Do the two texts share a substring which is at least half the length of
* the longer text?
* @param text1 First string
* @param text2 Second string
* @return Five element String array, containing the prefix of text1, the
* suffix of text1, the prefix of text2, the suffix of text2 and the
* common middle. Or null if there was no match.
*/
protected String[] diff_halfMatch(String text1, String text2) {
String longtext = text1.length() > text2.length() ? text1 : text2;
String shorttext = text1.length() > text2.length() ? text2 : text1;
if (longtext.length() < 10 || shorttext.length() < 1) {
return null; // Pointless.
}
// First check if the second quarter is the seed for a half-match.
String[] hm1 = diff_halfMatchI(longtext, shorttext,
(int) Math.ceil(longtext.length() / 4));
// Check again based on the third quarter.
String[] hm2 = diff_halfMatchI(longtext, shorttext,
(int) Math.ceil(longtext.length() / 2));
String[] hm;
if (hm1 == null && hm2 == null) {
return null;
} else if (hm2 == null) {
hm = hm1;
} else if (hm1 == null) {
hm = hm2;
} else {
// Both matched. Select the longest.
hm = hm1[4].length() > hm2[4].length() ? hm1 : hm2;
}
// A half-match was found, sort out the return data.
if (text1.length() > text2.length()) {
return hm;
//return new String[]{hm[0], hm[1], hm[2], hm[3], hm[4]};
} else {
return new String[]{hm[2], hm[3], hm[0], hm[1], hm[4]};
}
}
/**
* Does a substring of shorttext exist within longtext such that the
* substring is at least half the length of longtext?
* @param longtext Longer string
* @param shorttext Shorter string
* @param i Start index of quarter length substring within longtext
* @return Five element String array, containing the prefix of longtext, the
* suffix of longtext, the prefix of shorttext, the suffix of shorttext
* and the common middle. Or null if there was no match.
*/
private String[] diff_halfMatchI(String longtext, String shorttext, int i) {
// Start with a 1/4 length substring at position i as a seed.
String seed = longtext.substring(i,
i + (int) Math.floor(longtext.length() / 4));
int j = -1;
String best_common = "";
String best_longtext_a = "", best_longtext_b = "";
String best_shorttext_a = "", best_shorttext_b = "";
while ((j = shorttext.indexOf(seed, j + 1)) != -1) {
int prefixLength = diff_commonPrefix(longtext.substring(i),
shorttext.substring(j));
int suffixLength = diff_commonSuffix(longtext.substring(0, i),
shorttext.substring(0, j));
if (best_common.length() < suffixLength + prefixLength) {
best_common = shorttext.substring(j - suffixLength, j)
+ shorttext.substring(j, j + prefixLength);
best_longtext_a = longtext.substring(0, i - suffixLength);
best_longtext_b = longtext.substring(i + prefixLength);
best_shorttext_a = shorttext.substring(0, j - suffixLength);
best_shorttext_b = shorttext.substring(j + prefixLength);
}
}
if (best_common.length() >= longtext.length() / 2) {
return new String[]{best_longtext_a, best_longtext_b,
best_shorttext_a, best_shorttext_b, best_common};
} else {
return null;
}
}
/**
* Reduce the number of edits by eliminating semantically trivial equalities.
* @param diffs LinkedList of Diff objects
*/
public void diff_cleanupSemantic(LinkedList<Diff> diffs) {
if (diffs.isEmpty()) {
return;
}
boolean changes = false;
Stack<Diff> equalities = new Stack<Diff>(); // Stack of qualities.
String lastequality = null; // Always equal to equalities.lastElement().text
ListIterator<Diff> pointer = diffs.listIterator();
// Number of characters that changed prior to the equality.
int length_changes1 = 0;
// Number of characters that changed after the equality.
int length_changes2 = 0;
Diff thisDiff = pointer.next();
while (thisDiff != null) {
if (thisDiff.operation == Operation.EQUAL) {
// equality found
equalities.push(thisDiff);
length_changes1 = length_changes2;
length_changes2 = 0;
lastequality = thisDiff.text;
} else {
// an insertion or deletion
length_changes2 += thisDiff.text.length();
if (lastequality != null && (lastequality.length() <= length_changes1)
&& (lastequality.length() <= length_changes2)) {
//System.out.println("Splitting: '" + lastequality + "'");
// Walk back to offending equality.
while (thisDiff != equalities.lastElement()) {
thisDiff = pointer.previous();
}
pointer.next();
// Replace equality with a delete.
pointer.set(new Diff(Operation.DELETE, lastequality));
// Insert a coresponding an insert.
pointer.add(new Diff(Operation.INSERT, lastequality));
equalities.pop(); // Throw away the equality we just deleted.
if (!equalities.empty()) {
// Throw away the previous equality (it needs to be reevaluated).
equalities.pop();
}
if (equalities.empty()) {
// There are no previous equalities, walk back to the start.
while (pointer.hasPrevious()) {
pointer.previous();
}
} else {
// There is a safe equality we can fall back to.
thisDiff = equalities.lastElement();
while (thisDiff != pointer.previous()) {
// Intentionally empty loop.
}
}
length_changes1 = 0; // Reset the counters.
length_changes2 = 0;
lastequality = null;
changes = true;
}
}
thisDiff = pointer.hasNext() ? pointer.next() : null;
}
if (changes) {
diff_cleanupMerge(diffs);
}
diff_cleanupSemanticLossless(diffs);
}
/**
* Look 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<ins>at c</ins>ame. -> The <ins>cat </ins>came.
* @param diffs LinkedList of Diff objects
*/
public void diff_cleanupSemanticLossless(LinkedList<Diff> diffs) {
String equality1, edit, equality2;
String commonString;
int commonOffset;
int score, bestScore;
String bestEquality1, bestEdit, bestEquality2;
// Create a new iterator at the start.
ListIterator<Diff> pointer = diffs.listIterator();
Diff prevDiff = pointer.hasNext() ? pointer.next() : null;
Diff thisDiff = pointer.hasNext() ? pointer.next() : null;
Diff nextDiff = pointer.hasNext() ? pointer.next() : null;
// Intentionally ignore the first and last element (don't need checking).
while (nextDiff != null) {
if (prevDiff.operation == Operation.EQUAL &&
nextDiff.operation == Operation.EQUAL) {
// This is a single edit surrounded by equalities.
equality1 = prevDiff.text;
edit = thisDiff.text;
equality2 = nextDiff.text;
// First, shift the edit as far left as possible.
commonOffset = diff_commonSuffix(equality1, edit);
if (commonOffset != 0) {
commonString = edit.substring(edit.length() - commonOffset);
equality1 = equality1.substring(0, equality1.length() - commonOffset);
edit = commonString + edit.substring(0, edit.length() - commonOffset);
equality2 = commonString + equality2;
}
// Second, step character by character right, looking for the best fit.
bestEquality1 = equality1;
bestEdit = edit;
bestEquality2 = equality2;
bestScore = diff_cleanupSemanticScore(equality1, edit, equality2);
while (edit.charAt(0) == equality2.charAt(0)) {
equality1 += edit.charAt(0);
edit = edit.substring(1) + equality2.charAt(0);
equality2 = equality2.substring(1);
score = diff_cleanupSemanticScore(equality1, edit, equality2);
if (score >= bestScore) {
bestScore = score;
bestEquality1 = equality1;
bestEdit = edit;
bestEquality2 = equality2;
}
}
if (!prevDiff.text.equals(bestEquality1)) {
// We have an improvement, save it back to the diff.
prevDiff.text = bestEquality1;
thisDiff.text = bestEdit;
nextDiff.text = bestEquality2;
}
}
prevDiff = thisDiff;
thisDiff = nextDiff;
nextDiff = pointer.hasNext() ? pointer.next() : null;
}
}
/**
* Given three strings, compute a score representing whether the two internal
* boundaries fall on word boundaries.
* @param one First string
* @param two Second string
* @param three Third string
* @return The score.
*/
private int diff_cleanupSemanticScore(String one, String two, String three) {
int score = 0;
if (Character.isWhitespace(one.charAt(one.length() - 1))
|| Character.isWhitespace(two.charAt(0))) {
score++;
}
if (Character.isWhitespace(two.charAt(two.length() - 1))
|| Character.isWhitespace(three.charAt(0))) {
score++;
}
return score;
}
/**
* Reduce the number of edits by eliminating operationally trivial equalities.
* @param diffs LinkedList of Diff objects
*/
public void diff_cleanupEfficiency(LinkedList<Diff> diffs) {
if (diffs.isEmpty()) {
return;
}
boolean changes = false;
Stack<Diff> equalities = new Stack<Diff>(); // Stack of equalities.
String lastequality = null; // Always equal to equalities.lastElement().text
ListIterator<Diff> pointer = diffs.listIterator();
// Is there an insertion operation before the last equality.
boolean pre_ins = false;
// Is there a deletion operation before the last equality.
boolean pre_del = false;
// Is there an insertion operation after the last equality.
boolean post_ins = false;
// Is there a deletion operation after the last equality.
boolean post_del = false;
Diff thisDiff = pointer.next();
Diff safeDiff = thisDiff; // The last Diff that is known to be unsplitable.
while (thisDiff != null) {
if (thisDiff.operation == Operation.EQUAL) {
// equality found
if (thisDiff.text.length() < Diff_EditCost && (post_ins || post_del)) {
// Candidate found.
equalities.push(thisDiff);
pre_ins = post_ins;
pre_del = post_del;
lastequality = thisDiff.text;
} else {
// Not a candidate, and can never become one.
equalities.clear();
lastequality = null;
safeDiff = thisDiff;
}
post_ins = post_del = false;
} else {
// an insertion or deletion
if (thisDiff.operation == Operation.DELETE) {
post_del = true;
} else {
post_ins = true;
}
/*
* Five types to be split:
* <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del>
* <ins>A</ins>X<ins>C</ins><del>D</del>
* <ins>A</ins><del>B</del>X<ins>C</ins>
* <ins>A</del>X<ins>C</ins><del>D</del>
* <ins>A</ins><del>B</del>X<del>C</del>
*/
if (lastequality != null
&& ((pre_ins && pre_del && post_ins && post_del)
|| ((lastequality.length() < Diff_EditCost / 2)
&& ((pre_ins ? 1 : 0) + (pre_del ? 1 : 0)
+ (post_ins ? 1 : 0) + (post_del ? 1 : 0)) == 3))) {
//System.out.println("Splitting: '" + lastequality + "'");
// Walk back to offending equality.
while (thisDiff != equalities.lastElement()) {
thisDiff = pointer.previous();
}
pointer.next();
// Replace equality with a delete.
pointer.set(new Diff(Operation.DELETE, lastequality));
// Insert a coresponding an insert.
pointer.add(thisDiff = new Diff(Operation.INSERT, lastequality));
equalities.pop(); // Throw away the equality we just deleted.
lastequality = null;
if (pre_ins && pre_del) {
// No changes made which could affect previous entry, keep going.
post_ins = post_del = true;
equalities.clear();
safeDiff = thisDiff;
} else {
if (!equalities.empty()) {
// Throw away the previous equality (it needs to be reevaluated).
equalities.pop();
}
if (equalities.empty()) {
// There are no previous questionable equalities,
// walk back to the last known safe diff.
thisDiff = safeDiff;
} else {
// There is an equality we can fall back to.
thisDiff = equalities.lastElement();
}
while (thisDiff != pointer.previous()) {
// Intentionally empty loop.
}
post_ins = post_del = false;
}
changes = true;
}
}
thisDiff = pointer.hasNext() ? pointer.next() : null;