-
Notifications
You must be signed in to change notification settings - Fork 134
/
SMLSyntaxColouring.m
2239 lines (1751 loc) · 96 KB
/
SMLSyntaxColouring.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
// SMLTextView delegate
/*
MGSFragaria
Written by Jonathan Mitchell, [email protected]
Find the latest version at https://github.com/mugginsoft/Fragaria
Smultron version 3.6b1, 2009-09-12
Written by Peter Borg, [email protected]
Find the latest version at http://smultron.sourceforge.net
Copyright 2004-2009 Peter Borg
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.
*/
#import "MGSFragaria.h"
#import "MGSFragariaFramework.h"
// syntax colouring information dictionary keys
NSString *SMLSyntaxGroup = @"group";
NSString *SMLSyntaxGroupID = @"groupID";
NSString *SMLSyntaxWillColour = @"willColour";
NSString *SMLSyntaxAttributes = @"attributes";
NSString *SMLSyntaxInfo = @"syntaxInfo";
// syntax colouring group names
NSString *SMLSyntaxGroupNumber = @"number";
NSString *SMLSyntaxGroupCommand = @"command";
NSString *SMLSyntaxGroupInstruction = @"instruction";
NSString *SMLSyntaxGroupKeyword = @"keyword";
NSString *SMLSyntaxGroupAutoComplete = @"autocomplete";
NSString *SMLSyntaxGroupVariable = @"variable";
NSString *SMLSyntaxGroupFirstString = @"firstString";
NSString *SMLSyntaxGroupSecondString = @"secondString";
NSString *SMLSyntaxGroupAttribute = @"attribute";
NSString *SMLSyntaxGroupSingleLineComment = @"singleLineComment";
NSString *SMLSyntaxGroupMultiLineComment = @"multiLineComment";
NSString *SMLSyntaxGroupSecondStringPass2 = @"secondStringPass2";
// syntax definition dictionary keys
NSString *SMLSyntaxDefinitionAllowSyntaxColouring = @"allowSyntaxColouring";
NSString *SMLSyntaxDefinitionKeywords = @"keywords";
NSString *SMLSyntaxDefinitionAutocompleteWords = @"autocompleteWords";
NSString *SMLSyntaxDefinitionRecolourKeywordIfAlreadyColoured = @"recolourKeywordIfAlreadyColoured";
NSString *SMLSyntaxDefinitionKeywordsCaseSensitive = @"keywordsCaseSensitive";
NSString *SMLSyntaxDefinitionBeginCommand = @"beginCommand";
NSString *SMLSyntaxDefinitionEndCommand = @"endCommand";
NSString *SMLSyntaxDefinitionBeginInstruction = @"beginInstruction";
NSString *SMLSyntaxDefinitionEndInstruction = @"endInstruction";
NSString *SMLSyntaxDefinitionBeginVariable = @"beginVariable";
NSString *SMLSyntaxDefinitionEndVariable = @"endVariable";
NSString *SMLSyntaxDefinitionFirstString = @"firstString";
NSString *SMLSyntaxDefinitionSecondString = @"secondString";
NSString *SMLSyntaxDefinitionFirstSingleLineComment = @"firstSingleLineComment";
NSString *SMLSyntaxDefinitionSecondSingleLineComment = @"secondSingleLineComment";
NSString *SMLSyntaxDefinitionBeginFirstMultiLineComment = @"beginFirstMultiLineComment";
NSString *SMLSyntaxDefinitionEndFirstMultiLineComment = @"endFirstMultiLineComment";
NSString *SMLSyntaxDefinitionBeginSecondMultiLineComment = @"beginSecondMultiLineComment";
NSString *SMLSyntaxDefinitionEndSecondMultiLineComment = @"endSecondMultiLineComment";
NSString *SMLSyntaxDefinitionFunctionDefinition = @"functionDefinition";
NSString *SMLSyntaxDefinitionRemoveFromFunction = @"removeFromFunction";
NSString *SMLSyntaxDefinitionExcludeFromKeywordStartCharacterSet = @"excludeFromKeywordStartCharacterSet";
NSString *SMLSyntaxDefinitionExcludeFromKeywordEndCharacterSet = @"excludeFromKeywordEndCharacterSet";
NSString *SMLSyntaxDefinitionIncludeInKeywordStartCharacterSet = @"includeInKeywordStartCharacterSet";
NSString *SMLSyntaxDefinitionIncludeInKeywordEndCharacterSet = @"includeInKeywordEndCharacterSet";
static char SMLColoursChanged;
static char SMLMultiLineChanged;
static char SMLSyntaxDefinition;
// class extension
@interface SMLSyntaxColouring()
@property (copy) NSString *functionDefinition;
@property (copy) NSString *removeFromFunction;
@property (strong) NSString *secondString;
@property (strong) NSString *firstString;
@property (strong) NSString *beginCommand;
@property (strong) NSString *endCommand;
@property (strong) NSSet *keywords;
@property (strong) NSSet *autocompleteWords;
@property (strong) NSArray *keywordsAndAutocompleteWords;
@property (strong) NSString *beginInstruction;
@property (strong) NSString *endInstruction;
@property (strong) NSCharacterSet *beginVariableCharacterSet;
@property (strong) NSCharacterSet *endVariableCharacterSet;
@property (strong) NSString *firstSingleLineComment;
@property (strong) NSString *secondSingleLineComment;
@property (strong) NSMutableArray *singleLineComments;
@property (strong) NSMutableArray *multiLineComments;
@property (strong) NSString *beginFirstMultiLineComment;
@property (strong) NSString*endFirstMultiLineComment;
@property (strong) NSString*beginSecondMultiLineComment;
@property (strong) NSString*endSecondMultiLineComment;
@property (strong) NSCharacterSet *keywordStartCharacterSet;
@property (strong) NSCharacterSet *keywordEndCharacterSet;
@property (strong) NSCharacterSet *attributesCharacterSet;
@property (strong) NSCharacterSet *letterCharacterSet;
@property (strong) NSCharacterSet *numberCharacterSet;
@property (strong) NSCharacterSet *nameCharacterSet;
@property (assign) BOOL syntaxDefinitionAllowsColouring;
@property unichar decimalPointCharacter;
- (void)parseSyntaxDictionary:(NSDictionary *)syntaxDictionary;
- (void)applySyntaxDefinition;
- (NSString *)assignSyntaxDefinition;
- (void)performDocumentDelegateSelector:(SEL)selector withObject:(id)object;
- (void)autocompleteWordsTimerSelector:(NSTimer *)theTimer;
- (NSString *)completeString;
- (void)prepareRegularExpressions;
- (void)applyColourDefaults;
- (void)recolourRange:(NSRange)range;
- (void)removeAllColours;
- (void)removeColoursFromRange:(NSRange)range;
- (NSString *)guessSyntaxDefinitionExtensionFromFirstLine:(NSString *)firstLine;
- (void)pageRecolour;
- (void)setColour:(NSDictionary *)colour range:(NSRange)range;
- (void)highlightLineRange:(NSRange)lineRange;
- (void)undoManagerDidUndo:(NSNotification *)aNote;
- (BOOL)isSyntaxColouringRequired;
- (NSDictionary *)syntaxDictionary;
@end
@implementation SMLSyntaxColouring
@synthesize reactToChanges, functionDefinition, removeFromFunction, undoManager, secondString, firstString, keywords, autocompleteWords, keywordsAndAutocompleteWords, beginCommand, endCommand, beginInstruction, endInstruction, beginVariableCharacterSet, endVariableCharacterSet, firstSingleLineComment, secondSingleLineComment, singleLineComments, multiLineComments, beginFirstMultiLineComment, endFirstMultiLineComment, beginSecondMultiLineComment, endSecondMultiLineComment, keywordStartCharacterSet, keywordEndCharacterSet, attributesCharacterSet, letterCharacterSet, numberCharacterSet, decimalPointCharacter, syntaxErrors, syntaxDefinitionAllowsColouring, nameCharacterSet;
#pragma mark -
#pragma mark Instance methods
/*
- init
*/
- (id)init
{
self = [self initWithDocument:nil];
return self;
}
/*
- initWithDocument:
*/
- (id)initWithDocument:(id)theDocument
{
if ((self = [super init])) {
NSAssert(theDocument, @"bad document");
// retain the document
document = theDocument;
self.undoManager = [[NSUndoManager alloc] init];
// configure the document text view
NSTextView *textView = [document valueForKey:ro_MGSFOTextView];
NSAssert([textView isKindOfClass:[NSTextView class]], @"bad textview");
[textView setDelegate:self];
[[textView textStorage] setDelegate:self];
// configure ivars
lastCursorLocation = 0;
lastLineHighlightRange = NSMakeRange(0, 0);
reactToChanges = YES;
// configure layout managers
firstLayoutManager = (SMLLayoutManager *)[textView layoutManager];
// configure colouring
[self applyColourDefaults];
// letter character set
self.letterCharacterSet = [NSCharacterSet letterCharacterSet];
// name character set
NSMutableCharacterSet *temporaryCharacterSet = [[NSCharacterSet letterCharacterSet] mutableCopy];
[temporaryCharacterSet addCharactersInString:@"_"];
self.nameCharacterSet = [temporaryCharacterSet copy];
// keyword start character set
temporaryCharacterSet = [[NSCharacterSet letterCharacterSet] mutableCopy];
[temporaryCharacterSet addCharactersInString:@"_:@#"];
self.keywordStartCharacterSet = [temporaryCharacterSet copy];
// keyword end character set
// see http://www.fileformat.info/info/unicode/category/index.htm for categories that make up the sets
temporaryCharacterSet = [[NSCharacterSet whitespaceAndNewlineCharacterSet] mutableCopy];
[temporaryCharacterSet formUnionWithCharacterSet:[NSCharacterSet symbolCharacterSet]];
[temporaryCharacterSet formUnionWithCharacterSet:[NSCharacterSet punctuationCharacterSet]];
[temporaryCharacterSet removeCharactersInString:@"_-"]; // common separators in variable names
self.keywordEndCharacterSet = [temporaryCharacterSet copy];
// number character set
self.numberCharacterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789."];
self.decimalPointCharacter = [@"." characterAtIndex:0];
// attributes character set
temporaryCharacterSet = [[NSCharacterSet alphanumericCharacterSet] mutableCopy];
[temporaryCharacterSet addCharactersInString:@" -"]; // If there are two spaces before an attribute
self.attributesCharacterSet = [temporaryCharacterSet copy];
// configure syntax definition
[self applySyntaxDefinition];
// add undo notification observers
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(undoManagerDidUndo:)
name:@"NSUndoManagerDidUndoChangeNotification"
object:undoManager];
// add document KVO observers
[document addObserver:self forKeyPath:@"syntaxDefinition" options:NSKeyValueObservingOptionNew context:&SMLSyntaxDefinition];
// add NSUserDefaultsController KVO observers
NSUserDefaultsController *defaultsController = [NSUserDefaultsController sharedUserDefaultsController];
[defaultsController addObserver:self forKeyPath:@"values.FragariaCommandsColourWell" options:NSKeyValueObservingOptionNew context:&SMLColoursChanged];
[defaultsController addObserver:self forKeyPath:@"values.FragariaCommentsColourWell" options:NSKeyValueObservingOptionNew context:&SMLColoursChanged];
[defaultsController addObserver:self forKeyPath:@"values.FragariaInstructionsColourWell" options:NSKeyValueObservingOptionNew context:&SMLColoursChanged];
[defaultsController addObserver:self forKeyPath:@"values.FragariaKeywordsColourWell" options:NSKeyValueObservingOptionNew context:&SMLColoursChanged];
[defaultsController addObserver:self forKeyPath:@"values.FragariaAutocompleteColourWell" options:NSKeyValueObservingOptionNew context:&SMLColoursChanged];
[defaultsController addObserver:self forKeyPath:@"values.FragariaVariablesColourWell" options:NSKeyValueObservingOptionNew context:&SMLColoursChanged];
[defaultsController addObserver:self forKeyPath:@"values.FragariaStringsColourWell" options:NSKeyValueObservingOptionNew context:&SMLColoursChanged];
[defaultsController addObserver:self forKeyPath:@"values.FragariaAttributesColourWell" options:NSKeyValueObservingOptionNew context:&SMLColoursChanged];
[defaultsController addObserver:self forKeyPath:@"values.FragariaNumbersColourWell" options:NSKeyValueObservingOptionNew context:&SMLColoursChanged];
[defaultsController addObserver:self forKeyPath:@"values.FragariaColourCommands" options:NSKeyValueObservingOptionNew context:&SMLColoursChanged];
[defaultsController addObserver:self forKeyPath:@"values.FragariaColourComments" options:NSKeyValueObservingOptionNew context:&SMLColoursChanged];
[defaultsController addObserver:self forKeyPath:@"values.FragariaColourInstructions" options:NSKeyValueObservingOptionNew context:&SMLColoursChanged];
[defaultsController addObserver:self forKeyPath:@"values.FragariaColourKeywords" options:NSKeyValueObservingOptionNew context:&SMLColoursChanged];
[defaultsController addObserver:self forKeyPath:@"values.FragariaColourAutocomplete" options:NSKeyValueObservingOptionNew context:&SMLColoursChanged];
[defaultsController addObserver:self forKeyPath:@"values.FragariaColourVariables" options:NSKeyValueObservingOptionNew context:&SMLColoursChanged];
[defaultsController addObserver:self forKeyPath:@"values.FragariaColourStrings" options:NSKeyValueObservingOptionNew context:&SMLColoursChanged];
[defaultsController addObserver:self forKeyPath:@"values.FragariaColourAttributes" options:NSKeyValueObservingOptionNew context:&SMLColoursChanged];
[defaultsController addObserver:self forKeyPath:@"values.FragariaColourNumbers" options:NSKeyValueObservingOptionNew context:&SMLColoursChanged];
[defaultsController addObserver:self forKeyPath:@"values.FragariaColourMultiLineStrings" options:NSKeyValueObservingOptionNew context:&SMLColoursChanged];
[defaultsController addObserver:self forKeyPath:@"values.FragariaOnlyColourTillTheEndOfLine" options:NSKeyValueObservingOptionNew context:&SMLColoursChanged];
[defaultsController addObserver:self forKeyPath:@"values.FragariaHighlightCurrentLine" options:NSKeyValueObservingOptionNew context:&SMLColoursChanged];
[defaultsController addObserver:self forKeyPath:@"values.FragariaHighlightLineColourWell" options:NSKeyValueObservingOptionNew context:&SMLColoursChanged];
[defaultsController addObserver:self forKeyPath:@"values.FragariaColourMultiLineStrings" options:NSKeyValueObservingOptionNew context:SMLMultiLineChanged];
}
return self;
}
/*
- dealloc
*/
#pragma mark -
#pragma mark KVO
/*
- observeValueForKeyPath:ofObject:change:context:
*/
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if (context == &SMLColoursChanged) {
[self applyColourDefaults];
[self pageRecolour];
if ([[SMLDefaults valueForKey:MGSFragariaPrefsHighlightCurrentLine] boolValue] == YES) {
NSRange range = [[self completeString] lineRangeForRange:[[document valueForKey:ro_MGSFOTextView] selectedRange]];
[self highlightLineRange:range];
lastLineHighlightRange = range;
} else {
[self highlightLineRange:NSMakeRange(0, 0)];
}
} else if (context == &SMLMultiLineChanged) {
[self prepareRegularExpressions];
[self pageRecolour];
} else if (context== &SMLSyntaxDefinition) {
[self applySyntaxDefinition];
[self removeAllColours];
[self pageRecolour];
} else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
#pragma mark -
#pragma mark Syntax definition handling
/*
- applySyntaxDefinition
*/
- (void)applySyntaxDefinition
{
// parse
[self parseSyntaxDictionary:self.syntaxDictionary];
}
/*
- syntaxDictionary
*/
- (NSDictionary *)syntaxDictionary
{
NSString *definitionName = [document valueForKey:MGSFOSyntaxDefinitionName];
// if document has no syntax definition name then assign one
if (!definitionName) {
definitionName = [self assignSyntaxDefinition];
}
// get syntax dictionary
NSDictionary *syntaxDictionary = [[MGSSyntaxController sharedInstance] syntaxDictionaryWithName:definitionName];
return syntaxDictionary;
}
/*
- assignSyntaxDefinition
*/
- (NSString *)assignSyntaxDefinition
{
NSString *definitionName = [document valueForKey:MGSFOSyntaxDefinitionName];
if (definitionName) return definitionName;
NSString *documentExtension = [[document valueForKey:MGSFODocumentName] pathExtension];
NSString *lowercaseExtension = nil;
// If there is no extension try to guess definition from first line
if ([documentExtension isEqualToString:@""]) {
NSString *string = [[[document valueForKey:ro_MGSFOScrollView] documentView] string];
NSString *firstLine = [string substringWithRange:[string lineRangeForRange:NSMakeRange(0,0)]];
if ([firstLine hasPrefix:@"#!"] || [firstLine hasPrefix:@"%"] || [firstLine hasPrefix:@"<?"]) {
lowercaseExtension = [self guessSyntaxDefinitionExtensionFromFirstLine:firstLine];
}
} else {
lowercaseExtension = [documentExtension lowercaseString];
}
if (lowercaseExtension) {
definitionName = [[MGSSyntaxController sharedInstance] syntaxDefinitionNameWithExtension:lowercaseExtension];
}
if (!definitionName) {
definitionName = [MGSSyntaxController standardSyntaxDefinitionName];
}
// update document definition
[document setValue:definitionName forKey:MGSFOSyntaxDefinitionName];
return definitionName;
}
/*
- parseSyntaxDictionary
*/
- (void)parseSyntaxDictionary:(NSDictionary *)syntaxDictionary
{
NSMutableArray *keywordsAndAutocompleteWordsTemporary = [NSMutableArray array];
// If the plist file is malformed be sure to set the values to something
// syntax colouring
id value = [syntaxDictionary valueForKey:SMLSyntaxDefinitionAllowSyntaxColouring];
if (value) {
NSAssert([value isKindOfClass:[NSNumber class]], @"NSNumber expected");
self.syntaxDefinitionAllowsColouring = [value boolValue];
} else {
// default to YES
self.syntaxDefinitionAllowsColouring = YES;
}
// keywords
value = [syntaxDictionary valueForKey:SMLSyntaxDefinitionKeywords];
if (value) {
NSAssert([value isKindOfClass:[NSArray class]], @"NSArray expected");
self.keywords = [[NSSet alloc] initWithArray:value];
[keywordsAndAutocompleteWordsTemporary addObjectsFromArray:value];
}
// autocomplete words
value = [syntaxDictionary valueForKey:SMLSyntaxDefinitionAutocompleteWords];
if (value) {
NSAssert([value isKindOfClass:[NSArray class]], @"NSArray expected");
self.autocompleteWords = [[NSSet alloc] initWithArray:value];
[keywordsAndAutocompleteWordsTemporary addObjectsFromArray:value];
}
// colour autocomplete words is a preference
if ([[SMLDefaults valueForKey:MGSFragariaPrefsColourAutocomplete] boolValue] == YES) {
self.keywords = [NSSet setWithArray:keywordsAndAutocompleteWordsTemporary];
}
// keywords and autocomplete words
self.keywordsAndAutocompleteWords = [keywordsAndAutocompleteWordsTemporary sortedArrayUsingSelector:@selector(compare:)];
// recolour keywords
value = [syntaxDictionary valueForKey:SMLSyntaxDefinitionRecolourKeywordIfAlreadyColoured];
if (value) {
NSAssert([value isKindOfClass:[NSNumber class]], @"NSNumber expected");
recolourKeywordIfAlreadyColoured = [value boolValue];
}
// keywords case sensitive
value = [syntaxDictionary valueForKey:SMLSyntaxDefinitionKeywordsCaseSensitive];
if (value) {
NSAssert([value isKindOfClass:[NSNumber class]], @"NSNumber expected");
keywordsCaseSensitive = [value boolValue];
}
if (keywordsCaseSensitive == NO) {
NSMutableArray *lowerCaseKeywords = [[NSMutableArray alloc] init];
for (id item in keywords) {
[lowerCaseKeywords addObject:[item lowercaseString]];
}
NSSet *lowerCaseKeywordsSet = [[NSSet alloc] initWithArray:lowerCaseKeywords];
self.keywords = lowerCaseKeywordsSet;
}
// begin command
value = [syntaxDictionary valueForKey:SMLSyntaxDefinitionBeginCommand];
if (value) {
NSAssert([value isKindOfClass:[NSString class]], @"NSString expected");
self.beginCommand = value;
} else {
self.beginCommand = @"";
}
// end command
value = [syntaxDictionary valueForKey:SMLSyntaxDefinitionEndCommand];
if (value) {
NSAssert([value isKindOfClass:[NSString class]], @"NSString expected");
self.endCommand = value;
} else {
self.endCommand = @"";
}
// begin instruction
value = [syntaxDictionary valueForKey:SMLSyntaxDefinitionBeginInstruction];
if (value) {
NSAssert([value isKindOfClass:[NSString class]], @"NSString expected");
self.beginInstruction = value;
} else {
self.beginInstruction = @"";
}
// end instruction
value = [syntaxDictionary valueForKey:SMLSyntaxDefinitionEndInstruction];
if (value) {
NSAssert([value isKindOfClass:[NSString class]], @"NSString expected");
self.endInstruction = value;
} else {
self.endInstruction = @"";
}
// begin variable
value = [syntaxDictionary valueForKey:SMLSyntaxDefinitionBeginVariable];
if (value) {
NSAssert([value isKindOfClass:[NSString class]], @"NSString expected");
self.beginVariableCharacterSet = [NSCharacterSet characterSetWithCharactersInString:value];
} else {
self.beginVariableCharacterSet = [NSCharacterSet characterSetWithCharactersInString:@""];
}
// end variable
value = [syntaxDictionary valueForKey:SMLSyntaxDefinitionEndVariable];
if (value) {
NSAssert([value isKindOfClass:[NSString class]], @"NSString expected");
self.endVariableCharacterSet = [NSCharacterSet characterSetWithCharactersInString:value];
} else {
self.endVariableCharacterSet = [NSCharacterSet characterSetWithCharactersInString:@""];
}
// first string
value = [syntaxDictionary valueForKey:SMLSyntaxDefinitionFirstString];
if (value) {
NSAssert([value isKindOfClass:[NSString class]], @"NSString expected");
self.firstString = value;
if (![value isEqualToString:@""]) {
firstStringUnichar = [value characterAtIndex:0];
}
} else {
self.firstString = @"";
}
// second string
value = [syntaxDictionary valueForKey:SMLSyntaxDefinitionSecondString];
if (value) {
NSAssert([value isKindOfClass:[NSString class]], @"NSString expected");
self.secondString = value;
if (![value isEqualToString:@""]) {
secondStringUnichar = [value characterAtIndex:0];
}
} else {
self.secondString = @"";
}
// first single line comment
value = [syntaxDictionary valueForKey:SMLSyntaxDefinitionFirstSingleLineComment];
if (value) {
NSAssert([value isKindOfClass:[NSString class]], @"NSString expected");
self.firstSingleLineComment = value;
} else {
self.firstSingleLineComment = @"";
}
self.singleLineComments = [NSMutableArray arrayWithCapacity:2];
[self.singleLineComments addObject:firstSingleLineComment];
// second single line comment
value = [syntaxDictionary valueForKey:SMLSyntaxDefinitionSecondSingleLineComment];
if (value) {
NSAssert([value isKindOfClass:[NSString class]], @"NSString expected");
self.secondSingleLineComment = value;
} else {
self.secondSingleLineComment = @"";
}
[self.singleLineComments addObject:secondSingleLineComment];
// begin first multi line comment
value = [syntaxDictionary valueForKey:SMLSyntaxDefinitionBeginFirstMultiLineComment];
if (value) {
NSAssert([value isKindOfClass:[NSString class]], @"NSString expected");
self.beginFirstMultiLineComment = value;
} else {
self.beginFirstMultiLineComment = @"";
}
// end first multi line comment
value = [syntaxDictionary valueForKey:SMLSyntaxDefinitionEndFirstMultiLineComment];
if (value) {
NSAssert([value isKindOfClass:[NSString class]], @"NSString expected");
self.endFirstMultiLineComment = value;
} else {
self.endFirstMultiLineComment = @"";
}
self.multiLineComments = [NSMutableArray arrayWithCapacity:2];
[self.multiLineComments addObject:[NSArray arrayWithObjects:self.beginFirstMultiLineComment, self.endFirstMultiLineComment, nil]];
// begin second multi line comment
value = [syntaxDictionary valueForKey:SMLSyntaxDefinitionBeginSecondMultiLineComment];
if (value) {
NSAssert([value isKindOfClass:[NSString class]], @"NSString expected");
self.beginSecondMultiLineComment = value;
} else {
self.beginSecondMultiLineComment = @"";
}
// end second multi line comment
value = [syntaxDictionary valueForKey:SMLSyntaxDefinitionEndSecondMultiLineComment];
if (value) {
NSAssert([value isKindOfClass:[NSString class]], @"NSString expected");
self.endSecondMultiLineComment = value;
} else {
self.endSecondMultiLineComment = @"";
}
[self.multiLineComments addObject:[NSArray arrayWithObjects:self.beginSecondMultiLineComment, self.endSecondMultiLineComment, nil]];
// function definition
value = [syntaxDictionary valueForKey:SMLSyntaxDefinitionFunctionDefinition];
if (value) {
NSAssert([value isKindOfClass:[NSString class]], @"NSString expected");
self.functionDefinition = value;
} else {
self.functionDefinition = @"";
}
// remove from function
value = [syntaxDictionary valueForKey:SMLSyntaxDefinitionRemoveFromFunction];
if (value) {
NSAssert([value isKindOfClass:[NSString class]], @"NSString expected");
self.removeFromFunction = value;
} else {
self.removeFromFunction = @"";
}
// exclude characters from keyword start character set
value = [syntaxDictionary valueForKey:SMLSyntaxDefinitionExcludeFromKeywordStartCharacterSet];
if (value) {
NSAssert([value isKindOfClass:[NSString class]], @"NSString expected");
NSMutableCharacterSet *temporaryCharacterSet = [keywordStartCharacterSet mutableCopy];
[temporaryCharacterSet removeCharactersInString:value];
self.keywordStartCharacterSet = [temporaryCharacterSet copy];
}
// exclude characters from keyword end character set
value = [syntaxDictionary valueForKey:SMLSyntaxDefinitionExcludeFromKeywordEndCharacterSet];
if (value) {
NSAssert([value isKindOfClass:[NSString class]], @"NSString expected");
NSMutableCharacterSet *temporaryCharacterSet = [keywordEndCharacterSet mutableCopy];
[temporaryCharacterSet removeCharactersInString:value];
self.keywordEndCharacterSet = [temporaryCharacterSet copy];
}
// include characters in keyword start character set
value = [syntaxDictionary valueForKey:SMLSyntaxDefinitionIncludeInKeywordStartCharacterSet];
if (value) {
NSAssert([value isKindOfClass:[NSString class]], @"NSString expected");
NSMutableCharacterSet *temporaryCharacterSet = [keywordStartCharacterSet mutableCopy];
[temporaryCharacterSet addCharactersInString:value];
self.keywordStartCharacterSet = [temporaryCharacterSet copy];
}
// include characters in keyword end character set
value = [syntaxDictionary valueForKey:SMLSyntaxDefinitionIncludeInKeywordEndCharacterSet];
if (value) {
NSAssert([value isKindOfClass:[NSString class]], @"NSString expected");
NSMutableCharacterSet *temporaryCharacterSet = [keywordEndCharacterSet mutableCopy];
[temporaryCharacterSet addCharactersInString:value];
self.keywordEndCharacterSet = [temporaryCharacterSet copy];
}
[self prepareRegularExpressions];
}
/*
- guessSyntaxDefinitionExtensionFromFirstLine:
*/
- (NSString *)guessSyntaxDefinitionExtensionFromFirstLine:(NSString *)firstLine
{
NSString *returnString = nil;
NSRange firstLineRange = NSMakeRange(0, [firstLine length]);
if ([firstLine rangeOfString:@"perl" options:NSCaseInsensitiveSearch range:firstLineRange].location != NSNotFound) {
returnString = @"pl";
} else if ([firstLine rangeOfString:@"wish" options:NSCaseInsensitiveSearch range:firstLineRange].location != NSNotFound) {
returnString = @"tcl";
} else if ([firstLine rangeOfString:@"sh" options:NSCaseInsensitiveSearch range:firstLineRange].location != NSNotFound) {
returnString = @"sh";
} else if ([firstLine rangeOfString:@"php" options:NSCaseInsensitiveSearch range:firstLineRange].location != NSNotFound) {
returnString = @"php";
} else if ([firstLine rangeOfString:@"python" options:NSCaseInsensitiveSearch range:firstLineRange].location != NSNotFound) {
returnString = @"py";
} else if ([firstLine rangeOfString:@"awk" options:NSCaseInsensitiveSearch range:firstLineRange].location != NSNotFound) {
returnString = @"awk";
} else if ([firstLine rangeOfString:@"xml" options:NSCaseInsensitiveSearch range:firstLineRange].location != NSNotFound) {
returnString = @"xml";
} else if ([firstLine rangeOfString:@"ruby" options:NSCaseInsensitiveSearch range:firstLineRange].location != NSNotFound) {
returnString = @"rb";
} else if ([firstLine rangeOfString:@"%!ps" options:NSCaseInsensitiveSearch range:firstLineRange].location != NSNotFound) {
returnString = @"ps";
} else if ([firstLine rangeOfString:@"%pdf" options:NSCaseInsensitiveSearch range:firstLineRange].location != NSNotFound) {
returnString = @"pdf";
}
return returnString;
}
#pragma mark -
#pragma mark Regex handling
/*
- prepareRegularExpressions
*/
- (void)prepareRegularExpressions
{
if ([[SMLDefaults valueForKey:MGSFragariaPrefsColourMultiLineStrings] boolValue] == NO) {
firstStringPattern = [[ICUPattern alloc] initWithString:[NSString stringWithFormat:@"\\W%@[^%@\\\\\\r\\n]*+(?:\\\\(?:.|$)[^%@\\\\\\r\\n]*+)*+%@", self.firstString, self.firstString, self.firstString, self.firstString]];
secondStringPattern = [[ICUPattern alloc] initWithString:[NSString stringWithFormat:@"\\W%@[^%@\\\\\\r\\n]*+(?:\\\\(?:.|$)[^%@\\\\]*+)*+%@", self.secondString, self.secondString, self.secondString, self.secondString]];
} else {
firstStringPattern = [[ICUPattern alloc] initWithString:[NSString stringWithFormat:@"\\W%@[^%@\\\\]*+(?:\\\\(?:.|$)[^%@\\\\]*+)*+%@", self.firstString, self.firstString, self.firstString, self.firstString]];
secondStringPattern = [[ICUPattern alloc] initWithString:[NSString stringWithFormat:@"\\W%@[^%@\\\\]*+(?:\\\\(?:.|$)[^%@\\\\]*+)*+%@", self.secondString, self.secondString, self.secondString, self.secondString]];
}
}
#pragma mark -
#pragma mark Accessors
/*
- completeString
*/
- (NSString *)completeString
{
return [[document valueForKey:ro_MGSFOTextView] string];
}
#pragma mark -
#pragma mark Colouring
/*
- removeAllColours
*/
- (void)removeAllColours
{
NSRange wholeRange = NSMakeRange(0, [[self completeString] length]);
[firstLayoutManager removeTemporaryAttribute:NSForegroundColorAttributeName forCharacterRange:wholeRange];
}
/*
- removeColoursFromRange
*/
- (void)removeColoursFromRange:(NSRange)range
{
[firstLayoutManager removeTemporaryAttribute:NSForegroundColorAttributeName forCharacterRange:range];
}
/*
- pageRecolour
*/
- (void)pageRecolour
{
[self pageRecolourTextView:[document valueForKey:ro_MGSFOTextView]];
}
/*
- pageRecolourTextView:
*/
- (void)pageRecolourTextView:(SMLTextView *)textView
{
if (!self.isSyntaxColouringRequired) {
return;
}
if (textView == nil) {
return;
}
NSRect visibleRect = [[[textView enclosingScrollView] contentView] documentVisibleRect];
NSRange visibleRange = [[textView layoutManager] glyphRangeForBoundingRect:visibleRect inTextContainer:[textView textContainer]];
NSInteger beginningOfFirstVisibleLine = [[textView string] lineRangeForRange:NSMakeRange(visibleRange.location, 0)].location;
NSInteger endOfLastVisibleLine = NSMaxRange([[self completeString] lineRangeForRange:NSMakeRange(NSMaxRange(visibleRange), 0)]);
[self recolourRange:NSMakeRange(beginningOfFirstVisibleLine, endOfLastVisibleLine - beginningOfFirstVisibleLine)];
}
/*
- pageRecolourTextView:options:
*/
- (void)pageRecolourTextView:(SMLTextView *)textView options:(NSDictionary *)options
{
if (!textView) {
return;
}
if (!self.isSyntaxColouringRequired) {
return;
}
// colourAll option
NSNumber *colourAll = [options objectForKey:@"colourAll"];
if (!colourAll || ![colourAll boolValue]) {
[self pageRecolourTextView:textView];
return;
}
[self recolourRange:NSMakeRange(0, [[textView string] length])];
}
/*
- recolourRange:
*/
- (void)recolourRange:(NSRange)rangeToRecolour
{
if (reactToChanges == NO) {
return;
}
// establish behavior
BOOL shouldOnlyColourTillTheEndOfLine = [[SMLDefaults valueForKey:MGSFragariaPrefsOnlyColourTillTheEndOfLine] boolValue];
BOOL shouldColourMultiLineStrings = [[SMLDefaults valueForKey:MGSFragariaPrefsColourMultiLineStrings] boolValue];
// setup
NSString *documentString = [self completeString];
NSUInteger documentStringLength = [documentString length];
NSRange effectiveRange = rangeToRecolour;
NSRange rangeOfLine = NSMakeRange(0, 0);
NSRange foundRange = NSMakeRange(0, 0);
NSRange searchRange = NSMakeRange(0, 0);
NSUInteger searchSyntaxLength = 0;
NSUInteger colourStartLocation = 0, colourEndLocation = 0, endOfLine = 0;
NSUInteger colourLength = 0;
NSUInteger endLocationInMultiLine = 0;
NSUInteger beginLocationInMultiLine = 0;
NSUInteger queryLocation = 0;
unichar testCharacter = 0;
// trace
//NSLog(@"rangeToRecolor location %i length %i", rangeToRecolour.location, rangeToRecolour.length);
// adjust effective range
//
// When multiline strings are coloured we need to scan backwards to
// find where the string might have started if it's "above" the top of the screen.
//
if (shouldColourMultiLineStrings) {
NSInteger beginFirstStringInMultiLine = [documentString rangeOfString:self.firstString options:NSBackwardsSearch range:NSMakeRange(0, effectiveRange.location)].location;
if (beginFirstStringInMultiLine != NSNotFound && [[firstLayoutManager temporaryAttributesAtCharacterIndex:beginFirstStringInMultiLine effectiveRange:NULL] isEqualToDictionary:stringsColour]) {
NSInteger startOfLine = [documentString lineRangeForRange:NSMakeRange(beginFirstStringInMultiLine, 0)].location;
effectiveRange = NSMakeRange(startOfLine, rangeToRecolour.length + (rangeToRecolour.location - startOfLine));
}
}
// setup working locations based on the effective range
NSUInteger rangeLocation = effectiveRange.location;
NSUInteger maxRangeLocation = NSMaxRange(effectiveRange);
// assign range string
NSString *rangeString = [documentString substringWithRange:effectiveRange];
NSUInteger rangeStringLength = [rangeString length];
if (rangeStringLength == 0) {
return;
}
// allocate the range scanner
NSScanner *rangeScanner = [[NSScanner alloc] initWithString:rangeString];
[rangeScanner setCharactersToBeSkipped:nil];
// allocate the document scanner
NSScanner *documentScanner = [[NSScanner alloc] initWithString:documentString];
[documentScanner setCharactersToBeSkipped:nil];
// uncolour the range
[self removeColoursFromRange:effectiveRange];
// colouring delegate
id colouringDelegate = [document valueForKey:MGSFOSyntaxColouringDelegate];
BOOL delegateRespondsToShouldColourGroup = [colouringDelegate respondsToSelector:@selector(fragariaDocument:shouldColourGroupWithBlock:string:range:info:)];
BOOL delegateRespondsToDidColourGroup = [colouringDelegate respondsToSelector:@selector(fragariaDocument:didColourGroupWithBlock:string:range:info:)];
NSDictionary *delegateInfo = nil;
// define a block that the colour delegate can use to effect colouring
BOOL (^colourRangeBlock)(NSDictionary *, NSRange) = ^(NSDictionary *colourInfo, NSRange range) {
[self setColour:colourInfo range:range];
// at the moment we always succeed
return YES;
};
@try {
BOOL doColouring = YES;
//
// query delegate about colouring the document
//
if ([colouringDelegate respondsToSelector:@selector(fragariaDocument:shouldColourWithBlock:string:range:info:)]) {
// build minimal delegate info dictionary
delegateInfo = @{SMLSyntaxInfo : self.syntaxDictionary, SMLSyntaxWillColour : @(self.isSyntaxColouringRequired)};
// query delegate about colouring
doColouring = [colouringDelegate fragariaDocument:document shouldColourWithBlock:colourRangeBlock string:documentString range:rangeToRecolour info:delegateInfo ];
}
if (doColouring) {
//
// Numbers
//
doColouring = [[SMLDefaults valueForKey:MGSFragariaPrefsColourNumbers] boolValue];
// query delegate about colouring
if (delegateRespondsToShouldColourGroup) {
// build delegate info dictionary
delegateInfo = @{SMLSyntaxGroup : SMLSyntaxGroupNumber, SMLSyntaxGroupID : @(kSMLSyntaxGroupNumber), SMLSyntaxWillColour : @(doColouring), SMLSyntaxAttributes : numbersColour, SMLSyntaxInfo : self.syntaxDictionary};
// call the delegate
doColouring = [colouringDelegate fragariaDocument:document shouldColourGroupWithBlock:colourRangeBlock string:documentString range:rangeToRecolour info:delegateInfo ];
}
// do colouring
if (doColouring) {
// reset scanner
[rangeScanner mgs_setScanLocation:0];
// scan range to end
while (![rangeScanner isAtEnd]) {
// scan up to a number character
[rangeScanner scanUpToCharactersFromSet:self.numberCharacterSet intoString:NULL];
colourStartLocation = [rangeScanner scanLocation];
// scan to number end
[rangeScanner scanCharactersFromSet:self.numberCharacterSet intoString:NULL];
colourEndLocation = [rangeScanner scanLocation];
if (colourStartLocation == colourEndLocation) {
break;
}
// don't colour if preceding character is a letter.
// this prevents us from colouring numbers in variable names,
queryLocation = colourStartLocation + rangeLocation;
if (queryLocation > 0) {
testCharacter = [documentString characterAtIndex:queryLocation - 1];
// numbers can occur in variable, class and function names
// eg: var_1 should not be coloured as a number
if ([self.nameCharacterSet characterIsMember:testCharacter]) {
continue;
}
}
// TODO: handle constructs such as 1..5 which may occur within some loop constructs
// don't colour a trailing decimal point as some languages may use it as a line terminator
if (colourEndLocation > 0) {
queryLocation = colourEndLocation - 1;
testCharacter = [rangeString characterAtIndex:queryLocation];
if (testCharacter == self.decimalPointCharacter) {
colourEndLocation--;
}
}
[self setColour:numbersColour range:NSMakeRange(colourStartLocation + rangeLocation, colourEndLocation - colourStartLocation)];
}
// inform delegate that colouring is done
if (delegateRespondsToDidColourGroup) {
[colouringDelegate fragariaDocument:document didColourGroupWithBlock:colourRangeBlock string:documentString range:rangeToRecolour info:delegateInfo];
}
}
//
// Commands
//
doColouring = [[SMLDefaults valueForKey:MGSFragariaPrefsColourCommands] boolValue];
// query delegate about colouring
if (delegateRespondsToShouldColourGroup) {
// build delegate info dictionary
delegateInfo = @{SMLSyntaxGroup : SMLSyntaxGroupCommand, SMLSyntaxGroupID : @(kSMLSyntaxGroupCommand), SMLSyntaxWillColour : @(doColouring), SMLSyntaxAttributes : commandsColour, SMLSyntaxInfo : self.syntaxDictionary};
// call the delegate
doColouring = [colouringDelegate fragariaDocument:document shouldColourGroupWithBlock:colourRangeBlock string:documentString range:rangeToRecolour info:delegateInfo ];
}
if (doColouring && ![self.beginCommand isEqualToString:@""]) {
searchSyntaxLength = [self.endCommand length];
unichar beginCommandCharacter = [self.beginCommand characterAtIndex:0];
unichar endCommandCharacter = [self.endCommand characterAtIndex:0];
// reset scanner
[rangeScanner mgs_setScanLocation:0];
// scan range to end
while (![rangeScanner isAtEnd]) {
[rangeScanner scanUpToString:self.beginCommand intoString:nil];
colourStartLocation = [rangeScanner scanLocation];
endOfLine = NSMaxRange([rangeString lineRangeForRange:NSMakeRange(colourStartLocation, 0)]);
if (![rangeScanner scanUpToString:self.endCommand intoString:nil] || [rangeScanner scanLocation] >= endOfLine) {
[rangeScanner mgs_setScanLocation:endOfLine];
continue; // Don't colour it if it hasn't got a closing tag
} else {
// To avoid problems with strings like <yada <%=yada%> yada> we need to balance the number of begin- and end-tags
// If ever there's a beginCommand or endCommand with more than one character then do a check first
NSUInteger commandLocation = colourStartLocation + 1;
NSUInteger skipEndCommand = 0;
while (commandLocation < endOfLine) {
unichar commandCharacterTest = [rangeString characterAtIndex:commandLocation];
if (commandCharacterTest == endCommandCharacter) {
if (!skipEndCommand) {
break;