-
Notifications
You must be signed in to change notification settings - Fork 7
/
RScriptEditorTextView.m
1636 lines (1319 loc) · 55.9 KB
/
RScriptEditorTextView.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
/*
* R.app : a Cocoa front end to: "R A Computer Language for Statistical Data Analysis"
*
* R.app Copyright notes:
* Copyright (C) 2004-5 The R Foundation
* written by Stefano M. Iacus and Simon Urbanek
*
*
* R Copyright notes:
* Copyright (C) 1995-1996 Robert Gentleman and Ross Ihaka
* Copyright (C) 1998-2001 The R Development Core Team
* Copyright (C) 2002-2004 The R Foundation
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* A copy of the GNU General Public License is available via WWW at
* http://www.gnu.org/copyleft/gpl.html. You can also obtain it by
* writing to the Free Software Foundation, Inc., 59 Temple Place,
* Suite 330, Boston, MA 02111-1307 USA.
*
* RScriptEditorTextView.m
*
* Created by Hans-J. Bibiko on 15/02/2011.
*
*/
#import "RScriptEditorTextView.h"
#import "RScriptEditorTextStorage.h"
#import "RScriptEditorTypeSetter.h"
#import "RScriptEditorLayoutManager.h"
#import "RGUI.h"
#import "Tools/RTooltip.h"
#pragma mark -
#pragma mark flex init
/**
* Include all the extern variables and prototypes required for flex (used for syntax highlighting)
*/
#import "RScriptEditorTokens.h"
#import "RdScriptEditorTokens.h"
// R lexer
extern NSUInteger yylex();
extern NSUInteger yyuoffset, yyuleng;
typedef struct yy_buffer_state *YY_BUFFER_STATE;
void yy_switch_to_buffer(YY_BUFFER_STATE);
YY_BUFFER_STATE yy_scan_string (const char *);
// Rd lexer
extern NSUInteger rdlex();
typedef struct rd_buffer_state *RD_BUFFER_STATE;
void rd_switch_to_buffer(RD_BUFFER_STATE);
RD_BUFFER_STATE rd_scan_string (const char *);
static SEL _foldedSel;
#pragma mark -
#pragma mark attribute definition
#define kAPlinked @"Linked" // attribute for a via auto-pair inserted char
#define kAPval @"linked"
#define kLEXToken @"Quoted" // set via lex to indicate a quoted string
#define kLEXTokenValue @"isMarked"
#define kRkeyword @"s" // attribute for found R keywords
#define kQuote @"Quote"
#define kQuoteValue @"isQuoted"
#define kValue @"x"
#define kBTQuote @"BTQuote"
#define kBTQuoteValue @"isBTQuoted"
#pragma mark -
#define R_SYNTAX_HILITE_BIAS 2000
#define R_MAX_TEXT_SIZE_FOR_SYNTAX_HIGHLIGHTING 20000000
static inline const char* NSStringUTF8String(NSString* self)
{
typedef const char* (*SPUTF8StringMethodPtr)(NSString*, SEL);
static SPUTF8StringMethodPtr SPNSStringGetUTF8String;
if (!SPNSStringGetUTF8String) SPNSStringGetUTF8String = (SPUTF8StringMethodPtr)[NSString instanceMethodForSelector:@selector(UTF8String)];
const char* to_return = SPNSStringGetUTF8String(self, @selector(UTF8String));
return to_return;
}
static inline void NSMutableAttributedStringAddAttributeValueRange (NSMutableAttributedString* self, NSString* aStr, id aValue, NSRange aRange)
{
typedef void (*SPMutableAttributedStringAddAttributeValueRangeMethodPtr)(NSMutableAttributedString*, SEL, NSString*, id, NSRange);
static SPMutableAttributedStringAddAttributeValueRangeMethodPtr SPMutableAttributedStringAddAttributeValueRange;
if (!SPMutableAttributedStringAddAttributeValueRange) SPMutableAttributedStringAddAttributeValueRange = (SPMutableAttributedStringAddAttributeValueRangeMethodPtr)[self methodForSelector:@selector(addAttribute:value:range:)];
SPMutableAttributedStringAddAttributeValueRange(self, @selector(addAttribute:value:range:), aStr, aValue, aRange);
return;
}
static inline id NSMutableAttributedStringAttributeAtIndex (NSMutableAttributedString* self, NSString* aStr, NSUInteger index, NSRangePointer range)
{
typedef id (*SPMutableAttributedStringAttributeAtIndexMethodPtr)(NSMutableAttributedString*, SEL, NSString*, NSUInteger, NSRangePointer);
static SPMutableAttributedStringAttributeAtIndexMethodPtr SPMutableAttributedStringAttributeAtIndex;
if (!SPMutableAttributedStringAttributeAtIndex) SPMutableAttributedStringAttributeAtIndex = (SPMutableAttributedStringAttributeAtIndexMethodPtr)[self methodForSelector:@selector(attribute:atIndex:effectiveRange:)];
id r = SPMutableAttributedStringAttributeAtIndex(self, @selector(attribute:atIndex:effectiveRange:), aStr, index, range);
return r;
}
@implementation RScriptEditorTextView
- (void)awakeFromNib
{
// we are a subclass of RTextView which has its own awake and we must call it
[super awakeFromNib];
SLog(@"RScriptEditorTextView: awakeFromNib <%@>", self);
selfDelegate = (RDocumentWinCtrl*)[self delegate];
breakSyntaxHighlighting = 0;
_foldedSel = @selector(foldedAtIndex:);
// Bind scrollView programmatically - if done in RDocument.xib this'd lead to
// calling awakeFromNib twice
id scrView = (NSScrollView *)self.superview.superview;
if ([scrView isKindOfClass:[NSScrollView class]]) {
if(scrollView) [scrollView release];
scrollView = [scrView retain];
SLog(@"RScriptEditorTextView:awakeFromNib set scrollView");
}
prefs = [[NSUserDefaults standardUserDefaults] retain];
[[Preferences sharedPreferences] addDependent:self];
lineNumberingEnabled = [Preferences flagForKey:showLineNumbersKey withDefault:NO];
// Init textStorage and set self as delegate for the textView's textStorage to enable
// syntax highlighting, folding etc.
theTextStorage = [[RScriptEditorTextStorage alloc] initWithDelegate:self];
_foldedImp = [theTextStorage methodForSelector:_foldedSel];
// Make sure using foldingLayoutManager
if (![[self layoutManager] isKindOfClass:[RScriptEditorLayoutManager class]]) {
RScriptEditorLayoutManager *layoutManager = [[RScriptEditorLayoutManager alloc] init];
[[self textContainer] replaceLayoutManager:layoutManager];
[layoutManager release];
}
// disabled to get the current text range in textView safer
[[self layoutManager] setBackgroundLayoutEnabled:NO];
[[self layoutManager] replaceTextStorage:theTextStorage];
[(RScriptEditorTypeSetter*)[[self layoutManager] typesetter] setTextStorage:theTextStorage];
isSyntaxHighlighting = NO;
if([prefs objectForKey:highlightCurrentLine] == nil) [prefs setBool:YES forKey:highlightCurrentLine];
if([prefs objectForKey:indentNewLines] == nil) [prefs setBool:YES forKey:indentNewLines];
[self setFont:[Preferences unarchivedObjectForKey:RScriptEditorDefaultFont withDefault:[NSFont fontWithName:@"Monaco" size:11]]];
// Set defaults for general usage
braceHighlightInterval = [Preferences floatForKey:HighlightIntervalKey withDefault:0.3f];
argsHints = [Preferences flagForKey:prefShowArgsHints withDefault:YES];
lineWrappingEnabled = [Preferences flagForKey:enableLineWrappingKey withDefault:YES];
syntaxHighlightingEnabled = [Preferences flagForKey:showSyntaxColoringKey withDefault:YES];
deleteBackward = NO;
startListeningToBoundChanges = NO;
currentHighlight = -1;
// For now replaced selectedTextBackgroundColor by redColor
highlightColorAttr = [[NSDictionary alloc] initWithObjectsAndKeys:[NSColor redColor], NSBackgroundColorAttributeName, nil];
if([selfDelegate isRdDocument])
editorToolbar = [[RdEditorToolbar alloc] initWithEditor:selfDelegate];
else
editorToolbar = [[REditorToolbar alloc] initWithEditor:selfDelegate];
[self setAllowsDocumentBackgroundColorChange:YES];
[self setContinuousSpellCheckingEnabled:NO];
if(![Preferences flagForKey:enableLineWrappingKey withDefault: YES])
[scrollView setHasHorizontalScroller:YES];
if(!lineWrappingEnabled)
[self updateLineWrappingMode];
// Re-define tab stops for a better editing
[self setTabStops];
NSColor *c = [Preferences unarchivedObjectForKey:normalSyntaxColorKey withDefault:nil];
if (c) shColorNormal = c;
else shColorNormal=[NSColor colorWithDeviceRed:0.025 green:0.085 blue:0.600 alpha:1.0];
[shColorNormal retain];
c=[Preferences unarchivedObjectForKey:stringSyntaxColorKey withDefault:nil];
if (c) shColorString = c;
else shColorString=[NSColor colorWithDeviceRed:0.690 green:0.075 blue:0.000 alpha:1.0];
[shColorString retain];
c=[Preferences unarchivedObjectForKey:numberSyntaxColorKey withDefault:nil];
if (c) shColorNumber = c;
else shColorNumber=[NSColor colorWithDeviceRed:0.020 green:0.320 blue:0.095 alpha:1.0];
[shColorNumber retain];
c=[Preferences unarchivedObjectForKey:keywordSyntaxColorKey withDefault:nil];
if (c) shColorKeyword = c;
else shColorKeyword=[NSColor colorWithDeviceRed:0.765 green:0.535 blue:0.035 alpha:1.0];
[shColorKeyword retain];
c=[Preferences unarchivedObjectForKey:commentSyntaxColorKey withDefault:nil];
if (c) shColorComment = c;
else shColorComment=[NSColor colorWithDeviceRed:0.312 green:0.309 blue:0.309 alpha:1.0];
[shColorComment retain];
c=[Preferences unarchivedObjectForKey:identifierSyntaxColorKey withDefault:nil];
if (c) shColorIdentifier = c;
else shColorIdentifier=[NSColor colorWithDeviceRed:0.0 green:0.0 blue:0.0 alpha:1.0];
[shColorIdentifier retain];
c=[Preferences unarchivedObjectForKey:editorSelectionBackgroundColorKey withDefault:nil];
if (!c) c=[NSColor colorWithDeviceRed:0.71f green:0.835f blue:1.0f alpha:1.0f];
NSMutableDictionary *attr = [NSMutableDictionary dictionary];
[attr setDictionary:[self selectedTextAttributes]];
[attr setObject:c forKey:NSBackgroundColorAttributeName];
[self setSelectedTextAttributes:attr];
// Rd stuff
// c=[Preferences unarchivedObjectForKey:sectionRdSyntaxColorKey withDefault:nil];
// if (c) rdColorSection = c;
// else rdColorSection=[NSColor colorWithDeviceRed:0.8 green:0.0353 blue:0.02 alpha:1.0];
// [rdColorSection retain];
//
// c=[Preferences unarchivedObjectForKey:macroArgRdSyntaxColorKey withDefault:nil];
// if (c) rdColorMacroArg = c;
// else rdColorMacroArg=[NSColor colorWithDeviceRed:0.0 green:0.0 blue:0.98 alpha:1.0];
// [rdColorMacroArg retain];
//
// c=[Preferences unarchivedObjectForKey:macroGenRdSyntaxColorKey withDefault:nil];
// if (c) rdColorMacroGen = c;
// else rdColorMacroGen=[NSColor colorWithDeviceRed:0.4 green:0.78 blue:0.98 alpha:1.0];
// [rdColorMacroGen retain];
//
// c=[Preferences unarchivedObjectForKey:directiveRdSyntaxColorKey withDefault:nil];
// if (c) rdColorDirective = c;
// else rdColorDirective=[NSColor colorWithDeviceRed:0.0 green:0.785 blue:0.0 alpha:1.0];
// [rdColorDirective retain];
// c=[Preferences unarchivedObjectForKey:commentRdSyntaxColorKey withDefault:nil];
// if (c) rdColorComment = c;
// else rdColorComment=[NSColor colorWithDeviceRed:0.1 green:0.55 blue:0.05 alpha:1.0];
// [rdColorComment retain];
// c=[Preferences unarchivedObjectForKey:normalRdSyntaxColorKey withDefault:nil];
// if (c) rdColorNormal = c;
// else rdColorNormal=[NSColor colorWithDeviceRed:0.0 green:0.0 blue:0.0 alpha:1.0];
// [rdColorNormal retain];
c=[Preferences unarchivedObjectForKey:editorBackgroundColorKey withDefault:nil];
if (c) shColorBackground = c;
else shColorBackground=[NSColor colorWithDeviceRed:1.0 green:1.0 blue:1.0 alpha:1.0];
[shColorBackground retain];
c=[Preferences unarchivedObjectForKey:editorCurrentLineBackgroundColorKey withDefault:nil];
if (c) shColorCurrentLine = c;
else shColorCurrentLine=[NSColor colorWithDeviceRed:0.9 green:0.9 blue:0.9 alpha:0.8];
[shColorCurrentLine retain];
c=[Preferences unarchivedObjectForKey:editorCursorColorKey withDefault:nil];
if (c) shColorCursor = c;
else shColorCursor=[NSColor blackColor];
[shColorCursor retain];
[self setInsertionPointColor:shColorCursor];
// Register observers for the when editor background colors preference changes
[prefs addObserver:self forKeyPath:normalSyntaxColorKey options:NSKeyValueObservingOptionNew context:NULL];
[prefs addObserver:self forKeyPath:stringSyntaxColorKey options:NSKeyValueObservingOptionNew context:NULL];
[prefs addObserver:self forKeyPath:numberSyntaxColorKey options:NSKeyValueObservingOptionNew context:NULL];
[prefs addObserver:self forKeyPath:keywordSyntaxColorKey options:NSKeyValueObservingOptionNew context:NULL];
[prefs addObserver:self forKeyPath:commentSyntaxColorKey options:NSKeyValueObservingOptionNew context:NULL];
// [prefs addObserver:self forKeyPath:normalRdSyntaxColorKey options:NSKeyValueObservingOptionNew context:NULL];
// [prefs addObserver:self forKeyPath:commentRdSyntaxColorKey options:NSKeyValueObservingOptionNew context:NULL];
// [prefs addObserver:self forKeyPath:sectionRdSyntaxColorKey options:NSKeyValueObservingOptionNew context:NULL];
// [prefs addObserver:self forKeyPath:macroArgRdSyntaxColorKey options:NSKeyValueObservingOptionNew context:NULL];
// [prefs addObserver:self forKeyPath:macroGenRdSyntaxColorKey options:NSKeyValueObservingOptionNew context:NULL];
// [prefs addObserver:self forKeyPath:directiveRdSyntaxColorKey options:NSKeyValueObservingOptionNew context:NULL];
[prefs addObserver:self forKeyPath:editorBackgroundColorKey options:NSKeyValueObservingOptionNew context:NULL];
[prefs addObserver:self forKeyPath:editorCurrentLineBackgroundColorKey options:NSKeyValueObservingOptionNew context:NULL];
[prefs addObserver:self forKeyPath:identifierSyntaxColorKey options:NSKeyValueObservingOptionNew context:NULL];
[prefs addObserver:self forKeyPath:editorCursorColorKey options:NSKeyValueObservingOptionNew context:NULL];
[prefs addObserver:self forKeyPath:showSyntaxColoringKey options:NSKeyValueObservingOptionNew context:NULL];
[prefs addObserver:self forKeyPath:prefShowArgsHints options:NSKeyValueObservingOptionNew context:NULL];
[prefs addObserver:self forKeyPath:enableLineWrappingKey options:NSKeyValueObservingOptionNew context:NULL];
[prefs addObserver:self forKeyPath:RScriptEditorDefaultFont options:NSKeyValueObservingOptionNew context:NULL];
[prefs addObserver:self forKeyPath:HighlightIntervalKey options:NSKeyValueObservingOptionNew context:NULL];
[prefs addObserver:self forKeyPath:highlightCurrentLine options:NSKeyValueObservingOptionNew context:NULL];
[prefs addObserver:self forKeyPath:showLineNumbersKey options:NSKeyValueObservingOptionNew context:NULL];
[prefs addObserver:self forKeyPath:editorSelectionBackgroundColorKey options:NSKeyValueObservingOptionNew context:NULL];
if(syntaxHighlightingEnabled) {
[self setTextColor:shColorNormal];
[self setInsertionPointColor:shColorCursor];
} else {
[self setTextColor:shColorNormal];
[self setInsertionPointColor:shColorCursor];
}
#if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
[[self layoutManager] setAllowsNonContiguousLayout:YES];
#endif
// add NSViewBoundsDidChangeNotification to scrollView
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(boundsDidChangeNotification:) name:NSViewBoundsDidChangeNotification object:[scrollView contentView]];
}
- (void)dealloc {
SLog(@"RScriptEditorTextView: dealloc <%@>", self);
[theTextStorage release];
if(scrollView) [scrollView release];
if(editorToolbar) [editorToolbar release];
if(highlightColorAttr) [highlightColorAttr release];
if(shColorNormal) [shColorNormal release];
if(shColorString) [shColorString release];
if(shColorNumber) [shColorNumber release];
if(shColorKeyword) [shColorKeyword release];
if(shColorComment) [shColorComment release];
if(shColorIdentifier) [shColorIdentifier release];
if(shColorBackground) [shColorBackground release];
if(shColorCurrentLine) [shColorCurrentLine release];
if(shColorCursor) [shColorCursor release];
// if(rdColorNormal) [rdColorNormal release];
// if(rdColorComment) [rdColorComment release];
// if(rdColorSection) [rdColorSection release];
// if(rdColorMacroArg) [rdColorMacroArg release];
// if(rdColorMacroGen) [rdColorMacroGen release];
// if(rdColorDirective) [rdColorDirective release];
[[NSNotificationCenter defaultCenter] removeObserver:self];
[[Preferences sharedPreferences] removeDependent:self];
if(prefs) [prefs release];
[super dealloc];
}
- (id)scrollView
{
return scrollView;
}
- (void)setNonSyntaxHighlighting
{
[theTextStorage removeAttribute:NSForegroundColorAttributeName range:NSMakeRange(0, [[theTextStorage string] length])];
[theTextStorage removeAttribute:NSBackgroundColorAttributeName range:NSMakeRange(0, [[theTextStorage string] length])];
[self setTextColor:shColorNormal];
[self setInsertionPointColor:shColorCursor];
[self setNeedsDisplayInRect:[self visibleRect]];
}
/**
* This method is called as part of Key Value Observing which is used to watch for prefernce changes which effect the interface.
*/
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([keyPath isEqualToString:normalSyntaxColorKey]) {
if(shColorNormal) [shColorNormal release];
shColorNormal = [[NSUnarchiver unarchiveObjectWithData:[change objectForKey:NSKeyValueChangeNewKey]] retain];
if([self isEditable])
[self performSelector:@selector(doSyntaxHighlighting) withObject:nil afterDelay:0.1];
} else if ([keyPath isEqualToString:stringSyntaxColorKey]) {
if(shColorString) [shColorString release];
shColorString = [[NSUnarchiver unarchiveObjectWithData:[change objectForKey:NSKeyValueChangeNewKey]] retain];
if([self isEditable])
[self performSelector:@selector(doSyntaxHighlighting) withObject:nil afterDelay:0.1];
} else if ([keyPath isEqualToString:numberSyntaxColorKey]) {
if(shColorNumber) [shColorNumber release];
shColorNumber = [[NSUnarchiver unarchiveObjectWithData:[change objectForKey:NSKeyValueChangeNewKey]] retain];
if([self isEditable])
[self performSelector:@selector(doSyntaxHighlighting) withObject:nil afterDelay:0.1];
} else if ([keyPath isEqualToString:keywordSyntaxColorKey]) {
if(shColorKeyword) [shColorKeyword release];
shColorKeyword = [[NSUnarchiver unarchiveObjectWithData:[change objectForKey:NSKeyValueChangeNewKey]] retain];
if([self isEditable])
[self performSelector:@selector(doSyntaxHighlighting) withObject:nil afterDelay:0.1];
} else if ([keyPath isEqualToString:commentSyntaxColorKey]) {
if(shColorComment) [shColorComment release];
shColorComment = [[NSUnarchiver unarchiveObjectWithData:[change objectForKey:NSKeyValueChangeNewKey]] retain];
if([self isEditable])
[self performSelector:@selector(doSyntaxHighlighting) withObject:nil afterDelay:0.1];
} else if ([keyPath isEqualToString:identifierSyntaxColorKey]) {
if(shColorIdentifier) [shColorIdentifier release];
shColorIdentifier = [[NSUnarchiver unarchiveObjectWithData:[change objectForKey:NSKeyValueChangeNewKey]] retain];
if([self isEditable])
[self performSelector:@selector(doSyntaxHighlighting) withObject:nil afterDelay:0.1];
// } else if ([keyPath isEqualToString:sectionRdSyntaxColorKey]) {
// if(rdColorSection) [rdColorSection release];
// rdColorSection = [[NSUnarchiver unarchiveObjectWithData:[change objectForKey:NSKeyValueChangeNewKey]] retain];
// if([self isEditable])
// [self performSelector:@selector(doSyntaxHighlighting) withObject:nil afterDelay:0.1];
// } else if ([keyPath isEqualToString:macroArgRdSyntaxColorKey]) {
// if(rdColorMacroArg) [rdColorMacroArg release];
// rdColorMacroArg = [[NSUnarchiver unarchiveObjectWithData:[change objectForKey:NSKeyValueChangeNewKey]] retain];
// if([self isEditable])
// [self performSelector:@selector(doSyntaxHighlighting) withObject:nil afterDelay:0.1];
// } else if ([keyPath isEqualToString:macroGenRdSyntaxColorKey]) {
// if(rdColorMacroGen) [rdColorMacroGen release];
// rdColorMacroGen = [[NSUnarchiver unarchiveObjectWithData:[change objectForKey:NSKeyValueChangeNewKey]] retain];
// if([self isEditable])
// [self performSelector:@selector(doSyntaxHighlighting) withObject:nil afterDelay:0.1];
// } else if ([keyPath isEqualToString:directiveRdSyntaxColorKey]) {
// if(rdColorDirective) [rdColorDirective release];
// rdColorDirective = [[NSUnarchiver unarchiveObjectWithData:[change objectForKey:NSKeyValueChangeNewKey]] retain];
// if([self isEditable])
// [self performSelector:@selector(doSyntaxHighlighting) withObject:nil afterDelay:0.1];
} else if ([keyPath isEqualToString:editorCursorColorKey]) {
if(shColorCursor) [shColorCursor release];
shColorCursor = [[NSUnarchiver unarchiveObjectWithData:[change objectForKey:NSKeyValueChangeNewKey]] retain];
[self setInsertionPointColor:shColorCursor];
[self setNeedsDisplayInRect:[self visibleRect]];
} else if ([keyPath isEqualToString:identifierSyntaxColorKey]) {
if(shColorIdentifier) [shColorIdentifier release];
shColorIdentifier = [[NSUnarchiver unarchiveObjectWithData:[change objectForKey:NSKeyValueChangeNewKey]] retain];
if([self isEditable])
[self performSelector:@selector(doSyntaxHighlighting) withObject:nil afterDelay:0.1];
} else if ([keyPath isEqualToString:editorBackgroundColorKey]) {
if(shColorBackground) [shColorBackground release];
shColorBackground = [[NSUnarchiver unarchiveObjectWithData:[change objectForKey:NSKeyValueChangeNewKey]] retain];
[self setNeedsDisplayInRect:[self visibleRect]];
} else if ([keyPath isEqualToString:editorCurrentLineBackgroundColorKey]) {
if(shColorCurrentLine) [shColorCurrentLine release];
shColorCurrentLine = [[NSUnarchiver unarchiveObjectWithData:[change objectForKey:NSKeyValueChangeNewKey]] retain];
[self setNeedsDisplayInRect:[self visibleRect]];
} else if ([keyPath isEqualToString:editorSelectionBackgroundColorKey]) {
NSColor *c = [[NSUnarchiver unarchiveObjectWithData:[change objectForKey:NSKeyValueChangeNewKey]] retain];
NSMutableDictionary *attr = [NSMutableDictionary dictionary];
[attr setDictionary:[self selectedTextAttributes]];
[attr setObject:c forKey:NSBackgroundColorAttributeName];
[self setSelectedTextAttributes:attr];
[self setNeedsDisplayInRect:[self visibleRect]];
} else if ([keyPath isEqualToString:showSyntaxColoringKey]) {
syntaxHighlightingEnabled = [[change objectForKey:NSKeyValueChangeNewKey] boolValue];
if(syntaxHighlightingEnabled) {
[self performSelector:@selector(doSyntaxHighlighting) withObject:nil afterDelay:0.05f];
} else {
[self performSelector:@selector(setNonSyntaxHighlighting) withObject:nil afterDelay:0.05f];
}
} else if ([keyPath isEqualToString:enableLineWrappingKey]) {
[self updateLineWrappingMode];
[self performSelector:@selector(doSyntaxHighlighting) withObject:nil afterDelay:0.05f];
[self setNeedsDisplay:YES];
} else if ([keyPath isEqualToString:showLineNumbersKey]) {
lineNumberingEnabled = [[change objectForKey:NSKeyValueChangeNewKey] boolValue];
if(lineNumberingEnabled) {
NoodleLineNumberView *theRulerView = [[NoodleLineNumberView alloc] initWithScrollView:scrollView];
[scrollView setVerticalRulerView:theRulerView];
[scrollView setHasHorizontalRuler:NO];
[scrollView setHasVerticalRuler:YES];
[scrollView setRulersVisible:YES];
[theRulerView release];
[(NoodleLineNumberView*)[[self enclosingScrollView] verticalRulerView] setLineWrappingMode:[Preferences flagForKey:enableLineWrappingKey withDefault: YES]];
} else {
[scrollView setHasHorizontalRuler:NO];
[scrollView setHasVerticalRuler:NO];
[scrollView setRulersVisible:NO];
}
[self setNeedsDisplay:YES];
} else if ([keyPath isEqualToString:prefShowArgsHints]) {
argsHints = [[change objectForKey:NSKeyValueChangeNewKey] boolValue];
if(!argsHints) {
[selfDelegate setStatusLineText:@""];
} else {
[self currentFunctionHint];
}
} else if ([keyPath isEqualToString:highlightCurrentLine]) {
[self setNeedsDisplayInRect:[self visibleRect]];
} else if ([keyPath isEqualToString:RScriptEditorDefaultFont] && ![[[[self window] windowController] document] isRTF] && ![self selectedRange].length) {
[self setFont:[NSUnarchiver unarchiveObjectWithData:[change objectForKey:NSKeyValueChangeNewKey]]];
[self setNeedsDisplayInRect:[self visibleRect]];
} else if ([keyPath isEqualToString:HighlightIntervalKey]) {
braceHighlightInterval = [Preferences floatForKey:HighlightIntervalKey withDefault:0.3f];
}
}
- (void)updateLineWrappingMode
{
NSSize layoutSize;
lineWrappingEnabled = [Preferences flagForKey:enableLineWrappingKey withDefault: YES];
[self setHorizontallyResizable:YES];
if (!lineWrappingEnabled) {
NSRange curRange = [self selectedRange];
layoutSize = NSMakeSize(10e6,10e6);
[scrollView setHasHorizontalScroller:YES];
[self setMaxSize:layoutSize];
[[self textContainer] setContainerSize:layoutSize];
[[self textContainer] setWidthTracksTextView:NO];
[self scrollRangeToVisible:NSMakeRange(curRange.location, 0)];
} else {
[scrollView setHasHorizontalScroller:NO];
layoutSize = [self maxSize];
[self setMaxSize:layoutSize];
[[self textContainer] setContainerSize:layoutSize];
[[self textContainer] setWidthTracksTextView:YES];
// Enforce view to be re-layouted correctly
// by re-inserting the the current text buffer
[[self undoManager] disableUndoRegistration];
NSRange curRange = [self selectedRange];
NSString *t = [[NSString alloc] initWithString:[self string]];
[self selectAll:nil];
[self insertText:@""];
usleep(1000);
[self insertText:t];
[t release];
[self setSelectedRange:curRange];
[self scrollRangeToVisible:NSMakeRange(curRange.location, 0)];
[[self undoManager] enableUndoRegistration];
}
[[self textContainer] setHeightTracksTextView:NO];
}
- (void)drawRect:(NSRect)rect
{
// Draw background only for screen display but not while printing
if([NSGraphicsContext currentContextDrawingToScreen]) {
// Draw textview's background
[shColorBackground setFill];
NSRectFill(rect);
// Highlightes the current line if set in the Pref
// and if nothing is selected in the text view
if ([prefs boolForKey:highlightCurrentLine] && ![self selectedRange].length && ![self isSnippetMode]) {
NSUInteger rectCount;
NSRange curLineRange = [[self string] lineRangeForRange:[self selectedRange]];
// [theTextStorage ensureAttributesAreFixedInRange:curLineRange];
NSRectArray queryRects = [[self layoutManager] rectArrayForCharacterRange: curLineRange
withinSelectedCharacterRange: curLineRange
inTextContainer: [self textContainer]
rectCount: &rectCount ];
[shColorCurrentLine setFill];
NSRectFillListUsingOperation(queryRects, rectCount, NSCompositeSourceOver);
}
}
[super drawRect:rect];
}
#pragma mark -
/**
* Performs syntax highlighting, trigger undo behaviour
*/
- (void)textStorageDidProcessEditing:(NSNotification *)notification
{
// Make sure that the notification is from the correct textStorage object
if (theTextStorage != [notification object]) return;
NSInteger editedMask = [theTextStorage editedMask];
SLog(@"RScriptEditorTextView: textStorageDidProcessEditing <%@> with mask %d", self, editedMask);
// if the user really changed the text
if(editedMask != 1) {
// For larger text break a running syntax highlighting for user interaction
// to make them more responsive (typing and scrolling)
// if([[theTextStorage string] length] > 120000) {
// breakSyntaxHighlighting = 1;
// }
[self checkSnippets];
breakSyntaxHighlighting = 1;
// Cancel calling doSyntaxHighlighting
[NSObject cancelPreviousPerformRequestsWithTarget:self
selector:@selector(doSyntaxHighlighting)
object:nil];
[self performSelector:@selector(doSyntaxHighlighting) withObject:nil afterDelay:0.05f];
// Cancel setting undo break point
[NSObject cancelPreviousPerformRequestsWithTarget:self
selector:@selector(breakUndoCoalescing)
object:nil];
// Improve undo behaviour, i.e. it depends how fast the user types
[self performSelector:@selector(breakUndoCoalescing) withObject:nil afterDelay:0.8f];
[NSObject cancelPreviousPerformRequestsWithTarget:(RDocumentWinCtrl*)[self delegate]
selector:@selector(functionRescan)
object:nil];
// update function list to display the function in which the cursor is located
[(RDocumentWinCtrl*)[self delegate] performSelector:@selector(functionRescan) withObject:nil afterDelay:0.3f];
}
deleteBackward = NO;
startListeningToBoundChanges = YES;
}
#pragma mark -
- (BOOL)lineNumberingEnabled
{
return lineNumberingEnabled;
}
- (void)setDeleteBackward:(BOOL)delBack
{
deleteBackward = delBack;
}
/**
* Sets Tab Stops width for better editing behaviour
*/
- (void)setTabStops
{
SLog(@"RScriptEditorTextView: setTabStops <%@>", self);
NSFont *tvFont = [self font];
int i;
NSTextTab *aTab;
NSMutableArray *myArrayOfTabs;
NSMutableParagraphStyle *paragraphStyle;
BOOL oldEditableStatus = [self isEditable];
[self setEditable:YES];
int tabStopWidth = [Preferences integerForKey:RScriptEditorTabWidth withDefault:4];
if(tabStopWidth < 1) tabStopWidth = 1;
float theTabWidth = [[NSString stringWithString:@" "] sizeWithAttributes:[NSDictionary dictionaryWithObject:tvFont forKey:NSFontAttributeName]].width;
theTabWidth = (float)tabStopWidth * theTabWidth;
int numberOfTabs = 256/tabStopWidth;
myArrayOfTabs = [NSMutableArray arrayWithCapacity:numberOfTabs];
aTab = [[NSTextTab alloc] initWithType:NSLeftTabStopType location:theTabWidth];
[myArrayOfTabs addObject:aTab];
[aTab release];
for(i=1; i<numberOfTabs; i++) {
aTab = [[NSTextTab alloc] initWithType:NSLeftTabStopType location:theTabWidth + ((float)i * theTabWidth)];
[myArrayOfTabs addObject:aTab];
[aTab release];
}
paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[paragraphStyle setTabStops:myArrayOfTabs];
// Soft wrapped lines are indented slightly
[paragraphStyle setHeadIndent:4.0];
NSMutableDictionary *textAttributes = [[[NSMutableDictionary alloc] initWithCapacity:1] autorelease];
[textAttributes setObject:paragraphStyle forKey:NSParagraphStyleAttributeName];
NSRange range = NSMakeRange(0, [theTextStorage length]);
if ([self shouldChangeTextInRange:range replacementString:nil]) {
[theTextStorage setAttributes:textAttributes range: range];
[self didChangeText];
}
[self setTypingAttributes:textAttributes];
[self setDefaultParagraphStyle:paragraphStyle];
[self setFont:tvFont];
[self setEditable:oldEditableStatus];
[paragraphStyle release];
}
- (BOOL)isSyntaxHighlighting
{
return isSyntaxHighlighting;
}
- (BOOL)breakSyntaxHighlighting
{
return breakSyntaxHighlighting;
}
/**
* Syntax Highlighting.
*
* (The main bottleneck is the [NSTextStorage addAttribute:value:range:] method - the parsing itself is really fast!)
* Some sample code from Andrew Choi ( http://members.shaw.ca/akochoi-old/blog/2003/11-09/index.html#3 ) has been reused.
*/
- (void)doSyntaxHighlighting
{
if(!syntaxHighlightingEnabled)
breakSyntaxHighlighting = 0;
if (!syntaxHighlightingEnabled || [selfDelegate plain]) return;
isSyntaxHighlighting = YES;
NSString *selfstr = [theTextStorage string];
NSInteger strlength = (NSInteger)[selfstr length];
// do not highlight if text larger than 10MB
if(strlength > 10000000 || !strlength) {
isSyntaxHighlighting = NO;
breakSyntaxHighlighting = 0;
return;
}
// == Do highlighting partly (max R_SYNTAX_HILITE_BIAS*2 around visibleRange
// by considering entire lines).
// Get the text range currently displayed in the view port
NSRect visibleRect = [self visibleRect];
NSRange visibleRange = [[self layoutManager] glyphRangeForBoundingRectWithoutAdditionalLayout:visibleRect inTextContainer:[self textContainer]];
if(!visibleRange.length) {
isSyntaxHighlighting = NO;
breakSyntaxHighlighting = 0;
return;
}
NSInteger start = visibleRange.location - R_SYNTAX_HILITE_BIAS;
if (start > 0)
while(start > 0) {
if(CFStringGetCharacterAtIndex((CFStringRef)selfstr, start)=='\n')
break;
start--;
}
if(start < 0) start = 0;
NSInteger end = NSMaxRange(visibleRange) + R_SYNTAX_HILITE_BIAS;
if (end > strlength) {
end = strlength;
} else {
while(end < strlength) {
if(CFStringGetCharacterAtIndex((CFStringRef)selfstr, end)=='\n')
break;
end++;
}
}
NSRange textRange = NSMakeRange(start, end-start);
// only to be sure that nothing went wrongly
textRange = NSIntersectionRange(textRange, NSMakeRange(0, [theTextStorage length]));
if (!textRange.length || textRange.length > 30000) {
isSyntaxHighlighting = NO;
breakSyntaxHighlighting = 0;
return;
}
[theTextStorage beginEditing];
NSColor *tokenColor = nil;
size_t token;
NSRange tokenRange;
// initialise flex
yyuoffset = textRange.location; yyuleng = 0;
BOOL hasFoldedItems = [theTextStorage hasFoldedItems];
if([selfDelegate isRdDocument]) {
rd_switch_to_buffer(rd_scan_string(NSStringUTF8String([selfstr substringWithRange:textRange])));
// now loop through all the tokens
while ((token = rdlex())) {
if(hasFoldedItems && [theTextStorage foldedAtIndex: yyuoffset] > -1) continue;
switch (token) {
case RDPT_COMMENT:
tokenColor = shColorComment;
break;
case RDPT_SECTION:
tokenColor = shColorKeyword;
break;
case RDPT_MACRO_ARG:
tokenColor = shColorNumber;
break;
case RDPT_MACRO_GEN:
tokenColor = shColorNumber;
break;
case RDPT_DIRECTIVE:
tokenColor = shColorString;
break;
case RDPT_OTHER:
tokenColor = shColorNormal;
break;
default:
tokenColor = shColorNormal;
}
tokenRange = NSMakeRange(yyuoffset, yyuleng);
// make sure that tokenRange is valid (and therefore within textRange)
// otherwise a bug in the lex code could cause the the TextView to crash
// NOTE Disabled for testing purposes for speed it up
tokenRange = NSIntersectionRange(tokenRange, textRange);
if (!tokenRange.length) continue;
NSMutableAttributedStringAddAttributeValueRange(theTextStorage, NSForegroundColorAttributeName, tokenColor, tokenRange);
if(breakSyntaxHighlighting) {
// Cancel calling doSyntaxHighlighting
[NSObject cancelPreviousPerformRequestsWithTarget:self
selector:@selector(doSyntaxHighlighting)
object:nil];
[self performSelector:@selector(doSyntaxHighlighting) withObject:nil afterDelay:0.08f];
breakSyntaxHighlighting = 0;
break;
}
}
} else {
yy_switch_to_buffer(yy_scan_string(NSStringUTF8String([selfstr substringWithRange:textRange])));
// now loop through all the tokens
while ((token = yylex())) {
if(hasFoldedItems && [theTextStorage foldedAtIndex: yyuoffset] > -1) continue;
switch (token) {
case RPT_SINGLE_QUOTED_TEXT:
case RPT_DOUBLE_QUOTED_TEXT:
tokenColor = shColorString;
break;
case RPT_RESERVED_WORD:
tokenColor = shColorKeyword;
break;
case RPT_NUMERIC:
tokenColor = shColorNumber;
break;
case RPT_BACKTICK_QUOTED_TEXT:
tokenColor = shColorString;
break;
case RPT_COMMENT:
tokenColor = shColorComment;
break;
case RPT_VARIABLE:
tokenColor = shColorIdentifier;
break;
default:
tokenColor = shColorNormal;
}
tokenRange = NSMakeRange(yyuoffset, yyuleng);
// make sure that tokenRange is valid (and therefore within textRange)
// otherwise a bug in the lex code could cause the the TextView to crash
tokenRange = NSIntersectionRange(tokenRange, textRange);
if (!tokenRange.length) continue;
NSMutableAttributedStringAddAttributeValueRange(theTextStorage, NSForegroundColorAttributeName, tokenColor, tokenRange);
if(breakSyntaxHighlighting) {
// Cancel calling doSyntaxHighlighting
[NSObject cancelPreviousPerformRequestsWithTarget:self
selector:@selector(doSyntaxHighlighting)
object:nil];
[self performSelector:@selector(doSyntaxHighlighting) withObject:nil afterDelay:0.08f];
breakSyntaxHighlighting = 0;
break;
}
}
}
// set current textColor to the color of the caret's position - 1
// to try to suppress writing in normalColor before syntax highlighting
NSUInteger ix = [self selectedRange].location;
if(ix > 1) {
NSMutableDictionary *typeAttr = [NSMutableDictionary dictionary];
[typeAttr setDictionary:[self typingAttributes]];
NSColor *c = [theTextStorage attribute:NSForegroundColorAttributeName atIndex:ix-1 effectiveRange:nil];
if(c) [typeAttr setObject:c forKey:NSForegroundColorAttributeName];
[self setTypingAttributes:typeAttr];
}
[theTextStorage endEditing];
[self setNeedsDisplayInRect:visibleRect];
breakSyntaxHighlighting = 0;
isSyntaxHighlighting = NO;
}
-(void)resetHighlights
{
SLog(@"RScriptEditorTextView: resetHighlights with current highlite %d", currentHighlight);
if (currentHighlight>-1) {
if (currentHighlight<[theTextStorage length]) {
NSLayoutManager *lm = [self layoutManager];
if (lm) {
NSRange fr = NSMakeRange(currentHighlight,1);
NSDictionary *d = [lm temporaryAttributesAtCharacterIndex:currentHighlight effectiveRange:&fr];
if (!d || [d objectForKey:NSBackgroundColorAttributeName]==nil) {
fr = NSMakeRange(0,[[self string] length]);
SLog(@"resetHighlights: attribute at %d not found, clearing all %d characters - better safe than sorry", currentHighlight, fr.length);
}
[lm removeTemporaryAttribute:NSBackgroundColorAttributeName forCharacterRange:fr];
}
}
currentHighlight=-1;
}
}
-(void)highlightCharacter:(NSNumber*)loc
{
NSInteger pos = [loc intValue];
SLog(@"RScriptEditorTextView: highlightCharacter: %d", pos);
if (pos>=0 && pos<[[self string] length]) {
#if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
[self showFindIndicatorForRange:NSMakeRange(pos, 1)];
#else
[self resetHighlights];
NSLayoutManager *lm = [self layoutManager];
if (lm) {
currentHighlight = pos;
[lm setTemporaryAttributes:highlightColorAttr forCharacterRange:NSMakeRange(pos, 1)];
[self performSelector:@selector(resetBackgroundColor:) withObject:nil afterDelay:braceHighlightInterval];
}
#endif
}
else SLog(@"highlightCharacter: attempt to set highlight %d beyond the text range 0:%d - I refuse!", pos, [[self string] length] - 1);
}
-(void)resetBackgroundColor:(id)sender
{
[self resetHighlights];
}
/**
* Scrollview delegate after the textView's view port was changed.
* Manily used to update the syntax highlighting for a large text size
*/
- (void)boundsDidChangeNotification:(NSNotification *)notification
{
if(startListeningToBoundChanges) {
breakSyntaxHighlighting = 1;
[NSObject cancelPreviousPerformRequestsWithTarget:self
selector:@selector(doSyntaxHighlighting)
object:nil];
if(![theTextStorage changeInLength]) {
if([[theTextStorage string] length] > 120000)
breakSyntaxHighlighting = 2;
[self performSelector:@selector(doSyntaxHighlighting) withObject:nil afterDelay:0.08];
}
if(lineNumberingEnabled) {
[NSObject cancelPreviousPerformRequestsWithTarget:[[self enclosingScrollView] verticalRulerView]
selector:@selector(refresh)
object:nil];
[[[self enclosingScrollView] verticalRulerView] performSelector:@selector(refresh) withObject:nil afterDelay:0.001f];