forked from erkyrath/Inform7-IDE-Mac
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIFSyntaxStorage.m
1571 lines (1227 loc) · 46.4 KB
/
IFSyntaxStorage.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
//
// IFSyntaxStorage.m
// Inform
//
// Created by Andrew Hunter on 17/11/2004.
// Copyright 2004 Andrew Hunter. All rights reserved.
//
#import "IFSyntaxStorage.h"
#import "IFPreferences.h"
#import "IFNoHighlighter.h"
#define HighlighterDebug 0
#define SlowMode 0
#if SlowMode
static int maxPassLength = 2;
#else
static int maxPassLength = 65536;
#endif
@implementation IFSyntaxStorage
// = Initialisation =
- (id) sharedInit {
self = [super init];
if (self) {
// Setup variables
string = [[NSMutableAttributedString alloc] initWithString: @""];
lineStarts = malloc(sizeof(*lineStarts));
lineStates = [[NSMutableArray alloc] init];
charStyles = NULL;
lineStyles = [[NSMutableArray alloc] initWithObjects: [NSDictionary dictionary], nil];
syntaxStack = [[NSMutableArray alloc] init];
syntaxPos = 0;
highlighter = nil;
highlightingStack = [[NSMutableArray alloc] init];
numDerivative = 0;
derivative = NULL;
// Initial state
lineStarts[0] = 0;
nLines = 1;
[lineStates addObject:
[NSMutableArray arrayWithObjects:
[NSArray arrayWithObjects:
[NSNumber numberWithUnsignedInt: IFSyntaxStateDefault],
[NSNumber numberWithUnsignedInt: 0],
nil],
nil]]; // Initial stack starts with the default state
needsHighlighting.location = NSNotFound;
amountHighlighted = 0;
enableWrapIndent = YES;
enableElasticTabs = YES;
[self paragraphStyleForTabStops: 8];
// Register for preference change notifications
[[NSNotificationCenter defaultCenter] addObserver: self
selector: @selector(preferencesChanged:)
name: IFPreferencesChangedEarlierNotification
object: [IFPreferences sharedPreferences]];
}
return self;
}
- (id) init {
// Designated initialiser
self = [self sharedInit];
if (self) {
}
return self;
}
- (id) initWithString: (NSString*) newString {
// Designated initialiser
self = [self sharedInit];
if (self) {
// Update the string
[self replaceCharactersInRange: NSMakeRange(0,0)
withString: newString];
}
return self;
}
- (id) initWithAttributedString: (NSAttributedString*) newString {
// Designated initialiser
self = [self sharedInit];
if (self) {
// Update the string
[self replaceCharactersInRange: NSMakeRange(0,0)
withString: [newString string]];
[string release];
string = [newString mutableCopy];
}
return self;
}
- (void) dealloc {
[[NSNotificationCenter defaultCenter] removeObserver: self];
[string release];
[lineStates release];
free(lineStarts);
free(charStyles);
[lineStyles release];
[syntaxStack release];
if (highlighter) {
[highlighter setSyntaxStorage: nil];
[highlighter release];
}
[highlightingStack release];
if (intelSource) {
[intelSource setSyntaxStorage: nil];
[intelSource release];
}
if (intelData) [intelData release];
[paragraphStyles release];
[tabStops release];
if (derivative) free(derivative);
[super dealloc];
}
// = Utility methods =
#if HighlighterDebug
- (void) edited: (unsigned)editedMask range: (NSRange)range changeInLength: (int)delta {
NSLog(@"Highlighter: edited range (%i, %i) mask %x, change in length %i", range.location, range.length, editedMask, delta);
[super edited: editedMask range: range changeInLength: delta];
}
#endif
- (int) lineForIndex: (unsigned) index {
// Yet Another Binary Search
int low = 0;
int high = nLines - 1;
while (low <= high) {
int middle = (low + high)>>1;
unsigned lineStart = lineStarts[middle];
if (index < lineStart) {
// Not this line: search the lower half
high = middle-1;
continue;
}
unsigned lineEnd = middle<(nLines-1)?lineStarts[middle+1]:[string length];
if (index >= lineEnd) {
// Not this line: search the upper half
low = middle+1;
continue;
}
// Must be this line
return middle;
}
// If we fell off, must be the last line (lines are unsigned, so we can't fall off the bottom)
return nLines-1;
}
- (IFSyntaxStyle) styleAtIndex: (unsigned) index
effectiveRange: (NSRangePointer) range {
IFSyntaxStyle style = charStyles[index];
if (range) {
NSRange localRange; // Optimisation suggested by Shark
const IFSyntaxStyle* localStyles = charStyles; // Ditto
localRange.location = index;
localRange.length = 0;
while (localRange.location > 0) {
if (localStyles[localRange.location-1] == style) {
localRange.location--;
} else {
break;
}
}
unsigned strLen = [string length];
while (localRange.location+localRange.length < strLen) {
if (localStyles[localRange.location+localRange.length] == style) {
localRange.length++;
} else {
break;
}
}
*range = localRange;
}
return style;
}
// = Required NSTextStorage methods =
- (NSString*) string {
return [string string];
}
// Temp storage
static NSString* IFCombinedAttributes = @"IFCombinedAttributes";
static NSString* IFStyleAttributes = @"IFStyleAttributes";
static NSString* IFLineAttributes = @"IFLineAttributes";
- (NSDictionary*) attributesAtIndex: (unsigned) index
effectiveRange: (NSRangePointer) range {
if (!highlighter) {
return [string attributesAtIndex: index
effectiveRange: range];
}
// Get the basic style
IFSyntaxStyle style;
NSRange styleRange;
style = [self styleAtIndex: index
effectiveRange: &styleRange];
// Get the attributes for this style
NSDictionary* styleAttributes = [highlighter attributesForStyle: style];
// Get the attributes and range for the string
NSRange stringRange;
NSDictionary* stringAttributes = [string attributesAtIndex: index
effectiveRange: &stringRange];
NSRange finalRange = NSIntersectionRange(styleRange, stringRange);
if (range) *range = finalRange;
// Use the cached attributes if available
if ([[stringAttributes objectForKey: IFStyleAttributes] pointerValue] == styleAttributes) {
return [stringAttributes objectForKey: IFCombinedAttributes];
}
// Get the attributes for this line
int line = [self lineForIndex: finalRange.location];
NSDictionary* lineAttributes = nil;
#if HighlighterDebug
NSLog(@"Attributes: recalculating attributes at line %i. Old attributes were %p, new attributes are %p. Attribute range (%i, %i)",
line, [[stringAttributes objectForKey: IFStyleAttributes] pointerValue], styleAttributes, finalRange.location, finalRange.length);
#endif
if (line < [lineStyles count]) {
lineAttributes = [lineStyles objectAtIndex: line];
}
// Create the result (we're using CF calls for speed reasons)
CFMutableDictionaryRef attributes = CFDictionaryCreateMutableCopy(kCFAllocatorDefault,
0,
(CFDictionaryRef)stringAttributes);
if (lineAttributes)
[(NSMutableDictionary*)attributes addEntriesFromDictionary: lineAttributes];
if (styleAttributes)
[(NSMutableDictionary*)attributes addEntriesFromDictionary: styleAttributes];
if (CFDictionaryContainsKey(attributes, IFStyleAttributes))
CFDictionaryRemoveValue(attributes, IFStyleAttributes);
if (CFDictionaryContainsKey(attributes, IFCombinedAttributes))
CFDictionaryRemoveValue(attributes, IFCombinedAttributes);
// Cache it
[string addAttribute: IFCombinedAttributes
value: (NSDictionary*)attributes
range: finalRange];
[string addAttribute: IFStyleAttributes
value: [NSValue valueWithPointer: styleAttributes]
range: finalRange];
// Return it
return [(NSDictionary*)attributes autorelease];
}
- (void) replaceCharactersInRange: (NSRange) range
withString: (NSString*) newString {
int strLen = [string length];
int newLen = [newString length];
// Give the intelligence source an opportunity to rewrite the input if this is a single entry
if (intelSource && range.length == 0 && [newString length] == 1) {
editingRange = range;
NSString* rewritten = [intelSource rewriteInput: newString];
if (rewritten) {
// Tell the delegate about this
id delegate = [self delegate];
if (delegate && [delegate respondsToSelector: @selector(rewroteCharactersInStorage:range:originalString:replacementString:)]) {
[delegate rewroteCharactersInStorage: self
range: NSMakeRange(range.location, [newString length])
originalString: [[newString copy] autorelease]
replacementString: [[rewritten copy] autorelease]];
}
// The string we're inserting is now the contents of rewritten
newString = rewritten;
newLen = [newString length];
}
}
// The range of lines to be replaced
int firstLine = [self lineForIndex: range.location];
int lastLine = range.length>0?[self lineForIndex: range.location + range.length]:firstLine;
#if HighlighterDebug
NSLog(@"Highlighter: editing lines in the range %i-%i", firstLine, lastLine);
#endif
// Build the array of new lines
unsigned* newLineStarts = NULL;
int nNewLines = 0;
NSMutableArray* newLineStates = [[NSMutableArray alloc] init];
unsigned x;
for (x=0; x<newLen; x++) {
unichar thisChar = [newString characterAtIndex: x];
if (thisChar == '\n' || thisChar == '\r') {
nNewLines++;
newLineStarts = realloc(newLineStarts, sizeof(*newLineStarts)*nNewLines);
newLineStarts[nNewLines-1] = x + range.location+1;
[newLineStates addObject:
[NSMutableArray arrayWithObject:
[NSArray arrayWithObjects:
[NSNumber numberWithUnsignedInt: IFSyntaxStateNotHighlighted],
[NSNumber numberWithUnsignedInt: 0],
nil]]];
}
}
int lineDifference = ((int)nNewLines) - (int)(lastLine-firstLine);
#if HighlighterDebug
NSLog(@"Highlighter: %i %@ lines (%i total)", lineDifference, nNewLines<(lastLine-firstLine)?@"new":@"removed",nLines);
#endif
// Replace the line positions (first line is still at the same position, with the same initial state, of course)
if (nNewLines < (lastLine-firstLine)) {
// Update first
for (x=0; x<nNewLines; x++) {
lineStarts[firstLine+1+x] = newLineStarts[x];
}
if (intelData) {
// Remove the appropriate lines from the intelligence data
[intelData removeLines: NSMakeRange(firstLine+1, -lineDifference)];
}
[lineStyles removeObjectsInRange: NSMakeRange(firstLine+1, -lineDifference)];
// Move lines down
memmove(lineStarts + firstLine + nNewLines + 1,
lineStarts + lastLine + 1,
sizeof(*lineStarts)*(nLines - (lastLine + 1)));
lineStarts = realloc(lineStarts, sizeof(*lineStarts)*(nLines + lineDifference));
} else {
// Move lines up
lineStarts = realloc(lineStarts, sizeof(*lineStarts)*(nLines + lineDifference));
memmove(lineStarts + firstLine + nNewLines + 1,
lineStarts + lastLine + 1,
sizeof(*lineStarts)*(nLines - (lastLine + 1)));
[lineStyles removeObjectsInRange: NSMakeRange(firstLine+1, lastLine-(firstLine))];
if (intelData) [intelData removeLines: NSMakeRange(firstLine+1, lastLine-(firstLine))];
// Update last
for (x=0; x<nNewLines; x++) {
[lineStyles insertObject: [self paragraphStyleForTabStops: 0]
atIndex: firstLine+1];
if (intelData) [intelData insertLineBeforeLine: firstLine+1]; // Might be slow with cut+paste sometimes?
lineStarts[firstLine+1+x] = newLineStarts[x];
}
}
[lineStates replaceObjectsInRange: NSMakeRange(firstLine+1, lastLine-firstLine)
withObjectsFromArray: newLineStates];
// Update the remaining line positions
nLines += lineDifference;
int charDifference = newLen - range.length;
for (x=firstLine + nNewLines+1; x<nLines; x++) {
lineStarts[x] += charDifference;
}
// Clean up data we don't need any more
[newLineStates release];
free(newLineStarts);
newLineStarts = NULL;
// Update the character positions
if (newLen < range.length) {
// Move characters down
memmove(charStyles + range.location + newLen,
charStyles + range.location + range.length,
sizeof(*charStyles)*(strLen - (range.location + range.length)));
charStyles = realloc(charStyles, strLen + (newLen - range.length));
} else {
// Move charactes up
charStyles = realloc(charStyles, strLen + (newLen - range.length));
memmove(charStyles + range.location + newLen,
charStyles + range.location + range.length,
sizeof(*charStyles)*(strLen - (range.location + range.length)));
}
// Update the actual characters
[string replaceCharactersInRange: range
withString: newString];
// Note the edit
[self beginEditing];
// Highlight 'around' the range
NSRange highlightRange = range;
highlightRange.length = newLen;
// Characters no longer have valid states
for (x=0; x<highlightRange.length; x++) {
charStyles[x+highlightRange.location] = IFSyntaxStyleNotHighlighted;
}
[self stopBackgroundHighlighting];
[self highlightRangeSoon: highlightRange];
[self edited: NSTextStorageEditedCharacters
range: range
changeInLength: newLen - range.length];
[self endEditing];
}
- (void) setAttributes: (NSDictionary*) attributes
range: (NSRange) range {
// Remove our private attributes if they've got copied through
if ([attributes objectForKey: IFStyleAttributes] || [attributes objectForKey: IFCombinedAttributes]) {
NSMutableDictionary* newAttr = [attributes mutableCopy];
if ([newAttr objectForKey: IFStyleAttributes]) [newAttr removeObjectForKey: IFStyleAttributes];
if ([newAttr objectForKey: IFCombinedAttributes]) [newAttr removeObjectForKey: IFCombinedAttributes];
if ([newAttr objectForKey: IFLineAttributes]) [newAttr removeObjectForKey: IFLineAttributes];
attributes = [newAttr autorelease];
}
// Set the attributes in the string
[string setAttributes: attributes
range: range];
// Note that we're now edited
[self edited: NSTextStorageEditedAttributes
range: range
changeInLength: 0];
}
// = Setting/retrieving the highlighter =
- (void) setHighlighter: (id<IFSyntaxHighlighter,NSObject>) newHighlighter {
if (highlighter) [highlighter release];
if (!newHighlighter) newHighlighter = [[[IFNoHighlighter alloc] init] autorelease];
highlighter = [newHighlighter retain];
[paragraphStyles release]; paragraphStyles = nil;
[tabStops release]; tabStops = nil;
[self highlightRange: NSMakeRange(0, [self length])];
}
- (id<IFSyntaxHighlighter>) highlighter {
return highlighter;
}
// = Communication from the highlighter =
- (void) pushState {
[syntaxStack addObject: [NSArray arrayWithObjects:
[NSNumber numberWithUnsignedInt: syntaxState],
[NSNumber numberWithUnsignedInt: syntaxMode],
nil]];
}
- (IFSyntaxState) popState {
IFSyntaxState poppedState = [[[syntaxStack lastObject] objectAtIndex: 0] unsignedIntValue];
syntaxMode = [[[syntaxStack lastObject] objectAtIndex: 1] unsignedIntValue];
[syntaxStack removeLastObject];
return poppedState;
}
- (void) backtrackWithStyle: (IFSyntaxStyle) newStyle
length: (int) backtrackLength {
// Change the styles, going backwards for the specified length
int x;
for (x=syntaxPos-backtrackLength; x<syntaxPos; x++) {
if (x >= 0) charStyles[x] = newStyle;
}
}
- (void) setHighlighterMode: (IFHighlighterMode) newMode {
// Sets the 'mode' of the highlighter (additional state info, basically)
syntaxMode = newMode;
}
- (IFHighlighterMode) highlighterMode {
// Retrieves the mode
return syntaxMode;
}
static inline BOOL IsWhitespace(unichar c) {
if (c == ' ' || c == '\t')
return YES;
else
return NO;
}
- (BOOL) preceededByKeyword: (NSString*) keyword
offset: (int) offset {
// If the given keyword preceeds the current position (case insensitively), this returns true
if (syntaxPos == 0) return NO;
int pos = syntaxPos-1-offset;
NSString* str = [string string];
// Skip whitespace
while (pos > 0 && IsWhitespace([str characterAtIndex: pos]))
pos--;
// pos should now point at the last letter of the keyword (if it is the keyword)
pos++;
// See if the keyword is there
int keywordLen = [keyword length];
if (pos < keywordLen)
return NO;
NSString* substring = [str substringWithRange: NSMakeRange(pos-keywordLen, keywordLen)];
return [substring caseInsensitiveCompare: keyword]==NSOrderedSame;
}
// = Actually performing highlighting =
- (void) highlightRange: (NSRange) range {
// The range of lines to be highlighted
int firstLine = [self lineForIndex: range.location];
int lastLine = range.length>0?[self lineForIndex: range.location + range.length - 1]:firstLine;
#if HighlighterDebug
NSLog(@"Highlighter: highlighting range %i-%i (lines %i-%i)", range.location, range.location + range.length, firstLine, lastLine);
#endif
// Setup
[highlighter setSyntaxStorage: self];
// Perform the highlighting
int line;
NSArray* lastOldStack = nil; // The 'old' stack for the last line
NSRange lastElasticRange = NSMakeRange(-1, 0); // The last range formatted with elastic tabs
for (line=firstLine; line<=lastLine; line++) {
// The range of characters to be highlighted
unsigned firstChar = lineStarts[line];
unsigned lastChar = (line+1)<nLines?lineStarts[line+1]:[string length];
// Set up the state
[syntaxStack setArray: [lineStates objectAtIndex: line]];
syntaxState = [[[syntaxStack lastObject] objectAtIndex: 0] unsignedIntValue];
syntaxMode = [[[syntaxStack lastObject] objectAtIndex: 1] unsignedIntValue];
[syntaxStack removeLastObject];
IFSyntaxState initialState = syntaxState;
// Number of tab stops (used for paragraph highlighting later)
int numTabStops = 0;
BOOL countingTabs = YES;
// Highlight this line
for (syntaxPos=firstChar; syntaxPos<lastChar; syntaxPos++) {
// Current state
unichar curChar = [[string string] characterAtIndex: syntaxPos];
// Count tab stops
if (countingTabs) {
if (curChar == 9)
numTabStops++;
else
countingTabs = NO;
}
// Next state
IFSyntaxState nextState = [highlighter stateForCharacter: curChar
afterState: syntaxState];
// Next style
IFSyntaxStyle nextStyle = [highlighter styleForCharacter: curChar
nextState: nextState
lastState: syntaxState];
// Store the style
charStyles[syntaxPos] = nextStyle;
// Store the state
syntaxState = nextState;
}
// Provide an opportunity for the highlighter to hint keywords, etc
NSString* lineToHint = [[string string] substringWithRange: NSMakeRange(firstChar, lastChar-firstChar)];
#if HighlighterDebug
NSLog(@"Highlighter: finished line %i: '%@', rehinting", line, lineToHint);
#endif
[highlighter rehintLine: lineToHint
styles: charStyles+firstChar
initialState: initialState];
if (intelSource && intelData) {
// Gather intelligence for the line, if we have something to gather it with
[intelSource gatherIntelForLine: lineToHint
styles: charStyles+firstChar
initialState: initialState
lineNumber: line
intoData: intelData];
}
// Use our own ability to set attributes to set the number of tab stops
if (enableWrapIndent) {
NSDictionary* lastStyle = nil;
NSDictionary* newStyle = [self paragraphStyleForTabStops: numTabStops];
BOOL styleChanged = NO;
if ([lineStyles count] <= line) {
// Add a new style if it's needed for this line
styleChanged = YES;
for (;[lineStyles count] <= line;) {
[lineStyles addObject: newStyle];
}
} else {
// Alter the existing style
if (enableElasticTabs) {
// Adjust the head indent of the current style
lastStyle = [lineStyles objectAtIndex: line];
NSMutableParagraphStyle* paraStyle = [[[lastStyle objectForKey: NSParagraphStyleAttributeName] mutableCopy] autorelease];
NSParagraphStyle* newParaStyle = [newStyle objectForKey: NSParagraphStyleAttributeName];
styleChanged = [paraStyle headIndent] != [newParaStyle headIndent];
if (styleChanged) {
// Update the paragraph style
[paraStyle setHeadIndent: [newParaStyle headIndent]];
// Replace it in the dictionary for the line style
NSMutableDictionary* newLineStyle = [[newStyle mutableCopy] autorelease];
[newLineStyle setObject: newParaStyle
forKey: NSParagraphStyleAttributeName];
[lineStyles replaceObjectAtIndex: line
withObject: newLineStyle];
}
} else {
// Just use this style directly
lastStyle = [lineStyles objectAtIndex: line];
[lineStyles replaceObjectAtIndex: line
withObject: newStyle];
}
}
if (styleChanged) {
// Force an attribute update
[string removeAttribute: IFStyleAttributes
range: NSMakeRange(firstChar, lastChar-firstChar)];
[string addAttributes: newStyle
range: NSMakeRange(firstChar, lastChar-firstChar)];
}
}
// Deal with elastic tabs if necessary
if (enableElasticTabs) {
// Get the region affected by these elastic tabs
NSRange elasticRange = [self rangeOfElasticRegionAtIndex: firstChar];
if (elasticRange.location != NSNotFound && elasticRange.location != lastElasticRange.location && line < [lineStyles count]) {
// This is now the last elastic range (prevents us from formatting the same region twice)
lastElasticRange = elasticRange;
// Fetch the current paragraph style
NSParagraphStyle* currentPara = [[lineStyles objectAtIndex: line] objectForKey: NSParagraphStyleAttributeName];
// Lay out the tabs
NSArray* newTabStops = [self elasticTabsInRegion: elasticRange];
// Compare them
BOOL tabsIdentical = NO;
if ([[currentPara tabStops] count] == [newTabStops count]) {
tabsIdentical = YES;
int x;
for (x=0; x<[newTabStops count]; x++) {
if (![[newTabStops objectAtIndex: x] isEqual: [[currentPara tabStops] objectAtIndex: x]]) {
tabsIdentical = NO;
break;
}
}
}
// Update the tabs over this region if necessary
if (!tabsIdentical) {
int firstElasticLine = [self lineForIndex: elasticRange.location];
int lastElasticLine = [self lineForIndex: elasticRange.location + elasticRange.length];
if (elasticRange.location + elasticRange.length >= [self length]) lastElasticLine++;
int formatLine;
for (formatLine = firstElasticLine; formatLine < lastElasticLine; formatLine++) {
while (formatLine >= [lineStyles count]) {
// Create a default line style for this line
[lineStyles addObject: [self paragraphStyleForTabStops: 0]];
}
// Copy the styles for this line
NSMutableDictionary* style = [[lineStyles objectAtIndex: formatLine] mutableCopy];
NSMutableParagraphStyle* paraStyle = [[style objectForKey: NSParagraphStyleAttributeName] mutableCopy];
if (!paraStyle) paraStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[style autorelease]; [paraStyle autorelease];
// Update the paragraph style with the new tabstops
[paraStyle setTabStops: newTabStops];
[style setObject: paraStyle forKey: NSParagraphStyleAttributeName];
// Replace the line style
[lineStyles replaceObjectAtIndex: formatLine
withObject: style];
// Force an attribute update
int formatFirstChar = lineStarts[formatLine];
int formatLastChar = (formatLine+1<nLines)?lineStarts[formatLine+1]:[string length];
[string removeAttribute: IFStyleAttributes
range: NSMakeRange(formatFirstChar, formatLastChar-formatFirstChar)];
[string addAttributes: style
range: NSMakeRange(formatFirstChar, formatLastChar-formatFirstChar)];
}
// Mark the range as edited
[self edited: NSTextStorageEditedAttributes
range: elasticRange
changeInLength: 0];
}
}
}
// Finish the stack
[syntaxStack addObject:
[NSArray arrayWithObjects:
[NSNumber numberWithUnsignedInt: syntaxState],
[NSNumber numberWithUnsignedInt: syntaxMode],
nil]];
// Store the stack
[lastOldStack release];
lastOldStack = nil;
if (line+1 < [lineStates count]) {
lastOldStack = [[lineStates objectAtIndex: line+1] retain];
[lineStates replaceObjectAtIndex: line+1
withObject: [[syntaxStack copy] autorelease]];
}
}
// If the next line needs highlighting, mark it so
#if HighlighterDebug
NSLog(@"Highlighter: Finished at line %i", line);
#endif
if (line < nLines) {
#if HighlighterDebug
NSLog(@"Highlighter: Previous stack is %@, but stack now is %@", lastOldStack, [lineStates objectAtIndex: line]);
#endif
if (![lastOldStack isEqualToArray: [lineStates objectAtIndex: line]]) {
// The state at the start of this line has changed: mark it as invalid
unsigned firstChar = lineStarts[line];
unsigned lastChar = (line+1)<nLines?lineStarts[line+1]:[string length];
unsigned x;
for (x=firstChar; x<lastChar; x++) charStyles[x] = IFSyntaxStyleNotHighlighted;
NSRange newInvalidRange = NSMakeRange(firstChar, lastChar-firstChar);
if (needsHighlighting.location == NSNotFound)
needsHighlighting = newInvalidRange;
else
needsHighlighting = NSUnionRange(needsHighlighting, newInvalidRange);
}
}
// Clean up
[lastOldStack release];
[highlighter setSyntaxStorage: nil];
// Mark as edited
unsigned firstChar = lineStarts[firstLine];
unsigned lastChar = (lastLine+1)<nLines?lineStarts[lastLine+1]:[string length];
[self edited: NSTextStorageEditedAttributes
range: NSMakeRange(firstChar, lastChar-firstChar)
changeInLength: 0];
// Add to the number of highlighted characters
amountHighlighted += (lastChar-firstChar);
}
- (void) highlightRangeLater: (NSRange) range {
// Hack: improves apparent update performance for deeply mysterious reasons
//
// The text layout system doesn't like us calling back to finish the highlighting job finished
// after the user started it by editing the text, which creates a weird effect: when add a line
// by hitting enter, there's a delay before the update takes place. Taking this out removes the
// delay, but stuffs the highlighting up a bit.
//
// This callback ensures that the extra highlighting happens after the runloop runs through twice
// rather than once. This doesn't appear to eliminate the delay, but certainly appears to improve
// it.
//
// Unfortunately, this creates a visible delay in highlighting :-/
[[NSRunLoop currentRunLoop] performSelector: @selector(highlightRangeSooner:)
target: self
argument: [NSValue valueWithRange: range]
order: 9
modes: [NSArray arrayWithObject: NSDefaultRunLoopMode]];
}
- (void) highlightRangeSooner: (NSValue*) value {
[self highlightRangeSoon: [value rangeValue]];
}
- (void) highlightRangeSoon: (NSRange) range {
[[NSRunLoop currentRunLoop] performSelector: @selector(highlightRangeNow:)
target: self
argument: [NSValue valueWithRange: range]
order: 8
modes: [NSArray arrayWithObject: NSDefaultRunLoopMode]];
}
- (void) highlightRangeNow: (NSValue*) range {
if (highlighter == nil) return; // Nothing to do
// If a highlighter pass is already running...
if (needsHighlighting.location != NSNotFound) {
#if HighlighterDebug
NSLog(@"Highlighter: new data arrived while we were busy");
#endif
NSRange rangeValue = [range rangeValue];
if (rangeValue.location < needsHighlighting.location) {
// This location is earlier than the current highlighting location: it has a higher priority
#if HighlighterDebug
NSLog(@"Highlighter: Going backwards...");
#endif
[highlightingStack addObject: [NSValue valueWithRange: needsHighlighting]];
} else {
// This location is later than the current highlighting location: it should be left until later
#if HighlighterDebug
NSLog(@"Highlighter: Saving this for later...");
#endif
// Find where to store it (we could binary search here, but most of the time, the stack is small)
int pos;
for (pos = [highlightingStack count]-1; pos >= 0; pos--) {
NSRange thisRange = [[highlightingStack objectAtIndex: pos] rangeValue];
if (thisRange.location > rangeValue.location) break;
}
// Store this range
pos++;
[highlightingStack insertObject: range
atIndex: pos];
// Just continue highlighting as before, we'll get to this eventually
return;
}
}
// Highlighted nothing so far
amountHighlighted = 0;
// Highlight the range
[self beginEditing];
[self highlightRange: [range rangeValue]];
// Highlight anything else that might need it (until we hit the end of a highlighter pass)
while (amountHighlighted < maxPassLength && [self highlighterPass]);
[self endEditing];
// Continue highlighting in the background if required
[self startBackgroundHighlighting];
}
- (BOOL) highlighting {
return needsHighlighting.location!=NSNotFound;
}
- (BOOL) continueHighlightingFrom: (BOOL) positionReached {
unsigned strLen = [string length];
while ([highlightingStack count] > 0) {
// Get the next value from the stack
NSRange nextRange = [[highlightingStack lastObject] rangeValue];
[highlightingStack removeLastObject];
// Ignore anything beyond the end of the string
if (nextRange.location > strLen) continue;
if (nextRange.location >= positionReached) {
// This is the location to continue highlighting at
#if HighlighterDebug
NSLog(@"Highlighter: apparently we have some unfinished business");
#endif
needsHighlighting = nextRange;
return YES;
}
}
// No more stack, nothing more to highlight
return NO;
}
- (BOOL) highlighterPass {
// Highlight anything that needs highlighting
if (needsHighlighting.location == NSNotFound) return NO;
unsigned strLen = [string length];
if (needsHighlighting.location >= strLen) {
// Outside the string
needsHighlighting.location = NSNotFound;
return NO;
}
NSDate* startTime = nil;
if (maxPassLength > 2048) startTime = [NSDate date];
needsHighlighting = NSIntersectionRange(needsHighlighting, NSMakeRange(0, strLen));
unsigned highlightStart = needsHighlighting.location;
unsigned highlightEnd = needsHighlighting.location + needsHighlighting.length;
int x;
// Find the first character that needs highlighting
for (x=0; x<needsHighlighting.length; x++) {
if (charStyles[needsHighlighting.location + x] == IFSyntaxStyleNotHighlighted) {
highlightStart = needsHighlighting.location+x;
break;
}
}
if (x == needsHighlighting.length) {
// Everything is highlighted
if ([self continueHighlightingFrom: needsHighlighting.location + needsHighlighting.length]) {