-
Notifications
You must be signed in to change notification settings - Fork 134
/
SMLTextView.m
1213 lines (969 loc) · 39.1 KB
/
SMLTextView.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
/*
MGSFragaria
Written by Jonathan Mitchell, [email protected]
Find the latest version at https://github.com/mugginsoft/Fragaria
Smultron version 3.6b1, 2009-09-12
Written by Peter Borg, [email protected]
Find the latest version at http://smultron.sourceforge.net
Copyright 2004-2009 Peter Borg
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
#import "MGSFragaria.h"
#import "MGSFragariaFramework.h"
#import "SMLAutoCompleteDelegate.h"
static char SMLTextFontChanged;
static char SMLTextColourChanged;
static char SMLBackgroundColourChanged;
static char SMLSmartInsertDeleteChanged;
static char SMLTabWidthChanged;
static char SMLPageGuideChanged;
// class extension
@interface SMLTextView()
- (void)windowDidBecomeMainOrKey:(NSNotification *)note;
@property (strong) NSColor *pageGuideColour;
@end
@implementation SMLTextView
@synthesize colouredIBeamCursor, fragaria, pageGuideColour, lineWrap;
#pragma mark -
#pragma mark Instance methods
/*
- initWithFrame:
*/
- (id)initWithFrame:(NSRect)frame
{
if ((self = [super initWithFrame:frame])) {
SMLLayoutManager *layoutManager = [[SMLLayoutManager alloc] init];
[[self textContainer] replaceLayoutManager:layoutManager];
[self setDefaults];
// set initial line wrapping
lineWrap = YES;
[self updateLineWrap];
}
return self;
}
#pragma mark -
#pragma mark Accessors
/*
- lineHeight
*/
- (NSInteger)lineHeight
{
return lineHeight;
}
/*
- setDefaults
*/
- (void)setDefaults
{
[self setTabWidth];
[self setVerticallyResizable:YES];
[self setMaxSize:NSMakeSize(FLT_MAX, FLT_MAX)];
[self setAutoresizingMask:NSViewWidthSizable];
[self setAllowsUndo:YES];
if ([self respondsToSelector:@selector(setUsesFindBar:)]) {
[self setUsesFindBar:YES];
[self setIncrementalSearchingEnabled:NO];
} else {
[self setUsesFindPanel:YES];
}
[self setAllowsDocumentBackgroundColorChange:NO];
[self setRichText:NO];
[self setImportsGraphics:NO];
[self setUsesFontPanel:NO];
[self setContinuousSpellCheckingEnabled:[[SMLDefaults valueForKey:MGSFragariaPrefsAutoSpellCheck] boolValue]];
[self setGrammarCheckingEnabled:[[SMLDefaults valueForKey:MGSFragariaPrefsAutoGrammarCheck] boolValue]];
[self setSmartInsertDeleteEnabled:[[SMLDefaults valueForKey:MGSFragariaPrefsSmartInsertDelete] boolValue]];
[self setAutomaticLinkDetectionEnabled:[[SMLDefaults valueForKey:MGSFragariaPrefsAutomaticLinkDetection] boolValue]];
[self setAutomaticQuoteSubstitutionEnabled:[[SMLDefaults valueForKey:MGSFragariaPrefsAutomaticQuoteSubstitution] boolValue]];
[self setTextDefaults];
[self setAutomaticDataDetectionEnabled:YES];
[self setAutomaticTextReplacementEnabled:YES];
[self setPageGuideValues];
[self updateIBeamCursor];
NSTrackingArea *trackingArea = [[NSTrackingArea alloc] initWithRect:[self frame] options:(NSTrackingMouseEnteredAndExited | NSTrackingActiveWhenFirstResponder) owner:self userInfo:nil];
[self addTrackingArea:trackingArea];
NSUserDefaultsController *defaultsController = [NSUserDefaultsController sharedUserDefaultsController];
[defaultsController addObserver:self forKeyPath:@"values.FragariaTextFont" options:NSKeyValueObservingOptionNew context:&SMLTextFontChanged];
[defaultsController addObserver:self forKeyPath:@"values.FragariaTextColourWell" options:NSKeyValueObservingOptionNew context:&SMLTextColourChanged];
[defaultsController addObserver:self forKeyPath:@"values.FragariaBackgroundColourWell" options:NSKeyValueObservingOptionNew context:&SMLBackgroundColourChanged];
[defaultsController addObserver:self forKeyPath:@"values.FragariaSmartInsertDelete" options:NSKeyValueObservingOptionNew context:&SMLSmartInsertDeleteChanged];
[defaultsController addObserver:self forKeyPath:@"values.FragariaTabWidth" options:NSKeyValueObservingOptionNew context:&SMLTabWidthChanged];
[defaultsController addObserver:self forKeyPath:@"values.FragariaShowPageGuide" options:NSKeyValueObservingOptionNew context:&SMLPageGuideChanged];
[defaultsController addObserver:self forKeyPath:@"values.FragariaShowPageGuideAtColumn" options:NSKeyValueObservingOptionNew context:&SMLPageGuideChanged];
[defaultsController addObserver:self forKeyPath:@"values.FragariaSmartInsertDelete" options:NSKeyValueObservingOptionNew context:&SMLSmartInsertDeleteChanged];
lineHeight = [[[self textContainer] layoutManager] defaultLineHeightForFont:[NSUnarchiver unarchiveObjectWithData:[SMLDefaults valueForKey:MGSFragariaPrefsTextFont]]];
}
/*
- setTextDefaults
*/
- (void)setTextDefaults
{
[self setFont:[NSUnarchiver unarchiveObjectWithData:[SMLDefaults valueForKey:MGSFragariaPrefsTextFont]]];
[self setTextColor:[NSUnarchiver unarchiveObjectWithData:[SMLDefaults valueForKey:MGSFragariaPrefsTextColourWell]]];
[self setInsertionPointColor:[NSUnarchiver unarchiveObjectWithData:[SMLDefaults valueForKey:MGSFragariaPrefsTextColourWell]]];
[self setBackgroundColor:[NSUnarchiver unarchiveObjectWithData:[SMLDefaults valueForKey:MGSFragariaPrefsBackgroundColourWell]]];
}
/*
- setFrame:
*/
- (void)setFrame:(NSRect)rect
{
[super setFrame:rect];
[[fragaria objectForKey:ro_MGSFOLineNumbers] updateLineNumbersForClipView:[[self enclosingScrollView] contentView] checkWidth:NO recolour:YES];
}
#pragma mark -
#pragma mark Copy and paste
/*
- paste
*/
-(void)paste:(id)sender
{
// let super paste
[super paste:sender];
// add the NSTextView to the info dict
NSDictionary *info = @{@"NSTextView": self};
// send paste notification
NSNotification *note = [NSNotification notificationWithName:@"MGSTextDidPasteNotification" object:self userInfo:info];
[[NSNotificationCenter defaultCenter] postNotification:note];
// inform delegate of Fragaria paste
if ([self.delegate respondsToSelector:@selector(mgsTextDidPaste:)]) {
[(id)self.delegate mgsTextDidPaste:note];
}
}
#pragma mark -
#pragma mark KVO
/*
- observeValueForKeyPath:ofObject:change:context:
*/
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if (context == &SMLTextFontChanged) {
[self setFont:[NSUnarchiver unarchiveObjectWithData:[SMLDefaults valueForKey:MGSFragariaPrefsTextFont]]];
lineHeight = [[[self textContainer] layoutManager] defaultLineHeightForFont:[NSUnarchiver unarchiveObjectWithData:[SMLDefaults valueForKey:MGSFragariaPrefsTextFont]]];
[[fragaria objectForKey:ro_MGSFOLineNumbers] updateLineNumbersForClipView:[[self enclosingScrollView] contentView] checkWidth:NO recolour:YES];
[self setPageGuideValues];
} else if (context == &SMLTextColourChanged) {
[self setTextColor:[NSUnarchiver unarchiveObjectWithData:[SMLDefaults valueForKey:MGSFragariaPrefsTextColourWell]]];
[self setInsertionPointColor:[NSUnarchiver unarchiveObjectWithData:[SMLDefaults valueForKey:MGSFragariaPrefsTextColourWell]]];
[self setPageGuideValues];
[self updateIBeamCursor];
} else if (context == &SMLBackgroundColourChanged) {
[self setBackgroundColor:[NSUnarchiver unarchiveObjectWithData:[SMLDefaults valueForKey:MGSFragariaPrefsBackgroundColourWell]]];
} else if (context == &SMLSmartInsertDeleteChanged) {
[self setSmartInsertDeleteEnabled:[[SMLDefaults valueForKey:MGSFragariaPrefsSmartInsertDelete] boolValue]];
} else if (context == &SMLTabWidthChanged) {
[self setTabWidth];
} else if (context == &SMLPageGuideChanged) {
[self setPageGuideValues];
} else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
#pragma mark -
#pragma mark Drawing
/*
- isOpaque
*/
- (BOOL)isOpaque
{
return YES;
}
/*
- drawRect:
*/
- (void)drawRect:(NSRect)rect
{
[super drawRect:rect];
if (showPageGuide == YES) {
NSRect bounds = [self bounds];
if ([self needsToDrawRect:NSMakeRect(pageGuideX, 0, 1, bounds.size.height)] == YES) { // So that it doesn't draw the line if only e.g. the cursor updates
[self.pageGuideColour set];
[NSBezierPath strokeRect:NSMakeRect(pageGuideX, 0, 0, bounds.size.height)];
}
}
}
#pragma mark -
#pragma mark Mouse event handling
/*
- mouseDown:
*/
- (void)mouseDown:(NSEvent *)theEvent
{
if (([theEvent modifierFlags] & NSAlternateKeyMask) && ([theEvent modifierFlags] & NSCommandKeyMask)) { // If the option and command keys are pressed, change the cursor to grab-cursor
startPoint = [theEvent locationInWindow];
startOrigin = [[[self enclosingScrollView] contentView] documentVisibleRect].origin;
[[self enclosingScrollView] setDocumentCursor:[NSCursor openHandCursor]];
} else {
[super mouseDown:theEvent];
}
}
/*
- mouseDragged:
*/
- (void)mouseDragged:(NSEvent *)theEvent
{
if ([[NSCursor currentCursor] isEqual:[NSCursor openHandCursor]]) {
[self scrollPoint:NSMakePoint(startOrigin.x - ([theEvent locationInWindow].x - startPoint.x) * 3, startOrigin.y + ([theEvent locationInWindow].y - startPoint.y) * 3)];
} else {
[super mouseDragged:theEvent];
}
}
/*
- mouseUp:
*/
- (void)mouseUp:(NSEvent *)theEvent
{
#pragma unused(theEvent)
[[self enclosingScrollView] setDocumentCursor:[NSCursor IBeamCursor]];
}
/*
- mouseMoved:
*/
- (void)mouseMoved:(NSEvent *)theEvent
{
#pragma unused(theEvent)
if ([NSCursor currentCursor] == [NSCursor IBeamCursor]) {
[colouredIBeamCursor set];
}
}
/*
- menuForEvent:
*/
- (NSMenu *)menuForEvent:(NSEvent *)theEvent
{
NSMenu *menu = [super menuForEvent:theEvent];
return menu;
// TODO: consider what menu behaviour is appropriate
/*
NSArray *array = [menu itemArray];
for (id oldMenuItem in array) {
if ([oldMenuItem tag] == -123457) {
[menu removeItem:oldMenuItem];
}
}
[menu insertItem:[NSMenuItem separatorItem] atIndex:0];
NSEnumerator *collectionEnumerator = [[SMLBasic fetchAll:@"SnippetCollectionSortKeyName"] reverseObjectEnumerator];
for (id collection in collectionEnumerator) {
if ([collection valueForKey:@"name"] == nil) {
continue;
}
NSMenuItem *menuItem = [[NSMenuItem alloc] initWithTitle:[collection valueForKey:@"name"] action:nil keyEquivalent:@""];
[menuItem setTag:-123457];
NSMenu *subMenu = [[NSMenu alloc] init];
NSMutableArray *array = [NSMutableArray arrayWithArray:[[collection mutableSetValueForKey:@"snippets"] allObjects]];
[array sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
for (id snippet in array) {
if ([snippet valueForKey:@"name"] == nil) {
continue;
}
NSString *keyString;
if ([snippet valueForKey:@"shortcutMenuItemKeyString"] != nil) {
keyString = [snippet valueForKey:@"shortcutMenuItemKeyString"];
} else {
keyString = @"";
}
NSMenuItem *subMenuItem = [[NSMenuItem alloc] initWithTitle:[snippet valueForKey:@"name"] action:@selector(snippetShortcutFired:) keyEquivalent:@""];
[subMenuItem setTarget:[SMLToolsMenuController sharedInstance]];
[subMenuItem setRepresentedObject:snippet];
[subMenu insertItem:subMenuItem atIndex:0];
}
[menuItem setSubmenu:subMenu];
[menu insertItem:menuItem atIndex:0];
}
return menu;
*/
}
#pragma mark -
#pragma mark Tab and page guide handling
/*
- insertTab:
*/
- (void)insertTab:(id)sender
{
BOOL shouldShiftText = NO;
if ([self selectedRange].length > 0) { // Check to see if the selection is in the text or if it's at the beginning of a line or in whitespace; if one doesn't do this one shifts the line if there's only one suggestion in the auto-complete
NSRange rangeOfFirstLine = [[self string] lineRangeForRange:NSMakeRange([self selectedRange].location, 0)];
NSUInteger firstCharacterOfFirstLine = rangeOfFirstLine.location;
while ([[self string] characterAtIndex:firstCharacterOfFirstLine] == ' ' || [[self string] characterAtIndex:firstCharacterOfFirstLine] == '\t') {
firstCharacterOfFirstLine++;
}
if ([self selectedRange].location <= firstCharacterOfFirstLine) {
shouldShiftText = YES;
}
}
if (shouldShiftText) {
[[MGSTextMenuController sharedInstance] shiftRightAction:nil];
} else if ([[SMLDefaults valueForKey:MGSFragariaPrefsIndentWithSpaces] boolValue] == YES) {
NSMutableString *spacesString = [NSMutableString string];
NSInteger numberOfSpacesPerTab = [[SMLDefaults valueForKey:MGSFragariaPrefsTabWidth] integerValue];
if ([[SMLDefaults valueForKey:MGSFragariaPrefsUseTabStops] boolValue] == YES) {
NSInteger locationOnLine = [self selectedRange].location - [[self string] lineRangeForRange:[self selectedRange]].location;
if (numberOfSpacesPerTab != 0) {
NSInteger numberOfSpacesLess = locationOnLine % numberOfSpacesPerTab;
numberOfSpacesPerTab = numberOfSpacesPerTab - numberOfSpacesLess;
}
}
while (numberOfSpacesPerTab--) {
[spacesString appendString:@" "];
}
[self insertText:spacesString];
} else if ([self selectedRange].length > 0) { // If there's only one word matching in auto-complete there's no list but just the rest of the word inserted and selected; and if you do a normal tab then the text is removed so this will put the cursor at the end of that word
[self setSelectedRange:NSMakeRange(NSMaxRange([self selectedRange]), 0)];
} else {
[super insertTab:sender];
}
}
/*
- setTabWidth
*/
- (void)setTabWidth
{
// Set the width of every tab by first checking the size of the tab in spaces in the current font and then remove all tabs that sets automatically and then set the default tab stop distance
NSMutableString *sizeString = [NSMutableString string];
NSInteger numberOfSpaces = [[SMLDefaults valueForKey:MGSFragariaPrefsTabWidth] integerValue];
while (numberOfSpaces--) {
[sizeString appendString:@" "];
}
NSDictionary *sizeAttribute = [[NSDictionary alloc] initWithObjectsAndKeys:[NSUnarchiver unarchiveObjectWithData:[SMLDefaults valueForKey:MGSFragariaPrefsTextFont]], NSFontAttributeName, nil];
CGFloat sizeOfTab = [sizeString sizeWithAttributes:sizeAttribute].width;
NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
NSArray *array = [style tabStops];
for (id item in array) {
[style removeTabStop:item];
}
[style setDefaultTabInterval:sizeOfTab];
NSDictionary *attributes = [[NSDictionary alloc] initWithObjectsAndKeys:style, NSParagraphStyleAttributeName, nil];
[self setTypingAttributes:attributes];
}
/*
- setPageGuideValues
*/
- (void)setPageGuideValues
{
NSDictionary *sizeAttribute = [[NSDictionary alloc] initWithObjectsAndKeys:[NSUnarchiver unarchiveObjectWithData:[SMLDefaults valueForKey:MGSFragariaPrefsTextFont]], NSFontAttributeName, nil];
NSString *sizeString = @" ";
CGFloat sizeOfCharacter = [sizeString sizeWithAttributes:sizeAttribute].width;
pageGuideX = (sizeOfCharacter * ([[SMLDefaults valueForKey:MGSFragariaPrefsShowPageGuideAtColumn] integerValue] + 1)) - 1.5f; // -1.5 to put it between the two characters and draw only on one pixel and not two (as the system draws it in a special way), and that's also why the width above is set to zero
NSColor *color = [NSUnarchiver unarchiveObjectWithData:[SMLDefaults valueForKey:MGSFragariaPrefsTextColourWell]];
self.pageGuideColour = [color colorWithAlphaComponent:([color alphaComponent] / 4)]; // Use the same colour as the text but with more transparency
showPageGuide = [[SMLDefaults valueForKey:MGSFragariaPrefsShowPageGuide] boolValue];
[self display]; // To reflect the new values in the view
}
#pragma mark -
#pragma mark Text handling
/*
- insertText:
*/
- (void)insertText:(NSString *)aString
{
if ([aString isEqualToString:@"}"] && [[SMLDefaults valueForKey:MGSFragariaPrefsIndentNewLinesAutomatically] boolValue] == YES && [[SMLDefaults valueForKey:MGSFragariaPrefsAutomaticallyIndentBraces] boolValue] == YES) {
unichar characterToCheck;
NSInteger location = [self selectedRange].location;
NSString *completeString = [self string];
NSCharacterSet *whitespaceCharacterSet = [NSCharacterSet whitespaceCharacterSet];
NSRange currentLineRange = [completeString lineRangeForRange:NSMakeRange([self selectedRange].location, 0)];
NSInteger lineLocation = location;
NSInteger lineStart = currentLineRange.location;
while (--lineLocation >= lineStart) { // If there are any characters before } on the line skip indenting
if ([whitespaceCharacterSet characterIsMember:[completeString characterAtIndex:lineLocation]]) {
continue;
}
[super insertText:aString];
return;
}
BOOL hasInsertedBrace = NO;
NSUInteger skipMatchingBrace = 0;
while (location--) {
characterToCheck = [completeString characterAtIndex:location];
if (characterToCheck == '{') {
if (skipMatchingBrace == 0) { // If we have found the opening brace check first how much space is in front of that line so the same amount can be inserted in front of the new line
NSString *openingBraceLineWhitespaceString;
NSScanner *openingLineScanner = [[NSScanner alloc] initWithString:[completeString substringWithRange:[completeString lineRangeForRange:NSMakeRange(location, 0)]]];
[openingLineScanner setCharactersToBeSkipped:nil];
BOOL foundOpeningBraceWhitespace = [openingLineScanner scanCharactersFromSet:whitespaceCharacterSet intoString:&openingBraceLineWhitespaceString];
if (foundOpeningBraceWhitespace == YES) {
NSMutableString *newLineString = [NSMutableString stringWithString:openingBraceLineWhitespaceString];
[newLineString appendString:@"}"];
[newLineString appendString:[completeString substringWithRange:NSMakeRange([self selectedRange].location, NSMaxRange(currentLineRange) - [self selectedRange].location)]];
if ([self shouldChangeTextInRange:currentLineRange replacementString:newLineString]) {
[self replaceCharactersInRange:currentLineRange withString:newLineString];
[self didChangeText];
}
hasInsertedBrace = YES;
[self setSelectedRange:NSMakeRange(currentLineRange.location + [openingBraceLineWhitespaceString length] + 1, 0)]; // +1 because we have inserted a character
} else {
NSString *restOfLineString = [completeString substringWithRange:NSMakeRange([self selectedRange].location, NSMaxRange(currentLineRange) - [self selectedRange].location)];
if ([restOfLineString length] != 0) { // To fix a bug where text after the } can be deleted
NSMutableString *replaceString = [NSMutableString stringWithString:@"}"];
[replaceString appendString:restOfLineString];
hasInsertedBrace = YES;
NSInteger lengthOfWhiteSpace = 0;
if (foundOpeningBraceWhitespace == YES) {
lengthOfWhiteSpace = [openingBraceLineWhitespaceString length];
}
if ([self shouldChangeTextInRange:currentLineRange replacementString:replaceString]) {
[self replaceCharactersInRange:[completeString lineRangeForRange:currentLineRange] withString:replaceString];
[self didChangeText];
}
[self setSelectedRange:NSMakeRange(currentLineRange.location + lengthOfWhiteSpace + 1, 0)]; // +1 because we have inserted a character
} else {
[self replaceCharactersInRange:[completeString lineRangeForRange:currentLineRange] withString:@""]; // Remove whitespace before }
}
}
break;
} else {
skipMatchingBrace--;
}
} else if (characterToCheck == '}') {
skipMatchingBrace++;
}
}
if (hasInsertedBrace == NO) {
[super insertText:aString];
}
} else if ([aString isEqualToString:@"("] && [[SMLDefaults valueForKey:MGSFragariaPrefsAutoInsertAClosingParenthesis] boolValue] == YES) {
[super insertText:aString];
NSRange selectedRange = [self selectedRange];
if ([self shouldChangeTextInRange:selectedRange replacementString:@")"]) {
[self replaceCharactersInRange:selectedRange withString:@")"];
[self didChangeText];
[self setSelectedRange:NSMakeRange(selectedRange.location - 0, 0)];
}
} else if ([aString isEqualToString:@"{"] && [[SMLDefaults valueForKey:MGSFragariaPrefsAutoInsertAClosingBrace] boolValue] == YES) {
[super insertText:aString];
NSRange selectedRange = [self selectedRange];
if ([self shouldChangeTextInRange:selectedRange replacementString:@"}"]) {
[self replaceCharactersInRange:selectedRange withString:@"}"];
[self didChangeText];
[self setSelectedRange:NSMakeRange(selectedRange.location - 0, 0)];
}
} else {
[super insertText:aString];
}
}
/*
- insertNewline:
*/
- (void)insertNewline:(id)sender
{
[super insertNewline:sender];
// If we should indent automatically, check the previous line and scan all the whitespace at the beginning of the line into a string and insert that string into the new line
NSString *lastLineString = [[self string] substringWithRange:[[self string] lineRangeForRange:NSMakeRange([self selectedRange].location - 1, 0)]];
if ([[SMLDefaults valueForKey:MGSFragariaPrefsIndentNewLinesAutomatically] boolValue] == YES) {
NSString *previousLineWhitespaceString;
NSScanner *previousLineScanner = [[NSScanner alloc] initWithString:[[self string] substringWithRange:[[self string] lineRangeForRange:NSMakeRange([self selectedRange].location - 1, 0)]]];
[previousLineScanner setCharactersToBeSkipped:nil];
if ([previousLineScanner scanCharactersFromSet:[NSCharacterSet whitespaceCharacterSet] intoString:&previousLineWhitespaceString]) {
[self insertText:previousLineWhitespaceString];
}
if ([[SMLDefaults valueForKey:MGSFragariaPrefsAutomaticallyIndentBraces] boolValue] == YES) {
NSCharacterSet *characterSet = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSInteger idx = [lastLineString length];
while (idx--) {
if ([characterSet characterIsMember:[lastLineString characterAtIndex:idx]]) {
continue;
}
if ([lastLineString characterAtIndex:idx] == '{') {
[self insertTab:nil];
}
break;
}
}
}
}
/*
- setString:
*/
- (void)setString:(NSString *)aString
{
[super setString:aString];
[[fragaria objectForKey:ro_MGSFOLineNumbers] updateLineNumbersCheckWidth:YES recolour:YES];
}
/*
- setString:options:
*/
- (void)setString:(NSString *)text options:(NSDictionary *)options
{
NSRange all = NSMakeRange(0, [self.textStorage length]);
[self replaceCharactersInRange:all withString:text options:options];
}
/*
- replaceCharactersInRange:withString:options
*/
- (void)replaceCharactersInRange:(NSRange)range withString:(NSString *)text options:(NSDictionary *)options
{
BOOL undo = [[options objectForKey:@"undo"] boolValue];
BOOL textViewWasEmpty = ([self.textStorage length] == 0 ? YES : NO);
if ([self isEditable] && undo) {
// this sequence will be registered with the undo manager
if ([self shouldChangeTextInRange:range replacementString:text]) {
// modify he text storage
[self.textStorage beginEditing];
[self.textStorage replaceCharactersInRange:range withString:text];
[self.textStorage endEditing];
// reset the default font if text was empty as the font gets reset to system default.
if (textViewWasEmpty) {
[self setFont:[NSUnarchiver unarchiveObjectWithData:[SMLDefaults valueForKey:MGSFragariaPrefsTextFont]]];
}
// TODO: this doesn't seem to be having the desired effect
NSUndoManager *undoManager = [self undoManager];
[undoManager setActionName:NSLocalizedString(@"Content Change", @"undo content change")];
// complete the text change operation
[self didChangeText];
}
} else if (textViewWasEmpty) {
// this operation will not be registered with the undo manager
[self setString:text];
} else {
// this operation will not be registered with the undo manager
[self.textStorage replaceCharactersInRange:range withString:text];;
}
}
/*
- setAttributedString:
*/
- (void)setAttributedString:(NSAttributedString *)text
{
NSTextStorage *textStorage = [self textStorage];
[textStorage setAttributedString:text];
[[fragaria objectForKey:ro_MGSFOLineNumbers] updateLineNumbersCheckWidth:YES recolour:YES];
}
/*
- setAttributedString:options:
*/
- (void)setAttributedString:(NSAttributedString *)text options:(NSDictionary *)options
{
BOOL undo = [[options objectForKey:@"undo"] boolValue];
NSTextStorage *textStorage = [self textStorage];
if ([self isEditable] && undo) {
/*
see http://www.cocoabuilder.com/archive/cocoa/179875-exponent-action-in-nstextview-subclass.html
entitled: Re: "exponent" action in NSTextView subclass (SOLVED)
This details how to make programatic changes to the textStorage object.
*/
/*
code here reflects what occurs in - setString:options:
may be over complicated
*/
NSRange all = NSMakeRange(0, [textStorage length]);
BOOL textIsEmpty = ([textStorage length] == 0 ? YES : NO);
if ([self shouldChangeTextInRange:all replacementString:[text string]]) {
[textStorage beginEditing];
[textStorage setAttributedString:text];
[textStorage endEditing];
// reset the default font if text was empty as the font gets reset to system default.
if (textIsEmpty) {
[self setFont:[NSUnarchiver unarchiveObjectWithData:[SMLDefaults valueForKey:MGSFragariaPrefsTextFont]]];
}
[self didChangeText];
NSUndoManager *undoManager = [self undoManager];
// TODO: this doesn't seem to be having the desired effect
[undoManager setActionName:NSLocalizedString(@"Content Change", @"undo content change")];
}
} else {
[self setAttributedString:text];
}
}
/*
- appendString:
*/
- (void)appendString:(NSString *)aString
{
NSMutableString * string = [NSMutableString stringWithString:[super string]];
[string appendString:aString];
[self setString:string];
}
#pragma mark -
#pragma mark Selection handling
/*
- selectionRangeForProposedRange:granularity:
*/
- (NSRange)selectionRangeForProposedRange:(NSRange)proposedSelRange granularity:(NSSelectionGranularity)granularity
{
// If it's not a mouse event return unchanged
NSEventType eventType = [[NSApp currentEvent] type];
if (eventType != NSLeftMouseDown && eventType != NSLeftMouseUp) {
return [super selectionRangeForProposedRange:proposedSelRange granularity:granularity];
}
if (granularity != NSSelectByWord || [[self string] length] == proposedSelRange.location || [[NSApp currentEvent] clickCount] != 2) { // If it's not a double-click return unchanged
return [super selectionRangeForProposedRange:proposedSelRange granularity:granularity];
}
NSUInteger location = [super selectionRangeForProposedRange:proposedSelRange granularity:NSSelectByCharacter].location;
NSInteger originalLocation = location;
NSString *completeString = [self string];
unichar characterToCheck = [completeString characterAtIndex:location];
NSInteger skipMatchingBrace = 0;
NSUInteger lengthOfString = [completeString length];
if (lengthOfString == proposedSelRange.location) { // To avoid crash if a double-click occurs after any text
return [super selectionRangeForProposedRange:proposedSelRange granularity:granularity];
}
BOOL triedToMatchBrace = NO;
if (characterToCheck == ')') {
triedToMatchBrace = YES;
while (location--) {
characterToCheck = [completeString characterAtIndex:location];
if (characterToCheck == '(') {
if (!skipMatchingBrace) {
return NSMakeRange(location, originalLocation - location + 1);
} else {
skipMatchingBrace--;
}
} else if (characterToCheck == ')') {
skipMatchingBrace++;
}
}
NSBeep();
} else if (characterToCheck == '}') {
triedToMatchBrace = YES;
while (location--) {
characterToCheck = [completeString characterAtIndex:location];
if (characterToCheck == '{') {
if (!skipMatchingBrace) {
return NSMakeRange(location, originalLocation - location + 1);
} else {
skipMatchingBrace--;
}
} else if (characterToCheck == '}') {
skipMatchingBrace++;
}
}
NSBeep();
} else if (characterToCheck == ']') {
triedToMatchBrace = YES;
while (location--) {
characterToCheck = [completeString characterAtIndex:location];
if (characterToCheck == '[') {
if (!skipMatchingBrace) {
return NSMakeRange(location, originalLocation - location + 1);
} else {
skipMatchingBrace--;
}
} else if (characterToCheck == ']') {
skipMatchingBrace++;
}
}
NSBeep();
} else if (characterToCheck == '>') {
triedToMatchBrace = YES;
while (location--) {
characterToCheck = [completeString characterAtIndex:location];
if (characterToCheck == '<') {
if (!skipMatchingBrace) {
return NSMakeRange(location, originalLocation - location + 1);
} else {
skipMatchingBrace--;
}
} else if (characterToCheck == '>') {
skipMatchingBrace++;
}
}
NSBeep();
} else if (characterToCheck == '(') {
triedToMatchBrace = YES;
while (++location < lengthOfString) {
characterToCheck = [completeString characterAtIndex:location];
if (characterToCheck == ')') {
if (!skipMatchingBrace) {
return NSMakeRange(originalLocation, location - originalLocation + 1);
} else {
skipMatchingBrace--;
}
} else if (characterToCheck == '(') {
skipMatchingBrace++;
}
}
NSBeep();
} else if (characterToCheck == '{') {
triedToMatchBrace = YES;
while (++location < lengthOfString) {
characterToCheck = [completeString characterAtIndex:location];
if (characterToCheck == '}') {
if (!skipMatchingBrace) {
return NSMakeRange(originalLocation, location - originalLocation + 1);
} else {
skipMatchingBrace--;
}
} else if (characterToCheck == '{') {
skipMatchingBrace++;
}
}
NSBeep();
} else if (characterToCheck == '[') {
triedToMatchBrace = YES;
while (++location < lengthOfString) {
characterToCheck = [completeString characterAtIndex:location];
if (characterToCheck == ']') {
if (!skipMatchingBrace) {
return NSMakeRange(originalLocation, location - originalLocation + 1);
} else {
skipMatchingBrace--;
}
} else if (characterToCheck == '[') {
skipMatchingBrace++;
}
}
NSBeep();
} else if (characterToCheck == '<') {
triedToMatchBrace = YES;
while (++location < lengthOfString) {
characterToCheck = [completeString characterAtIndex:location];
if (characterToCheck == '>') {
if (!skipMatchingBrace) {
return NSMakeRange(originalLocation, location - originalLocation + 1);
} else {
skipMatchingBrace--;
}
} else if (characterToCheck == '<') {
skipMatchingBrace++;
}
}
NSBeep();
}
// If it has a found a "starting" brace but not found a match, a double-click should only select the "starting" brace and not what it usually would select at a double-click
if (triedToMatchBrace) {
return [super selectionRangeForProposedRange:NSMakeRange(proposedSelRange.location, 1) granularity:NSSelectByCharacter];
} else {
NSInteger startLocation = originalLocation;
NSInteger stopLocation = originalLocation;
NSInteger minLocation = [super selectionRangeForProposedRange:proposedSelRange granularity:NSSelectByWord].location;
NSInteger maxLocation = NSMaxRange([super selectionRangeForProposedRange:proposedSelRange granularity:NSSelectByWord]);
BOOL hasFoundSomething = NO;
while (--startLocation >= minLocation) {
if ([completeString characterAtIndex:startLocation] == '.' || [completeString characterAtIndex:startLocation] == ':') {
hasFoundSomething = YES;
break;
}
}
while (++stopLocation < maxLocation) {
if ([completeString characterAtIndex:stopLocation] == '.' || [completeString characterAtIndex:stopLocation] == ':') {
hasFoundSomething = YES;
break;
}
}
if (hasFoundSomething == YES) {
return NSMakeRange(startLocation + 1, stopLocation - startLocation - 1);
} else {
return [super selectionRangeForProposedRange:proposedSelRange granularity:granularity];
}
}
}
#pragma mark -
#pragma mark Persistence
/*
- save:
*/
- (IBAction)save:(id)sender
{
#pragma unused(sender)
// no implicit save functionality
}
#pragma mark -
#pragma mark Cursor handling
/*
- updateIBeamCursor:
*/
- (void)updateIBeamCursor
{
NSColor *textColour = [[NSUnarchiver unarchiveObjectWithData:[SMLDefaults valueForKey:MGSFragariaPrefsTextColourWell]] colorUsingColorSpaceName:NSCalibratedWhiteColorSpace];
if (textColour != nil && [textColour whiteComponent] < 0.01 && [textColour alphaComponent] > 0.990) { // Keep the original cursor if it's black
[self setColouredIBeamCursor:[NSCursor IBeamCursor]];
} else {
NSImage *cursorImage = [[NSCursor IBeamCursor] image];
[cursorImage lockFocus];
[(NSColor *)[NSUnarchiver unarchiveObjectWithData:[SMLDefaults valueForKey:MGSFragariaPrefsTextColourWell]] set];
NSRectFillUsingOperation(NSMakeRect(0, 0, [cursorImage size].width, [cursorImage size].height), NSCompositeSourceAtop);
[cursorImage unlockFocus];
NSCursor *cursor = [[NSCursor alloc] initWithImage:cursorImage hotSpot:[[NSCursor IBeamCursor] hotSpot]];
[self setColouredIBeamCursor:cursor];
}
}
/*
- cursorUpdate:
*/
- (void)cursorUpdate:(NSEvent *)event
{
#pragma unused(event)
[colouredIBeamCursor set];
}
#pragma mark -
#pragma mark Find
/*
- performFindPanelAction:
*/
- (void)performFindPanelAction:(id)sender
{
[super performFindPanelAction:sender];
}
#pragma mark -
#pragma mark Auto Completion
/*
- rangeForUserCompletion
*/
- (NSRange)rangeForUserCompletion
{
NSRange cursor = [self selectedRange];
NSUInteger loc = cursor.location;
// Check for selections (can only autocomplete when nothing is selected)
if (cursor.length > 0)
{
return NSMakeRange(NSNotFound, 0);
}