forked from KosmicTask/Fragaria
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SMLTextView.m
921 lines (749 loc) · 30.6 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
/*
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"
// class extension
@interface SMLTextView()
- (void)windowDidBecomeMainOrKey:(NSNotification *)note;
@end
@implementation SMLTextView
@synthesize colouredIBeamCursor, fragaria;
#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];
}
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];
[self setUsesFindPanel:YES];
[self setAllowsDocumentBackgroundColorChange:NO];
[self setRichText:NO];
[self setImportsGraphics:NO];
[self setUsesFontPanel:NO];
[self setContinuousSpellCheckingEnabled:[[SMLDefaults valueForKey:@"AutoSpellCheck"] boolValue]];
[self setGrammarCheckingEnabled:[[SMLDefaults valueForKey:@"AutoGrammarCheck"] boolValue]];
[self setSmartInsertDeleteEnabled:[[SMLDefaults valueForKey:@"SmartInsertDelete"] boolValue]];
[self setAutomaticLinkDetectionEnabled:[[SMLDefaults valueForKey:@"AutomaticLinkDetection"] boolValue]];
[self setAutomaticQuoteSubstitutionEnabled:[[SMLDefaults valueForKey:@"AutomaticQuoteSubstitution"] 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.TextFont" options:NSKeyValueObservingOptionNew context:@"TextFontChanged"];
[defaultsController addObserver:self forKeyPath:@"values.TextColourWell" options:NSKeyValueObservingOptionNew context:@"TextColourChanged"];
[defaultsController addObserver:self forKeyPath:@"values.BackgroundColourWell" options:NSKeyValueObservingOptionNew context:@"BackgroundColourChanged"];
[defaultsController addObserver:self forKeyPath:@"values.SmartInsertDelete" options:NSKeyValueObservingOptionNew context:@"SmartInsertDeleteChanged"];
[defaultsController addObserver:self forKeyPath:@"values.TabWidth" options:NSKeyValueObservingOptionNew context:@"TabWidthChanged"];
[defaultsController addObserver:self forKeyPath:@"values.ShowPageGuide" options:NSKeyValueObservingOptionNew context:@"PageGuideChanged"];
[defaultsController addObserver:self forKeyPath:@"values.ShowPageGuideAtColumn" options:NSKeyValueObservingOptionNew context:@"PageGuideChanged"];
[defaultsController addObserver:self forKeyPath:@"values.SmartInsertDelete" options:NSKeyValueObservingOptionNew context:@"SmartInsertDeleteChanged"];
lineHeight = [[[self textContainer] layoutManager] defaultLineHeightForFont:[NSUnarchiver unarchiveObjectWithData:[SMLDefaults valueForKey:@"TextFont"]]];
}
/*
- scrollView
Added by MrAsterisco on 23/03/2012
*/
- (NSScrollView*)scrollView {
return (NSScrollView*)[[self superview] superview];
}
/*
- setTextDefaults
*/
- (void)setTextDefaults
{
[self setFont:[NSUnarchiver unarchiveObjectWithData:[SMLDefaults valueForKey:@"TextFont"]]];
[self setTextColor:[NSUnarchiver unarchiveObjectWithData:[SMLDefaults valueForKey:@"TextColourWell"]]];
[self setInsertionPointColor:[NSUnarchiver unarchiveObjectWithData:[SMLDefaults valueForKey:@"TextColourWell"]]];
[self setBackgroundColor:[NSUnarchiver unarchiveObjectWithData:[SMLDefaults valueForKey:@"BackgroundColourWell"]]];
}
/*
- setFrame:
*/
- (void)setFrame:(NSRect)rect
{
[super setFrame:rect];
[[fragaria objectForKey:ro_MGSFOLineNumbers] updateLineNumbersForClipView:[[self enclosingScrollView] contentView] checkWidth:NO recolour:YES];
}
/*
- setString:
*/
- (void)setString:(NSString *)aString
{
[super setString:aString];
[[fragaria objectForKey:ro_MGSFOLineNumbers] updateLineNumbersCheckWidth:YES recolour:YES];
}
#pragma mark -
#pragma mark KVO
/*
- observeValueForKeyPath:ofObject:change:context:
*/
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([(__bridge NSString *)context isEqualToString:@"TextFontChanged"]) {
[self setFont:[NSUnarchiver unarchiveObjectWithData:[SMLDefaults valueForKey:@"TextFont"]]];
lineHeight = [[[self textContainer] layoutManager] defaultLineHeightForFont:[NSUnarchiver unarchiveObjectWithData:[SMLDefaults valueForKey:@"TextFont"]]];
[[fragaria objectForKey:ro_MGSFOLineNumbers] updateLineNumbersForClipView:[[self enclosingScrollView] contentView] checkWidth:NO recolour:YES];
[self setPageGuideValues];
} else if ([(__bridge NSString *)context isEqualToString:@"TextColourChanged"]) {
[self setTextColor:[NSUnarchiver unarchiveObjectWithData:[SMLDefaults valueForKey:@"TextColourWell"]]];
[self setInsertionPointColor:[NSUnarchiver unarchiveObjectWithData:[SMLDefaults valueForKey:@"TextColourWell"]]];
[self setPageGuideValues];
[self updateIBeamCursor];
} else if ([(__bridge NSString *)context isEqualToString:@"BackgroundColourChanged"]) {
[self setBackgroundColor:[NSUnarchiver unarchiveObjectWithData:[SMLDefaults valueForKey:@"BackgroundColourWell"]]];
} else if ([(__bridge NSString *)context isEqualToString:@"SmartInsertDeleteChanged"]) {
[self setSmartInsertDeleteEnabled:[[SMLDefaults valueForKey:@"SmartInsertDelete"] boolValue]];
} else if ([(__bridge NSString *)context isEqualToString:@"TabWidthChanged"]) {
[self setTabWidth];
} else if ([(__bridge NSString *)context isEqualToString:@"PageGuideChanged"]) {
[self setPageGuideValues];
} else if ([(__bridge NSString *)context isEqualToString:@"SmartInsertDeleteChanged"]) {
[self setSmartInsertDeleteEnabled:[[SMLDefaults valueForKey:@"SmartInsertDelete"] boolValue]];
} 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
[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:@"IndentWithSpaces"] boolValue] == YES) {
NSMutableString *spacesString = [NSMutableString string];
NSInteger numberOfSpacesPerTab = [[SMLDefaults valueForKey:@"TabWidth"] integerValue];
if ([[SMLDefaults valueForKey:@"UseTabStops"] 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:@"TabWidth"] integerValue];
while (numberOfSpaces--) {
[sizeString appendString:@" "];
}
NSDictionary *sizeAttribute = [[NSDictionary alloc] initWithObjectsAndKeys:[NSUnarchiver unarchiveObjectWithData:[SMLDefaults valueForKey:@"TextFont"]], 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:@"TextFont"]], NSFontAttributeName, nil];
NSString *sizeString = [NSString stringWithString:@" "];
CGFloat sizeOfCharacter = [sizeString sizeWithAttributes:sizeAttribute].width;
pageGuideX = (sizeOfCharacter * ([[SMLDefaults valueForKey:@"ShowPageGuideAtColumn"] 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:@"TextColourWell"]];
pageGuideColour = [color colorWithAlphaComponent:([color alphaComponent] / 4)]; // Use the same colour as the text but with more transparency
showPageGuide = [[SMLDefaults valueForKey:@"ShowPageGuide"] 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:@"IndentNewLinesAutomatically"] boolValue] == YES && [[SMLDefaults valueForKey:@"AutomaticallyIndentBraces"] 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:@"AutoInsertAClosingParenthesis"] 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:@"AutoInsertAClosingBrace"] 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:@"IndentNewLinesAutomatically"] 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:@"AutomaticallyIndentBraces"] 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:options:
*/
- (void)setString:(NSString *)text options:(NSDictionary *)options
{
BOOL undo = [[options objectForKey:@"undo"] boolValue];
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.
*/
NSTextStorage *textStorage = [self textStorage];
NSRange all = NSMakeRange(0, [textStorage length]);
BOOL textIsEmpty = ([textStorage length] == 0 ? YES : NO);
if ([self shouldChangeTextInRange:all replacementString:text]) {
[textStorage beginEditing];
[textStorage replaceCharactersInRange:all withString: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:@"TextFont"]]];
}
[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 setString:text];
}
}
#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:@"TextColourWell"]] 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:@"TextColourWell"]] 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 NSView
/*
- viewWillMoveToWindow:
*/
- (void)viewWillMoveToWindow:(NSWindow *)newWindow
{
[super viewWillMoveToWindow:newWindow];
}
/*
- viewDidMoveToWindow
*/
- (void)viewDidMoveToWindow
{
if ([self window]) {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowDidBecomeMainOrKey:) name:NSWindowDidBecomeKeyNotification object:[self window]];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowDidBecomeMainOrKey:) name:NSWindowDidBecomeMainNotification object:[self window]];
}
[super viewDidMoveToWindow];
}
/*
- becomeFirstResponder
*/
- (BOOL)becomeFirstResponder
{
[MGSFragaria setCurrentInstance:self.fragaria];
return [super becomeFirstResponder];
}
#pragma mark -
#pragma mark Notification methods
/*
- windowDidBecomeMainOrKey:
*/
- (void)windowDidBecomeMainOrKey:(NSNotification *)note
{
#pragma unused(note)
[MGSFragaria setCurrentInstance:self.fragaria];
}
@end