-
Notifications
You must be signed in to change notification settings - Fork 30
/
DiffMatchPatch.m
executable file
·2770 lines (2520 loc) · 102 KB
/
DiffMatchPatch.m
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 2010 geheimwerk.de.
* http://code.google.com/p/google-diff-match-patch/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author: [email protected] (Neil Fraser)
* ObjC port: [email protected] (Jan Weiß)
*/
#import "DiffMatchPatch.h"
#import "NSString+JavaSubstring.h"
#import "NSString+UriCompatibility.h"
#import "NSMutableDictionary+DMPExtensions.h"
#import "DiffMatchPatchCFUtilities.h"
#import "JXArcCompatibilityMacros.h"
#if !defined(MAX_OF_CONST_AND_DIFF)
// Determines the maximum of two expressions:
// The first is a constant (first parameter) while the second expression is
// the difference between the second and third parameter. The way this is
// calculated prevents integer overflow in the result of the difference.
#define MAX_OF_CONST_AND_DIFF(A,B,C) ((B) <= (C) ? (A) : (B) - (C) + (A))
#endif
// JavaScript-style splice function
void splice(NSMutableArray *input, NSUInteger start, NSUInteger count, NSArray *objects);
/* NSMutableArray * */ void splice(NSMutableArray *input, NSUInteger start, NSUInteger count, NSArray *objects) {
NSRange deletionRange = NSMakeRange(start, count);
if (objects == nil) {
[input removeObjectsInRange:deletionRange];
} else {
[input replaceObjectsInRange:deletionRange withObjectsFromArray:objects];
}
}
@implementation Diff
@synthesize operation;
@synthesize text;
/**
* Constructor. Initializes the diff with the provided values.
* @param operation One of DIFF_INSERT, DIFF_DELETE or DIFF_EQUAL.
* @param text The text being applied.
*/
+ (id)diffWithOperation:(Operation)anOperation
andText:(NSString *)aText;
{
return JX_AUTORELEASE([[self alloc] initWithOperation:anOperation andText:aText]);
}
- (id)initWithOperation:(Operation)anOperation
andText:(NSString *)aText;
{
self = [super init];
if (self) {
self.operation = anOperation;
self.text = aText;
}
return self;
}
#if (JX_HAS_ARC == 0)
- (void)dealloc
{
self.text = nil;
[super dealloc];
}
#endif
- (id)copyWithZone:(NSZone *)zone
{
id newDiff = [[[self class] allocWithZone:zone]
initWithOperation:self.operation
andText:self.text];
return newDiff;
}
/**
* Display a human-readable version of this Diff.
* @return text version.
*/
- (NSString *)description
{
NSString *prettyText = [self.text stringByReplacingOccurrencesOfString:@"\n" withString:@"\u00b6"];
NSString *operationName = nil;
switch (self.operation) {
case DIFF_DELETE:
operationName = @"DIFF_DELETE";
break;
case DIFF_INSERT:
operationName = @"DIFF_INSERT";
break;
case DIFF_EQUAL:
operationName = @"DIFF_EQUAL";
break;
default:
break;
}
return [NSString stringWithFormat:@"Diff(%@,\"%@\")", operationName, prettyText];
}
/**
* Is this Diff equivalent to another Diff?
* @param obj Another Diff to compare against.
* @return YES or NO.
*/
- (BOOL)isEqual:(id)obj
{
// If parameter is nil return NO.
if (obj == nil) {
return NO;
}
// If parameter cannot be cast to Diff return NO.
if (![obj isKindOfClass:[Diff class]]) {
return NO;
}
// Return YES if the fields match.
Diff *p = (Diff *)obj;
return p.operation == self.operation && [p.text isEqualToString:self.text];
}
- (BOOL)isEqualToDiff:(Diff *)obj
{
// If parameter is nil return NO.
if (obj == nil) {
return NO;
}
// Return YES if the fields match.
return obj.operation == self.operation && [obj.text isEqualToString:self.text];
}
- (NSUInteger)hash
{
return ([text hash] ^ (NSUInteger)operation);
}
@end
@implementation Patch
@synthesize diffs;
@synthesize start1;
@synthesize start2;
@synthesize length1;
@synthesize length2;
- (id)init
{
self = [super init];
if (self) {
self.diffs = [NSMutableArray array];
}
return self;
}
#if (JX_HAS_ARC == 0)
- (void)dealloc
{
self.diffs = nil;
[super dealloc];
}
#endif
- (id)copyWithZone:(NSZone *)zone
{
Patch *newPatch = [[[self class] allocWithZone:zone] init];
newPatch.diffs = JX_AUTORELEASE([[NSMutableArray alloc] initWithArray:self.diffs copyItems:YES]);
newPatch.start1 = self.start1;
newPatch.start2 = self.start2;
newPatch.length1 = self.length1;
newPatch.length2 = self.length2;
return newPatch;
}
/**
* Emulate GNU diff's format.
* Header: @@ -382,8 +481,9 @@
* Indicies are printed as 1-based, not 0-based.
* @return The GNU diff NSString.
*/
- (NSString *)description
{
NSString *coords1;
NSString *coords2;
if (self.length1 == 0) {
coords1 = [NSString stringWithFormat:@"%lu,0",
(unsigned long)self.start1];
} else if (self.length1 == 1) {
coords1 = [NSString stringWithFormat:@"%lu",
(unsigned long)self.start1 + 1];
} else {
coords1 = [NSString stringWithFormat:@"%lu,%lu",
(unsigned long)self.start1 + 1, (unsigned long)self.length1];
}
if (self.length2 == 0) {
coords2 = [NSString stringWithFormat:@"%lu,0",
(unsigned long)self.start2];
} else if (self.length2 == 1) {
coords2 = [NSString stringWithFormat:@"%lu",
(unsigned long)self.start2 + 1];
} else {
coords2 = [NSString stringWithFormat:@"%lu,%lu",
(unsigned long)self.start2 + 1, (unsigned long)self.length2];
}
NSMutableString *text = [NSMutableString stringWithFormat:@"@@ -%@ +%@ @@\n",
coords1, coords2];
// Escape the body of the patch with %xx notation.
for (Diff *aDiff in self.diffs) {
switch (aDiff.operation) {
case DIFF_INSERT:
[text appendString:@"+"];
break;
case DIFF_DELETE:
[text appendString:@"-"];
break;
case DIFF_EQUAL:
[text appendString:@" "];
break;
}
[text appendString:[aDiff.text diff_stringByAddingPercentEscapesForEncodeUriCompatibility]];
[text appendString:@"\n"];
}
return text;
}
@end
@implementation DiffMatchPatch
@synthesize Diff_Timeout;
@synthesize Diff_EditCost;
@synthesize Match_Threshold;
@synthesize Match_Distance;
@synthesize Patch_DeleteThreshold;
@synthesize Patch_Margin;
- (id)init
{
self = [super init];
if (self) {
Diff_Timeout = 1.0f;
Diff_EditCost = 4;
Match_Threshold = 0.5f;
Match_Distance = 1000;
Patch_DeleteThreshold = 0.5f;
Patch_Margin = 4;
Match_MaxBits = 32;
}
return self;
}
#if 0
- (void)dealloc
{
[super dealloc];
}
#endif
#pragma mark Diff Functions
// DIFF FUNCTIONS
/**
* 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 YES.
* @param text1 Old NSString to be diffed.
* @param text2 New NSString to be diffed.
* @return NSMutableArray of Diff objects.
*/
- (NSMutableArray *)diff_mainOfOldString:(NSString *)text1
andNewString:(NSString *)text2;
{
return [self diff_mainOfOldString:text1 andNewString:text2 checkLines:YES];
}
/**
* 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 NO, then don't run a
* line-level diff first to identify the changed areas.
* If YES, then run a faster slightly less optimal diff.
* @return NSMutableArray of Diff objects.
*/
- (NSMutableArray *)diff_mainOfOldString:(NSString *)text1
andNewString:(NSString *)text2
checkLines:(BOOL)checklines;
{
// Set a deadline by which time the diff must be complete.
NSTimeInterval deadline;
if (Diff_Timeout <= 0) {
deadline = [[NSDate distantFuture] timeIntervalSinceReferenceDate];
} else {
deadline = [[NSDate dateWithTimeIntervalSinceNow:Diff_Timeout] timeIntervalSinceReferenceDate];
}
return [self diff_mainOfOldString:text1 andNewString:text2 checkLines:checklines deadline:deadline];
}
/**
* Find the differences between two texts. Simplifies the problem by
* stripping any common prefix or suffix off the texts before diffing.
* @param text1 Old NSString to be diffed.
* @param text2 New NSString to be diffed.
* @param checklines Speedup flag. If NO, then don't run a
* line-level diff first to identify the changed areas.
* If YES, then run a faster slightly less optimal diff
* @param deadline Time when the diff should be complete by. Used
* internally for recursive calls. Users should set DiffTimeout
* instead.
* @return NSMutableArray of Diff objects.
*/
- (NSMutableArray *)diff_mainOfOldString:(NSString *)text1
andNewString:(NSString *)text2
checkLines:(BOOL)checklines
deadline:(NSTimeInterval)deadline;
{
// Check for null inputs.
if (text1 == nil || text2 == nil) {
NSLog(@"Null inputs. (diff_main)");
return nil;
}
// Check for equality (speedup).
NSMutableArray *diffs;
if ([text1 isEqualToString:text2]) {
diffs = [NSMutableArray array];
if (text1.length != 0) {
[diffs addObject:[Diff diffWithOperation:DIFF_EQUAL andText:text1]];
}
return diffs;
}
// Trim off common prefix (speedup).
NSUInteger commonlength = (NSUInteger)diff_commonPrefix(JX_BRIDGED_CAST(CFStringRef, text1), JX_BRIDGED_CAST(CFStringRef, text2));
NSString *commonprefix = [text1 substringToIndex:commonlength];
text1 = [text1 substringFromIndex:commonlength];
text2 = [text2 substringFromIndex:commonlength];
// Trim off common suffix (speedup).
commonlength = (NSUInteger)diff_commonSuffix(JX_BRIDGED_CAST(CFStringRef, text1), JX_BRIDGED_CAST(CFStringRef, text2));
NSString *commonsuffix = [text1 substringFromIndex:text1.length - commonlength];
text1 = [text1 substringToIndex:(text1.length - commonlength)];
text2 = [text2 substringToIndex:(text2.length - commonlength)];
// Compute the diff on the middle block.
diffs = [self diff_computeFromOldString:text1 andNewString:text2 checkLines:checklines deadline:deadline];
// Restore the prefix and suffix.
if (commonprefix.length != 0) {
[diffs insertObject:[Diff diffWithOperation:DIFF_EQUAL andText:commonprefix] atIndex:0];
}
if (commonsuffix.length != 0) {
[diffs addObject:[Diff diffWithOperation:DIFF_EQUAL andText:commonsuffix]];
}
[self diff_cleanupMerge:diffs];
return diffs;
}
/**
* Determine the common prefix of two strings.
* @param text1 First string.
* @param text2 Second string.
* @return The number of characters common to the start of each string.
*/
- (NSUInteger)diff_commonPrefixOfFirstString:(NSString *)text1
andSecondString:(NSString *)text2;
{
return (NSUInteger)diff_commonPrefix(JX_BRIDGED_CAST(CFStringRef, text1), JX_BRIDGED_CAST(CFStringRef, text2));
}
/**
* Determine the common suffix of two strings.
* @param text1 First string.
* @param text2 Second string.
* @return The number of characters common to the end of each string.
*/
- (NSUInteger)diff_commonSuffixOfFirstString:(NSString *)text1
andSecondString:(NSString *)text2;
{
return (NSUInteger)diff_commonSuffix(JX_BRIDGED_CAST(CFStringRef, text1), JX_BRIDGED_CAST(CFStringRef, text2));
}
/**
* Determine if the suffix of one CFStringRef is the prefix of another.
* @param text1 First NSString.
* @param text2 Second NSString.
* @return The number of characters common to the end of the first
* CFStringRef and the start of the second CFStringRef.
*/
- (NSUInteger)diff_commonOverlapOfFirstString:(NSString *)text1
andSecondString:(NSString *)text2;
{
return (NSUInteger)diff_commonOverlap(JX_BRIDGED_CAST(CFStringRef, text1), JX_BRIDGED_CAST(CFStringRef, text2));
}
/**
* Do the two texts share a substring which is at least half the length of
* the longer text?
* This speedup can produce non-minimal diffs.
* @param text1 First NSString.
* @param text2 Second NSString.
* @return Five element NSString 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.
*/
- (NSArray *)diff_halfMatchOfFirstString:(NSString *)text1
andSecondString:(NSString *)text2;
{
return JX_TRANSFER_CF_TO_OBJC(NSArray *, diff_halfMatchCreate(JX_BRIDGED_CAST(CFStringRef, text1), JX_BRIDGED_CAST(CFStringRef, text2), Diff_Timeout));
}
/**
* Does a substring of shorttext exist within longtext such that the
* substring is at least half the length of longtext?
* @param longtext Longer NSString.
* @param shorttext Shorter NSString.
* @param i Start index of quarter length substring within longtext.
* @return Five element NSArray, containing the prefix of longtext, the
* suffix of longtext, the prefix of shorttext, the suffix of shorttext
* and the common middle. Or nil if there was no match.
*/
- (NSArray *)diff_halfMatchIOfLongString:(NSString *)longtext
andShortString:(NSString *)shorttext
index:(NSInteger)index;
{
return JX_TRANSFER_CF_TO_OBJC(NSArray *, diff_halfMatchICreate(JX_BRIDGED_CAST(CFStringRef, longtext), JX_BRIDGED_CAST(CFStringRef, shorttext), (CFIndex)index));
}
/**
* Find the differences between two texts. Assumes that the texts do not
* have any common prefix or suffix.
* @param text1 Old NSString to be diffed.
* @param text2 New NSString to be diffed.
* @param checklines Speedup flag. If NO, then don't run a
* line-level diff first to identify the changed areas.
* If YES, then run a faster slightly less optimal diff.
* @param deadline Time the diff should be complete by.
* @return NSMutableArray of Diff objects.
*/
- (NSMutableArray *)diff_computeFromOldString:(NSString *)text1
andNewString:(NSString *)text2
checkLines:(BOOL)checklines
deadline:(NSTimeInterval)deadline;
{
NSMutableArray *diffs = [NSMutableArray array];
if (text1.length == 0) {
// Just add some text (speedup).
[diffs addObject:[Diff diffWithOperation:DIFF_INSERT andText:text2]];
return diffs;
}
if (text2.length == 0) {
// Just delete some text (speedup).
[diffs addObject:[Diff diffWithOperation:DIFF_DELETE andText:text1]];
return diffs;
}
NSString *longtext = text1.length > text2.length ? text1 : text2;
NSString *shorttext = text1.length > text2.length ? text2 : text1;
NSUInteger i = [longtext rangeOfString:shorttext].location;
if (i != NSNotFound) {
// Shorter text is inside the longer text (speedup).
Operation op = (text1.length > text2.length) ? DIFF_DELETE : DIFF_INSERT;
[diffs addObject:[Diff diffWithOperation:op andText:[longtext substringToIndex:i]]];
[diffs addObject:[Diff diffWithOperation:DIFF_EQUAL andText:shorttext]];
[diffs addObject:[Diff diffWithOperation:op andText:[longtext substringFromIndex:(i + shorttext.length)]]];
return diffs;
}
if (shorttext.length == 1) {
// Single character string.
// After the previous speedup, the character can't be an equality.
[diffs addObject:[Diff diffWithOperation:DIFF_DELETE andText:text1]];
[diffs addObject:[Diff diffWithOperation:DIFF_INSERT andText:text2]];
return diffs;
}
// Check to see if the problem can be split in two.
NSArray *hm = JX_TRANSFER_CF_TO_OBJC(NSArray *, diff_halfMatchCreate(JX_BRIDGED_CAST(CFStringRef, text1), JX_BRIDGED_CAST(CFStringRef, text2), Diff_Timeout));
if (hm != nil) {
JX_NEW_AUTORELEASE_POOL_WITH_NAME(splitPool)
// A half-match was found, sort out the return data.
NSString *text1_a = [hm objectAtIndex:0];
NSString *text1_b = [hm objectAtIndex:1];
NSString *text2_a = [hm objectAtIndex:2];
NSString *text2_b = [hm objectAtIndex:3];
NSString *mid_common = [hm objectAtIndex:4];
// Send both pairs off for separate processing.
NSMutableArray *diffs_a = [self diff_mainOfOldString:text1_a andNewString:text2_a checkLines:checklines deadline:deadline];
NSMutableArray *diffs_b = [self diff_mainOfOldString:text1_b andNewString:text2_b checkLines:checklines deadline:deadline];
// Merge the results.
diffs = JX_RETAIN(diffs_a);
[diffs addObject:[Diff diffWithOperation:DIFF_EQUAL andText:mid_common]];
[diffs addObjectsFromArray:diffs_b];
JX_END_AUTORELEASE_POOL_WITH_NAME(splitPool)
return JX_AUTORELEASE(diffs);
}
if (checklines && text1.length > 100 && text2.length > 100) {
return [self diff_lineModeFromOldString:text1 andNewString:text2 deadline:deadline];
}
JX_NEW_AUTORELEASE_POOL_WITH_NAME(bisectPool)
diffs = JX_RETAIN([self diff_bisectOfOldString:text1 andNewString:text2 deadline:deadline]);
JX_END_AUTORELEASE_POOL_WITH_NAME(bisectPool)
return JX_AUTORELEASE(diffs);
}
/**
* Do a quick line-level diff on both strings, then rediff the parts for
* greater accuracy.
* This speedup can produce non-minimal diffs.
* @param text1 Old NSString to be diffed.
* @param text2 New NSString to be diffed.
* @param deadline Time when the diff should be complete by.
* @return NSMutableArray of Diff objects.
*/
- (NSMutableArray *)diff_lineModeFromOldString:(NSString *)text1
andNewString:(NSString *)text2
deadline:(NSTimeInterval)deadline;
{
// Scan the text on a line-by-line basis first.
NSArray *b = [self diff_linesToCharsForFirstString:text1 andSecondString:text2];
text1 = (NSString *)[b objectAtIndex:0];
text2 = (NSString *)[b objectAtIndex:1];
NSMutableArray *linearray = (NSMutableArray *)[b objectAtIndex:2];
NSMutableArray *diffs;
JX_NEW_AUTORELEASE_POOL_WITH_NAME(recursePool)
diffs = JX_RETAIN([self diff_mainOfOldString:text1 andNewString:text2 checkLines:NO deadline:deadline]);
JX_END_AUTORELEASE_POOL_WITH_NAME(recursePool)
// Convert the diff back to original text.
[self diff_chars:diffs toLines:linearray];
// Eliminate freak matches (e.g. blank lines)
[self diff_cleanupSemantic:diffs];
// Rediff any Replacement blocks, this time character-by-character.
// Add a dummy entry at the end.
[diffs addObject:[Diff diffWithOperation:DIFF_EQUAL andText:@""]];
NSUInteger thisPointer = 0;
NSUInteger count_delete = 0;
NSUInteger count_insert = 0;
NSString *text_delete = @"";
NSString *text_insert = @"";
while (thisPointer < diffs.count) {
switch (((Diff *)[diffs objectAtIndex:thisPointer]).operation) {
case DIFF_INSERT:
count_insert++;
text_insert = [text_insert stringByAppendingString:((Diff *)[diffs objectAtIndex:thisPointer]).text];
break;
case DIFF_DELETE:
count_delete++;
text_delete = [text_delete stringByAppendingString:((Diff *)[diffs objectAtIndex:thisPointer]).text];
break;
case DIFF_EQUAL:
// Upon reaching an equality, check for prior redundancies.
if (count_delete >= 1 && count_insert >= 1) {
// Delete the offending records and add the merged ones.
NSMutableArray *a = [self diff_mainOfOldString:text_delete andNewString:text_insert checkLines:NO deadline:deadline];
[diffs removeObjectsInRange:NSMakeRange(thisPointer - count_delete - count_insert,
count_delete + count_insert)];
thisPointer = thisPointer - count_delete - count_insert;
NSUInteger insertionIndex = thisPointer;
for (Diff *thisDiff in a) {
[diffs insertObject:thisDiff atIndex:insertionIndex];
insertionIndex++;
}
thisPointer = thisPointer + a.count;
}
count_insert = 0;
count_delete = 0;
text_delete = @"";
text_insert = @"";
break;
}
thisPointer++;
}
[diffs removeLastObject]; // Remove the dummy entry at the end.
return JX_AUTORELEASE(diffs); // Retained in autorelease pool above.
}
/**
* 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 NSString to encode.
* @param lineArray NSMutableArray of unique strings.
* @param lineHash Map of strings to indices.
* @return Encoded string.
*/
- (NSString *)diff_linesToCharsMungeOfText:(NSString *)text
lineArray:(NSMutableArray *)lineArray
lineHash:(NSMutableDictionary *)lineHash;
{
return JX_TRANSFER_CF_TO_OBJC(NSString *, diff_linesToCharsMungeCFStringCreate(JX_BRIDGED_CAST(CFStringRef, text),
JX_BRIDGED_CAST(CFMutableArrayRef, lineArray),
JX_BRIDGED_CAST(CFMutableDictionaryRef, lineHash)));
}
/**
* Split a text into a list of strings. Reduce the texts to a string of
* hashes where each Unicode character represents one word (or boundary between words).
* @param text NSString to encode.
* @param wordArray NSMutableArray of unique strings.
* @param wordHash Map of strings to indices.
* @return Encoded string.
*/
- (NSString *)diff_wordsToCharsMungeOfText:(NSString *)text
wordArray:(NSMutableArray *)wordArray
wordHash:(NSMutableDictionary *)wordHash;
{
return JX_TRANSFER_CF_TO_OBJC(NSString *, diff_wordsToCharsMungeCFStringCreate(JX_BRIDGED_CAST(CFStringRef, text),
JX_BRIDGED_CAST(CFMutableArrayRef, wordArray),
JX_BRIDGED_CAST(CFMutableDictionaryRef, wordHash)));
}
/**
* Split a text into a list of strings. Reduce the texts to a string of
* hashes where each Unicode character represents one sentence.
* @param text NSString to encode.
* @param sentenceArray NSMutableArray of unique strings.
* @param sentenceHash Map of strings to indices.
* @return Encoded string.
*/
- (NSString *)diff_sentencesToCharsMungeOfText:(NSString *)text
sentenceArray:(NSMutableArray *)sentenceArray
sentenceHash:(NSMutableDictionary *)sentenceHash;
{
return JX_TRANSFER_CF_TO_OBJC(NSString *, diff_sentencesToCharsMungeCFStringCreate(JX_BRIDGED_CAST(CFStringRef, text),
JX_BRIDGED_CAST(CFMutableArrayRef, sentenceArray),
JX_BRIDGED_CAST(CFMutableDictionaryRef, sentenceHash)));
}
/**
* Split a text into a list of strings. Reduce the texts to a string of
* hashes where each Unicode character represents one paragraph.
* @param text NSString to encode.
* @param paragraphArray NSMutableArray of unique strings.
* @param paragraphHash Map of strings to indices.
* @return Encoded string.
*/
- (NSString *)diff_paragraphsToCharsMungeOfText:(NSString *)text
paragraphArray:(NSMutableArray *)paragraphArray
paragraphHash:(NSMutableDictionary *)paragraphHash;
{
return JX_TRANSFER_CF_TO_OBJC(NSString *, diff_paragraphsToCharsMungeCFStringCreate(JX_BRIDGED_CAST(CFStringRef, text),
JX_BRIDGED_CAST(CFMutableArrayRef, paragraphArray),
JX_BRIDGED_CAST(CFMutableDictionaryRef, paragraphHash)));
}
/**
* Split a text into a list of strings. Reduce the texts to a string of
* hashes where each Unicode character represents one text fragment delimitered by line breaks (including the trailing line break characters if any).
* In this context “line break” does not refere to “something you get when you press the return-key”.
* Instead it refers to “line break boundaries” as defined in “UAX #14: Unicode Line Breaking Algorithm” (http://www.unicode.org/reports/tr14/).
* @param text NSString to encode.
* @param lineArray NSMutableArray of unique strings.
* @param lineHash Map of strings to indices.
* @return Encoded string.
*/
- (NSString *)diff_lineBreakDelimiteredToCharsMungeOfText:(NSString *)text
lineArray:(NSMutableArray *)lineArray
lineHash:(NSMutableDictionary *)lineHash;
{
return JX_TRANSFER_CF_TO_OBJC(NSString *, diff_lineBreakDelimiteredToCharsMungeCFStringCreate(JX_BRIDGED_CAST(CFStringRef, text),
JX_BRIDGED_CAST(CFMutableArrayRef, lineArray),
JX_BRIDGED_CAST(CFMutableDictionaryRef, lineHash)));
}
/**
* Find the 'middle snake' of a diff, split the problem in two
* and return the recursively constructed diff.
* See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations.
* @param text1 Old string to be diffed.
* @param text2 New string to be diffed.
* @param deadline Time at which to bail if not yet complete.
* @return NSMutableArray of Diff objects.
*/
- (NSMutableArray *)diff_bisectOfOldString:(NSString *)_text1
andNewString:(NSString *)_text2
deadline:(NSTimeInterval)deadline;
{
#define text1CharacterAtIndex(A) text1_chars[(A)]
#define text2CharacterAtIndex(A) text2_chars[(A)]
#define freeBuffers() if (text1_buffer != NULL) free(text1_buffer);\
if (text2_buffer != NULL) free(text2_buffer);\
free(v1);\
free(v2);
BOOL validDeadline = (deadline != [[NSDate distantFuture] timeIntervalSinceReferenceDate]);
CFStringRef text1 = JX_BRIDGED_CAST(CFStringRef, _text1);
CFStringRef text2 = JX_BRIDGED_CAST(CFStringRef, _text2);
// Cache the text lengths to prevent multiple calls.
CFIndex text1_length = CFStringGetLength(text1);
CFIndex text2_length = CFStringGetLength(text2);
CFIndex max_d = (text1_length + text2_length + 1) / 2;
CFIndex v_offset = max_d;
CFIndex v_length = 2 * max_d;
CFIndex *v1 = malloc(v_length * sizeof(CFIndex));
CFIndex *v2 = malloc(v_length * sizeof(CFIndex));
for (CFIndex x = 0; x < v_length; x++) {
v1[x] = -1;
v2[x] = -1;
}
v1[v_offset + 1] = 0;
v2[v_offset + 1] = 0;
CFIndex delta = text1_length - text2_length;
// Prepare access to chars arrays for text1 (massive speedup).
const UniChar *text1_chars;
UniChar *text1_buffer = NULL;
diff_CFStringPrepareUniCharBuffer(text1, &text1_chars, &text1_buffer, CFRangeMake(0, text1_length));
// Prepare access to chars arrays for text2 (massive speedup).
const UniChar *text2_chars;
UniChar *text2_buffer = NULL;
diff_CFStringPrepareUniCharBuffer(text2, &text2_chars, &text2_buffer, CFRangeMake(0, text2_length));
// If the total number of characters is odd, then the front path will
// collide with the reverse path.
BOOL front = (delta % 2 != 0);
// Offsets for start and end of k loop.
// Prevents mapping of space beyond the grid.
CFIndex k1start = 0;
CFIndex k1end = 0;
CFIndex k2start = 0;
CFIndex k2end = 0;
NSMutableArray *diffs;
for (CFIndex d = 0; d < max_d; d++) {
// Bail out if deadline is reached.
if (validDeadline && ([NSDate timeIntervalSinceReferenceDate] > deadline)) {
break;
}
// Walk the front path one step.
for (CFIndex k1 = -d + k1start; k1 <= d - k1end; k1 += 2) {
CFIndex k1_offset = v_offset + k1;
CFIndex x1;
if ( k1 == -d || (k1 != d && v1[k1_offset - 1] < v1[k1_offset + 1]) ) {
x1 = v1[k1_offset + 1];
} else {
x1 = v1[k1_offset - 1] + 1;
}
CFIndex y1 = x1 - k1;
while (x1 < text1_length && y1 < text2_length
&& text1CharacterAtIndex(x1) == text2CharacterAtIndex(y1)) {
x1++;
y1++;
}
v1[k1_offset] = x1;
if (x1 > text1_length) {
// Ran off the right of the graph.
k1end += 2;
} else if (y1 > text2_length) {
// Ran off the bottom of the graph.
k1start += 2;
} else if (front) {
CFIndex k2_offset = v_offset + delta - k1;
if (k2_offset >= 0 && k2_offset < v_length && v2[k2_offset] != -1) {
// Mirror x2 onto top-left coordinate system.
CFIndex x2 = text1_length - v2[k2_offset];
if (x1 >= x2) {
freeBuffers();
// Overlap detected.
return [self diff_bisectSplitOfOldString:_text1
andNewString:_text2
x:x1
y:y1
deadline:deadline];
}
}
}
}
// Walk the reverse path one step.
for (CFIndex k2 = -d + k2start; k2 <= d - k2end; k2 += 2) {
CFIndex k2_offset = v_offset + k2;
CFIndex x2;
if ( k2 == -d || (k2 != d && v2[k2_offset - 1] < v2[k2_offset + 1]) ) {
x2 = v2[k2_offset + 1];
} else {
x2 = v2[k2_offset - 1] + 1;
}
CFIndex y2 = x2 - k2;
while (x2 < text1_length && y2 < text2_length
&& text1CharacterAtIndex(text1_length - x2 - 1)
== text2CharacterAtIndex(text2_length - y2 - 1)) {
x2++;
y2++;
}
v2[k2_offset] = x2;
if (x2 > text1_length) {
// Ran off the left of the graph.
k2end += 2;
} else if (y2 > text2_length) {
// Ran off the top of the graph.
k2start += 2;
} else if (!front) {
CFIndex k1_offset = v_offset + delta - k2;
if (k1_offset >= 0 && k1_offset < v_length && v1[k1_offset] != -1) {
CFIndex x1 = v1[k1_offset];
CFIndex y1 = v_offset + x1 - k1_offset;
// Mirror x2 onto top-left coordinate system.
x2 = text1_length - x2;
if (x1 >= x2) {
// Overlap detected.
freeBuffers();
return [self diff_bisectSplitOfOldString:_text1
andNewString:_text2
x:x1
y:y1
deadline:deadline];
}
}
}
}
}
freeBuffers();
// Diff took too long and hit the deadline or
// number of diffs equals number of characters, no commonality at all.
diffs = [NSMutableArray array];
[diffs addObject:[Diff diffWithOperation:DIFF_DELETE andText:_text1]];
[diffs addObject:[Diff diffWithOperation:DIFF_INSERT andText:_text2]];
return diffs;
#undef freeTextBuffers
#undef text1CharacterAtIndex
#undef text2CharacterAtIndex
}
/**
* Given the location of the 'middle snake', split the diff in two parts
* and recurse.
* @param text1 Old string to be diffed.
* @param text2 New string to be diffed.
* @param x Index of split point in text1.
* @param y Index of split point in text2.
* @param deadline Time at which to bail if not yet complete.
* @return NSMutableArray of Diff objects.
*/
- (NSMutableArray *)diff_bisectSplitOfOldString:(NSString *)text1
andNewString:(NSString *)text2
x:(NSUInteger)x
y:(NSUInteger)y
deadline:(NSTimeInterval)deadline;
{
NSString *text1a = [text1 substringToIndex:x];
NSString *text2a = [text2 substringToIndex:y];
NSString *text1b = [text1 substringFromIndex:x];
NSString *text2b = [text2 substringFromIndex:y];
// Compute both diffs serially.
NSMutableArray *diffs = [self diff_mainOfOldString:text1a
andNewString:text2a
checkLines:NO
deadline:deadline];
NSMutableArray *diffsb = [self diff_mainOfOldString:text1b
andNewString:text2b
checkLines:NO
deadline:deadline];
[diffs addObjectsFromArray: diffsb];
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 NSString.
* @param text2 Second NSString.
* @return Three element NSArray, containing the encoded text1, the
* encoded text2 and the NSMutableArray of unique strings. The zeroth element
* of the NSArray of unique strings is intentionally blank.
*/
- (NSArray *)diff_linesToCharsForFirstString:(NSString *)text1
andSecondString:(NSString *)text2;
{
NSMutableArray *lineArray = [NSMutableArray array]; // NSString objects
CFMutableDictionaryRef lineHash = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, NULL); // keys: NSString, values:raw CFIndex
// e.g. [lineArray objectAtIndex:4] == "Hello\n"
// e.g. [lineHash objectForKey:"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 nil character.
[lineArray addObject:@""];
NSArray *result;
JX_NEW_AUTORELEASE_POOL_WITH_NAME(mungePool)
NSString *chars1 = JX_TRANSFER_CF_TO_OBJC(NSString *, diff_linesToCharsMungeCFStringCreate(JX_BRIDGED_CAST(CFStringRef, text1),
JX_BRIDGED_CAST(CFMutableArrayRef, lineArray),
lineHash));
NSString *chars2 = JX_TRANSFER_CF_TO_OBJC(NSString *, diff_linesToCharsMungeCFStringCreate(JX_BRIDGED_CAST(CFStringRef, text2),
JX_BRIDGED_CAST(CFMutableArrayRef, lineArray),
lineHash));
result = [[NSArray alloc] initWithObjects:chars1, chars2, lineArray, nil];
CFRelease(lineHash);
JX_END_AUTORELEASE_POOL_WITH_NAME(mungePool)
return JX_AUTORELEASE(result);
}
+ (CFOptionFlags)tokenizerOptionsForMode:(DiffTokenMode)mode;
{
CFOptionFlags tokenizerOptions;
switch (mode) {
case DiffWordTokens:
tokenizerOptions = kCFStringTokenizerUnitWordBoundary;
break;
case DiffSentenceTokens:
tokenizerOptions = kCFStringTokenizerUnitSentence;
break;
case DiffLineBreakDelimiteredTokens:
tokenizerOptions = kCFStringTokenizerUnitLineBreak;
break;
case DiffParagraphTokens:
default:
tokenizerOptions = kCFStringTokenizerUnitParagraph;
break;
}
return tokenizerOptions;
}
/**
* Split two texts into a list of strings. Reduce the texts to a string of
* hashes where each Unicode character represents one token (or boundary between tokens).
* A token can be a type of text fragment: a word, sentence, paragraph or line.
* The type is determined by the mode object.
* @param text1 First NSString.
* @param text2 Second NSString.
* @param mode value determining the tokenization mode.
* @return Three element NSArray, containing the encoded text1, the
* encoded text2 and the NSMutableArray of unique strings. The zeroth element
* of the NSArray of unique strings is intentionally blank.
*/
- (NSArray *)diff_tokensToCharsForFirstString:(NSString *)text1
andSecondString:(NSString *)text2
mode:(DiffTokenMode)mode;
{
CFOptionFlags tokenizerOptions = [[self class] tokenizerOptionsForMode:mode];
NSMutableArray *tokenArray = [NSMutableArray array]; // NSString objects
CFMutableDictionaryRef tokenHash = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, NULL); // keys: NSString, values:raw CFIndex
// e.g. [tokenArray objectAtIndex:4] == "Hello"