forked from KosmicTask/Fragaria
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SMLSyntaxColouring.m
1550 lines (1259 loc) · 59.5 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"
// class extension
@interface SMLSyntaxColouring()
- (void)parseSyntaxDictionary:(NSDictionary *)syntaxDictionary;
- (void)applySyntaxDefinition;
- (NSString *)assignSyntaxDefinition;
- (void)performDocumentDelegateSelector:(SEL)selector withObject:(id)object;
- (void)autocompleteWordsTimerSelector:(NSTimer *)theTimer;
- (void)liveUpdatePreviewTimerSelector:(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;
@end
@implementation SMLSyntaxColouring
@synthesize reactToChanges, functionDefinition, removeFromFunction, secondLayoutManager,
thirdLayoutManager, fourthLayoutManager, undoManager;
#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;
undoManager = [[NSUndoManager alloc] init];
// configure the document text view
NSTextView *textView = [document valueForKey:@"firstTextView"];
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
letterCharacterSet = [NSCharacterSet letterCharacterSet];
// keyword start character set
NSMutableCharacterSet *temporaryCharacterSet = [[NSCharacterSet letterCharacterSet] mutableCopy];
[temporaryCharacterSet addCharactersInString:@"_:@#"];
keywordStartCharacterSet = [temporaryCharacterSet copy];
// keyword end character set
temporaryCharacterSet = [[NSCharacterSet whitespaceAndNewlineCharacterSet] mutableCopy];
[temporaryCharacterSet formUnionWithCharacterSet:[NSCharacterSet symbolCharacterSet]];
[temporaryCharacterSet formUnionWithCharacterSet:[NSCharacterSet punctuationCharacterSet]];
[temporaryCharacterSet removeCharactersInString:@"_"];
keywordEndCharacterSet = [temporaryCharacterSet copy];
// attributes character set
temporaryCharacterSet = [[NSCharacterSet alphanumericCharacterSet] mutableCopy];
[temporaryCharacterSet addCharactersInString:@" -"]; // If there are two spaces before an attribute
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:@"syntaxDefinition"];
// add NSUserDefaultsController KVO observers
NSUserDefaultsController *defaultsController = [NSUserDefaultsController sharedUserDefaultsController];
[defaultsController addObserver:self forKeyPath:@"values.CommandsColourWell" options:NSKeyValueObservingOptionNew context:@"ColoursChanged"];
[defaultsController addObserver:self forKeyPath:@"values.CommentsColourWell" options:NSKeyValueObservingOptionNew context:@"ColoursChanged"];
[defaultsController addObserver:self forKeyPath:@"values.InstructionsColourWell" options:NSKeyValueObservingOptionNew context:@"ColoursChanged"];
[defaultsController addObserver:self forKeyPath:@"values.KeywordsColourWell" options:NSKeyValueObservingOptionNew context:@"ColoursChanged"];
[defaultsController addObserver:self forKeyPath:@"values.AutocompleteColourWell" options:NSKeyValueObservingOptionNew context:@"ColoursChanged"];
[defaultsController addObserver:self forKeyPath:@"values.VariablesColourWell" options:NSKeyValueObservingOptionNew context:@"ColoursChanged"];
[defaultsController addObserver:self forKeyPath:@"values.StringsColourWell" options:NSKeyValueObservingOptionNew context:@"ColoursChanged"];
[defaultsController addObserver:self forKeyPath:@"values.AttributesColourWell" options:NSKeyValueObservingOptionNew context:@"ColoursChanged"];
[defaultsController addObserver:self forKeyPath:@"values.ColourCommands" options:NSKeyValueObservingOptionNew context:@"ColoursChanged"];
[defaultsController addObserver:self forKeyPath:@"values.ColourComments" options:NSKeyValueObservingOptionNew context:@"ColoursChanged"];
[defaultsController addObserver:self forKeyPath:@"values.ColourInstructions" options:NSKeyValueObservingOptionNew context:@"ColoursChanged"];
[defaultsController addObserver:self forKeyPath:@"values.ColourKeywords" options:NSKeyValueObservingOptionNew context:@"ColoursChanged"];
[defaultsController addObserver:self forKeyPath:@"values.ColourAutocomplete" options:NSKeyValueObservingOptionNew context:@"ColoursChanged"];
[defaultsController addObserver:self forKeyPath:@"values.ColourVariables" options:NSKeyValueObservingOptionNew context:@"ColoursChanged"];
[defaultsController addObserver:self forKeyPath:@"values.ColourStrings" options:NSKeyValueObservingOptionNew context:@"ColoursChanged"];
[defaultsController addObserver:self forKeyPath:@"values.ColourAttributes" options:NSKeyValueObservingOptionNew context:@"ColoursChanged"];
[defaultsController addObserver:self forKeyPath:@"values.ColourMultiLineStrings" options:NSKeyValueObservingOptionNew context:@"ColoursChanged"];
[defaultsController addObserver:self forKeyPath:@"values.OnlyColourTillTheEndOfLine" options:NSKeyValueObservingOptionNew context:@"ColoursChanged"];
[defaultsController addObserver:self forKeyPath:@"values.HighlightCurrentLine" options:NSKeyValueObservingOptionNew context:@"ColoursChanged"];
[defaultsController addObserver:self forKeyPath:@"values.HighlightLineColourWell" options:NSKeyValueObservingOptionNew context:@"ColoursChanged"];
[defaultsController addObserver:self forKeyPath:@"values.ColourMultiLineStrings" options:NSKeyValueObservingOptionNew context:@"MultiLineChanged"];
}
return self;
}
#pragma mark -
#pragma mark KVO
/*
- observeValueForKeyPath:ofObject:change:context:
*/
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([(__bridge NSString *)context isEqualToString:@"ColoursChanged"]) {
[self applyColourDefaults];
[self pageRecolour];
if ([[SMLDefaults valueForKey:@"HighlightCurrentLine"] boolValue] == YES) {
NSRange range = [[self completeString] lineRangeForRange:[[document valueForKey:@"firstTextView"] selectedRange]];
[self highlightLineRange:range];
lastLineHighlightRange = range;
} else {
[self highlightLineRange:NSMakeRange(0, 0)];
}
} else if ([(__bridge NSString *)context isEqualToString:@"MultiLineChanged"]) {
[self prepareRegularExpressions];
[self pageRecolour];
} else if ([(__bridge NSString *)context isEqualToString:@"syntaxDefinition"]) {
[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
{
NSString *definitionName = [document valueForKey:@"syntaxDefinition"];
// if document has no syntax definition name then assign one
if (!definitionName) {
definitionName = [self assignSyntaxDefinition];
}
// get syntax dictionary
NSDictionary *syntaxDictionary = [[MGSSyntaxController sharedInstance] syntaxDictionaryWithName:definitionName];
// parse
[self parseSyntaxDictionary:syntaxDictionary];
}
/*
- assignSyntaxDefinition
*/
- (NSString *)assignSyntaxDefinition
{
NSString *definitionName = [document valueForKey:@"syntaxDefinition"];
if (definitionName) return definitionName;
NSString *defaultDefinitionName = [SMLDefaults valueForKey:@"SyntaxColouringPopUpString"];
NSString *documentExtension = [[document valueForKey:@"name"] pathExtension];
if ([[SMLDefaults valueForKey:@"SyntaxColouringMatrix"] integerValue] == 1) { // Always use...
definitionName = defaultDefinitionName;
} else {
NSString *lowercaseExtension = nil;
// If there is no extension try to guess definition from first line
if ([documentExtension isEqualToString:@""]) {
NSString *string = [[[document valueForKey:@"firstTextScrollView"] 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:@"syntaxDefinition"];
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
if ([syntaxDictionary valueForKey:@"keywords"]) {
keywords = [[NSSet alloc] initWithArray:[syntaxDictionary valueForKey:@"keywords"]];
[keywordsAndAutocompleteWordsTemporary addObjectsFromArray:[syntaxDictionary valueForKey:@"keywords"]];
}
if ([syntaxDictionary valueForKey:@"autocompleteWords"]) {
autocompleteWords = [[NSSet alloc] initWithArray:[syntaxDictionary valueForKey:@"autocompleteWords"]];
[keywordsAndAutocompleteWordsTemporary addObjectsFromArray:[syntaxDictionary valueForKey:@"autocompleteWords"]];
}
if ([[SMLDefaults valueForKey:@"ColourAutocompleteWordsAsKeywords"] boolValue] == YES) {
keywords = [NSSet setWithArray:keywordsAndAutocompleteWordsTemporary];
}
keywordsAndAutocompleteWords = [keywordsAndAutocompleteWordsTemporary sortedArrayUsingSelector:@selector(compare:)];
if ([syntaxDictionary valueForKey:@"recolourKeywordIfAlreadyColoured"]) {
recolourKeywordIfAlreadyColoured = [[syntaxDictionary valueForKey:@"recolourKeywordIfAlreadyColoured"] boolValue];
}
if ([syntaxDictionary valueForKey:@"keywordsCaseSensitive"]) {
keywordsCaseSensitive = [[syntaxDictionary valueForKey:@"keywordsCaseSensitive"] boolValue];
}
if (keywordsCaseSensitive == NO) {
NSMutableArray *lowerCaseKeywords = [[NSMutableArray alloc] init];
for (id item in keywords) {
[lowerCaseKeywords addObject:[item lowercaseString]];
}
NSSet *lowerCaseKeywordsSet = [[NSSet alloc] initWithArray:lowerCaseKeywords];
keywords = lowerCaseKeywordsSet;
}
if ([syntaxDictionary valueForKey:@"beginCommand"]) {
beginCommand = [syntaxDictionary valueForKey:@"beginCommand"];
} else {
beginCommand = @"";
}
if ([syntaxDictionary valueForKey:@"endCommand"]) {
endCommand = [syntaxDictionary valueForKey:@"endCommand"];
} else {
endCommand = @"";
}
if ([syntaxDictionary valueForKey:@"beginInstruction"]) {
beginInstruction = [syntaxDictionary valueForKey:@"beginInstruction"];
} else {
beginInstruction = @"";
}
if ([syntaxDictionary valueForKey:@"endInstruction"]) {
endInstruction = [syntaxDictionary valueForKey:@"endInstruction"];
} else {
endInstruction = @"";
}
if ([syntaxDictionary valueForKey:@"beginVariable"]) {
beginVariable = [NSCharacterSet characterSetWithCharactersInString:[syntaxDictionary valueForKey:@"beginVariable"]];
}
if ([syntaxDictionary valueForKey:@"endVariable"]) {
endVariable = [NSCharacterSet characterSetWithCharactersInString:[syntaxDictionary valueForKey:@"endVariable"]];
} else {
endVariable = [NSCharacterSet characterSetWithCharactersInString:@""];
}
if ([syntaxDictionary valueForKey:@"firstString"]) {
firstString = [syntaxDictionary valueForKey:@"firstString"];
if (![[syntaxDictionary valueForKey:@"firstString"] isEqualToString:@""]) {
firstStringUnichar = [[syntaxDictionary valueForKey:@"firstString"] characterAtIndex:0];
}
} else {
firstString = @"";
}
if ([syntaxDictionary valueForKey:@"secondString"]) {
secondString = [syntaxDictionary valueForKey:@"secondString"];
if (![[syntaxDictionary valueForKey:@"secondString"] isEqualToString:@""]) {
secondStringUnichar = [[syntaxDictionary valueForKey:@"secondString"] characterAtIndex:0];
}
} else {
secondString = @"";
}
// single line comment definitions
if ([syntaxDictionary valueForKey:@"firstSingleLineComment"]) {
firstSingleLineComment = [syntaxDictionary valueForKey:@"firstSingleLineComment"];
} else {
firstSingleLineComment = @"";
}
singleLineComments = [NSMutableArray arrayWithCapacity:2];
[singleLineComments addObject:firstSingleLineComment];
if ([syntaxDictionary valueForKey:@"secondSingleLineComment"]) {
secondSingleLineComment = [syntaxDictionary valueForKey:@"secondSingleLineComment"];
} else {
secondSingleLineComment = @"";
}
[singleLineComments addObject:secondSingleLineComment];
// multi line comment definitions
if ([syntaxDictionary valueForKey:@"beginFirstMultiLineComment"]) {
beginFirstMultiLineComment = [syntaxDictionary valueForKey:@"beginFirstMultiLineComment"];
} else {
beginFirstMultiLineComment = @"";
}
if ([syntaxDictionary valueForKey:@"endFirstMultiLineComment"]) {
endFirstMultiLineComment = [syntaxDictionary valueForKey:@"endFirstMultiLineComment"];
} else {
endFirstMultiLineComment = @"";
}
multiLineComments = [NSMutableArray arrayWithCapacity:2];
[multiLineComments addObject:[NSArray arrayWithObjects:beginFirstMultiLineComment, endFirstMultiLineComment, nil]];
if ([syntaxDictionary valueForKey:@"beginSecondMultiLineComment"]) {
beginSecondMultiLineComment = [syntaxDictionary valueForKey:@"beginSecondMultiLineComment"];
} else {
beginSecondMultiLineComment = @"";
}
if ([syntaxDictionary valueForKey:@"endSecondMultiLineComment"]) {
endSecondMultiLineComment = [syntaxDictionary valueForKey:@"endSecondMultiLineComment"];
} else {
endSecondMultiLineComment = @"";
}
[multiLineComments addObject:[NSArray arrayWithObjects:beginSecondMultiLineComment, endSecondMultiLineComment, nil]];
if ([syntaxDictionary valueForKey:@"functionDefinition"]) {
self.functionDefinition = [syntaxDictionary valueForKey:@"functionDefinition"];
} else {
self.functionDefinition = @"";
}
if ([syntaxDictionary valueForKey:@"removeFromFunction"]) {
self.removeFromFunction = [syntaxDictionary valueForKey:@"removeFromFunction"];
} else {
self.removeFromFunction = @"";
}
if ([syntaxDictionary valueForKey:@"excludeFromKeywordStartCharacterSet"]) {
NSMutableCharacterSet *temporaryCharacterSet = [keywordStartCharacterSet mutableCopy];
[temporaryCharacterSet removeCharactersInString:[syntaxDictionary valueForKey:@"excludeFromKeywordStartCharacterSet"]];
keywordStartCharacterSet = [temporaryCharacterSet copy];
}
if ([syntaxDictionary valueForKey:@"excludeFromKeywordEndCharacterSet"]) {
NSMutableCharacterSet *temporaryCharacterSet = [keywordEndCharacterSet mutableCopy];
[temporaryCharacterSet removeCharactersInString:[syntaxDictionary valueForKey:@"excludeFromKeywordEndCharacterSet"]];
keywordEndCharacterSet = [temporaryCharacterSet copy];
}
if ([syntaxDictionary valueForKey:@"includeInKeywordStartCharacterSet"]) {
NSMutableCharacterSet *temporaryCharacterSet = [keywordStartCharacterSet mutableCopy];
[temporaryCharacterSet addCharactersInString:[syntaxDictionary valueForKey:@"includeInKeywordStartCharacterSet"]];
keywordStartCharacterSet = [temporaryCharacterSet copy];
}
if ([syntaxDictionary valueForKey:@"includeInKeywordEndCharacterSet"]) {
NSMutableCharacterSet *temporaryCharacterSet = [keywordEndCharacterSet mutableCopy];
[temporaryCharacterSet addCharactersInString:[syntaxDictionary valueForKey:@"includeInKeywordEndCharacterSet"]];
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:@"ColourMultiLineStrings"] boolValue] == NO) {
firstStringPattern = [[ICUPattern alloc] initWithString:[NSString stringWithFormat:@"\\W%@[^%@\\\\\\r\\n]*+(?:\\\\(?:.|$)[^%@\\\\\\r\\n]*+)*+%@", firstString, firstString, firstString, firstString]];
secondStringPattern = [[ICUPattern alloc] initWithString:[NSString stringWithFormat:@"\\W%@[^%@\\\\\\r\\n]*+(?:\\\\(?:.|$)[^%@\\\\]*+)*+%@", secondString, secondString, secondString, secondString]];
} else {
firstStringPattern = [[ICUPattern alloc] initWithString:[NSString stringWithFormat:@"\\W%@[^%@\\\\]*+(?:\\\\(?:.|$)[^%@\\\\]*+)*+%@", firstString, firstString, firstString, firstString]];
secondStringPattern = [[ICUPattern alloc] initWithString:[NSString stringWithFormat:@"\\W%@[^%@\\\\]*+(?:\\\\(?:.|$)[^%@\\\\]*+)*+%@", secondString, secondString, secondString, secondString]];
}
}
#pragma mark -
#pragma mark Accessors
/*
- completeString
*/
- (NSString *)completeString
{
return [[document valueForKey:@"firstTextView"] string];
}
#pragma mark -
#pragma mark Colouring
/*
- removeAllColours
*/
- (void)removeAllColours
{
NSRange wholeRange = NSMakeRange(0, [[self completeString] length]);
[firstLayoutManager removeTemporaryAttribute:NSForegroundColorAttributeName forCharacterRange:wholeRange];
if (secondLayoutManager != nil) {
[secondLayoutManager removeTemporaryAttribute:NSForegroundColorAttributeName forCharacterRange:wholeRange];
}
if (thirdLayoutManager != nil) {
[thirdLayoutManager removeTemporaryAttribute:NSForegroundColorAttributeName forCharacterRange:wholeRange];
}
if (fourthLayoutManager != nil) {
[fourthLayoutManager removeTemporaryAttribute:NSForegroundColorAttributeName forCharacterRange:wholeRange];
}
}
/*
- removeColoursFromRange
*/
- (void)removeColoursFromRange:(NSRange)range
{
[firstLayoutManager removeTemporaryAttribute:NSForegroundColorAttributeName forCharacterRange:range];
if (secondLayoutManager != nil) {
[secondLayoutManager removeTemporaryAttribute:NSForegroundColorAttributeName forCharacterRange:range];
}
if (thirdLayoutManager != nil) {
[thirdLayoutManager removeTemporaryAttribute:NSForegroundColorAttributeName forCharacterRange:range];
}
if (fourthLayoutManager != nil) {
[fourthLayoutManager removeTemporaryAttribute:NSForegroundColorAttributeName forCharacterRange:range];
}
}
/*
- pageRecolour
*/
- (void)pageRecolour
{
[self pageRecolourTextView:[document valueForKey:@"firstTextView"]];
if (secondLayoutManager != nil) {
[self pageRecolourTextView:[document valueForKey:@"secondTextView"]];
}
if (thirdLayoutManager != nil) {
[self pageRecolourTextView:[document valueForKey:@"thirdTextView"]];
}
if (fourthLayoutManager != nil) {
[self pageRecolourTextView:[document valueForKey:@"fourthTextView"]];
}
}
/*
- pageRecolourTextView:
*/
- (void)pageRecolourTextView:(SMLTextView *)textView
{
if ([[document valueForKey:@"isSyntaxColoured"] boolValue] == NO) {
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 ([[document valueForKey:@"isSyntaxColoured"] boolValue] == NO) {
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)range
{
if (reactToChanges == NO) {
return;
}
BOOL shouldOnlyColourTillTheEndOfLine = [[SMLDefaults valueForKey:@"OnlyColourTillTheEndOfLine"] boolValue];
BOOL shouldColourMultiLineStrings = [[SMLDefaults valueForKey:@"ColourMultiLineStrings"] boolValue];
NSString *completeString = [self completeString];
NSRange effectiveRange = range;
NSRange rangeOfLine = NSMakeRange(0, 0);
NSRange foundRange = NSMakeRange(0, 0);
NSRange searchRange = NSMakeRange(0, 0);
NSUInteger searchSyntaxLength = 0;
NSUInteger beginning = 0, end = 0, endOfLine = 0, length = 0;
if (shouldColourMultiLineStrings) { // When multiline strings are coloured it needs to go backwards to find where the string might have started if it's "above" the top of the screen
NSInteger beginFirstStringInMultiLine = [completeString rangeOfString:firstString options:NSBackwardsSearch range:NSMakeRange(0, effectiveRange.location)].location;
if (beginFirstStringInMultiLine != NSNotFound && [[firstLayoutManager temporaryAttributesAtCharacterIndex:beginFirstStringInMultiLine effectiveRange:NULL] isEqualToDictionary:stringsColour]) {
NSInteger startOfLine = [completeString lineRangeForRange:NSMakeRange(beginFirstStringInMultiLine, 0)].location;
effectiveRange = NSMakeRange(startOfLine, range.length + (range.location - startOfLine));
}
}
NSUInteger rangeLocation = effectiveRange.location;
NSUInteger maxRange = NSMaxRange(effectiveRange);
searchString = [completeString substringWithRange:effectiveRange];
NSUInteger searchStringLength = [searchString length];
if (searchStringLength == 0) {
return;
}
NSScanner *scanner = [[NSScanner alloc] initWithString:searchString];
[scanner setCharactersToBeSkipped:nil];
NSScanner *completeDocumentScanner = [[NSScanner alloc] initWithString:completeString];
[completeDocumentScanner setCharactersToBeSkipped:nil];
NSUInteger completeStringLength = [completeString length];
NSUInteger endLocationInMultiLine = 0;
NSUInteger beginLocationInMultiLine = 0;
// uncolour the range
[self removeColoursFromRange:range];
@try {
//
// Commands
//
if (![beginCommand isEqualToString:@""] && [[SMLDefaults valueForKey:@"ColourCommands"] boolValue] == YES) {
searchSyntaxLength = [endCommand length];
unichar beginCommandCharacter = [beginCommand characterAtIndex:0];
unichar endCommandCharacter = [endCommand characterAtIndex:0];
while (![scanner isAtEnd]) {
[scanner scanUpToString:beginCommand intoString:nil];
beginning = [scanner scanLocation];
endOfLine = NSMaxRange([searchString lineRangeForRange:NSMakeRange(beginning, 0)]);
if (![scanner scanUpToString:endCommand intoString:nil] || [scanner scanLocation] >= endOfLine) {
[scanner 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 = beginning + 1;
NSUInteger skipEndCommand = 0;
while (commandLocation < endOfLine) {
unichar commandCharacterTest = [searchString characterAtIndex:commandLocation];
if (commandCharacterTest == endCommandCharacter) {
if (!skipEndCommand) {
break;
} else {
skipEndCommand--;
}
}
if (commandCharacterTest == beginCommandCharacter) {
skipEndCommand++;
}
commandLocation++;
}
if (commandLocation < endOfLine) {
[scanner mgs_setScanLocation:commandLocation + searchSyntaxLength];
} else {
[scanner mgs_setScanLocation:endOfLine];
}
}
[self setColour:commandsColour range:NSMakeRange(beginning + rangeLocation, [scanner scanLocation] - beginning)];
}
}
//
// Instructions
//
if (![beginInstruction isEqualToString:@""] && [[SMLDefaults valueForKey:@"ColourInstructions"] boolValue] == YES) {
// It takes too long to scan the whole document if it's large, so for instructions, first multi-line comment and second multi-line comment search backwards and begin at the start of the first beginInstruction etc. that it finds from the present position and, below, break the loop if it has passed the scanned range (i.e. after the end instruction)
beginLocationInMultiLine = [completeString rangeOfString:beginInstruction options:NSBackwardsSearch range:NSMakeRange(0, rangeLocation)].location;
endLocationInMultiLine = [completeString rangeOfString:endInstruction options:NSBackwardsSearch range:NSMakeRange(0, rangeLocation)].location;
if (beginLocationInMultiLine == NSNotFound || (endLocationInMultiLine != NSNotFound && beginLocationInMultiLine < endLocationInMultiLine)) {
beginLocationInMultiLine = rangeLocation;
}
searchSyntaxLength = [endInstruction length];
while (![completeDocumentScanner isAtEnd]) {
searchRange = NSMakeRange(beginLocationInMultiLine, range.length);
if (NSMaxRange(searchRange) > completeStringLength) {
searchRange = NSMakeRange(beginLocationInMultiLine, completeStringLength - beginLocationInMultiLine);
}
beginning = [completeString rangeOfString:beginInstruction options:NSLiteralSearch range:searchRange].location;
if (beginning == NSNotFound) {
break;
}
[completeDocumentScanner mgs_setScanLocation:beginning];
if (![completeDocumentScanner scanUpToString:endInstruction intoString:nil] || [completeDocumentScanner scanLocation] >= completeStringLength) {
if (shouldOnlyColourTillTheEndOfLine) {
[completeDocumentScanner mgs_setScanLocation:NSMaxRange([completeString lineRangeForRange:NSMakeRange(beginning, 0)])];
} else {
[completeDocumentScanner mgs_setScanLocation:completeStringLength];
}
} else {
if ([completeDocumentScanner scanLocation] + searchSyntaxLength <= completeStringLength) {
[completeDocumentScanner mgs_setScanLocation:[completeDocumentScanner scanLocation] + searchSyntaxLength];
}
}
[self setColour:instructionsColour range:NSMakeRange(beginning, [completeDocumentScanner scanLocation] - beginning)];
if ([completeDocumentScanner scanLocation] > maxRange) {
break;
}
beginLocationInMultiLine = [completeDocumentScanner scanLocation];
}
}
//
// Keywords
//
if ([keywords count] != 0 && [[SMLDefaults valueForKey:@"ColourKeywords"] boolValue] == YES) {
[scanner mgs_setScanLocation:0];
while (![scanner isAtEnd]) {
[scanner scanUpToCharactersFromSet:keywordStartCharacterSet intoString:nil];
beginning = [scanner scanLocation];
if ((beginning + 1) < searchStringLength) {
[scanner mgs_setScanLocation:(beginning + 1)];
}
[scanner scanUpToCharactersFromSet:keywordEndCharacterSet intoString:nil];
end = [scanner scanLocation];
if (end > searchStringLength || beginning == end) {
break;
}
NSString *keywordTestString = nil;
if (!keywordsCaseSensitive) {
keywordTestString = [[completeString substringWithRange:NSMakeRange(beginning + rangeLocation, end - beginning)] lowercaseString];
} else {
keywordTestString = [completeString substringWithRange:NSMakeRange(beginning + rangeLocation, end - beginning)];
}
if ([keywords containsObject:keywordTestString]) {
if (!recolourKeywordIfAlreadyColoured) {
if ([[firstLayoutManager temporaryAttributesAtCharacterIndex:beginning + rangeLocation effectiveRange:NULL] isEqualToDictionary:commandsColour]) {
continue;
}
}
[self setColour:keywordsColour range:NSMakeRange(beginning + rangeLocation, [scanner scanLocation] - beginning)];
}
}
}
//
// Autocomplete
//
if ([autocompleteWords count] != 0 && [[SMLDefaults valueForKey:@"ColourAutocomplete"] boolValue] == YES) {
[scanner mgs_setScanLocation:0];
while (![scanner isAtEnd]) {
[scanner scanUpToCharactersFromSet:keywordStartCharacterSet intoString:nil];
beginning = [scanner scanLocation];
if ((beginning + 1) < searchStringLength) {
[scanner mgs_setScanLocation:(beginning + 1)];
}
[scanner scanUpToCharactersFromSet:keywordEndCharacterSet intoString:nil];
end = [scanner scanLocation];
if (end > searchStringLength || beginning == end) {
break;
}
NSString *autocompleteTestString = nil;
if (!keywordsCaseSensitive) {
autocompleteTestString = [[completeString substringWithRange:NSMakeRange(beginning + rangeLocation, end - beginning)] lowercaseString];
} else {
autocompleteTestString = [completeString substringWithRange:NSMakeRange(beginning + rangeLocation, end - beginning)];
}
if ([autocompleteWords containsObject:autocompleteTestString]) {
if (!recolourKeywordIfAlreadyColoured) {
if ([[firstLayoutManager temporaryAttributesAtCharacterIndex:beginning + rangeLocation effectiveRange:NULL] isEqualToDictionary:commandsColour]) {
continue;
}
}
[self setColour:autocompleteWordsColour range:NSMakeRange(beginning + rangeLocation, [scanner scanLocation] - beginning)];
}
}
}
//
// Variables
//
if (beginVariable != nil && [[SMLDefaults valueForKey:@"ColourVariables"] boolValue] == YES) {
[scanner mgs_setScanLocation:0];
while (![scanner isAtEnd]) {
[scanner scanUpToCharactersFromSet:beginVariable intoString:nil];
beginning = [scanner scanLocation];
if (beginning + 1 < searchStringLength) {
if ([firstSingleLineComment isEqualToString:@"%"] && [searchString characterAtIndex:beginning + 1] == '%') { // To avoid a problem in LaTex with \%
if ([scanner scanLocation] < searchStringLength) {
[scanner mgs_setScanLocation:beginning + 1];
}
continue;
}
}
endOfLine = NSMaxRange([searchString lineRangeForRange:NSMakeRange(beginning, 0)]);
if (![scanner scanUpToCharactersFromSet:endVariable intoString:nil] || [scanner scanLocation] >= endOfLine) {
[scanner mgs_setScanLocation:endOfLine];
length = [scanner scanLocation] - beginning;
} else {
length = [scanner scanLocation] - beginning;
if ([scanner scanLocation] < searchStringLength) {
[scanner mgs_setScanLocation:[scanner scanLocation] + 1];
}
}
[self setColour:variablesColour range:NSMakeRange(beginning + rangeLocation, length)];
}
}
//
// Second string, first pass
//
if (![secondString isEqualToString:@""] && [[SMLDefaults valueForKey:@"ColourStrings"] boolValue] == YES) {
@try {
secondStringMatcher = [[ICUMatcher alloc] initWithPattern:secondStringPattern overString:searchString];
}
@catch (NSException *exception) {
return;
}
while ([secondStringMatcher findNext]) {
foundRange = [secondStringMatcher rangeOfMatch];
[self setColour:stringsColour range:NSMakeRange(foundRange.location + rangeLocation + 1, foundRange.length - 1)];
}
}
//
// First string
//
if (![firstString isEqualToString:@""] && [[SMLDefaults valueForKey:@"ColourStrings"] boolValue] == YES) {
@try {
firstStringMatcher = [[ICUMatcher alloc] initWithPattern:firstStringPattern overString:searchString];
}
@catch (NSException *exception) {
return;
}
while ([firstStringMatcher findNext]) {
foundRange = [firstStringMatcher rangeOfMatch];
if ([[firstLayoutManager temporaryAttributesAtCharacterIndex:foundRange.location + rangeLocation effectiveRange:NULL] isEqualToDictionary:stringsColour]) {
continue;
}
[self setColour:stringsColour range:NSMakeRange(foundRange.location + rangeLocation + 1, foundRange.length - 1)];
}
}
//
// Attributes
//
if ([[SMLDefaults valueForKey:@"ColourAttributes"] boolValue] == YES) {
[scanner mgs_setScanLocation:0];
while (![scanner isAtEnd]) {
[scanner scanUpToString:@" " intoString:nil];
beginning = [scanner scanLocation];
if (beginning + 1 < searchStringLength) {
[scanner mgs_setScanLocation:beginning + 1];
} else {
break;
}
if (![[firstLayoutManager temporaryAttributesAtCharacterIndex:(beginning + rangeLocation) effectiveRange:NULL] isEqualToDictionary:commandsColour]) {
continue;
}
[scanner scanCharactersFromSet:attributesCharacterSet intoString:nil];
end = [scanner scanLocation];
if (end + 1 < searchStringLength) {
[scanner mgs_setScanLocation:[scanner scanLocation] + 1];
}
if ([completeString characterAtIndex:end + rangeLocation] == '=') {
[self setColour:attributesColour range:NSMakeRange(beginning + rangeLocation, end - beginning)];
}
}
}
//
// Colour single-line comments
//
for (NSString *singleLineComment in singleLineComments) {
if (![singleLineComment isEqualToString:@""] && [[SMLDefaults valueForKey:@"ColourComments"] boolValue] == YES) {
// reset scanner
[scanner mgs_setScanLocation:0];
searchSyntaxLength = [singleLineComment length];
// scan
while (![scanner isAtEnd]) {
// scan for comment
[scanner scanUpToString:singleLineComment intoString:nil];
beginning = [scanner scanLocation];
// common case handling
if ([singleLineComment isEqualToString:@"//"]) {
if (beginning > 0 && [searchString characterAtIndex:beginning - 1] == ':') {
[scanner mgs_setScanLocation:beginning + 1];
continue; // To avoid http:// ftp:// file:// etc.
}
} else if ([singleLineComment isEqualToString:@"#"]) {
if (searchStringLength > 1) {
rangeOfLine = [searchString lineRangeForRange:NSMakeRange(beginning, 0)];
if ([searchString rangeOfString:@"#!" options:NSLiteralSearch range:rangeOfLine].location != NSNotFound) {
[scanner mgs_setScanLocation:NSMaxRange(rangeOfLine)];
continue; // Don't treat the line as a comment if it begins with #!
} else if (beginning > 0 && [searchString characterAtIndex:beginning - 1] == '$') {
[scanner mgs_setScanLocation:beginning + 1];
continue; // To avoid $#
} else if (beginning > 0 && [searchString characterAtIndex:beginning - 1] == '&') {
[scanner mgs_setScanLocation:beginning + 1];
continue; // To avoid &#
}
}
} else if ([singleLineComment isEqualToString:@"%"]) {
if (searchStringLength > 1) {
if (beginning > 0 && [searchString characterAtIndex:beginning - 1] == '\\') {
[scanner mgs_setScanLocation:beginning + 1];
continue; // To avoid \% in LaTex
}
}
}
// If the comment is within an already coloured string then disregard it
if (beginning + rangeLocation + searchSyntaxLength < completeStringLength) {
if ([[firstLayoutManager temporaryAttributesAtCharacterIndex:beginning + rangeLocation effectiveRange:NULL] isEqualToDictionary:stringsColour]) {
[scanner mgs_setScanLocation:beginning + 1];
continue;
}
}
// this is a single line comment so we can scan to the end of the line
endOfLine = NSMaxRange([searchString lineRangeForRange:NSMakeRange(beginning, 0)]);
[scanner mgs_setScanLocation:endOfLine];
// colour the comment
[self setColour:commentsColour range:NSMakeRange(beginning + rangeLocation, [scanner scanLocation] - beginning)];
}
}
}
//
// Multi-line comments
//
for (NSArray *multiLineComment in multiLineComments) {
NSString *beginMultiLineComment = [multiLineComment objectAtIndex:0];