-
Notifications
You must be signed in to change notification settings - Fork 14
/
UKSyntaxColoredTextViewController.m
1331 lines (1086 loc) · 45.4 KB
/
UKSyntaxColoredTextViewController.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
//
// UKSyntaxColoredTextViewController.m
// UKSyntaxColoredDocument
//
// Created by Uli Kusterer on 13.03.10.
// Copyright 2010 Uli Kusterer.
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
// -----------------------------------------------------------------------------
// Headers:
// -----------------------------------------------------------------------------
#import "UKSyntaxColoredTextViewController.h"
#import "NSArray+Color.h"
#import "NSScanner+SkipUpToCharset.h"
#import "UKHelperMacros.h"
// -----------------------------------------------------------------------------
// Globals:
// -----------------------------------------------------------------------------
static BOOL sSyntaxColoredTextDocPrefsInited = NO;
// -----------------------------------------------------------------------------
// Macros:
// -----------------------------------------------------------------------------
#define TEXTVIEW ((NSTextView*)[self view])
@implementation UKSyntaxColoredTextViewController
// -----------------------------------------------------------------------------
// makeSurePrefsAreInited
// Called by each view on creation to make sure we load the default colors
// and user-defined identifiers from SyntaxColorDefaults.plist.
// -----------------------------------------------------------------------------
+(void) makeSurePrefsAreInited
{
if( !sSyntaxColoredTextDocPrefsInited )
{
NSUserDefaults* prefs = [NSUserDefaults standardUserDefaults];
[prefs registerDefaults: [NSDictionary dictionaryWithContentsOfFile: [[NSBundle mainBundle] pathForResource: @"SyntaxColorDefaults" ofType: @"plist"]]];
sSyntaxColoredTextDocPrefsInited = YES;
}
}
// -----------------------------------------------------------------------------
// initWithNibName:bundle:
// Constructor that inits sourceCode member variable as a flag. It's
// storage for the text until the NIB's been loaded.
// -----------------------------------------------------------------------------
-(id) initWithNibName: (NSString*)inNibName bundle: (NSBundle*)inBundle
{
self = [super initWithNibName: inNibName bundle: inBundle];
if( self )
{
autoSyntaxColoring = YES;
maintainIndentation = YES;
syntaxColoringBusy = NO;
}
return self;
}
-(void) dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver: self];
[super dealloc];
}
-(void) setUpSyntaxColoring
{
// Set up some sensible defaults for syntax coloring:
[[self class] makeSurePrefsAreInited];
// Register for "text changed" notifications of our text storage:
[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(processEditing:)
name: NSTextStorageDidProcessEditingNotification
object: [TEXTVIEW textStorage]];
// Make sure text isn't wrapped:
[self turnOffWrapping];
// Do initial syntax coloring of our file:
[self recolorCompleteFile: nil];
// Text view selects at end of text, use something more sensible:
NSRange startSelRange = [self defaultSelectedRange];
[TEXTVIEW setSelectedRange: startSelRange];
[self textView: TEXTVIEW willChangeSelectionFromCharacterRange: startSelRange
toCharacterRange: startSelRange]; // Update UI to show selection.
// Make sure we can use "find" if we're on 10.3:
if( [TEXTVIEW respondsToSelector: @selector(setUsesFindPanel:)] )
[TEXTVIEW setUsesFindPanel: YES];
}
-(void) setDelegate: (id<UKSyntaxColoredTextViewDelegate>)inDelegate
{
delegate = inDelegate;
}
-(id) delegate
{
return delegate;
}
// -----------------------------------------------------------------------------
// setView:
// We've just been given a view! Apply initial syntax coloring.
// -----------------------------------------------------------------------------
-(void) setView: (NSView*)theView
{
[super setView: theView];
[(NSTextView*)theView setDelegate: self];
[self setUpSyntaxColoring]; // TODO: If someone calls this twice, we should only call part of this twice!
}
// -----------------------------------------------------------------------------
// processEditing:
// Part of the text was changed. Recolor it.
// -----------------------------------------------------------------------------
-(void) processEditing: (NSNotification*)notification
{
NSTextStorage *textStorage = [notification object];
NSRange range = [textStorage editedRange];
NSUInteger changeInLen = [textStorage changeInLength];
BOOL wasInUndoRedo = [[self undoManager] isUndoing] || [[self undoManager] isRedoing];
BOOL textLengthMayHaveChanged = NO;
// Was delete op or undo that could have changed text length?
if( wasInUndoRedo )
{
textLengthMayHaveChanged = YES;
range = [TEXTVIEW selectedRange];
}
if( changeInLen <= 0 )
textLengthMayHaveChanged = YES;
// Try to get chars around this to recolor any identifier we're in:
if( textLengthMayHaveChanged )
{
if( range.location > 0 )
range.location--;
if( (range.location +range.length +2) < [textStorage length] )
range.length += 2;
else if( (range.location +range.length +1) < [textStorage length] )
range.length += 1;
}
NSRange currRange = range;
// Perform the syntax coloring:
if( autoSyntaxColoring && range.length > 0 )
{
NSRange effectiveRange;
NSString* rangeMode;
rangeMode = [textStorage attribute: TD_SYNTAX_COLORING_MODE_ATTR
atIndex: currRange.location
effectiveRange: &effectiveRange];
NSUInteger x = range.location;
/* TODO: If we're in a multi-line comment and we're typing a comment-end
character, or we're in a string and we're typing a quote character,
this should include the rest of the text up to the next comment/string
end character in the recalc. */
// Scan up to prev line break:
while( x > 0 )
{
unichar theCh = [[textStorage string] characterAtIndex: x];
if( theCh == '\n' || theCh == '\r' )
break;
--x;
}
currRange.location = x;
// Scan up to next line break:
x = range.location +range.length;
while( x < [textStorage length] )
{
unichar theCh = [[textStorage string] characterAtIndex: x];
if( theCh == '\n' || theCh == '\r' )
break;
++x;
}
currRange.length = x -currRange.location;
// Open identifier, comment etc.? Make sure we include the whole range.
if( rangeMode != nil )
currRange = NSUnionRange( currRange, effectiveRange );
// Actually recolor the changed part:
[self recolorRange: currRange];
}
}
// -----------------------------------------------------------------------------
// toggleAutoSyntaxColoring:
// Action for menu item that toggles automatic syntax coloring on and off.
// -----------------------------------------------------------------------------
-(IBAction) toggleAutoSyntaxColoring: (id)sender
{
[self setAutoSyntaxColoring: ![self autoSyntaxColoring]];
[self recolorCompleteFile: nil];
}
// -----------------------------------------------------------------------------
// setAutoSyntaxColoring:
// Accessor to turn automatic syntax coloring on or off.
// -----------------------------------------------------------------------------
-(void) setAutoSyntaxColoring: (BOOL)state
{
autoSyntaxColoring = state;
}
// -----------------------------------------------------------------------------
// autoSyntaxColoring
// Accessor for determining whether automatic syntax coloring is on or off.
// -----------------------------------------------------------------------------
-(BOOL) autoSyntaxColoring
{
return autoSyntaxColoring;
}
// -----------------------------------------------------------------------------
// toggleMaintainIndentation:
// Action for menu item that toggles indentation maintaining on and off.
// -----------------------------------------------------------------------------
-(IBAction) toggleMaintainIndentation: (id)sender
{
[self setMaintainIndentation: ![self maintainIndentation]];
}
// -----------------------------------------------------------------------------
// setMaintainIndentation:
// Accessor to turn indentation maintaining on or off.
// -----------------------------------------------------------------------------
-(void) setMaintainIndentation: (BOOL)state
{
maintainIndentation = state;
}
// -----------------------------------------------------------------------------
// maintainIndentation
// Accessor for determining whether indentation maintaining is on or off.
// -----------------------------------------------------------------------------
-(BOOL) maintainIndentation
{
return maintainIndentation;
}
// -----------------------------------------------------------------------------
// goToLine:
// This selects the specified line of the document.
// -----------------------------------------------------------------------------
-(void) goToLine: (NSUInteger)lineNum
{
NSRange theRange = { 0, 0 };
NSString* vString = [TEXTVIEW string];
NSUInteger currLine = 1;
NSCharacterSet* vSet = [NSCharacterSet characterSetWithCharactersInString: @"\n\r"];
unsigned x;
unsigned lastBreakOffs = 0;
unichar lastBreakChar = 0;
for( x = 0; x < [vString length]; x++ )
{
unichar theCh = [vString characterAtIndex: x];
// Skip non-linebreak chars:
if( ![vSet characterIsMember: theCh] )
continue;
// If this is the LF in a CRLF sequence, only count it as one line break:
if( theCh == '\n' && lastBreakOffs == (x-1)
&& lastBreakChar == '\r' )
{
lastBreakOffs = 0;
lastBreakChar = 0;
theRange.location++;
continue;
}
// Calc range and increase line number:
theRange.length = x -theRange.location +1;
if( currLine >= lineNum )
break;
currLine++;
theRange.location = theRange.location +theRange.length;
lastBreakOffs = x;
lastBreakChar = theCh;
}
[TEXTVIEW scrollRangeToVisible: theRange];
[TEXTVIEW setSelectedRange: theRange];
}
// -----------------------------------------------------------------------------
// turnOffWrapping
// Makes the view so wide that text won't wrap anymore.
// -----------------------------------------------------------------------------
#define REALLY_LARGE_NUMBER 1.0e7 // FLT_MAX is too large and causes our rect to be shortened again.
-(void) turnOffWrapping
{
NSTextContainer* textContainer = [TEXTVIEW textContainer];
NSRect frame = { { 0, 0 }, { 0, 0 } };
NSScrollView* scrollView = [TEXTVIEW enclosingScrollView];
// Make sure we can see right edge of line:
[scrollView setHasHorizontalScroller: YES];
// Make text container so wide it won't wrap:
[textContainer setContainerSize: NSMakeSize(REALLY_LARGE_NUMBER, REALLY_LARGE_NUMBER)];
[textContainer setWidthTracksTextView: NO];
[textContainer setHeightTracksTextView: NO];
// Make sure text view is wide enough:
frame.origin = NSMakePoint( 0.0, 0.0 );
frame.size = [scrollView contentSize];
[TEXTVIEW setMaxSize: NSMakeSize(REALLY_LARGE_NUMBER, REALLY_LARGE_NUMBER)];
[TEXTVIEW setHorizontallyResizable: YES];
[TEXTVIEW setVerticallyResizable: YES];
[TEXTVIEW setAutoresizingMask: NSViewNotSizable];
}
// -----------------------------------------------------------------------------
// goToCharacter:
// This selects the specified character in the document.
// -----------------------------------------------------------------------------
-(void) goToCharacter: (NSUInteger)charNum
{
[self goToRangeFrom: charNum toChar: charNum +1];
}
// -----------------------------------------------------------------------------
// goToRangeFrom:toChar:
// Main bottleneck for selecting ranges in our file.
// -----------------------------------------------------------------------------
-(void) goToRangeFrom: (NSUInteger)startCh toChar: (NSUInteger)endCh
{
NSRange theRange = { 0, 0 };
theRange.location = startCh -1;
theRange.length = endCh -startCh;
if( startCh == 0 || startCh > [[TEXTVIEW string] length] )
return;
[TEXTVIEW scrollRangeToVisible: theRange];
[TEXTVIEW setSelectedRange: theRange];
}
// -----------------------------------------------------------------------------
// restoreText:
// Main bottleneck for our (very primitive and inefficient) undo
// implementation. This takes a copy of the previous state of the
// *entire text* and restores it.
// -----------------------------------------------------------------------------
-(void) restoreText: (NSString*)textToRestore
{
[[self undoManager] disableUndoRegistration];
[TEXTVIEW setString: textToRestore];
[[self undoManager] enableUndoRegistration];
}
// -----------------------------------------------------------------------------
// indentSelection:
// Indent the selected lines by one more level (i.e. one more tab).
// -----------------------------------------------------------------------------
-(IBAction) indentSelection: (id)sender
{
[[self undoManager] beginUndoGrouping];
NSString* prevText = [[[[TEXTVIEW textStorage] string] copy] autorelease];
[[self undoManager] registerUndoWithTarget: self selector: @selector(restoreText:) object: prevText];
NSRange selRange = [TEXTVIEW selectedRange],
nuSelRange = selRange;
NSUInteger x;
NSMutableString* str = [[TEXTVIEW textStorage] mutableString];
// Unselect any trailing returns so we don't indent the next line after a full-line selection.
if( selRange.length > 1 && ([str characterAtIndex: selRange.location +selRange.length -1] == '\n'
|| [str characterAtIndex: selRange.location +selRange.length -1] == '\r') )
selRange.length--;
for( x = selRange.location +selRange.length -1; x >= selRange.location; x-- )
{
if( [str characterAtIndex: x] == '\n'
|| [str characterAtIndex: x] == '\r' )
{
[str insertString: @"\t" atIndex: x+1];
nuSelRange.length++;
}
if( x == 0 )
break;
}
[str insertString: @"\t" atIndex: nuSelRange.location];
nuSelRange.length++;
[TEXTVIEW setSelectedRange: nuSelRange];
[[self undoManager] endUndoGrouping];
}
// -----------------------------------------------------------------------------
// unindentSelection:
// Un-indent the selected lines by one level (i.e. remove one tab from each
// line's start).
// -----------------------------------------------------------------------------
-(IBAction) unindentSelection: (id)sender
{
NSRange selRange = [TEXTVIEW selectedRange],
nuSelRange = selRange;
NSUInteger x, n;
NSUInteger lastIndex = selRange.location +selRange.length -1;
NSMutableString* str = [[TEXTVIEW textStorage] mutableString];
// Unselect any trailing returns so we don't indent the next line after a full-line selection.
if( selRange.length > 1 && ([str characterAtIndex: selRange.location +selRange.length -1] == '\n'
|| [str characterAtIndex: selRange.location +selRange.length -1] == '\r') )
selRange.length--;
if( selRange.length == 0 )
return;
[[self undoManager] beginUndoGrouping];
NSString* prevText = [[[[TEXTVIEW textStorage] string] copy] autorelease];
[[self undoManager] registerUndoWithTarget: self selector: @selector(restoreText:) object: prevText];
for( x = lastIndex; x >= selRange.location; x-- )
{
if( [str characterAtIndex: x] == '\n'
|| [str characterAtIndex: x] == '\r' )
{
if( (x +1) <= lastIndex)
{
if( [str characterAtIndex: x+1] == '\t' )
{
[str deleteCharactersInRange: NSMakeRange(x+1,1)];
nuSelRange.length--;
}
else
{
for( n = x+1; (n <= (x+4)) && (n <= lastIndex); n++ )
{
if( [str characterAtIndex: x+1] != ' ' )
break;
[str deleteCharactersInRange: NSMakeRange(x+1,1)];
nuSelRange.length--;
}
}
}
}
if( x == 0 )
break;
}
if( [str characterAtIndex: nuSelRange.location] == '\t' )
{
[str deleteCharactersInRange: NSMakeRange(nuSelRange.location,1)];
nuSelRange.length--;
}
else
{
for( n = 1; (n <= 4) && (n <= lastIndex); n++ )
{
if( [str characterAtIndex: nuSelRange.location] != ' ' )
break;
[str deleteCharactersInRange: NSMakeRange(nuSelRange.location,1)];
nuSelRange.length--;
}
}
[TEXTVIEW setSelectedRange: nuSelRange];
[[self undoManager] endUndoGrouping];
}
// -----------------------------------------------------------------------------
// toggleCommentForSelection:
// Add a comment to the start of this line/remove an existing comment.
// -----------------------------------------------------------------------------
-(IBAction) toggleCommentForSelection: (id)sender
{
NSRange selRange = [TEXTVIEW selectedRange];
NSUInteger x;
NSMutableString* str = [[TEXTVIEW textStorage] mutableString];
if( selRange.length == 0 )
selRange.length++;
// Are we at the end of a line?
if ([str characterAtIndex: selRange.location] == '\n' ||
[str characterAtIndex: selRange.location] == '\r')
{
if( selRange.location > 0 )
{
selRange.location--;
selRange.length++;
}
}
// Move the selection to the start of a line
while( selRange.location > 0 )
{
if( [str characterAtIndex: selRange.location] == '\n'
|| [str characterAtIndex: selRange.location] == '\r')
{
selRange.location++;
selRange.length--;
break;
}
selRange.location--;
selRange.length++;
}
// Select up to the end of a line
while ( (selRange.location +selRange.length) < [str length]
&& !([str characterAtIndex:selRange.location+selRange.length-1] == '\n'
|| [str characterAtIndex:selRange.location+selRange.length-1] == '\r') )
{
selRange.length++;
}
if (selRange.length == 0)
return;
[[self undoManager] beginUndoGrouping];
NSString* prevText = [[[[TEXTVIEW textStorage] string] copy] autorelease];
[[self undoManager] registerUndoWithTarget: self selector: @selector(restoreText:) object: prevText];
// Unselect any trailing returns so we don't comment the next line after a full-line selection.
while( ([str characterAtIndex: selRange.location +selRange.length -1] == '\n' ||
[str characterAtIndex: selRange.location +selRange.length -1] == '\r')
&& selRange.length > 0 )
{
selRange.length--;
}
NSRange nuSelRange = selRange;
NSString* commentPrefix = [[self syntaxDefinitionDictionary] objectForKey: @"OneLineCommentPrefix"];
if( !commentPrefix || [commentPrefix length] == 0 )
commentPrefix = @"# ";
NSUInteger commentPrefixLength = [commentPrefix length];
NSString* trimmedCommentPrefix = [commentPrefix stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]];
if( !trimmedCommentPrefix || [trimmedCommentPrefix length] == 0 ) // Comments apparently *are* whitespace.
trimmedCommentPrefix = commentPrefix;
NSUInteger trimmedCommentPrefixLength = [trimmedCommentPrefix length];
for( x = selRange.location +selRange.length -1; x >= selRange.location; x-- )
{
BOOL hitEnd = (x == selRange.location);
BOOL hitLineBreak = [str characterAtIndex: x] == '\n' || [str characterAtIndex: x] == '\r';
if( hitLineBreak || hitEnd )
{
NSUInteger startOffs = x+1;
if( hitEnd && !hitLineBreak )
startOffs = x;
NSUInteger possibleCommentLength = 0;
if( commentPrefixLength <= (selRange.length +selRange.location -startOffs) )
possibleCommentLength = commentPrefixLength;
else if( trimmedCommentPrefixLength <= (selRange.length +selRange.location -startOffs) )
possibleCommentLength = trimmedCommentPrefixLength;
NSString * lineStart = [str substringWithRange: NSMakeRange( startOffs, possibleCommentLength )];
BOOL haveWhitespaceToo = [lineStart hasPrefix: commentPrefix];
if( [lineStart hasPrefix: trimmedCommentPrefix] )
{
NSInteger commentLength = haveWhitespaceToo ? commentPrefixLength : trimmedCommentPrefixLength;
[str deleteCharactersInRange: NSMakeRange(startOffs, commentLength)];
nuSelRange.length -= commentLength;
}
else
{
[str insertString: commentPrefix atIndex: startOffs];
nuSelRange.length += commentPrefixLength;
}
}
if( x == 0 )
break;
}
[TEXTVIEW setSelectedRange: nuSelRange];
[[self undoManager] endUndoGrouping];
}
// -----------------------------------------------------------------------------
// validateMenuItem:
// Make sure check marks of the "Toggle auto syntax coloring" and "Maintain
// indentation" menu items are set up properly.
// -----------------------------------------------------------------------------
-(BOOL) validateMenuItem: (NSMenuItem*)menuItem
{
if( [menuItem action] == @selector(toggleAutoSyntaxColoring:) )
{
[menuItem setState: [self autoSyntaxColoring]];
return YES;
}
else if( [menuItem action] == @selector(toggleMaintainIndentation:) )
{
[menuItem setState: [self maintainIndentation]];
return YES;
}
else
return [super validateMenuItem: menuItem];
}
// -----------------------------------------------------------------------------
// recolorCompleteFile:
// IBAction to do a complete recolor of the whole friggin' document.
// This is called once after the document's been loaded and leaves some
// custom styles in the document which are used by recolorRange to properly
// perform recoloring of parts.
// -----------------------------------------------------------------------------
-(IBAction) recolorCompleteFile: (id)sender
{
NSRange range = NSMakeRange( 0, [[TEXTVIEW textStorage] length] );
[self recolorRange: range];
}
// -----------------------------------------------------------------------------
// recolorRange:
// Try to apply syntax coloring to the text in our text view. This
// overwrites any styles the text may have had before. This function
// guarantees that it'll preserve the selection.
//
// Note that the order in which the different things are colorized is
// important. E.g. identifiers go first, followed by comments, since that
// way colors are removed from identifiers inside a comment and replaced
// with the comment color, etc.
//
// The range passed in here is special, and may not include partial
// identifiers or the end of a comment. Make sure you include the entire
// multi-line comment etc. or it'll lose color.
// -----------------------------------------------------------------------------
-(void) recolorRange: (NSRange)range
{
if( syntaxColoringBusy ) // Prevent endless loop when recoloring's replacement of text causes processEditing to fire again.
return;
if( TEXTVIEW == nil || range.length == 0 ) // Don't like doing useless stuff.
return;
@try
{
syntaxColoringBusy = YES;
if( [delegate respondsToSelector: @selector(textViewControllerWillStartSyntaxRecoloring:)] )
[delegate textViewControllerWillStartSyntaxRecoloring: self];
// Kludge fix for case where we sometimes exceed text length:ra
NSInteger diff = [[TEXTVIEW textStorage] length] -(range.location +range.length);
if( diff < 0 )
range.length += diff;
// Get the text we'll be working with:
NSDictionary* vStyles = [self defaultTextAttributes];
NSMutableAttributedString* vString = [[NSMutableAttributedString alloc] initWithString: [[[TEXTVIEW textStorage] string] substringWithRange: range] attributes: vStyles];
[vString autorelease];
// Load colors and fonts to use from preferences:
// Load our dictionary which contains info on coloring this language:
NSDictionary* vSyntaxDefinition = [self syntaxDefinitionDictionary];
NSEnumerator* vComponentsEnny = [[vSyntaxDefinition objectForKey: @"Components"] objectEnumerator];
if( vComponentsEnny == nil ) // No list of components to colorize?
{
// @finally takes care of cleaning up syntaxColoringBusy etc. here.
return;
}
// Loop over all available components:
NSDictionary* vCurrComponent = nil;
NSUserDefaults* vPrefs = [NSUserDefaults standardUserDefaults];
while( (vCurrComponent = [vComponentsEnny nextObject]) )
{
NSString* vComponentType = [vCurrComponent objectForKey: @"Type"];
NSString* vComponentName = [vCurrComponent objectForKey: @"Name"];
NSString* vColorKeyName = [@"SyntaxColoring:Color:" stringByAppendingString: vComponentName];
NSColor* vColor = [[vPrefs arrayForKey: vColorKeyName] colorValue];
if( !vColor )
vColor = [[vCurrComponent objectForKey: @"Color"] colorValue];
if( [vComponentType isEqualToString: @"BlockComment"] )
{
[self colorCommentsFrom: [vCurrComponent objectForKey: @"Start"]
to: [vCurrComponent objectForKey: @"End"] inString: vString
withColor: vColor andMode: vComponentName];
}
else if( [vComponentType isEqualToString: @"OneLineComment"] )
{
[self colorOneLineComment: [vCurrComponent objectForKey: @"Start"]
inString: vString withColor: vColor andMode: vComponentName];
}
else if( [vComponentType isEqualToString: @"String"] )
{
[self colorStringsFrom: [vCurrComponent objectForKey: @"Start"]
to: [vCurrComponent objectForKey: @"End"]
inString: vString withColor: vColor andMode: vComponentName
andEscapeChar: [vCurrComponent objectForKey: @"EscapeChar"]];
}
else if( [vComponentType isEqualToString: @"Tag"] )
{
[self colorTagFrom: [vCurrComponent objectForKey: @"Start"]
to: [vCurrComponent objectForKey: @"End"] inString: vString
withColor: vColor andMode: vComponentName
exceptIfMode: [vCurrComponent objectForKey: @"IgnoredComponent"]];
}
else if( [vComponentType isEqualToString: @"Keywords"] )
{
NSArray* vIdents = [vCurrComponent objectForKey: @"Keywords"];
if( !vIdents && [delegate respondsToSelector: @selector(userIdentifiersForKeywordComponentName:)] )
vIdents = [delegate userIdentifiersForKeywordComponentName: vComponentName];
if( !vIdents )
vIdents = [[NSUserDefaults standardUserDefaults] objectForKey: [@"SyntaxColoring:Keywords:" stringByAppendingString: vComponentName]];
if( !vIdents && [vComponentName isEqualToString: @"UserIdentifiers"] )
vIdents = [[NSUserDefaults standardUserDefaults] objectForKey: TD_USER_DEFINED_IDENTIFIERS];
if( vIdents )
{
NSCharacterSet* vIdentCharset = nil;
NSString* vCurrIdent = nil;
NSString* vCsStr = [vCurrComponent objectForKey: @"Charset"];
if( vCsStr )
vIdentCharset = [NSCharacterSet characterSetWithCharactersInString: vCsStr];
NSEnumerator* vItty = [vIdents objectEnumerator];
while( vCurrIdent = [vItty nextObject] )
[self colorIdentifier: vCurrIdent inString: vString withColor: vColor
andMode: vComponentName charset: vIdentCharset];
}
}
}
// Replace the range with our recolored part:
[[TEXTVIEW textStorage] replaceCharactersInRange: range withAttributedString: vString];
[[TEXTVIEW textStorage] fixFontAttributeInRange: range]; // Make sure Japanese etc. fallback fonts get applied.
}
@finally
{
if( [delegate respondsToSelector: @selector(textViewControllerDidFinishSyntaxRecoloring:)] )
[delegate textViewControllerDidFinishSyntaxRecoloring: self];
syntaxColoringBusy = NO;
[self textView: TEXTVIEW willChangeSelectionFromCharacterRange: [TEXTVIEW selectedRange]
toCharacterRange: [TEXTVIEW selectedRange]];
}
}
// -----------------------------------------------------------------------------
// textView:willChangeSelectionFromCharacterRange:toCharacterRange:
// Delegate method called when our selection changes. Updates our status
// display to indicate which characters are selected.
// -----------------------------------------------------------------------------
-(NSRange) textView: (NSTextView*)theTextView willChangeSelectionFromCharacterRange: (NSRange)oldSelectedCharRange
toCharacterRange: (NSRange)newSelectedCharRange
{
NSUInteger startCh = newSelectedCharRange.location,
endCh = newSelectedCharRange.location +newSelectedCharRange.length;
NSUInteger lineNo = 0,
lastLineStart = 0,
x = 0;
NSUInteger startChLine = 0, endChLine = 0;
unichar lastBreakChar = 0;
NSUInteger lastBreakOffs = 0;
// Calc line number:
for( x = 0; (x < startCh) && (x < [[theTextView string] length]); x++ )
{
unichar theCh = [[theTextView string] characterAtIndex: x];
switch( theCh )
{
case '\n':
if( lastBreakOffs == (x-1) && lastBreakChar == '\r' ) // LF in CRLF sequence? Treat this as a single line break.
{
lastBreakOffs = 0;
lastBreakChar = 0;
continue;
}
// Else fall through!
case '\r':
lineNo++;
lastLineStart = x +1;
lastBreakOffs = x;
lastBreakChar = theCh;
break;
}
}
startChLine = (newSelectedCharRange.location -lastLineStart);
endChLine = (newSelectedCharRange.location -lastLineStart) +newSelectedCharRange.length;
// Let delegate know what to display:
if( [delegate respondsToSelector: @selector(selectionInTextViewController:changedToStartCharacter:endCharacter:inLine:startCharacterInDocument:endCharacterInDocument:)] )
[delegate selectionInTextViewController: self
changedToStartCharacter: startChLine endCharacter: endChLine
inLine: lineNo startCharacterInDocument: startCh
endCharacterInDocument: endCh];
return newSelectedCharRange;
}
-(BOOL) respondsToSelector: (SEL)aSelector
{
if( ![super respondsToSelector: aSelector] )
return [self.delegate respondsToSelector: aSelector];
else
return YES;
}
-(id) forwardingTargetForSelector: (SEL)aSelector
{
id newTarget = [super forwardingTargetForSelector: aSelector];
if( newTarget == nil )
return self.delegate;
return newTarget;
}
// -----------------------------------------------------------------------------
// syntaxDefinitionFilename
// Like nibName, this should return the name of the syntax
// definition file to use. Advanced users may use this to allow different
// coloring to take place depending on the file extension by returning
// different file names here.
//
// Note that the ".plist" extension is automatically appended to the file
// name.
//
// By default, this asks the delegate for a file name, and if that doesn't
// provide one, it returns "SyntaxDefinition".
// -----------------------------------------------------------------------------
-(NSString*) syntaxDefinitionFilename
{
NSString* syntaxDefFN = nil;
if( [delegate respondsToSelector: @selector(syntaxDefinitionFilenameForTextViewController:)] )
syntaxDefFN = [delegate syntaxDefinitionFilenameForTextViewController: self];
if( !syntaxDefFN )
syntaxDefFN = @"SyntaxDefinition";
return syntaxDefFN;
}
// -----------------------------------------------------------------------------
// syntaxDefinitionDictionary
// This returns the syntax definition dictionary to use, which indicates
// what ranges of text to colorize. Advanced users may use this to allow
// different coloring to take place depending on the file extension by
// returning different dictionaries here.
//
// By default, this asks the delegate for a syntax definition dictionary,
// or if that doesn't provide one, reads a dictionary from the .plist file
// in Resources indicated by -syntaxDefinitionFilename.
// -----------------------------------------------------------------------------
-(NSDictionary*) syntaxDefinitionDictionary
{
NSDictionary* theDict = nil;
if( [delegate respondsToSelector: @selector(syntaxDefinitionDictionaryForTextViewController:)] )
theDict = [delegate syntaxDefinitionDictionaryForTextViewController: self];
if( !theDict )
{
NSBundle* theBundle = [self nibBundle];
if( !theBundle )
theBundle = [NSBundle bundleForClass: [self class]]; // Usually the main bundle, but be nice to plugins.
theDict = [NSDictionary dictionaryWithContentsOfFile: [theBundle pathForResource: [self syntaxDefinitionFilename] ofType: @"plist"]];
}
return theDict;
}
// -----------------------------------------------------------------------------
// textAttributesForComponentName:color:
// Return the styles to use for the given mode/color. This calls upon the
// delegate to provide the styles, or if not, just set the color. This is
// also responsible for setting the TD_SYNTAX_COLORING_MODE_ATTR attribute
// so we can extend a range for partial recoloring to color the full block
// comment or whatever which is being changed (in case the user types a
// sequence that would end that block comment or similar).
// -----------------------------------------------------------------------------
-(NSDictionary*) textAttributesForComponentName: (NSString*)attr color: (NSColor*)col
{
NSDictionary* vLocalStyles = [delegate respondsToSelector:@selector(textAttributesForComponentName:color:)] ? [delegate textAttributesForComponentName: attr color: col] : nil;
NSMutableDictionary*vStyles = [[[self defaultTextAttributes] mutableCopy] autorelease];
if( vLocalStyles )
[vStyles addEntriesFromDictionary: vLocalStyles];
else
[vStyles setObject: col forKey: NSForegroundColorAttributeName];
// Make sure partial recoloring works:
[vStyles setObject: attr forKey: TD_SYNTAX_COLORING_MODE_ATTR];
return vStyles;
}
// -----------------------------------------------------------------------------
// colorStringsFrom:to:inString:withColor:andMode:andEscapeChar:
// Apply syntax coloring to all strings. This is basically the same code
// as used for multi-line comments, except that it ignores the end
// character if it is preceded by a backslash.
// -----------------------------------------------------------------------------
-(void) colorStringsFrom: (NSString*) startCh to: (NSString*) endCh inString: (NSMutableAttributedString*) s
withColor: (NSColor*) col andMode:(NSString*)attr andEscapeChar: (NSString*)vStringEscapeCharacter
{
NS_DURING
NSScanner* vScanner = [NSScanner scannerWithString: [s string]];