forked from R-macos/Mac-GUI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RDocumentWinCtrl.m
2161 lines (1856 loc) · 72.3 KB
/
RDocumentWinCtrl.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 1/11/05.
*/
#import "RGUI.h"
#import "RDocumentWinCtrl.h"
#import "PreferenceKeys.h"
#import "RController.h"
#import "RDocumentController.h"
#import "REngine/REngine.h"
#import "Tools/FileCompletion.h"
#import "Tools/CodeCompletion.h"
#import "RegexKitLite.h"
#import "RTextView.h"
#import "HelpManager.h"
#import "NSTextView_RAdditions.h"
#import "RScriptEditorTextStorage.h"
#import "NSString_RAdditions.h"
#import "RWindow.h"
#import "NoodleLineNumberView.h"
#import "Tools/RTooltip.h"
// R defines "error" which is deadly as we use open ... with ... error: where error then gets replaced by Rf_error
#ifdef error
#undef error
#endif
/**
* Include all the extern variables and prototypes required for flex (used for symbol parsing)
*/
#import "RSymbolTokens.h"
// Symbol lexer
extern NSUInteger symlex();
extern NSUInteger symuoffset, symuleng;
typedef struct sym_buffer_state *SYM_BUFFER_STATE;
void sym_switch_to_buffer(SYM_BUFFER_STATE);
SYM_BUFFER_STATE sym_scan_string (const char *);
BOOL defaultsInitialized = NO;
NSColor *shColorNormal;
NSColor *shColorString;
NSColor *shColorNumber;
NSColor *shColorKeyword;
NSColor *shColorComment;
NSColor *shColorIdentifier;
NSInteger _alphabeticSort(id string1, id string2, void *reverse);
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;
}
@implementation RDocumentWinCtrl
//- (id)init { // NOTE: init is *not* used! put any initialization in windowDidLoad
static RDocumentWinCtrl *staticCodedRWC = nil;
// FIXME: this is a very, very ugly hack to work around a bug in Cocoa:
// "Customize Toolbar.." creates a copy of the custom views in the tollbar and
// one of it is the help search view (defined in the RDocument NIB). It turns
// out that a copy is made by encoding and decoding it. However, due to some
// strange bug in Cocoa this leads to instantiation of RDocumentWinCtrl via initWithCoder:
// which is then released immediately. This leads to a crash, so we work
// around this by retaining that copy thus making sure it won't be released.
// In order to reduce the memory overhead we keep around only one instance
// of this "special" controller and keep returning it.
- (id)initWithCoder: (NSCoder*) coder {
SLog(@"RDocumentWinCtrl.initWithCoder<%@>: %@ **** this is due to a bug in Cocoa! Working around it:", self, coder);
if (!staticCodedRWC) {
staticCodedRWC = [super initWithCoder:coder];
SLog(@" - creating static answer: %@", staticCodedRWC);
} else {
SLog(@" - release original, return static answer %@", staticCodedRWC);
[self release];
self = staticCodedRWC;
}
return [self retain]; // add a retain because it will be matched by the caller
}
- (void)dealloc {
SLog(@"RDocumentWinCtrl.dealloc<%@>", self);
[[NSNotificationCenter defaultCenter] removeObserver:self];
[[Preferences sharedPreferences] removeDependent:self];
[texItems release];
if (helpTempFile) [[NSFileManager defaultManager] removeFileAtPath:helpTempFile handler:nil];
if (functionMenuInvalidAttribute) [functionMenuInvalidAttribute release];
if (pragmaMenuAttribute) [pragmaMenuAttribute release];
if (functionMenuCommentAttribute) [functionMenuCommentAttribute release];
[super dealloc];
}
/**
* Sort function (mainly used to sort the words in the textView)
*/
NSInteger _alphabeticSort(id string1, id string2, void *reverse)
{
return [string1 localizedCaseInsensitiveCompare:string2];
}
/**
* 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:prefShowArgsHints])
argsHints = [Preferences flagForKey:prefShowArgsHints withDefault:YES];
else if ([keyPath isEqualToString:showBraceHighlightingKey])
showMatchingBraces = [Preferences flagForKey:showBraceHighlightingKey withDefault:YES];
}
- (void) replaceContentsWithRtf: (NSData*) rtfContents
{
[textView replaceCharactersInRange:
NSMakeRange(0, [[textView textStorage] length])
withRTF:rtfContents];
[textView setSelectedRange:NSMakeRange(0,0)];
}
- (void)layoutTextView
{
[[textView layoutManager] ensureLayoutForCharacterRange:NSMakeRange([[textView string] length],0)];
}
- (void) replaceContentsWithString: (NSString*) strContents
{
[textView setString:strContents];
#if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
[textView setSelectedRange:NSMakeRange(0,0)];
[self performSelector:@selector(layoutTextView) withObject:nil afterDelay:0.5];
#endif
[[self window] setDocumentEdited:NO];
}
- (NSData*) contentsAsRtf
{
return [textView RTFFromRange:
NSMakeRange(0, [[textView string] length])];
}
- (NSString*) contentsAsString
{
return [textView string];
}
- (NSTextView *) textView {
return textView;
}
- (void) setPlain: (BOOL) plain
{
plainFile=plain;
if (plain && useHighlighting && textView)
[textView setTextColor:shColorNormal range:NSMakeRange(0,[[textView textStorage] length])];
else if (!plain && useHighlighting && textView)
[textView performSelector:@selector(doSyntaxHighlighting) withObject:nil afterDelay:0.0];
}
- (BOOL) plain
{
return plainFile;
}
- (BOOL) isRdDocument
{
return ([[[self document] fileType] isEqualToString:ftRdDoc]) ? YES : NO;
}
// fileEncoding is passed through to the document - bound by the save box
- (int) fileEncoding
{
SLog(@"%@ fileEncoding (%@ gives %d)", self, [self document], [[self document] fileEncoding]);
return [[self document] fileEncoding];
}
- (void) setFileEncoding: (int) encoding
{
SLog(@"%@ setFileEncoding: %d (doc %@)", self, encoding, [self document]);
[[self document] setFileEncoding:encoding];
}
- (id) initWithWindowNibName:(NSString*) nib
{
self = [super initWithWindowNibName:nib];
SLog(@"RDocumentWinCtrl<%@>.initWithNibName:%@", self, nib);
if (self) {
plainFile=NO;
hsType=1;
currentHighlight=-1;
updating=NO;
helpTempFile=nil;
execNewlineFlag=NO;
lastLineWasCodeIndented = NO;
isFormattingRcode = NO;
isFunctionScanning = NO;
texItems = [[NSArray arrayWithObjects:
@"R",
@"RdOpts",
@"Rdversion",
@"CRANpkg",
@"S3method",
@"S4method",
@"Sexpr",
@"acronym",
@"alias",
@"arguments",
@"author",
@"begin",
@"bold",
@"cite",
@"code",
@"command",
@"concept",
@"cr",
@"dQuote",
@"deqn",
@"describe",
@"description",
@"details",
@"dfn",
@"docType",
@"dontrun",
@"dontshow",
@"donttest",
@"dots",
@"email",
@"emph",
@"enc",
@"encoding",
@"end",
@"enumerate",
@"env",
@"eqn",
@"examples",
@"file",
@"figure",
@"format",
@"ge",
@"href",
@"if",
@"ifelse",
@"item",
@"itemize",
@"kbd",
@"keyword",
@"ldots",
@"left",
@"link",
@"linkS4class",
@"method",
@"name",
@"newcommand",
@"note",
@"option",
@"out",
@"pkg",
@"preformatted",
@"references",
@"renewcommand",
@"right",
@"sQuote",
@"samp",
@"section",
@"seealso",
@"source",
@"special",
@"strong",
@"subsection",
@"synopsis",
@"tab",
@"tabular",
@"testonly",
@"title",
@"url",
@"usage",
@"value",
@"var",
@"verb",
nil] retain];
[self setShouldCloseDocument:YES];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(helpSearchTypeChanged)
name:@"HelpSearchTypeChanged"
object:nil];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(RDocumentDidResize:)
name:NSWindowDidResizeNotification
object:nil];
}
return self;
}
// we don't need this one, because the default implementation automatically calls the one w/o owner
// - (id) initWithWindowNibName:(NSString*) nib owner: (id) owner
- (void) windowDidLoad
{
SLog(@"RDocumentWinCtrl(%@).windowDidLoad", self);
// Add full screen support for MacOSX Lion or higher
// [[self window] setCollectionBehavior:[[self window] collectionBehavior] | NSWindowCollectionBehaviorFullScreenPrimary];
showMatchingBraces = [Preferences flagForKey:showBraceHighlightingKey withDefault: YES];
argsHints = [Preferences flagForKey:prefShowArgsHints withDefault:YES];
[[NSUserDefaults standardUserDefaults] addObserver:self forKeyPath:showBraceHighlightingKey options:NSKeyValueObservingOptionNew context:NULL];
[[NSUserDefaults standardUserDefaults] addObserver:self forKeyPath:prefShowArgsHints options:NSKeyValueObservingOptionNew context:NULL];
// FIXME: we did we use this?
//[[self window] setBackgroundColor:[NSColor clearColor]];
//[[self window] setOpaque:NO];
SLog(@" - load document contents into textView");
[(RDocument*)[self document] loadInitialContents];
// If not line wrapping update textView explicitly in order to set scrollView correctly
if(![Preferences flagForKey:enableLineWrappingKey withDefault: YES])
[textView updateLineWrappingMode];
[[textView undoManager] removeAllActions];
[self helpSearchTypeChanged];
if(plainFile) [fnListBox setHidden:YES];
[super windowDidLoad];
[[self window] makeKeyAndOrderFront:self];
// TODO control font size due to tollbar setting small or normal
// now the new size will set for any new opened doc
pragmaMenuAttribute = [[NSDictionary dictionaryWithObjectsAndKeys:
[NSColor blueColor], NSForegroundColorAttributeName,
[fnListBox font], NSFontAttributeName,
nil] retain];
functionMenuInvalidAttribute = [[NSDictionary dictionaryWithObjectsAndKeys:
[NSColor redColor], NSForegroundColorAttributeName,
[fnListBox font], NSFontAttributeName,
nil] retain];
functionMenuCommentAttribute =[[NSDictionary dictionaryWithObjectsAndKeys:
[NSColor grayColor], NSForegroundColorAttributeName,
[fnListBox font], NSFontAttributeName,
nil] retain];
SLog(@" - scan document for functions");
// [self functionRescan];
if([textView lineNumberingEnabled]) {
SLog(@" - set up line numbering for text view");
NoodleLineNumberView *theRulerView = [[NoodleLineNumberView alloc] initWithScrollView:[textView enclosingScrollView]];
[[textView enclosingScrollView] setVerticalRulerView:theRulerView];
[[textView enclosingScrollView] setHasHorizontalRuler:NO];
[[textView enclosingScrollView] setHasVerticalRuler:YES];
[[textView enclosingScrollView] setRulersVisible:YES];
[theRulerView release];
[(NoodleLineNumberView*)[[textView enclosingScrollView] verticalRulerView] setLineWrappingMode:[Preferences flagForKey:enableLineWrappingKey withDefault: YES]];
[[self window] makeFirstResponder:theRulerView];
}
[self functionReset];
// Needed for showing tooltips of folded items
[[self window] setAcceptsMouseMovedEvents:YES];
// FIXME: this is a hack for layout issues in Big Sur
// by forcing re-size we force layout to be updated - is there a better way?
NSRect clRect = [[self window] contentLayoutRect];
clRect.size.width += 1;
[[self window] setContentSize:clRect.size];
clRect.size.width -= 1;
[[self window] setContentSize:clRect.size];
// Make the text view fist responder so the user can start typing
[[self window] makeFirstResponder:textView];
SLog(@" - windowDidLoad is done");
return;
}
- (void) RDocumentDidResize: (NSNotification *)notification
{
[self setStatusLineText:[self statusLineText]];
}
- (NSView*) saveOpenAccView
{
return saveOpenAccView;
}
- (NSUndoManager*) windowWillReturnUndoManager: (NSWindow*) sender
{
return [[self document] undoManager];
}
- (void) setStatusLineText: (NSString*) text
{
SLog(@"RDocumentWinCtrl.setStatusLine: \"%@\"", [text description]);
if(text == nil || ![text length]) {
[statusLine setStringValue:@""];
[statusLine setToolTip:@""];
return;
}
// Adjust status line to show a single line in the middle of the status bar
// otherwise to come up with at least two visible lines
float w = NSSizeToCGSize([text sizeWithAttributes:[NSDictionary dictionaryWithObject:[statusLine font] forKey:NSFontAttributeName]]).width + 2.0f;
NSSize p = [statusLine frame].size;
p.height = (w > p.width) ? 22 : 17;
[statusLine setFrameSize:p];
[statusLine setToolTip:text];
[statusLine setStringValue:text];
[statusLine setNeedsDisplay:YES];
// Run NSDefaultRunLoopMode to allow to update status line
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
beforeDate:[NSDate distantPast]];
}
- (BOOL) hintForFunction: (NSString*) fn
{
BOOL success = NO;
if([[self document] hasREditFlag]) {
[self setStatusLineText:NLS(@"(arguments lookup is disabled while R is busy)")];
return NO;
}
if (preventReentrance && insideR>0) {
[self setStatusLineText:NLS(@"(arguments lookup is disabled while R is busy)")];
return NO;
}
if (![[REngine mainEngine] beginProtected]) {
[self setStatusLineText:NLS(@"(arguments lookup is disabled while R is busy)")];
return NO;
}
RSEXP *x = [[REngine mainEngine] evaluateString:[NSString stringWithFormat:@"try(gsub('\\\\s+',' ',paste(capture.output(print(args(%@))),collapse='')),silent=TRUE)", fn]];
if (x) {
NSString *res = [x string];
if (res && [res length]>10 && [res hasPrefix:@"function"]) {
NSRange lastClosingParenthesis = [res rangeOfString:@")" options:NSBackwardsSearch];
if(lastClosingParenthesis.length) {
res = [res substringToIndex:NSMaxRange(lastClosingParenthesis)];
res = [fn stringByAppendingString:[res substringFromIndex:9]];
success = YES;
[self setStatusLineText:res];
}
}
[x release];
}
[[REngine mainEngine] endProtected];
return success;
}
- (NSString*) statusLineText
{
return [statusLine stringValue];
}
- (void) functionReset
{
SLog(@"RDocumentWinCtrl.functionReset");
if (fnListBox) {
NSString *placeHolderStr = @"";
NSString *tooltipStr = @"";
if([[[self document] fileType] isEqualToString:ftRSource]) {
placeHolderStr = NLS(@"<functions>");
tooltipStr = NLS(@"List of Functions");
}
else if([[[self document] fileType] isEqualToString:ftRdDoc]) {
placeHolderStr = NLS(@"<sections>");
tooltipStr = NLS(@"List of Sections");
}
NSMenuItem *fmi = [[NSMenuItem alloc] initWithTitle:placeHolderStr action:nil keyEquivalent:@""];
[fmi setTag:-1];
[fnListBox removeAllItems];
[fnListBox setToolTip:tooltipStr];
[[fnListBox menu] addItem:fmi];
[fmi release];
[fnListBox setEnabled:NO];
}
SLog(@" - reset done");
}
- (void) functionAdd: (NSString*) fn atPosition: (int) pos
{
if (fnListBox) {
[fnListBox setEnabled:YES];
if ([[[fnListBox menu] itemAtIndex:0] tag]==-1)
[fnListBox removeAllItems];
NSMenuItem *mi = [fnListBox itemWithTitle:fn];
if (!mi) {
mi = [[NSMenuItem alloc] initWithTitle:fn action:@selector(goFunction:) keyEquivalent:@""];
[mi setTag: pos];
[[fnListBox menu] addItem:mi];
} else {
[mi setTag:pos];
}
}
}
- (void) functionGo: (id) sender
{
NSString *s = [[textView textStorage] string];
NSMenuItem *mi = (NSMenuItem*) sender;
int pos = [mi tag];
if (pos>=0 && pos<[s length]) {
NSRange fr = NSMakeRange(pos,0);
[textView setSelectedRange:fr];
[textView scrollRangeToVisible:fr];
}
}
- (BOOL) isFunctionScanning
{
return isFunctionScanning;
}
- (void) functionRescan
{
if(plainFile || isFunctionScanning || [textView isSyntaxHighlighting]) {
if(plainFile)
[fnListBox setEnabled:NO];
return;
}
// Cancel pending functionRescan calls
[NSObject cancelPreviousPerformRequestsWithTarget:self
selector:@selector(functionRescan)
object:nil];
if([textView breakSyntaxHighlighting]) {
// Cancel calling functionRescan
[NSObject cancelPreviousPerformRequestsWithTarget:self
selector:@selector(functionRescan)
object:nil];
[self performSelector:@selector(functionRescan) withObject:nil afterDelay:0.3f];
return;
}
isFunctionScanning = YES;
NSTextStorage *ts = [textView textStorage];
NSString *s = [ts string];
unsigned long strLength = [s length];
int oix = 0;
int pim = 0;
int sit = 0;
int fnf = 0;
NSMenu *fnm = [fnListBox menu];
NSRange sr = [textView selectedRange];
[self functionReset];
if([s length]<8) {
isFunctionScanning = NO;
return;
}
NSString *fn = nil;
NSMenuItem *mi = nil;
NSAttributedString *fna = nil;
SLog(@"RDoumentWinCtrl.functionRescan");
if([[[self document] fileType] isEqualToString:ftRSource]) {
NSInteger level = 0; // counter for function declaration inside a function declaration
// Dummy string for generating n times the string " " for structuring the menu
NSString *levelTemplate = @" ";
NSArray *d = nil;
// initialise flex
size_t token;
NSRange tokenRange;
symuoffset = 0; symuleng = 0;
sym_switch_to_buffer(sym_scan_string(NSStringUTF8String(s)));
// now loop through all the tokens
while ((token = symlex())) {
if([textView breakSyntaxHighlighting]) {
isFunctionScanning = NO;
return;
}
switch (token) {
case RSYM_FUNCTION: // a valid function name was found
fn = [NSString stringWithFormat:@" %@%@%@",
[levelTemplate substringWithRange:NSMakeRange(0,(level>16) ? 48 : (level*3))],
(level)?@" └ ":@"",
[s substringWithRange:NSMakeRange(symuoffset, symuleng)]];
fn = [fn stringByReplacingOccurrencesOfRegex:@"\\s*<.*" withString:@""];
mi = nil;
SLog(@" - found function %d:%d \"%@\"", symuoffset, symuleng, fn);
fnf++;
if (symuoffset<=sr.location) sit=pim;
mi = [[NSMenuItem alloc] initWithTitle:fn action:@selector(functionGo:) keyEquivalent:@""];
[mi setTag:symuoffset];
[mi setTarget:self];
[fnm addItem:mi];
[mi release];
pim++;
break;
case RSYM_INV_FUNCTION: // an invalid function name was found
fn = [NSString stringWithFormat:@" %@%@%@",
[levelTemplate substringWithRange:NSMakeRange(0,(level>16) ? 48 : (level*3))],
(level)?@" └ ":@"",
[s substringWithRange:NSMakeRange(symuoffset, symuleng)]];
fn = [fn stringByReplacingOccurrencesOfRegex:@"\\s*<.*" withString:@""];
mi = nil;
SLog(@" - found invalid function %d:%d \"%@\"", symuoffset, symuleng, fn);
fnf++;
if (symuoffset<=sr.location) sit=pim;
mi = [[NSMenuItem alloc] initWithTitle:fn action:@selector(functionGo:) keyEquivalent:@""];
fna = [[NSAttributedString alloc] initWithString:fn attributes:functionMenuInvalidAttribute];
[mi setAttributedTitle:fna];
[fna release];
[mi setTag:symuoffset];
[mi setTarget:self];
[fnm addItem:mi];
[mi release];
pim++;
break;
case RSYM_METHOD1: // setMethod(f, sig)
d = [s captureComponentsMatchedByRegex:@"(?m)([\"'])([^\"']+)\\1[^\"']+?([\"'])([^\"']+)\\3" range:NSMakeRange(symuoffset, symuleng)];
if(d && [d count] == 5) {
fn = [NSString stringWithFormat:@" %@%@- %@ (%@)",
[levelTemplate substringWithRange:NSMakeRange(0,(level>16) ? 48 : (level*3))],
(level)?@" └ ":@"",
[d objectAtIndex:2],
[d lastObject]];
mi = nil;
SLog(@" - found method1 %d:%d \"%@\"", symuoffset, symuleng, fn);
fnf++;
if (symuoffset<=sr.location) sit=pim;
mi = [[NSMenuItem alloc] initWithTitle:fn action:@selector(functionGo:) keyEquivalent:@""];
[mi setTag:symuoffset];
[mi setTarget:self];
[fnm addItem:mi];
[mi release];
pim++;
}
break;
case RSYM_METHOD2: // setMethod(sig, f)
d = [s captureComponentsMatchedByRegex:@"(?m)([\"'])([^\"']+)\\1[^\"']+?([\"'])([^\"']+)\\3" range:NSMakeRange(symuoffset, symuleng)];
if(d && [d count] == 5) {
fn = [NSString stringWithFormat:@" %@%@- %@ (%@)",
[levelTemplate substringWithRange:NSMakeRange(0,(level>16) ? 48 : (level*3))],
(level)?@" └ ":@"",
[d lastObject],
[d objectAtIndex:2]];
mi = nil;
SLog(@" - found method2 %d:%d \"%@\"", symuoffset, symuleng, fn);
fnf++;
if (symuoffset<=sr.location) sit=pim;
mi = [[NSMenuItem alloc] initWithTitle:fn action:@selector(functionGo:) keyEquivalent:@""];
[mi setTag:symuoffset];
[mi setTarget:self];
[fnm addItem:mi];
[mi release];
pim++;
}
break;
case RSYM_CLASS: // setClass
tokenRange = NSMakeRange(symuoffset, symuleng);
fn = [NSString stringWithFormat:@" %@%@- (%@)",
[levelTemplate substringWithRange:NSMakeRange(0,(level>16) ? 48 : (level*3))],
(level)?@" └ ":@"",
[[s substringWithRange:tokenRange] stringByMatching:@"([\"'])([^\"']+)\\1" capture:2L]];
mi = nil;
SLog(@" - found class %d:%d \"%@\"", symuoffset, symuleng, fn);
fnf++;
if (symuoffset<=sr.location) sit=pim;
mi = [[NSMenuItem alloc] initWithTitle:fn action:@selector(functionGo:) keyEquivalent:@""];
[mi setTag:symuoffset];
[mi setTarget:self];
[fnm addItem:mi];
[mi release];
pim++;
break;
case RSYM_PRAGMA: // a literal pragma mark was found; it will displayed in blue to structure large R scripts
fn = [[s substringWithRange:NSMakeRange(symuoffset, symuleng)] stringByMatching:@"^(#pragma\\s+mark\\s+)(.*?)\\s*$" capture:2L];
mi = nil;
SLog(@" - found pragma %d:%d \"%@\"", symuoffset, symuleng, fn);
fnf++;
if (symuoffset<=sr.location) sit=pim;
mi = [[NSMenuItem alloc] initWithTitle:fn action:@selector(functionGo:) keyEquivalent:@""];
fna = [[NSAttributedString alloc] initWithString:fn attributes:pragmaMenuAttribute];
[mi setAttributedTitle:fna];
[fna release];
[mi setTag:symuoffset];
[mi setTarget:self];
[fnm addItem:mi];
[mi release];
pim++;
break;
case RSYM_PRAGMA_LINE: // insert a menu separator line
mi = nil;
SLog(@" - found identifier for separator");
fnf++;
if (symuoffset<=sr.location) sit=pim;
[fnm addItem:[NSMenuItem separatorItem]];
pim++;
break;
case RSYM_LEVEL_DOWN: // { was found; increase level
level++;
break;
case RSYM_LEVEL_UP: // } was found; decrease level
level--;
if(level<0) level = 0;
break;
default:
;
}
}
}
else if([[[self document] fileType] isEqualToString:ftRdDoc]) {
while (1) {
NSError *err = nil;
NSRange r = [s rangeOfRegex:@"\\\\(s(ynopsis\\{|ource\\{|ubsection\\{|e(ction\\{|ealso\\{))|Rd(Opts\\{|version\\{)|n(ote\\{|ame\\{)|concept\\{|title\\{|Sexpr(\\{|\\[)|d(ocType\\{|e(scription\\{|tails\\{))|usage\\{|e(ncoding\\{|xamples\\{)|value\\{|keyword\\{|format\\{|a(uthor\\{|lias\\{|rguments\\{)|references\\{)" options:0 inRange:NSMakeRange(oix,strLength-oix) capture:1 error:&err];
// RdOpts{, Rdversion{, Sexpr[, Sexpr{, alias{, arguments{, author{, concept{, description{, details{, docType{, encoding{, examples{, format{, keyword{, name{, note{, references{, section{, seealso{, source{, synopsis{, title{, usage{, value{
// Break if nothing is found
if (!r.length) break;
if (err) break;
oix = NSMaxRange(r);
SLog(@" - potential section at %d \"\"", r.location, fn);
int li = r.location-1;
unichar fc;
while (li>0 && ((fc=CFStringGetCharacterAtIndex((CFStringRef)s, li)) ==' ' || fc=='\t' || fc=='\r' || fc=='\n')) li--;
if([textView parserContextForPosition: li + 2] == pcComment)
continue; // section declaration is commented out
// due to finial bracket decrease range length by 1
r.length--;
fn = [s substringWithRange:r];
// get (sub)section name
if([fn isEqualToString:@"section"] || [fn isEqualToString:@"subsection"]) {
BOOL found = NO;
NSInteger start = oix;
NSInteger i = start;
NSInteger nameLen = 0;
while(i < strLength) {
if( CFStringGetCharacterAtIndex((CFStringRef)s,i) == '}' ) {
found = YES;
break;
}
i++;
nameLen++;
if( nameLen > 99 ) {
break;
}
}
fn = [NSString stringWithFormat:@"%@ - %@%@",
fn,
[s substringWithRange:NSMakeRange(start, nameLen)],
(found) ? @"" : (nameLen<100) ? @"~" : @"…"];
}
int fp = r.location-1;
mi = nil;
fnf++;
if (fp<=sr.location) sit=pim;
mi = [[NSMenuItem alloc] initWithTitle:fn action:@selector(functionGo:) keyEquivalent:@""];
[mi setTag:fp];
[mi setTarget:self];
[fnm addItem:mi];
[mi release];
pim++;
}
}
if (fnf) {
[fnListBox setEnabled:YES];
[fnListBox removeItemAtIndex:0];
[fnListBox selectItemAtIndex:sit];
}
isFunctionScanning = NO;
SLog(@" - rescan finished (%d sections)", fnf);
}
- (void) updatePreferences {
SLog(@"RDocumentWinCtrl.updatePreferences");
// for sanity's sake
// if (!defaultsInitialized) {
// [RDocumentWinCtrl setDefaultSyntaxHighlightingColors];
// defaultsInitialized=YES;
// }
//
// NSColor *c = [Preferences unarchivedObjectForKey: backgColorKey withDefault: nil];
// if (c && c != [[self window] backgroundColor]) {
// [[self window] setBackgroundColor:c];
// // [[self window] display];
// }
// c=[Preferences unarchivedObjectForKey:normalSyntaxColorKey withDefault:nil];
// if (c) { [shColorNormal release]; shColorNormal = [c retain]; [textView setInsertionPointColor:c]; }
// c=[Preferences unarchivedObjectForKey:stringSyntaxColorKey withDefault:nil];
// if (c) { [shColorString release]; shColorString = [c retain]; }
// c=[Preferences unarchivedObjectForKey:numberSyntaxColorKey withDefault:nil];
// if (c) { [shColorNumber release]; shColorNumber = [c retain]; }
// c=[Preferences unarchivedObjectForKey:keywordSyntaxColorKey withDefault:nil];
// if (c) { [shColorKeyword release]; shColorKeyword = [c retain]; }
// c=[Preferences unarchivedObjectForKey:commentSyntaxColorKey withDefault:nil];
// if (c) { [shColorComment release]; shColorComment = [c retain]; }
// c=[Preferences unarchivedObjectForKey:identifierSyntaxColorKey withDefault:nil];
// if (c) { [shColorIdentifier release]; shColorIdentifier = [c retain]; }
// argsHints=[Preferences flagForKey:prefShowArgsHints withDefault:YES];
//
// [self setHighlighting:[Preferences flagForKey:showSyntaxColoringKey withDefault: YES]];
// showMatchingBraces = [Preferences flagForKey:showBraceHighlightingKey withDefault: YES];
// [textView setNeedsDisplay:YES];
SLog(@" - preferences updated");
}
- (IBAction)saveDocumentAs:(id)sender
{
RDocument *cd = [[RDocumentController sharedDocumentController] currentDocument];
// if cd document is a REdit call do not allow to save it under another name
// to preserving REdit editing
if (cd && [cd hasREditFlag]) {
[cd saveDocument:sender];
return;
}
[cd saveDocumentAs:sender];
}
- (IBAction)saveDocument:(id)sender
{
RDocument *cd = [[RDocumentController sharedDocumentController] currentDocument];
// if cd document is a REdit call ensure that the last character is a line ending
// to avoid error in edit()
if (cd && [cd hasREditFlag]) {
NSRange selectedRange = [textView selectedRange];
if(![[textView string] length])
[[[textView textStorage] mutableString] setString:@"\n"];
if([[textView string] characterAtIndex:[[textView string] length]-1] != '\n') {
[[[textView textStorage] mutableString] appendString:@"\n"];
[textView setSelectedRange:NSIntersectionRange(selectedRange, NSMakeRange(0, [[textView string] length]))];
}
}
[cd saveDocument:sender];
}
- (IBAction)printDocument:(id)sender
{
NSPrintInfo *printInfo;
NSPrintInfo *sharedInfo;
NSPrintOperation *printOp;
NSMutableDictionary *printInfoDict;
NSMutableDictionary *sharedDict;
sharedInfo = [NSPrintInfo sharedPrintInfo];
sharedDict = [sharedInfo dictionary];
printInfoDict = [NSMutableDictionary dictionaryWithDictionary:
sharedDict];
printInfo = [[NSPrintInfo alloc] initWithDictionary: printInfoDict];
[printInfo setHorizontalPagination: NSFitPagination];
[printInfo setVerticalPagination: NSAutoPagination];
[printInfo setVerticallyCentered:NO];
[textView setBackgroundColor:[NSColor whiteColor]];
printOp = [NSPrintOperation printOperationWithView:textView
printInfo:printInfo];
[printOp setShowPanels:YES];
[printOp runOperationModalForWindow:[self window]
delegate:self
didRunSelector:@selector(sheetDidEnd:returnCode:contextInfo:)
contextInfo:@""];
[self updatePreferences];
}
- (IBAction)reInterpretDocument:(id)sender;
{
RDocument* doc = [[NSDocumentController sharedDocumentController] documentForWindow:[NSApp keyWindow]];
if(doc)
[doc reinterpretInEncoding:(NSStringEncoding)[[sender representedObject] unsignedIntValue]];
else
NSBeep();
}
- (IBAction)shiftRight:(id)sender
{
[textView shiftSelectionRight];
}
- (IBAction)shiftLeft:(id)sender
{
[textView shiftSelectionLeft];
}
- (IBAction)goToLine:(id)sender
{
[NSApp beginSheet:goToLineSheet
modalForWindow:[self window]
modalDelegate:self
didEndSelector:@selector(sheetDidEnd:returnCode:contextInfo:)
contextInfo:@"goToLine"];
}
- (IBAction)goToLineCloseSheet:(id)sender
{
[NSApp endSheet:goToLineSheet returnCode:[sender tag]];
}
- (void) setHighlighting: (BOOL) use
{
useHighlighting=use;
if (textView) {
if (use)
[textView performSelector:@selector(doSyntaxHighlighting) withObject:nil afterDelay:0.0];
else
[textView setTextColor:[NSColor blackColor] range:NSMakeRange(0,[[textView textStorage] length])];
}
}
- (void)highlightBracesAfterDidProcessEditing
{
[self highlightBracesWithShift:0 andWarn:YES];
}
- (void) highlightBracesWithShift: (int) shift andWarn: (BOOL) warn
{
NSString *completeString = [[textView textStorage] string];
NSUInteger completeStringLength = [completeString length];
if (completeStringLength < 2) return;
NSRange selRange = [textView selectedRange];