forked from gnachman/iTerm2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LineBuffer.m
1696 lines (1569 loc) · 58 KB
/
LineBuffer.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
// -*- mode:objc -*-
// $Id: $
/*
** LineBuffer.h
**
** Copyright (c) 2002, 2003
**
** Author: George Nachman
**
** Project: iTerm
**
** Description: Implements a buffer of lines. It can hold a large number
** of lines and can quickly format them to a fixed width.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program 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 General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#import <LineBuffer.h>
#import "RegexKitLite/RegexKitLite.h"
#import "BackgroundThread.h"
@implementation ResultRange
@end
@implementation XYRange
@end
@implementation LineBlock
- (LineBlock*) initWithRawBufferSize: (int) size
{
raw_buffer = (screen_char_t*) malloc(sizeof(screen_char_t) * size);
buffer_start = raw_buffer;
start_offset = 0;
first_entry = 0;
buffer_size = size;
// Allocate enough space for a bunch of 80-character lines. It can grow if needed.
cll_capacity = 1 + size/80;
cll_entries = 0;
cumulative_line_lengths = (int*) malloc(sizeof(int) * cll_capacity);
is_partial = NO;
cached_numlines_width = -1;
return self;
}
- (void) dealloc
{
if (raw_buffer) {
free(raw_buffer);
}
if (cumulative_line_lengths) {
free(cumulative_line_lengths);
}
[super dealloc];
}
- (LineBlock *)copy {
LineBlock *theCopy = [[LineBlock alloc] init];
theCopy->raw_buffer = (screen_char_t*) malloc(sizeof(screen_char_t) * buffer_size);
memmove(theCopy->raw_buffer, raw_buffer, sizeof(screen_char_t) * buffer_size);
size_t bufferStartOffset = (buffer_start - raw_buffer);
theCopy->buffer_start = theCopy->raw_buffer + bufferStartOffset;
theCopy->start_offset = start_offset;
theCopy->first_entry = first_entry;
theCopy->buffer_size = buffer_size;
size_t cll_size = sizeof(int) * cll_capacity;
theCopy->cumulative_line_lengths = (int*) malloc(cll_size);
memmove(theCopy->cumulative_line_lengths, cumulative_line_lengths, cll_size);
theCopy->cll_capacity = cll_capacity;
theCopy->cll_entries = cll_entries;
theCopy->is_partial = is_partial;
theCopy->cached_numlines = cached_numlines;
theCopy->cached_numlines_width = cached_numlines_width;
return theCopy;
}
- (int) rawSpaceUsed
{
if (cll_entries == 0) {
return 0;
} else {
return cumulative_line_lengths[cll_entries - 1];
}
}
- (void) _appendCumulativeLineLength: (int) cumulativeLength
{
if (cll_entries == cll_capacity) {
cll_capacity *= 2;
cumulative_line_lengths = (int*) realloc((void*) cumulative_line_lengths, cll_capacity * sizeof(int));
}
cumulative_line_lengths[cll_entries] = cumulativeLength;
++cll_entries;
}
// used by dump to format a line of screen_char_t's into an asciiz string.
static char* formatsct(screen_char_t* src, int len, char* dest) {
if (len > 999) len = 999;
int i;
for (i = 0; i < len; ++i) {
dest[i] = (src[i].code && !src[i].complexChar) ? src[i].code : '.';
}
dest[i] = 0;
return dest;
}
- (void)dump:(int)rawOffset
{
char temp[1000];
int i;
int prev;
if (first_entry > 0) {
prev = cumulative_line_lengths[first_entry - 1];
} else {
prev = 0;
}
for (i = first_entry; i < cll_entries; ++i) {
BOOL iscont = (i == cll_entries-1) && is_partial;
NSLog(@"Line %d, length %d, offset from raw=%d, abs pos=%d, continued=%s: %s\n", i, cumulative_line_lengths[i] - prev, prev, prev + rawOffset, iscont?"yes":"no",
formatsct(buffer_start+prev-start_offset, cumulative_line_lengths[i]-prev, temp));
prev = cumulative_line_lengths[i];
}
}
- (BOOL) appendLine: (screen_char_t*) buffer length: (int) length partial:(BOOL) partial
{
const int space_used = [self rawSpaceUsed];
const int free_space = buffer_size - space_used - start_offset;
if (length > free_space) {
return NO;
}
// There's a bit of an edge case here: if you're appending an empty
// non-partial line to a partial line, we need it to append a blank line
// after the continued line. In practice this happens because a line is
// long but then the wrapped portion is erased and the EOL_SOFT flag stays
// behind. It would be really complex to ensure consistency of line-wrapping
// flags because the screen contents are changed in so many places.
if (is_partial && !(!partial && length == 0)) {
// append to an existing line
NSAssert(cll_entries > 0, @"is_partial but has no entries");
cumulative_line_lengths[cll_entries - 1] += length;
} else {
// add a new line
[self _appendCumulativeLineLength: (space_used + length)];
}
is_partial = partial;
memcpy(raw_buffer + space_used, buffer, sizeof(screen_char_t) * length);
cached_numlines_width = -1;
return YES;
}
- (int) getPositionOfLine: (int*)lineNum atX: (int) x withWidth: (int)width
{
int length;
int eol;
screen_char_t* p = [self getWrappedLineWithWrapWidth: width
lineNum: lineNum
lineLength: &length
includesEndOfLine: &eol];
if (!p) {
return -1;
} else {
return p - raw_buffer + x;
}
}
// Count the number of "full lines" in buffer up to position 'length'. A full
// line is one that, after wrapping, goes all the way to the edge of the screen
// and has at least one character wrap around. It is equal to the number of
// lines after wrapping minus one. Examples:
//
// 2 Full Lines: 0 Full Lines: 0 Full Lines: 1 Full Line:
// |xxxxx| |x | |xxxxxx| |xxxxxx|
// |xxxxx| |x |
// |x |
static int NumberOfFullLines(screen_char_t* buffer, int length, int width)
{
// In the all-single-width case, it should return (length - 1) / width.
int fullLines = 0;
for (int i = width; i < length; i += width) {
if (buffer[i].code == DWC_RIGHT) {
--i;
}
++fullLines;
}
return fullLines;
}
// Finds a where the nth line begins after wrapping and returns its offset from the start of the buffer.
//
// In the following example, this would return:
// pointer to a if n==0, pointer to g if n==1, asserts if n > 1
// |abcdef|
// |ghi |
//
// It's more complex with double-width characters.
// In this example, suppose XX is a double-width character.
//
// Returns a pointer to a if n==0, pointer XX if n==1, asserts if n > 1:
// |abcde| <- line is short after wrapping
// |XXzzzz|
static int OffsetOfWrappedLine(screen_char_t* p, int n, int length, int width) {
int lines = 0;
int i = 0;
while (lines < n) {
// Advance i to the start of the next line
i += width;
++lines;
assert(i < length);
if (p[i].code == DWC_RIGHT) {
// Oops, the line starts with the second half of a double-width
// character. Wrap the last character of the previous line on to
// this line.
--i;
}
}
return i;
}
- (screen_char_t*) getWrappedLineWithWrapWidth: (int) width
lineNum: (int*) lineNum
lineLength: (int*) lineLength
includesEndOfLine: (int*) includesEndOfLine
{
int prev = 0;
int length;
int i;
for (i = first_entry; i < cll_entries; ++i) {
int cll = cumulative_line_lengths[i] - start_offset;
length = cll - prev;
int spans = NumberOfFullLines(buffer_start + prev, length, width);
if (*lineNum > spans) {
// Consume the entire raw line and keep looking for more.
int consume = spans + 1;
*lineNum -= consume;
} else { // *lineNum <= spans
// We found the raw line that inclues the wrapped line we're searching for.
// eat up *lineNum many width-sized wrapped lines from this start of the current full line
int offset = OffsetOfWrappedLine(buffer_start + prev,
*lineNum,
length,
width);
*lineNum = 0;
// offset: the relevant part of the raw line begins at this offset into it
*lineLength = length - offset; // the length of the suffix of the raw line, beginning at the wrapped line we want
if (*lineLength > width) {
// return an infix of the full line
if (buffer_start[prev + offset + width].code == DWC_RIGHT) {
// Result would end with the first half of a double-width character
*lineLength = width - 1;
*includesEndOfLine = EOL_DWC;
} else {
*lineLength = width;
*includesEndOfLine = EOL_SOFT;
}
} else {
// return a suffix of the full line
if (i == cll_entries - 1 && is_partial) {
// If this is the last line and it's partial then it doesn't have an end-of-line.
*includesEndOfLine = EOL_SOFT;
} else {
*includesEndOfLine = EOL_HARD;
}
}
return buffer_start + prev + offset;
}
prev = cll;
}
return NULL;
}
- (int) getNumLinesWithWrapWidth: (int) width
{
if (width == cached_numlines_width) {
return cached_numlines;
}
int count = 0;
int prev = 0;
int i;
// Count the number of wrapped lines in the block by computing the sum of the number
// of wrapped lines each raw line would use.
for (i = first_entry; i < cll_entries; ++i) {
int cll = cumulative_line_lengths[i] - start_offset;
int length = cll - prev;
count += NumberOfFullLines(buffer_start + prev, length, width) + 1;
prev = cll;
}
// Save the result so it doesn't have to be recalculated until some relatively rare operation
// occurs that invalidates the cache.
cached_numlines_width = width;
cached_numlines = count;
return count;
}
- (BOOL) hasCachedNumLinesForWidth: (int) width
{
return cached_numlines_width == width;
}
- (BOOL) popLastLineInto: (screen_char_t**) ptr withLength: (int*) length upToWidth: (int) width
{
if (cll_entries == first_entry) {
// There is no last line to pop.
return NO;
}
int start;
if (cll_entries == first_entry + 1) {
start = 0;
} else {
start = cumulative_line_lengths[cll_entries - 2] - start_offset;
}
const int end = cumulative_line_lengths[cll_entries - 1] - start_offset;
const int available_len = end - start;
if (available_len > width) {
// The last raw line is longer than width. So get the last part of it after wrapping.
// If the width is four and the last line is "0123456789" then return "89". It would
// wrap as: 0123/4567/89. If there are double-width characters, this ensures they are
// not split across lines when computing the wrapping.
// If there were only single width characters, the formula would be:
// width * ((available_len - 1) / width);
int offset_from_start = OffsetOfWrappedLine(buffer_start + start,
NumberOfFullLines(buffer_start + start,
available_len,
width),
available_len,
width);
*length = available_len - offset_from_start;
*ptr = buffer_start + start + offset_from_start;
cumulative_line_lengths[cll_entries - 1] -= *length;
is_partial = YES;
} else {
// The last raw line is not longer than width. Return the whole thing.
*length = available_len;
*ptr = buffer_start + start;
--cll_entries;
is_partial = NO;
}
if (cll_entries == first_entry) {
// Popped the last line. Reset everything.
buffer_start = raw_buffer;
start_offset = 0;
first_entry = 0;
cll_entries = 0;
}
// Mark the cache dirty.
cached_numlines_width = -1;
return YES;
}
- (BOOL) isEmpty
{
return cll_entries == first_entry;
}
- (int) numRawLines
{
return cll_entries - first_entry;
}
- (int) numEntries
{
return cll_entries;
}
- (int) startOffset
{
return start_offset;
}
- (int) getRawLineLength: (int) linenum
{
NSAssert(linenum < cll_entries && linenum >= 0, @"Out of bounds");
int prev;
if (linenum == 0) {
prev = 0;
} else {
prev = cumulative_line_lengths[linenum-1] - start_offset;
}
return cumulative_line_lengths[linenum] - start_offset - prev;
}
- (screen_char_t*) rawLine: (int) linenum
{
int start;
if (linenum == 0) {
start = 0;
} else {
start = cumulative_line_lengths[linenum - 1];
}
return raw_buffer + start;
}
- (void) changeBufferSize: (int) capacity
{
NSAssert(capacity >= [self rawSpaceUsed], @"Truncating used space");
raw_buffer = (screen_char_t*) realloc((void*) raw_buffer, sizeof(screen_char_t) * capacity);
buffer_start = raw_buffer + start_offset;
buffer_size = capacity;
cached_numlines_width = -1;
}
- (int) rawBufferSize
{
return buffer_size;
}
- (BOOL) hasPartial
{
return is_partial;
}
- (void) shrinkToFit
{
[self changeBufferSize: [self rawSpaceUsed]];
}
- (int) dropLines:(int)n withWidth:(int)width chars:(int *)charsDropped;
{
cached_numlines_width = -1;
int orig_n = n;
int prev = 0;
int length;
int i;
*charsDropped = 0;
int initialOffset = start_offset;
for (i = first_entry; i < cll_entries; ++i) {
int cll = cumulative_line_lengths[i] - start_offset;
length = cll - prev;
// Get the number of full-length wrapped lines in this raw line. If there
// were only single-width characters the formula would be:
// (length - 1) / width;
int spans = NumberOfFullLines(buffer_start + prev, length, width);
if (n > spans) {
// Consume the entire raw line and keep looking for more.
int consume = spans + 1;
n -= consume;
} else { // n <= spans
// We found the raw line that inclues the wrapped line we're searching for.
// Set offset to the offset into the raw line where the nth wrapped
// line begins. If there were only single-width characters the formula
// would be:
// offset = n * width;
int offset = OffsetOfWrappedLine(buffer_start + prev, n, length, width);
buffer_start += prev + offset;
start_offset = buffer_start - raw_buffer;
first_entry = i;
*charsDropped = start_offset - initialOffset;
return orig_n;
}
prev = cll;
}
// Consumed the whole buffer.
cll_entries = 0;
buffer_start = raw_buffer;
start_offset = 0;
first_entry = 0;
*charsDropped = [self rawSpaceUsed];
return orig_n - n;
}
- (int) _lineRawOffset: (int) anIndex
{
if (anIndex == first_entry) {
return start_offset;
} else {
return cumulative_line_lengths[anIndex - 1];
}
}
const unichar kPrefixChar = 1;
const unichar kSuffixChar = 2;
static NSString* RewrittenRegex(NSString* originalRegex) {
// Convert ^ in a context where it refers to the start of string to kPrefixChar
// Convert $ in a context where it refers to the end of string to kSuffixChar
// ^ is NOT start-of-string when:
// - it is escaped
// - it is preceeded by an unescaped [
// - it is preceeded by an unescaped [:
// $ is NOT end-of-string when:
// - it is escaped
//
// It might be possible to write this as a regular substitution but it would be a crazy mess.
NSMutableString* rewritten = [NSMutableString stringWithCapacity:[originalRegex length]];
BOOL escaped = NO;
BOOL inSet = NO;
BOOL firstCharInSet = NO;
unichar prevChar = 0;
for (int i = 0; i < [originalRegex length]; i++) {
BOOL nextCharIsFirstInSet = NO;
unichar c = [originalRegex characterAtIndex:i];
switch (c) {
case '\\':
escaped = !escaped;
break;
case '[':
if (!inSet && !escaped) {
inSet = YES;
nextCharIsFirstInSet = YES;
}
break;
case ']':
if (inSet && !escaped) {
inSet = NO;
}
break;
case ':':
if (inSet && firstCharInSet && prevChar == '[') {
nextCharIsFirstInSet = YES;
}
break;
case '^':
if (!escaped && !firstCharInSet) {
c = kPrefixChar;
}
break;
case '$':
if (!escaped) {
c = kSuffixChar;
}
break;
}
prevChar = c;
firstCharInSet = nextCharIsFirstInSet;
[rewritten appendFormat:@"%C", c];
}
return rewritten;
}
static int CoreSearch(NSString* needle, screen_char_t* rawline, int raw_line_length, int start, int end,
int options, int* resultLength, NSString* haystack, unichar* charHaystack,
int* deltas, int deltaOffset)
{
int apiOptions = 0;
NSRange range;
BOOL regex;
if (options & FindOptRegex) {
regex = YES;
} else {
regex = NO;
}
if (regex) {
BOOL backwards = NO;
if (options & FindOptBackwards) {
backwards = YES;
}
if (options & FindOptCaseInsensitive) {
apiOptions |= RKLCaseless;
}
NSError* regexError = nil;
NSRange temp;
NSString* rewrittenRegex = RewrittenRegex(needle);
NSString* sanitizedHaystack = [haystack stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%c", kPrefixChar]
withString:[NSString stringWithFormat:@"%c", 3]];
sanitizedHaystack = [sanitizedHaystack stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%c", kSuffixChar]
withString:[NSString stringWithFormat:@"%c", 3]];
NSString* sandwich;
BOOL hasPrefix = YES;
BOOL hasSuffix = YES;
if (end == raw_line_length) {
if (start == 0) {
sandwich = [NSString stringWithFormat:@"%C%@%C", kPrefixChar, sanitizedHaystack, kSuffixChar];
} else {
hasPrefix = NO;
sandwich = [NSString stringWithFormat:@"%@%C", sanitizedHaystack, kSuffixChar];
}
} else {
hasSuffix = NO;
sandwich = [NSString stringWithFormat:@"%C%@", kPrefixChar, sanitizedHaystack, kSuffixChar];
}
temp = [sandwich rangeOfRegex:rewrittenRegex
options:apiOptions
inRange:NSMakeRange(0, [sandwich length])
capture:0
error:®exError];
range = temp;
if (backwards) {
int locationAdjustment = hasSuffix ? 1 : 0;
// keep searching from one char after the start of the match until we don't find anything.
// regexes aren't good at searching backwards.
while (!regexError && temp.location != NSNotFound && temp.location+locationAdjustment < [sandwich length]) {
if (temp.length != 0) {
range = temp;
}
temp.location += MAX(1, temp.length);
temp = [sandwich rangeOfRegex:rewrittenRegex
options:apiOptions
inRange:NSMakeRange(temp.location, [sandwich length] - temp.location)
capture:0
error:®exError];
}
}
if (range.length == 0) {
range.location = NSNotFound;
}
if (!regexError && range.location != NSNotFound) {
if (hasSuffix && range.location + range.length == [sandwich length]) {
// match includes $
--range.length;
if (range.length == 0) {
// matched only on $
--range.location;
}
}
if (hasPrefix && range.location == 0) {
--range.length;
} else if (hasPrefix) {
--range.location;
}
}
if (range.length <= 0) {
// match on ^ or $
range.location = NSNotFound;
}
if (regexError) {
NSLog(@"regex error: %@", regexError);
range.length = 0;
range.location = NSNotFound;
}
} else {
if (options & FindOptBackwards) {
apiOptions |= NSBackwardsSearch;
}
if (options & FindOptCaseInsensitive) {
apiOptions |= NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch;
}
range = [haystack rangeOfString:needle options:apiOptions];
}
int result = -1;
if (range.location != NSNotFound) {
int adjustedLocation;
int adjustedLength;
adjustedLocation = range.location + deltas[range.location] + deltaOffset;
adjustedLength = range.length + deltas[range.location + range.length] -
(deltas[range.location] + deltaOffset);
*resultLength = adjustedLength;
result = adjustedLocation + start;
}
return result;
}
static int Search(NSString* needle,
screen_char_t* rawline,
int raw_line_length,
int start,
int end,
int options,
int* resultLength)
{
NSString* haystack;
unichar* charHaystack;
int* deltas;
haystack = ScreenCharArrayToString(rawline,
start,
end,
&charHaystack,
&deltas);
// screen_char_t[i + deltas[i]] begins its run at charHaystack[i]
int result = CoreSearch(needle, rawline, raw_line_length, start, end, options, resultLength,
haystack, charHaystack, deltas, deltas[0]);
free(deltas);
free(charHaystack);
return result;
}
- (void) _findInRawLine:(int) entry
needle:(NSString*)needle
options:(int) options
skip:(int) skip
length:(int) raw_line_length
multipleResults:(BOOL)multipleResults
results:(NSMutableArray*)results
{
screen_char_t* rawline = raw_buffer + [self _lineRawOffset:entry];
if (skip > raw_line_length) {
skip = raw_line_length;
}
if (skip < 0) {
skip = 0;
}
if (options & FindOptBackwards) {
// This algorithm is wacky and slow but stay with me here:
// When you search backward, the most common case is that you are
// repeating the previous search but with a one-character longer
// needle (having grown at the end). So the rightmost result we can
// accept is one whose leftmost position is at the leftmost position of
// the previous result.
//
// Example: Consider a previosu search of [jump]
// The quick brown fox jumps over the lazy dog.
// ^^^^
// The search is then extended to [jumps]. We want to return:
// The quick brown fox jumps over the lazy dog.
// ^^^^^
// Ideally, we would search only the necessary part of the haystack:
// Search("The quick brown fox jumps", "jumps")
//
// But what we did there was to add one byte to the haystack. That works
// for ascii, but not in other cases. Let us consider a localized
// German search where "ss" matches "ß". Let's first search for [jump]
// in this translation:
//
// Ein quicken Braunfox jumpss uber die Lazydog.
// ^^^^
// Then the needle becomes [jumpß]. Under the previous algorithm we'd
// extend the haystack to:
// Ein quicken Braunfox jumps
// And there is no match for jumpß.
//
// So to do the optimal algorithm, you'd have to know how many characters
// to add to the haystack in the worst localized case. With decomposed
// diacriticals, the upper bound is unclear.
//
// I'm going to err on the side of correctness over performance. I'm
// sure this could be improved if needed. One obvious
// approach is to use the naïve algorithm when the text is all ASCII.
//
// Thus, the algorithm is to do a reverse search until a hit is found
// that begins not before 'skip', which is the leftmost acceptable
// position.
int limit = raw_line_length;
int tempResultLength;
int tempPosition;
NSString* haystack;
unichar* charHaystack;
int* deltas;
haystack = ScreenCharArrayToString(rawline,
0,
limit,
&charHaystack,
&deltas);
int numUnichars = [haystack length];
do {
haystack = CharArrayToString(charHaystack, numUnichars);
tempPosition = CoreSearch(needle, rawline, raw_line_length, 0, limit, options,
&tempResultLength, haystack, charHaystack, deltas, 0);
limit = tempPosition + tempResultLength - 1;
// find i so that i-deltas[i] == limit
while (numUnichars >= 0 && numUnichars + deltas[numUnichars] > limit) {
--numUnichars;
}
if (tempPosition != -1 && tempPosition <= skip) {
ResultRange* r = [[[ResultRange alloc] init] autorelease];
r->position = tempPosition;
r->length = tempResultLength;
[results addObject:r];
}
} while (tempPosition != -1 && (multipleResults || tempPosition > skip));
free(deltas);
free(charHaystack);
} else {
// Search forward
// TODO: test this
int tempResultLength;
int tempPosition;
while (skip < raw_line_length) {
tempPosition = Search(needle, rawline, raw_line_length, skip, raw_line_length,
options, &tempResultLength);
if (tempPosition != -1) {
ResultRange* r = [[[ResultRange alloc] init] autorelease];
r->position = tempPosition;
r->length = tempResultLength;
[results addObject:r];
if (!multipleResults) {
break;
}
skip = tempPosition + 1;
} else {
break;
}
}
}
}
- (int) _lineLength: (int) anIndex
{
int prev;
if (anIndex == first_entry) {
prev = start_offset;
} else {
prev = cumulative_line_lengths[anIndex - 1];
}
return cumulative_line_lengths[anIndex] - prev;
}
- (int) _findEntryBeforeOffset: (int) offset
{
assert(offset >= start_offset);
int i;
for (i = first_entry; i < cll_entries; ++i) {
if (cumulative_line_lengths[i] > offset) {
return i;
}
}
return -1;
}
- (void) findSubstring: (NSString*) substring
options: (int) options
atOffset: (int) offset
results: (NSMutableArray*) results
multipleResults:(BOOL)multipleResults
{
if (offset == -1) {
offset = [self rawSpaceUsed] - 1;
}
int entry;
int limit;
int dir;
if (options & FindOptBackwards) {
entry = [self _findEntryBeforeOffset: offset];
if (entry == -1) {
// Maybe there were no lines or offset was <= start_offset.
return;
}
limit = first_entry - 1;
dir = -1;
} else {
entry = first_entry;
limit = cll_entries;
dir = 1;
}
while (entry != limit) {
int line_raw_offset = [self _lineRawOffset:entry];
int skipped = offset - line_raw_offset;
if (skipped < 0) {
skipped = 0;
}
NSMutableArray* newResults = [NSMutableArray arrayWithCapacity:1];
[self _findInRawLine:entry
needle:substring
options:options
skip:skipped
length:[self _lineLength: entry]
multipleResults:multipleResults
results:newResults];
for (ResultRange* r in newResults) {
r->position += line_raw_offset;
[results addObject:r];
}
if ([newResults count] && !multipleResults) {
return;
}
entry += dir;
}
}
// Returns YES if the position is valid for this block.
- (BOOL)convertPosition:(int)position
withWidth:(int)width
toX:(int*)x
toY:(int*)y
{
int i;
*x = 0;
*y = 0;
int prev = start_offset;
for (i = first_entry; i < cll_entries; ++i) {
int eol = cumulative_line_lengths[i];
int line_length = eol - prev;
if (position >= eol) {
// Get the number of full-width lines in the raw line. If there were
// only single-width characters the formula would be:
// spans = (line_length - 1) / width;
int spans = NumberOfFullLines(raw_buffer + prev, line_length, width);
*y += spans + 1;
} else {
// The position we're searching for is in this (unwrapped) line.
int bytes_to_consume_in_this_line = position - prev;
int dwc_peek = 0;
// If the position is the left half of a double width char then include the right half in
// the following call to NumberOfFullLines.
if (bytes_to_consume_in_this_line < line_length &&
prev + bytes_to_consume_in_this_line + 1 < eol) {
assert(prev + bytes_to_consume_in_this_line + 1 < buffer_size);
if (raw_buffer[prev + bytes_to_consume_in_this_line + 1].code == DWC_RIGHT) {
++dwc_peek;
}
}
int consume = NumberOfFullLines(raw_buffer + prev,
MIN(line_length, bytes_to_consume_in_this_line + 1 + dwc_peek),
width);
*y += consume;
if (consume > 0) {
// Offset from prev where the consume'th line begin.
int offset = OffsetOfWrappedLine(raw_buffer + prev,
consume,
line_length,
width);
// We know that position falls in this line. Set x to the number
// of chars after the beginning on the line. If there were only
// single-width chars the formula would be:
// bytes_to_consume_in_this_line % (consume * width);
*x = position - (prev + offset);
} else {
*x = bytes_to_consume_in_this_line;
}
return YES;
}
prev = eol;
}
NSLog(@"Didn't find position %d", position);
return NO;
}
@end
@implementation LineBuffer
// Append a block
- (LineBlock*) _addBlockOfSize: (int) size
{
LineBlock* block = [[LineBlock alloc] initWithRawBufferSize: size];
[blocks addObject: block];
[block release];
return block;
}
// The real implementation of init. We prefer not to explose the notion of block sizes to
// clients, so this is internal.
- (LineBuffer*) initWithBlockSize: (int) bs
{
block_size = bs;
blocks = [[NSMutableArray alloc] initWithCapacity: 1];
[self _addBlockOfSize: block_size];
max_lines = -1;
num_wrapped_lines_width = -1;
num_dropped_blocks = 0;
return self;
}
- (void)dealloc
{
// This causes the blocks to be released in a background thread.
// When a LineBuffer is really gigantic, it can take
// quite a bit of time to release all the blocks.
[blocks performSelector:@selector(removeAllObjects)
onThread:[BackgroundThread backgroundThread]
withObject:nil
waitUntilDone:NO];
[blocks release];
[super dealloc];
}
// This is called a lot so it's a C function to avoid obj_msgSend
static int RawNumLines(LineBuffer* buffer, int width) {
if (buffer->num_wrapped_lines_width == width) {
return buffer->num_wrapped_lines_cache;
}
int count = 0;
int i;
for (i = 0; i < [buffer->blocks count]; ++i) {
LineBlock* block = [buffer->blocks objectAtIndex: i];
count += [block getNumLinesWithWrapWidth: width];
}
buffer->num_wrapped_lines_width = width;
buffer->num_wrapped_lines_cache = count;
return count;
}
// drop lines if needed until max_lines is reached.
- (void) _dropLinesForWidth: (int) width
{
if (max_lines == -1) {