-
Notifications
You must be signed in to change notification settings - Fork 7
/
RTextView.m
2168 lines (1801 loc) · 75.9 KB
/
RTextView.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.
*
* Created by Simon Urbanek on 5/11/05.
* $Id: RTextView.m 7927 2021-02-12 02:19:59Z urbaneks $
*/
#import "RTextView.h"
#import "HelpManager.h"
#import "RGUI.h"
#import "RegexKitLite.h"
#import "RController.h"
#import "NSTextView_RAdditions.h"
#import "RDocumentWinCtrl.h"
#import "NSString_RAdditions.h"
// linked character attributes
#define kTALinked @"link"
#define kTAVal @"x"
// some helper functions for handling rectangles and points
// needed in roundedBezierPathAroundRange:
static inline CGFloat RRectTop(NSRect rectangle) { return rectangle.origin.y; }
static inline CGFloat RRectBottom(NSRect rectangle) { return rectangle.origin.y+rectangle.size.height; }
static inline CGFloat RRectLeft(NSRect rectangle) { return rectangle.origin.x; }
static inline CGFloat RRectRight(NSRect rectangle) { return rectangle.origin.x+rectangle.size.width; }
static inline CGFloat RPointDistance(NSPoint a, NSPoint b) { return sqrtf( (a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y) ); }
static inline NSPoint RPointOnLine(NSPoint a, NSPoint b, CGFloat t) { return NSMakePoint(a.x*(1.0f-t) + b.x*t, a.y*(1.0f-t) + b.y*t); }
// declared external
BOOL RTextView_autoCloseBrackets = YES;
#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_7
// declare the following methods to avoid compiler warnings
@interface NSTextView (SuppressWarnings)
- (void)swipeWithEvent:(NSEvent *)event;
- (void)setAutomaticTextReplacementEnabled:(BOOL)flag;
- (void)setAutomaticSpellingCorrectionEnabled:(BOOL)flag;
- (void)setAutomaticDataDetectionEnabled:(BOOL)flag;
- (void)setAutomaticDashSubstitutionEnabled:(BOOL)flag;
@end
#endif
#pragma mark -
#pragma mark Private API
@interface RTextView (Private)
- (void)selectMatchingPairAt:(NSInteger)position;
- (NSString*)functionNameForCurrentScope;
@end
#pragma mark -
@implementation RTextView
- (id) initWithCoder: (NSCoder*) coder
{
self = [super initWithCoder:coder];
if (self) {
separatingTokensSet = [[NSCharacterSet characterSetWithCharactersInString: @"()'\"+-=/* ,\t]{}^|&!;<>?`\n\\"] retain];
undoBreakTokensSet = [[NSCharacterSet characterSetWithCharactersInString: @"+- .,|&*/:!?<>=\n"] retain];
wordCharSet = [NSMutableCharacterSet alphanumericCharacterSet];
[wordCharSet addCharactersInString:@"_.\\"];
[wordCharSet retain];
}
return self;
}
- (void)awakeFromNib
{
SLog(@"RTextView: awakeFromNib %@", self);
// commentTokensSet = [[NSCharacterSet characterSetWithCharactersInString: @"#"] retain];
console = NO;
RTextView_autoCloseBrackets = YES;
SLog(@" - delegate: %@", [self delegate]);
isRdDocument = NO;
if([[self window] windowController] && [[[self window] windowController] respondsToSelector:@selector(isRdDocument)])
isRdDocument = ([[[self window] windowController] isRdDocument]);
// work-arounds for brain-dead "features" in Lion
if ([self respondsToSelector:@selector(setAutomaticQuoteSubstitutionEnabled:)])
[self setAutomaticQuoteSubstitutionEnabled:NO];
if ([self respondsToSelector:@selector(setAutomaticTextReplacementEnabled:)])
[self setAutomaticTextReplacementEnabled:NO];
if ([self respondsToSelector:@selector(setAutomaticSpellingCorrectionEnabled:)])
[self setAutomaticSpellingCorrectionEnabled:NO];
if ([self respondsToSelector:@selector(setAutomaticLinkDetectionEnabled:)])
[self setAutomaticLinkDetectionEnabled:NO];
if ([self respondsToSelector:@selector(setAutomaticDataDetectionEnabled:)])
[self setAutomaticDataDetectionEnabled:NO];
if ([self respondsToSelector:@selector(setAutomaticDashSubstitutionEnabled:)])
[self setAutomaticDashSubstitutionEnabled:NO];
[self endSnippetSession];
}
- (void)dealloc
{
if(separatingTokensSet) [separatingTokensSet release];
if(undoBreakTokensSet) [undoBreakTokensSet release];
if(wordCharSet) [wordCharSet release];
// if(commentTokensSet) [commentTokensSet release];
[super dealloc];
}
- (BOOL)acceptsFirstResponder
{
// Close sharedColorPanel if visible to avoid color changes
if([[NSColorPanel sharedColorPanel] isVisible])
[[NSColorPanel sharedColorPanel] close];
return YES;
}
- (NSBezierPath*)roundedBezierPathAroundRange:(NSRange)aRange
{
// This method was modified taken from the open source project "Sequel Pro"
// http://www.sequelpro.com
//
// which follows the
// GNU GENERAL PUBLIC LICENSE
// http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
//
// more details:
// http://www.sequelpro.com/legal/
// http://www.sequelpro.com/developers/
// parameters for snippet highlighting
CGFloat kappa = 0.5522847498f; // magic number from http://www.whizkidtech.redprince.net/bezier/circle/
CGFloat radius = 6;
CGFloat horzInset = -3;
CGFloat vertInset = 0.3f;
BOOL connectDisconnectedPartsWithLine = NO;
NSBezierPath *framePath = [NSBezierPath bezierPath];
NSUInteger rectCount;
NSRectArray rects = [[self layoutManager] rectArrayForCharacterRange: aRange
withinSelectedCharacterRange: aRange
inTextContainer: [self textContainer]
rectCount: &rectCount ];
if (rectCount>2 || (rectCount>1 && (RRectRight(rects[1]) >= RRectLeft(rects[0]) || connectDisconnectedPartsWithLine))) {
// highlight complicated multiline snippet
NSRect lineRects[4];
lineRects[0] = rects[0];
lineRects[1] = rects[1];
lineRects[2] = rects[rectCount-2];
lineRects[3] = rects[rectCount-1];
for(int j=0;j<4;j++) lineRects[j] = NSInsetRect(lineRects[j], horzInset, vertInset);
NSPoint vertices[8];
vertices[0] = NSMakePoint( RRectLeft(lineRects[0]), RRectTop(lineRects[0]) ); // point a
vertices[1] = NSMakePoint( RRectRight(lineRects[0]), RRectTop(lineRects[0]) ); // point b
vertices[2] = NSMakePoint( RRectRight(lineRects[2]), RRectBottom(lineRects[2]) ); // point c
vertices[3] = NSMakePoint( RRectRight(lineRects[3]), RRectBottom(lineRects[2]) ); // point d
vertices[4] = NSMakePoint( RRectRight(lineRects[3]), RRectBottom(lineRects[3]) ); // point e
vertices[5] = NSMakePoint( RRectLeft(lineRects[3]), RRectBottom(lineRects[3]) ); // point f
vertices[6] = NSMakePoint( RRectLeft(lineRects[1]), RRectTop(lineRects[1]) ); // point g
vertices[7] = NSMakePoint( RRectLeft(lineRects[0]), RRectTop(lineRects[1]) ); // point h
for (NSUInteger j=0; j<8; j++) {
NSPoint curr = vertices[j];
NSPoint prev = vertices[(j+8-1)%8];
NSPoint next = vertices[(j+1)%8];
CGFloat s = radius/RPointDistance(prev, curr);
if (s>0.5) s = 0.5f;
CGFloat t = radius/RPointDistance(curr, next);
if (t>0.5) t = 0.5f;
NSPoint a = RPointOnLine(curr, prev, 0.5f);
NSPoint b = RPointOnLine(curr, prev, s);
NSPoint c = curr;
NSPoint d = RPointOnLine(curr, next, t);
NSPoint e = RPointOnLine(curr, next, 0.5f);
if (j==0) [framePath moveToPoint:a];
[framePath lineToPoint: b];
[framePath curveToPoint:d controlPoint1:RPointOnLine(b, c, kappa) controlPoint2:RPointOnLine(d, c, kappa)];
[framePath lineToPoint: e];
}
} else {
//highlight disconnected snippet parts (or single line snippet)
for (NSUInteger j=0; j<rectCount; j++) {
NSRect rect = rects[j];
rect = NSInsetRect(rect, horzInset, vertInset);
[framePath appendBezierPathWithRoundedRect:rect xRadius:radius yRadius:radius];
}
}
return framePath;
}
- (void)drawRect:(NSRect)rect {
// Draw background only for screen display but not while printing
if([NSGraphicsContext currentContextDrawingToScreen]) {
// Draw textview's background since due to the snippet highlighting we're responsible for it.
NSColor *bgColor = [NSColor clearColor];
NSColor *frameColor = [NSColor clearColor];
if([[self delegate] isKindOfClass:[RController class]])
frameColor = [Preferences unarchivedObjectForKey:selectionColorKey withDefault:[NSColor colorWithCalibratedRed:0.71f green:0.835f blue:1.0f alpha:1.0f]];
else
frameColor = [Preferences unarchivedObjectForKey:editorSelectionBackgroundColorKey withDefault:[NSColor colorWithCalibratedRed:0.71f green:0.835f blue:1.0f alpha:1.0f]];
bgColor = [frameColor colorWithAlphaComponent:0.4];
// Highlight snippets
if(snippetControlCounter > -1) {
// Is the caret still inside a snippet
if([self checkForCaretInsideSnippet]) {
for(NSInteger i=0; i<snippetControlMax; i++) {
if(snippetControlArray[i][0] > -1) {
// choose the colors for the snippet parts
if(i == currentSnippetIndex) {
[bgColor setFill];
[frameColor setStroke];
} else {
[bgColor setFill];
[frameColor setStroke];
}
NSBezierPath *snippetPath = [self roundedBezierPathAroundRange: NSMakeRange(snippetControlArray[i][0],snippetControlArray[i][1]) ];
[snippetPath fill];
[snippetPath stroke];
}
}
} else {
[self endSnippetSession];
}
}
}
[super drawRect:rect];
}
- (void)keyDown:(NSEvent *)theEvent
{
if(![self isEditable]) {
[super keyDown:theEvent];
return;
}
NSString *rc = [theEvent charactersIgnoringModifiers];
NSString *cc = [theEvent characters];
unsigned long modFlags = [theEvent modifierFlags];
long allFlags = (NSShiftKeyMask|NSControlKeyMask|NSAlternateKeyMask|NSCommandKeyMask);
long curFlags = (modFlags & allFlags);
BOOL hilite = NO;
SLog(@"RTextView: keyDown: %@ *** \"%@\" %lx", theEvent, rc, modFlags);
if([rc length] && [undoBreakTokensSet characterIsMember:[rc characterAtIndex:0]]) [self breakUndoCoalescing];
if ([rc isEqual:@"."] && (modFlags&allFlags)==NSControlKeyMask) {
SLog(@" - send complete: to self");
[self complete:self];
return;
}
if ([rc isEqual:@"="]) {
long mf = modFlags & allFlags;
if ( mf ==NSControlKeyMask) {
[self breakUndoCoalescing];
[self insertText:@"<-"];
return;
}
if ( mf == NSAlternateKeyMask ) {
[self breakUndoCoalescing];
[self insertText:@"!="];
return;
}
}
if ([rc isEqual:@"-"] && (modFlags&allFlags)==NSAlternateKeyMask) {
[self breakUndoCoalescing];
[self insertText:[NSString stringWithFormat:@"%@<- ",
([self selectedRange].location && [[self string] characterAtIndex:[self selectedRange].location-1] != ' ')?@" ":@""]];
return;
}
if ([rc isEqual:@"h"] && (modFlags&allFlags)==NSControlKeyMask) {
SLog(@" - send showHelpForCurrentFunction to self");
[self showHelpForCurrentFunction];
return;
}
// Detect if matching bracket should be highlighted
if(cc && [cc length]==1 && [[[NSUserDefaults standardUserDefaults] objectForKey:showBraceHighlightingKey] isEqualToString:@"YES"]) {
switch([cc characterAtIndex:0]) {
case '(':
case '[':
case '{':
case ')':
case ']':
case '}':
hilite = YES;
}
}
if (cc && [cc length]==1 && [[[NSUserDefaults standardUserDefaults] objectForKey:kAutoCloseBrackets] isEqualToString:@"YES"]) {
unichar ck = [cc characterAtIndex:0];
NSString *complement = nil;
NSRange r = [self selectedRange];
BOOL acCheck = NO;
switch (ck) {
case '{':
complement = @"}";
case '(':
if (!complement) complement = @")";
case '[':
if (!complement) complement = @"]";
case '"':
if (!complement) {
complement = @"\"";
acCheck = YES;
if ([self parserContextForPosition:r.location] != pcExpression) break;
}
case '`':
if (!complement) {
complement = @"`";
acCheck = YES;
if ([self parserContextForPosition:r.location] != pcExpression) break;
}
case '\'':
if (!complement) {
complement = @"\'";
acCheck = YES;
if ([self parserContextForPosition:r.location] != pcExpression) break;
}
// Check if something is selected and wrap it into matching pair characters and preserve the selection
// - in RConsole only if selection is in the last line
if(((([self isRConsole] && ([[self string] lineRangeForRange:NSMakeRange([[self string] length]-1,0)].location+1 < r.location)) || ![self isRConsole]))
&& [self wrapSelectionWithPrefix:[NSString stringWithFormat:@"%c", ck] suffix:complement]) {
SLog(@"RTextView: selection was wrapped with auto-pairs");
return;
}
// Try to suppress unnecessary auto-pairing
if( !isRdDocument && [self isCursorAdjacentToAlphanumCharWithInsertionOf:ck] && ![self isNextCharMarkedBy:kTALinked withValue:kTAVal] && ![self selectedRange].length ){
SLog(@"RTextView: suppressed auto-pairing");
[super keyDown:theEvent];
if(hilite && [[self delegate] respondsToSelector:@selector(highlightBracesWithShift:andWarn:)])
[(id)[self delegate] highlightBracesWithShift:-1 andWarn:YES];
return;
}
SLog(@"RTextView: open bracket chracter %c", ck);
[super keyDown:theEvent];
{
r = [self selectedRange];
if (r.location != NSNotFound) {
// NSAttributedString *as = [[NSAttributedString alloc] initWithString:complement attributes:
// [NSDictionary dictionaryWithObject:TAVal forKey:kTALinked]];
NSTextStorage *ts = [self textStorage];
// Register the auto-pairing for undo and insert the complement
[self shouldChangeTextInRange:r replacementString:complement];
[self replaceCharactersInRange:r withString:complement];
r.length=1;
[ts addAttribute:kTALinked value:kTAVal range:r];
r.length=0;
[self setSelectedRange:r];
}
return;
}
case '}':
case ')':
case ']':
acCheck = YES;
}
if (acCheck) {
NSRange r = [self selectedRange];
if (r.location != NSNotFound && r.length == 0) {
NSTextStorage *ts = [self textStorage];
id attr = nil;
@try {
attr = [ts attribute:kTALinked atIndex:r.location effectiveRange:0];
}
@catch (id ue) {}
if (attr) {
unsigned int cuc = [[ts string] characterAtIndex:r.location];
SLog(@"RTextView: encountered linked character '%c', while writing '%c'", cuc, ck);
if (cuc == ck) {
r.length = 1;
SLog(@"RTextView: selecting linked character for removal on type");
[self setSelectedRange:r];
}
}
}
SLog(@"RTextView: closing bracket chracter %c", ck);
}
}
// Check for {SHIFT}TAB to try to insert snippet via TAB trigger
// or if snippet mode select next/prev snippet
if ([theEvent keyCode] == 48 && [self isEditable]){
NSRange targetRange = [self getRangeForCurrentWord];
NSString *tabTrigger = [[self string] substringWithRange:targetRange];
// Is TAB trigger active change selection according to {SHIFT}TAB
if(snippetControlCounter > -1){
if(curFlags==(NSShiftKeyMask)) { // select previous snippet
currentSnippetIndex--;
// Look for previous defined snippet since snippet numbers must not serial like 1, 5, and 12 e.g.
while(snippetControlArray[currentSnippetIndex][0] == -1 && currentSnippetIndex > -2)
currentSnippetIndex--;
if(currentSnippetIndex < 0) {
currentSnippetIndex = 0;
while(snippetControlArray[currentSnippetIndex][0] == -1 && currentSnippetIndex < 20)
currentSnippetIndex++;
NSBeep();
}
[self selectCurrentSnippet];
return;
} else { // select next snippet
currentSnippetIndex++;
// Look for next defined snippet since snippet numbers must not serial like 1, 5, and 12 e.g.
while(snippetControlArray[currentSnippetIndex][0] == -1 && currentSnippetIndex < 20)
currentSnippetIndex++;
if(currentSnippetIndex > snippetControlMax) { // for safety reasons
[self endSnippetSession];
} else {
[self selectCurrentSnippet];
return;
}
}
[self endSnippetSession];
return;
}
// Check if tab trigger is defined; if so insert it, otherwise pass through event
if(snippetControlCounter < 0 && [tabTrigger length]) {
// TODO will come soon [HJBB]
[super keyDown:theEvent];
return;
}
}
[super keyDown:theEvent];
if(hilite && [[self delegate] respondsToSelector:@selector(highlightBracesWithShift:andWarn:)])
[(id)[self delegate] highlightBracesWithShift:-1 andWarn:YES];
}
- (void)deleteBackward:(id)sender
{
NSRange r = [self selectedRange];
if (r.length == 0 && r.location > 0)
[self selectMatchingPairAt:r.location];
[super deleteBackward:sender];
}
- (void)deleteForward:(id)sender
{
NSRange r = [self selectedRange];
if (r.length == 0)
[self selectMatchingPairAt:r.location + 1];
[super deleteForward:sender];
}
/**
* If the textview has a selection, wrap it with the supplied prefix and suffix strings;
* return whether or not any wrap was performed.
*/
- (BOOL) wrapSelectionWithPrefix:(NSString *)prefix suffix:(NSString *)suffix
{
NSRange currentRange = [self selectedRange];
// Only proceed if a selection is active
if (currentRange.length == 0 || ![self isEditable])
return NO;
NSString *selString = [[self string] substringWithRange:currentRange];
// Replace the current selection with the selected string wrapped in prefix and suffix
[self insertText:[NSString stringWithFormat:@"%@%@%@", prefix, selString, suffix]];
// Re-select original selection
NSRange innerSelectionRange = NSMakeRange(currentRange.location+1, [selString length]);
[self setSelectedRange:innerSelectionRange];
// Mark last autopair character as autopair-linked
[[self textStorage] addAttribute:kTALinked value:kTAVal range:NSMakeRange(NSMaxRange(innerSelectionRange), 1)];
return YES;
}
/**
* Returns the parser context for the passed cursor position
*
* @param position The cursor position to test
*/
- (int)parserContextForPosition:(NSInteger)position
{
int context = pcExpression;
if (position < 1)
return context;
CFStringRef string = (CFStringRef)[self string];
if (position > [[self string] length])
position = [[self string] length];
// NSRange thisLine = [string lineRangeForRange:NSMakeRange(position, 0)];
CFIndex lineStart;
CFStringGetLineBounds(string, CFRangeMake(position, 0), &lineStart, NULL, NULL);
// we do NOT support multi-line strings, so the line always starts as an expression
if (lineStart == position)
return context;
SLog(@"RTextView: parserContextForPosition: %ld, line start: %ld", (long)position, (long)lineStart);
long i = lineStart;
BOOL skip = NO;
unichar c;
unichar commentSign = (isRdDocument) ? '%' : '#';
while (i < position) {
c = CFStringGetCharacterAtIndex(string, i);
if (skip) {
skip = NO;
} else {
if (c == '\\' && (context < pcComment)) {
skip = YES;
}
else if (c == '"') {
if (context == pcStringDQ)
context = pcExpression;
else if (context == pcExpression)
context = pcStringDQ;
}
else if (c == '\'') {
if (context == pcStringSQ)
context = pcExpression;
else if (context == pcExpression)
context = pcStringSQ;
}
else if (c == '`') {
if (context == pcStringBQ)
context = pcExpression;
else if (context == pcExpression)
context = pcStringBQ;
}
else if(context == pcExpression) {
if(c == commentSign)
context = pcComment;
}
}
i++;
}
return context;
}
/**
* Returns the range for user completion
*/
- (NSRange)rangeForUserCompletion
{
NSRange userRange = NSMakeRange(NSNotFound, 0);
NSRange selection = [self selectedRange];
NSString *string = [self string];
int cursor = NSMaxRange(selection); // we complete at the end of the selection
int context = [self parserContextForPosition:cursor];
SLog(@"RTextView: rangeForUserCompletion: parser context: %d", context);
if (context == pcComment) return NSMakeRange(NSNotFound,0); // no completion in comments
if (context == pcStringDQ || context == pcStringSQ) // we're in a string, hence file completion
// the beginning of the range doesn't matter, because we're guaranteed to find a string separator on the same line
userRange = [string rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:(context == pcStringDQ) ? @"\" /" : @"' /"]
options:NSBackwardsSearch|NSLiteralSearch
range:NSMakeRange(0, selection.location)];
if (context == pcExpression || context == pcStringBQ) // we're in an expression or back-quote, so use R separating tokens (we could be smarter about the BQ but well..)
userRange = [string rangeOfCharacterFromSet:separatingTokensSet
options:NSBackwardsSearch|NSLiteralSearch
range:NSMakeRange(0, selection.location)];
if( userRange.location == NSNotFound )
// everything is one expression - we're guaranteed to be in the first line (because \n would match)
return NSMakeRange(0, cursor);
if( userRange.length < 1 ) // nothing to complete
return NSMakeRange(NSNotFound, 0);
if( userRange.location == selection.location - 1 ) { // just before cursor means empty completion
userRange.location++;
userRange.length = 0;
} else { // normal completion
userRange.location++; // skip past first bad one
userRange.length = selection.location - userRange.location;
SLog(@" - returned range: %ld:%ld", userRange.location, userRange.length);
// FIXME: do we really need to change it? Cocoa should be doing it .. (and does in Lion)
if (os_version < 11.0)
[self setSelectedRange:userRange];
}
return userRange;
}
/**
* Checks if the char after the current caret position/selection matches a supplied attribute
*/
- (BOOL) isNextCharMarkedBy:(id)attribute withValue:(id)aValue
{
NSUInteger caretPosition = [self selectedRange].location;
// Perform bounds checking
if (caretPosition >= [[self string] length]) return NO;
// Perform the check
if ([[[self textStorage] attribute:attribute atIndex:caretPosition effectiveRange:nil] isEqualToString:aValue])
return YES;
return NO;
}
/**
* Checks if the caret adjoins to an alphanumeric char |word or word| or wo|rd
* Exception for word| and char is a “(” or “[” to allow e.g. auto-pairing () for functions
*/
- (BOOL) isCursorAdjacentToAlphanumCharWithInsertionOf:(unichar)aChar
{
NSUInteger caretPosition = [self selectedRange].location;
NSCharacterSet *alphanum = [NSCharacterSet alphanumericCharacterSet];
BOOL leftIsAlphanum = NO;
BOOL rightIsAlphanum = NO;
BOOL charIsOpenBracket = (aChar == '(' || aChar == '[');
NSUInteger bufferLength = [[self string] length];
if(!bufferLength) return NO;
// Check previous/next character for being alphanum
// @try block for bounds checking
@try
{
if(caretPosition==0)
leftIsAlphanum = NO;
else
leftIsAlphanum = [alphanum characterIsMember:[[self string] characterAtIndex:caretPosition-1]] && !charIsOpenBracket;
} @catch(id ae) { }
@try {
if(caretPosition >= bufferLength)
rightIsAlphanum = NO;
else
rightIsAlphanum= [alphanum characterIsMember:[[self string] characterAtIndex:caretPosition]];
} @catch(id ae) { }
return (leftIsAlphanum ^ rightIsAlphanum || (leftIsAlphanum && rightIsAlphanum));
}
/**
* Sets the console mode
*
* @param isConsole If self is in console mode (YES) or not (NO)
*/
- (void)setConsoleMode:(BOOL)isConsole
{
console = isConsole;
SLog(@"RTextView: set console flag to %@ (%@)", isConsole?@"yes":@"no", self);
}
/**
* Shows the Help page for the current function relative to the current cursor position or
* if something is selected for the selection in the HelpManager
*
* Notes:
* - if the cursor is in between or adjacent to an alphanumeric word take this one if it not a pure numeric value
* - if nothing found try to parse backwards from cursor position to find the active function name according to opened and closed parentheses
* examples | := cursor
* a(b(1,2|,3)) -> b
* a(b(1,2,3)|) -> a
* - if nothing found set the input focus to the Help search field either in RConsole or in R script editor
*/
- (void) showHelpForCurrentFunction
{
NSString *helpString = [self functionNameForCurrentScope];
if(helpString && [helpString length]) {
int oldSearchType = [[HelpManager sharedController] searchType];
[[HelpManager sharedController] setSearchType:kExactMatch];
[[HelpManager sharedController] showHelpFor:helpString];
[[HelpManager sharedController] setSearchType:oldSearchType];
return;
}
id aSearchField = nil;
NSWindow *keyWin = [NSApp keyWindow];
if(![[keyWin toolbar] isVisible])
[keyWin toggleToolbarShown:nil];
if([[self delegate] respondsToSelector:@selector(searchToolbarView)])
aSearchField = [(id)[self delegate] searchToolbarView];
if(aSearchField == nil || ![aSearchField isKindOfClass:[NSSearchField class]]) return;
[aSearchField setStringValue:[[self string] substringWithRange:[self getRangeForCurrentWord]]];
if([[aSearchField stringValue] length])
[[HelpManager sharedController] showHelpFor:[aSearchField stringValue]];
else
[[NSApp keyWindow] makeFirstResponder:aSearchField];
}
- (void)currentFunctionHint
{
NSString *helpString = [self functionNameForCurrentScope];
if(helpString && ![helpString isMatchedByRegex:@"(?s)[\\s\\[\\]\\(\\)\\{\\};\\?!]"] && [[self delegate] respondsToSelector:@selector(hintForFunction:)]) {
SLog(@"RTextView: currentFunctionHint for '%@'", helpString);
[(RController*)[self delegate] hintForFunction:helpString];
}
}
/**
* Shifts the selection, if any, rightwards by indenting any selected lines with one tab.
* If the caret is within a line, the selection is not changed after the index; if the selection
* has length, all lines crossed by the length are indented and fully selected.
* Returns whether or not an indentation was performed.
*/
- (BOOL) shiftSelectionRight
{
NSString *textViewString = [[self textStorage] string];
NSRange currentLineRange;
NSRange selectedRange = [self selectedRange];
if (selectedRange.location == NSNotFound || ![self isEditable]) return NO;
NSString *indentString = @"\t";
// if ([prefs soft]) {
// NSUInteger numberOfSpaces = [prefs soft width];
// if(numberOfSpaces < 1) numberOfSpaces = 1;
// if(numberOfSpaces > 32) numberOfSpaces = 32;
// NSMutableString *spaces = [NSMutableString string];
// for(NSUInteger i = 0; i < numberOfSpaces; i++)
// [spaces appendString:@" "];
// indentString = [NSString stringWithString:spaces];
// }
// Indent the currently selected line if the caret is within a single line
if (selectedRange.length == 0) {
// Extract the current line range based on the text caret
currentLineRange = [textViewString lineRangeForRange:selectedRange];
// Register the indent for undo
[self shouldChangeTextInRange:NSMakeRange(currentLineRange.location, 0) replacementString:indentString];
// Insert the new tab
[self replaceCharactersInRange:NSMakeRange(currentLineRange.location, 0) withString:indentString];
return YES;
}
// Otherwise, something is selected
NSRange firstLineRange = [textViewString lineRangeForRange:NSMakeRange(selectedRange.location,0)];
NSUInteger lastLineMaxRange = NSMaxRange([textViewString lineRangeForRange:NSMakeRange(NSMaxRange(selectedRange)-1,0)]);
// Expand selection for first and last line to begin and end resp. but not the last line ending
NSRange blockRange = NSMakeRange(firstLineRange.location, lastLineMaxRange - firstLineRange.location);
if([textViewString characterAtIndex:NSMaxRange(blockRange)-1] == '\n' || [textViewString characterAtIndex:NSMaxRange(blockRange)-1] == '\r')
blockRange.length--;
// Replace \n by \n\t of all lines in blockRange
NSString *newString;
// check for line ending
if([textViewString characterAtIndex:NSMaxRange(firstLineRange)-1] == '\r')
newString = [indentString stringByAppendingString:
[[textViewString substringWithRange:blockRange]
stringByReplacingOccurrencesOfString:@"\r" withString:[NSString stringWithFormat:@"\r%@", indentString]]];
else
newString = [indentString stringByAppendingString:
[[textViewString substringWithRange:blockRange]
stringByReplacingOccurrencesOfString:@"\n" withString:[NSString stringWithFormat:@"\n%@", indentString]]];
// Do insertion via insertText in order to ensure proper layouting
[self setSelectedRange:blockRange];
[self insertText:newString];
[self setSelectedRange:NSMakeRange(blockRange.location, [newString length])];
if(blockRange.length == [newString length])
return NO;
else
return YES;
}
/**
* Shifts the selection, if any, leftwards by un-indenting any selected lines by one tab if possible.
* If the caret is within a line, the selection is not changed after the undent; if the selection has
* length, all lines crossed by the length are un-indented and fully selected.
* Returns whether or not an indentation was performed.
*/
- (BOOL) shiftSelectionLeft
{
NSString *textViewString = [[self textStorage] string];
NSRange currentLineRange;
if ([self selectedRange].location == NSNotFound || ![self isEditable]) return NO;
// Undent the currently selected line if the caret is within a single line
if ([self selectedRange].length == 0) {
// Extract the current line range based on the text caret
currentLineRange = [textViewString lineRangeForRange:[self selectedRange]];
// Ensure that the line has length and that the first character is a tab
if (currentLineRange.length < 1
|| ([textViewString characterAtIndex:currentLineRange.location] != '\t' && [textViewString characterAtIndex:currentLineRange.location] != ' '))
return NO;
NSRange replaceRange;
// Check for soft indention
NSUInteger indentStringLength = 1;
// if ([prefs soft]) {
// NSUInteger numberOfSpaces = [prefs soft width];
// if(numberOfSpaces < 1) numberOfSpaces = 1;
// if(numberOfSpaces > 32) numberOfSpaces = 32;
// indentStringLength = numberOfSpaces;
// replaceRange = NSIntersectionRange(NSMakeRange(currentLineRange.location, indentStringLength), NSMakeRange(0,[[self string] length]));
// // Correct length for only white spaces
// NSString *possibleIndentString = [[[self textStorage] string] substringWithRange:replaceRange];
// NSUInteger numberOfLeadingWhiteSpaces = [possibleIndentString rangeOfRegex:@"^(\\s*)" capture:1L].length;
// if(numberOfLeadingWhiteSpaces == NSNotFound) numberOfLeadingWhiteSpaces = 0;
// replaceRange = NSMakeRange(currentLineRange.location, numberOfLeadingWhiteSpaces);
// } else {
replaceRange = NSMakeRange(currentLineRange.location, indentStringLength);
// }
// Register the undent for undo
[self shouldChangeTextInRange:replaceRange replacementString:@""];
// Remove the tab
[self replaceCharactersInRange:replaceRange withString:@""];
return YES;
}
// Otherwise, something is selected
NSRange firstLineRange = [textViewString lineRangeForRange:NSMakeRange([self selectedRange].location,0)];
NSUInteger lastLineMaxRange = NSMaxRange([textViewString lineRangeForRange:NSMakeRange(NSMaxRange([self selectedRange])-1,0)]);
// Expand selection for first and last line to begin and end resp. but the last line ending
NSRange blockRange = NSMakeRange(firstLineRange.location, lastLineMaxRange - firstLineRange.location);
if([textViewString characterAtIndex:NSMaxRange(blockRange)-1] == '\n' || [textViewString characterAtIndex:NSMaxRange(blockRange)-1] == '\r')
blockRange.length--;
// Check for soft or hard indention
NSString *indentString = @"\t";
NSUInteger indentStringLength = 1;
// if ([prefs soft]) {
// indentStringLength = [prefs soft width];
// if(indentStringLength < 1) indentStringLength = 1;
// if(indentStringLength > 32) indentStringLength = 32;
// NSMutableString *spaces = [NSMutableString string];
// for(NSUInteger i = 0; i < indentStringLength; i++)
// [spaces appendString:@" "];
// indentString = [NSString stringWithString:spaces];
// }
// Check if blockRange starts with SPACE or TAB
// (this also catches the first line of the entire text buffer or
// if only one line is selected)
NSInteger leading = 0;
if([textViewString characterAtIndex:blockRange.location] == ' '
|| [textViewString characterAtIndex:blockRange.location] == '\t')
leading += indentStringLength;
// Replace \n[ \t] by \n of all lines in blockRange
NSString *newString;
// check for line ending
if([textViewString characterAtIndex:NSMaxRange(firstLineRange)-1] == '\r')
newString = [[textViewString substringWithRange:NSMakeRange(blockRange.location+leading, blockRange.length-leading)]
stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"\r%@", indentString] withString:@"\r"];
else
newString = [[textViewString substringWithRange:NSMakeRange(blockRange.location+leading, blockRange.length-leading)]
stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"\n%@", indentString] withString:@"\n"];
// Do insertion via insertText in order to ensure proper layouting
[self setSelectedRange:blockRange];
[self insertText:newString];
[self setSelectedRange:NSMakeRange(blockRange.location, [newString length])];
if(blockRange.length == [newString length])
return NO;
else
return YES;
}
#pragma mark -
/**
* Selects matching pairs if the character before position and at position are linked
*
* @param position The cursor position to test
*/
- (void)selectMatchingPairAt:(NSInteger)position
{
if(position < 1 || position >= [[self string] length])
return;
unichar c = [[self string] characterAtIndex:position - 1];
unichar cc = 0;
switch (c) {
case '(': cc=')'; break;
case '{': cc='}'; break;
case '[': cc=']'; break;
case '"':
case '`':
case '\'':
cc=c; break;
}
if (cc) {
unichar cs = [[self string] characterAtIndex:position];
if (cs == cc) {
id attr = [[self textStorage] attribute:kTALinked atIndex:position effectiveRange:0];
if (attr) {
[self setSelectedRange:NSMakeRange(position - 1, 2)];
SLog(@"RTextView: selected matching pair");
}
}
}
}