/
ViDocument.m
2453 lines (2090 loc) · 75.9 KB
/
ViDocument.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
/*
* Copyright (c) 2008-2012 Martin Hedenfalk <martin@vicoapp.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <sys/time.h>
#import "Vico-Swift.h"
#import "ViDocument.h"
#import "ViDocumentView.h"
#import "ViBundleStore.h"
#import "ViCharsetDetector.h"
#import "ViTextStorage.h"
#import "NSString-additions.h"
#import "NSString-scopeSelector.h"
#import "NSArray-patterns.h"
#import "ViScope.h"
#import "ViSymbolTransform.h"
#import "ViThemeStore.h"
#import "SFTPConnection.h" /* Only for SSH2_FX_NO_SUCH_FILE constant. */
#import "ViError.h"
#import "NSObject+SPInvocationGrabbing.h"
#import "ViAppController.h"
#import "ViPreferencePaneEdit.h"
#import "ViEventManager.h"
#import "ViDocumentController.h"
#import "NSURL-additions.h"
#import "ViTextView.h"
#import "ViFold.h"
BOOL __makeNewWindowInsteadOfTab = NO;
@interface ViDocument (internal)
- (void)highlightEverything;
- (void)setWrapping:(BOOL)flag;
- (void)enableLineNumbers:(BOOL)flag relative:(BOOL)relative forScrollView:(NSScrollView *)aScrollView;
- (void)enableLineNumbers:(BOOL)flag relative:(BOOL)relative;
- (void)setTypingAttributes;
- (NSString *)suggestEncoding:(NSStringEncoding *)outEncoding forData:(NSData *)data;
- (BOOL)addData:(NSData *)data;
- (void)invalidateSymbolsInRange:(NSRange)range;
- (void)pushMarks:(NSInteger)delta fromLocation:(NSUInteger)location;
- (void)updateTabSize;
- (void)updateWrapping;
- (void)eachTextView:(void (^)(ViTextView *))callback;
@end
@implementation ViDocument
@synthesize symbols = _symbols;
@synthesize filteredSymbols = _filteredSymbols;
@synthesize symbolScopes = _symbolScopes;
@synthesize symbolTransforms = _symbolTransforms;
@synthesize views = _views;
@synthesize bundle = _bundle;
@synthesize theme = _theme;
@synthesize language = _language;
@synthesize encoding = _encoding;
@synthesize isTemporary = _isTemporary;
@synthesize snippet = _snippet;
@synthesize busy = _busy;
@synthesize loader = _loader;
@synthesize closeCallback = _closeCallback;
@synthesize ignoreChangeCountNotification = _ignoreChangeCountNotification;
@synthesize textStorage = _textStorage;
@synthesize matchingParenRange = _matchingParenRange;
@synthesize hiddenView = _hiddenView;
@synthesize syntaxParser = _syntaxParser;
@synthesize marks = _marks;
@synthesize modified = _modified;
@synthesize localMarks = _localMarks;
+ (BOOL)canConcurrentlyReadDocumentsOfType:(NSString *)typeName
{
return NO;
}
- (id)init
{
if ((self = [super init]) != nil) {
_symbols = [[NSMutableArray alloc] init];
_views = [[NSMutableSet alloc] init];
_localMarks = [[ViMarkManager sharedManager] makeStack];
_localMarks.name = [NSString stringWithFormat:@"Local marks for document %p", self];
_marks = [[NSMutableSet alloc] init];
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults addObserver:self forKeyPath:@"number" options:0 context:NULL];
[userDefaults addObserver:self forKeyPath:@"relativenumber" options:0 context:NULL];
[userDefaults addObserver:self forKeyPath:@"tabstop" options:0 context:NULL];
[userDefaults addObserver:self forKeyPath:@"fontsize" options:0 context:NULL];
[userDefaults addObserver:self forKeyPath:@"fontname" options:0 context:NULL];
[userDefaults addObserver:self forKeyPath:@"linebreak" options:0 context:NULL];
[userDefaults addObserver:self forKeyPath:@"wrap" options:0 context:NULL];
[userDefaults addObserver:self forKeyPath:@"list" options:0 context:NULL];
[userDefaults addObserver:self forKeyPath:@"matchparen" options:0 context:NULL];
_textStorage = [[ViTextStorage alloc] init];
[_textStorage setDelegate:self];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(textStorageDidChangeLines:)
name:ViTextStorageChangedLinesNotification
object:_textStorage];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(editPreferenceChanged:)
name:ViEditPreferenceChangedNotification
object:nil];
NSString *symbolIconsFile = [[ViAppController supportDirectory] stringByAppendingPathComponent:@"symbol-icons.plist"] ;
if (![[NSFileManager defaultManager] fileExistsAtPath:symbolIconsFile])
symbolIconsFile = [[NSBundle mainBundle] pathForResource:@"symbol-icons"
ofType:@"plist"];
_symbolIcons = [[NSDictionary alloc] initWithContentsOfFile:symbolIconsFile];
[self configureForURL:nil];
_forcedEncoding = 0;
_encoding = NSUTF8StringEncoding;
_theme = [[ViThemeStore defaultStore] defaultTheme];
[self setTypingAttributes];
/*
* Disable automatic undo groups created in each pass of the run loop.
* This duplicates our own undo grouping and makes the document never
* regain its un-edited state.
*/
[[self undoManager] setGroupsByEvent:NO];
MEMDEBUG(@"init %@", self);
}
DEBUG_INIT();
return self;
}
DEBUG_FINALIZE();
- (void)dealloc
{
DEBUG_DEALLOC();
[[ViEventManager defaultManager] clearFor:self];
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults removeObserver:self forKeyPath:@"number"];
[userDefaults removeObserver:self forKeyPath:@"relativenumber"];
[userDefaults removeObserver:self forKeyPath:@"tabstop"];
[userDefaults removeObserver:self forKeyPath:@"fontsize"];
[userDefaults removeObserver:self forKeyPath:@"fontname"];
[userDefaults removeObserver:self forKeyPath:@"linebreak"];
[userDefaults removeObserver:self forKeyPath:@"wrap"];
[userDefaults removeObserver:self forKeyPath:@"list"];
[userDefaults removeObserver:self forKeyPath:@"matchparen"];
[[NSNotificationCenter defaultCenter] removeObserver:self];
for (ViDocumentView *view in _views) {
MEMDEBUG(@"got remaining view %@", view);
[_textStorage removeLayoutManager:[(ViTextView *)[view innerView] layoutManager]];
[view setDocument:nil];
}
[_hiddenView setDocument:nil];
}
- (BOOL)dataAppearsBinary:(NSData *)data
{
NSString *string = nil;
if (_forcedEncoding)
string = [[NSString alloc] initWithData:data encoding:_forcedEncoding];
if (string == nil)
string = [self suggestEncoding:NULL forData:data];
return ([string rangeOfString:[NSString stringWithFormat:@"%C", (unichar)0]].location != NSNotFound);
}
- (void)openFailedAlertDidEnd:(NSAlert *)alert
returnCode:(NSInteger)returnCode
contextInfo:(void *)contextInfo
{
DEBUG(@"alert is %@", alert);
}
- (void)deferred:(id<ViDeferred>)deferred status:(NSString *)statusMessage
{
[self message:@"%@", statusMessage];
}
- (BOOL)readFromURL:(NSURL *)absoluteURL
ofType:(NSString *)typeName
error:(NSError **)outError
{
[self setSymbols:[NSMutableArray array]];
[[ViEventManager defaultManager] emit:ViEventWillLoadDocument for:self with:self, absoluteURL, nil];
DEBUG(@"read from %@", absoluteURL);
__block BOOL firstChunk = YES;
void (^dataCallback)(NSData *data) = ^(NSData *data) {
if (firstChunk && [self dataAppearsBinary:data]) {
NSAlert *alert = [[NSAlert alloc] init];
[alert setMessageText:[NSString stringWithFormat:@"%@ appears to be a binary file",
[absoluteURL lastPathComponent]]];
[alert addButtonWithTitle:@"Continue"];
[alert addButtonWithTitle:@"Cancel"];
[alert setInformativeText:@"Are you sure you want to continue opening the file?"];
NSUInteger ret = [alert runModal];
if (ret == NSAlertSecondButtonReturn) {
DEBUG(@"cancelling deferred %@", _loader);
[_loader cancel];
[self setLoader:nil];
return;
}
}
if (firstChunk)
[self setString:@""]; /* Make sure document is empty before appending data. */
[self addData:data];
firstChunk = NO;
if ([_loader respondsToSelector:@selector(progress)]) {
CGFloat progress = [_loader progress];
if (progress >= 0)
[self message:@"%.1f%% loaded", progress * 100.0];
}
};
/* If the completion callback is called immediately, we can return an error directly. */
__block NSError *returnError = nil;
void (^completionCallback)(NSURL *, NSDictionary *, NSError *error) = ^(NSURL *normalizedURL, NSDictionary *attributes, NSError *error) {
DEBUG(@"error is %@", error);
returnError = error;
[self setBusy:NO];
[self setLoader:nil];
if (error) {
/* If the file doesn't exist, treat it as an untitled file. */
if ([error isFileNotFoundError]) {
DEBUG(@"treating non-existent file %@ as untitled file", normalizedURL);
[self setFileURL:normalizedURL];
[self message:@"%@: new file", [self title]];
[[ViEventManager defaultManager] emitDelayed:ViEventDidLoadDocument for:self with:self, nil];
returnError = nil;
} else if ([error isOperationCancelledError]) {
DEBUG(@"cancelled loading of %@", normalizedURL);
DEBUG(@"self is %p", self);
DEBUG(@"self is %@", self);
[self message:@"cancelled loading of %@", normalizedURL];
[self setFileURL:nil];
if (_closeCallback)
_closeCallback(2);
[self setCloseCallback:nil];
} else {
/* Make sure this document has focus, then show an alert sheet. */
[_windowController displayDocument:self positioned:ViViewPositionDefault];
[self setFileURL:nil];
NSAlert *alert = [[NSAlert alloc] init];
[alert setMessageText:[NSString stringWithFormat:@"Couldn't open %@",
normalizedURL]];
[alert addButtonWithTitle:@"OK"];
[alert setInformativeText:[error localizedDescription]];
[alert beginSheetModalForWindow:[_windowController window]
modalDelegate:self
didEndSelector:@selector(openFailedAlertDidEnd:returnCode:contextInfo:)
contextInfo:nil];
if (_closeCallback)
_closeCallback(3);
[self setCloseCallback:nil];
}
} else {
DEBUG(@"loaded %@ with attributes %@", normalizedURL, attributes);
[self setFileModificationDate:[attributes fileModificationDate]];
[self setIsTemporary:NO];
[self setFileURL:normalizedURL];
[self message:@"%@: %lu lines", [self title], [_textStorage lineCount]];
[[NSNotificationCenter defaultCenter] postNotificationName:ViDocumentLoadedNotification
object:self];
[self eachTextView:^(ViTextView *tv) {
[tv documentDidLoad:self];
}];
[[ViEventManager defaultManager] emitDelayed:ViEventDidLoadDocument
for:self
with:self, nil];
}
};
[self setFileType:@"Document"];
[self setFileURL:absoluteURL];
[self setIsTemporary:YES]; /* Prevents triggering checkDocumentChanged in window controller. */
[self eachTextView:^(ViTextView *tv) {
[tv prepareRevertDocument];
}];
[self setBusy:YES];
[self setLoader:[[ViURLManager defaultManager] dataWithContentsOfURL:absoluteURL
onData:dataCallback
onCompletion:completionCallback]];
DEBUG(@"got deferred loader %@", _loader);
[_loader setDelegate:self];
if (outError)
*outError = returnError;
return returnError == nil ? YES : NO;
}
- (void)setBusy:(BOOL)value
{
_busy = value;
// Also post a mode change notification.
NSNotification *notification = [NSNotification notificationWithName:ViDocumentBusyChangedNotification object:self];
[[NSNotificationQueue defaultQueue] enqueueNotification:notification postingStyle:NSPostASAP];
}
- (BOOL)isEntireFileLoaded
{
return (_loader == nil);
}
- (id)initWithContentsOfURL:(NSURL *)absoluteURL
ofType:(NSString *)typeName
error:(NSError **)outError
{
DEBUG(@"init with URL %@ of type %@", absoluteURL, typeName);
if ((self = [self init]) != nil) {
[self readFromURL:absoluteURL ofType:typeName error:outError];
}
return self;
}
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context
{
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
if ([keyPath isEqualToString:@"number"])
[self enableLineNumbers:[userDefaults boolForKey:keyPath] relative:[userDefaults boolForKey:@"relativenumber"]];
else if ([keyPath isEqualToString:@"relativenumber"]) {
[self enableLineNumbers:[userDefaults boolForKey:@"number"] relative:[userDefaults boolForKey:keyPath]];
} else if ([keyPath isEqualToString:@"wrap"])
[self updateWrapping];
else if ([keyPath isEqualToString:@"tabstop"]) {
[self updateTabSize];
} else if ([keyPath isEqualToString:@"fontsize"] ||
[keyPath isEqualToString:@"fontname"] ||
[keyPath isEqualToString:@"linebreak"]) {
[self eachTextView:^(ViTextView *tv) {
ViLayoutManager *lm = (ViLayoutManager *)[tv layoutManager];
[lm setAttributesForInvisibles:[_theme invisiblesAttributes]];
[lm invalidateDisplayForCharacterRange:NSMakeRange(0, [_textStorage length])];
[tv updateFont];
}];
[self setTypingAttributes];
[self updatePageGuide];
} else if ([keyPath isEqualToString:@"list"]) {
[self eachTextView:^(ViTextView *tv) {
ViLayoutManager *lm = (ViLayoutManager *)[tv layoutManager];
[lm setShowsInvisibleCharacters:[userDefaults boolForKey:@"list"]];
[lm invalidateDisplayForCharacterRange:NSMakeRange(0, [_textStorage length])];
}];
} else if ([keyPath isEqualToString:@"matchparen"]) {
if ([userDefaults boolForKey:keyPath])
[self eachTextView:^(ViTextView *tv) {
[tv highlightSmartPairAtLocation:[tv caret]];
}];
else
[self setMatchingParenRange:NSMakeRange(NSNotFound, 0)];
}
}
- (void)editPreferenceChanged:(NSNotification *)notification
{
[self updateWrapping];
[self updateTabSize];
[self setTypingAttributes];
}
#pragma mark -
#pragma mark NSDocument interface
- (BOOL)keepBackupFile
{
return YES;
}
- (void)showWindows
{
[super showWindows];
[_windowController displayDocument:self positioned:ViViewPositionDefault];
}
- (ViWindowController *)windowController
{
return _windowController;
}
- (void)closeWindowController:(ViWindowController *)aController
{
[self removeWindowController:aController]; // XXX: does this release aController ?
if (aController == _windowController) {
/*
* XXX: This is a f*cking disaster!
* Find a new default window controller.
* Ask each windows' window controller if it contains this document.
*/
_windowController = nil;
for (NSWindow *window in [NSApp windows]) {
ViWindowController *wincon = [window windowController];
if (wincon == aController || ![wincon isKindOfClass:[ViWindowController class]])
continue;
if ([[wincon documents] containsObject:self]) {
_windowController = wincon;
break;
}
}
}
}
- (void)addWindowController:(NSWindowController *)aController
{
[super addWindowController:aController];
_windowController = (ViWindowController *)aController;
}
- (void)makeWindowControllers
{
ViWindowController *winCon = nil;
if (__makeNewWindowInsteadOfTab) {
winCon = [[ViWindowController alloc] init];
__makeNewWindowInsteadOfTab = NO;
} else {
winCon = [ViWindowController currentWindowController];
if (winCon == nil)
winCon = [[ViWindowController alloc] init];
}
[self addWindowController:winCon];
[winCon addNewTab:self];
}
- (void)eachTextView:(void (^)(ViTextView *))callback
{
for (ViDocumentView *docView in _views) {
NSView *view = [docView innerView];
if ([view isKindOfClass:[ViTextView class]])
callback((ViTextView *)view);
}
if (_hiddenView) {
NSView *view = [_hiddenView innerView];
if ([view isKindOfClass:[ViTextView class]])
callback((ViTextView *)view);
}
}
- (void)removeView:(ViDocumentView *)aDocumentView
{
if ([_views count] == 1) {
DEBUG(@"set hidden view to %@", aDocumentView);
[self setHiddenView:aDocumentView];
} else {
[_textStorage removeLayoutManager:[[aDocumentView textView] layoutManager]];
[aDocumentView setDocument:nil];
}
DEBUG(@"remove view %@", aDocumentView);
[_views removeObject:aDocumentView];
}
- (void)addView:(ViDocumentView *)docView
{
if (docView && ![_views containsObject:docView]) {
[_views addObject:docView];
[self setHiddenView:nil];
}
}
- (ViTextView *)text
{
if (_scriptView == nil) {
ViLayoutManager *layoutManager = [[ViLayoutManager alloc] init];
[_textStorage addLayoutManager:layoutManager];
[layoutManager setDelegate:self];
NSRect frame = NSMakeRect(0, 0, 10, 10);
NSTextContainer *container = [[NSTextContainer alloc] initWithContainerSize:frame.size];
[layoutManager addTextContainer:container];
_scriptView = [[ViTextView alloc] initWithFrame:frame textContainer:container];
[_scriptView initWithDocument:self viParser:[ViParser parserWithDefaultMap:[ViMap normalMap]]];
[[ViEventManager defaultManager] emit:ViEventDidMakeView for:self with:self, [NSNull null], _scriptView, nil];
}
return _scriptView;
}
- (ViDocumentView *)makeViewWithParser:(ViParser *)aParser
{
if (_hiddenView) {
DEBUG(@"returning hidden view %@", _hiddenView);
_hiddenView.textView.keyManager.parser = aParser;
return _hiddenView;
}
ViDocumentView *documentView = [[ViDocumentView alloc] initWithDocument:self];
if (documentView == nil)
return nil;
[self addView:documentView];
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
/*
* Recreate the text system hierarchy with our text storage and layout manager.
*/
ViLayoutManager *layoutManager = [[ViLayoutManager alloc] init];
[_textStorage addLayoutManager:layoutManager];
[layoutManager setDelegate:self];
[layoutManager setShowsInvisibleCharacters:[userDefaults boolForKey:@"list"]];
[layoutManager setShowsControlCharacters:YES];
[layoutManager setAttributesForInvisibles:[_theme invisiblesAttributes]];
NSView *innerView = [documentView innerView];
NSRect frame = [innerView frame];
NSTextContainer *container = [[NSTextContainer alloc] initWithContainerSize:frame.size];
[layoutManager addTextContainer:container];
[container setWidthTracksTextView:YES];
[container setHeightTracksTextView:YES];
ViTextView *textView = [[ViTextView alloc] initWithFrame:frame textContainer:container];
[documentView replaceTextView:textView];
[textView initWithDocument:self viParser:aParser];
[self enableLineNumbers:[userDefaults boolForKey:@"number"]
relative:[userDefaults boolForKey:@"relativenumber"]
forScrollView:[textView enclosingScrollView]];
[self updatePageGuide];
[textView setWrapping:_wrap duringInit:YES];
[[ViEventManager defaultManager] emit:ViEventDidMakeView for:self with:self, documentView, textView, nil];
return documentView;
}
- (ViDocumentView *)makeView
{
return [self makeViewWithParser:[_windowController parser]];
}
- (ViDocumentView *)cloneView:(ViDocumentView *)oldView
{
ViDocumentView *newView = [self makeView];
[[newView textView] setCaret:[[oldView textView] caret]];
return newView;
}
- (NSData *)dataOfType:(NSString *)typeName error:(NSError **)outError
{
NSStringEncoding enc = _encoding;
if (_retrySaveOperation)
enc = NSUTF8StringEncoding;
DEBUG(@"using encoding %@", [NSString localizedNameOfStringEncoding:enc]);
NSData *data = [[_textStorage string] dataUsingEncoding:enc];
if (data == nil && outError)
*outError = [ViError errorWithFormat:@"The %@ encoding is not appropriate.",
[NSString localizedNameOfStringEncoding:_encoding]];
return data;
}
- (BOOL)attemptRecoveryFromError:(NSError *)error
optionIndex:(NSUInteger)recoveryOptionIndex
{
if (recoveryOptionIndex == 1) {
_retrySaveOperation = YES;
return YES;
}
return NO;
}
- (void)didPresentErrorWithRecovery:(BOOL)didRecover
contextInfo:(void *)contextInfo
{
DEBUG(@"didRecover = %s", didRecover ? "YES" : "NO");
}
- (void)continueSavingAfterError:(NSError *)error
{
BOOL didSave = NO;
if (error == nil) {
didSave = [self saveToURL:[self fileURL]
ofType:[self fileType]
forSaveOperation:NSSaveOperation
error:&error];
}
if (error && !([[error domain] isEqualToString:NSCocoaErrorDomain] && [error code] == NSUserCancelledError))
[NSApp presentError:error];
DEBUG(@"calling delegate %@ with selector %@", _didSaveDelegate, NSStringFromSelector(_didSaveSelector));
if (_didSaveDelegate && _didSaveSelector) {
ViDocument __unsafe_unretained *thisDocument = self;
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:
[_didSaveDelegate methodSignatureForSelector:_didSaveSelector]];
[invocation setSelector:_didSaveSelector];
[invocation setArgument:&thisDocument atIndex:2];
[invocation setArgument:&didSave atIndex:3];
[invocation setArgument:&_didSaveContext atIndex:4];
[invocation invokeWithTarget:_didSaveDelegate];
}
_didSaveDelegate = nil;
_didSaveSelector = nil;
_didSaveContext = NULL;
}
- (void)fileModifiedAlertDidEnd:(NSAlert *)alert
returnCode:(NSInteger)returnCode
contextInfo:(void *)contextInfo
{
NSError *error = nil;
if (returnCode == NSAlertFirstButtonReturn)
error = [ViError operationCancelled];
[self continueSavingAfterError:error];
}
- (BOOL)shouldRunSavePanelWithAccessoryView
{
/* Do not show the "File Formats" accessory view. */
return NO;
}
- (BOOL)prepareSavePanel:(NSSavePanel *)savePanel
{
[savePanel setDirectoryURL:[[self windowController] baseURL]];
return YES;
}
- (void)saveDocumentWithDelegate:(id)delegate
didSaveSelector:(SEL)selector
contextInfo:(void *)contextInfo
{
if ([self fileURL]) {
__block NSError *error = nil;
__block NSDictionary *attributes = nil;
ViURLManager *urlman = [ViURLManager defaultManager];
id<ViDeferred> deferred = [urlman attributesOfItemAtURL:[self fileURL]
onCompletion:^(NSURL *_url, NSDictionary *_attrs, NSError *_err) {
if (_err && ![_err isFileNotFoundError]) {
error = _err;
} else {
attributes = _attrs;
}
}];
if ([deferred respondsToSelector:@selector(waitInWindow:message:)])
[deferred waitInWindow:[_windowController window]
message:[NSString stringWithFormat:@"Saving %@...",
[[self fileURL] lastPathComponent]]];
else
[deferred wait];
DEBUG(@"done getting attributes of %@, error is %@", [self fileURL], error);
_didSaveDelegate = delegate;
_didSaveSelector = selector;
_didSaveContext = contextInfo;
if (!error && attributes && ![[attributes fileType] isEqualToString:NSFileTypeRegular])
error = [ViError errorWithFormat:@"%@ is not a regular file.", [[self fileURL] lastPathComponent]];
if (!error && attributes && ![[attributes fileModificationDate] isEqual:[self fileModificationDate]]) {
NSAlert *alert = [[NSAlert alloc] init];
[alert setMessageText:@"This document’s file has been changed by another application since you opened or saved it."];
[alert addButtonWithTitle:@"Don't Save"];
[alert addButtonWithTitle:@"Save"];
[alert setInformativeText:@"The changes made by the other application will be lost if you save. Save anyway?"];
[alert beginSheetModalForWindow:[_windowController window]
modalDelegate:self
didEndSelector:@selector(fileModifiedAlertDidEnd:returnCode:contextInfo:)
contextInfo:nil];
} else {
[self continueSavingAfterError:error];
}
} else
[super saveDocumentWithDelegate:delegate
didSaveSelector:selector
contextInfo:contextInfo];
}
- (BOOL)writeSafelyToURL:(NSURL *)url
ofType:(NSString *)typeName
forSaveOperation:(NSSaveOperationType)saveOperation
error:(NSError **)outError
{
DEBUG(@"write to %@", url);
_retrySaveOperation = NO;
if (![[_textStorage string] canBeConvertedToEncoding:_encoding]) {
NSString *reason = [NSString stringWithFormat:
@"The %@ encoding is not appropriate.",
[NSString localizedNameOfStringEncoding:_encoding]];
NSString *suggestion = @"Consider saving the file as UTF-8 instead.";
NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
reason, NSLocalizedFailureReasonErrorKey,
suggestion, NSLocalizedRecoverySuggestionErrorKey,
self, NSRecoveryAttempterErrorKey,
[NSArray arrayWithObjects:@"OK", @"Save as UTF-8", nil], NSLocalizedRecoveryOptionsErrorKey,
nil];
NSError *err = [NSError errorWithDomain:ViErrorDomain code:1 userInfo:userInfo];
if (![self presentError:err]) {
if (outError) /* Suppress the callers error. */
*outError = [ViError operationCancelled];
return NO;
}
if (saveOperation == NSSaveOperation || saveOperation == NSSaveAsOperation)
_encoding = NSUTF8StringEncoding;
}
NSData *data = [self dataOfType:typeName error:outError];
if (data == nil)
/* Should not happen. We've already checked for encoding problems. */
return NO;
__block NSError *returnError = nil;
ViURLManager *urlman = [ViURLManager defaultManager];
id<ViDeferred> deferred = [urlman writeDataSafely:data
toURL:url
onCompletion:^(NSURL *normalizedURL, NSDictionary *attributes, NSError *error) {
if (error) {
returnError = error;
} else {
[self message:@"%@: wrote %lu byte", normalizedURL, [data length]];
if (saveOperation == NSSaveOperation || saveOperation == NSSaveAsOperation) {
DEBUG(@"setting normalized URL %@", normalizedURL);
[self setFileURL:normalizedURL];
[self setFileModificationDate:[attributes fileModificationDate]];
[self updateChangeCount:NSChangeCleared];
if (saveOperation == NSSaveOperation)
[[ViEventManager defaultManager] emitDelayed:ViEventDidSaveDocument for:self with:self, nil];
else if (saveOperation == NSSaveAsOperation)
[[ViEventManager defaultManager] emit:ViEventDidSaveAsDocument for:self with:self, normalizedURL, nil];
}
if (_isTemporary)
[[ViURLManager defaultManager] notifyChangedDirectoryAtURL:[normalizedURL URLByDeletingLastPathComponent]];
_isTemporary = NO;
}
}];
if ([deferred respondsToSelector:@selector(waitInWindow:message:)])
[deferred waitInWindow:[_windowController window]
message:[NSString stringWithFormat:@"Saving %@...",
[url lastPathComponent]]];
else
[deferred wait];
DEBUG(@"done saving file, error is %@", returnError);
if (returnError) {
if (outError)
*outError = returnError;
return NO;
}
return YES;
}
- (BOOL)saveToURL:(NSURL *)absoluteURL
ofType:(NSString *)typeName
forSaveOperation:(NSSaveOperationType)saveOperation
error:(NSError **)outError
{
DEBUG(@"saving %@ to %@", self, absoluteURL);
if (saveOperation == NSSaveOperation)
[[ViEventManager defaultManager] emit:ViEventWillSaveDocument for:self with:self, nil];
else if (saveOperation == NSSaveAsOperation)
[[ViEventManager defaultManager] emit:ViEventWillSaveAsDocument for:self with:self, absoluteURL, nil];
[self endUndoGroup];
if ([self writeSafelyToURL:absoluteURL
ofType:typeName
forSaveOperation:saveOperation
error:outError]) {
_ignoreChangeCountNotification = YES;
[[self nextRunloop] setIgnoreChangeCountNotification:NO];
return YES;
}
return NO;
}
- (NSString *)suggestEncoding:(NSStringEncoding *)outEncoding forData:(NSData *)data
{
NSString *string = nil;
NSStringEncoding enc = 0;
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
/* Check for a user-overridden encoding in preferences. */
NSDictionary *encodingOverride = [userDefaults dictionaryForKey:@"encodingOverride"];
NSNumber *savedEncoding = [encodingOverride objectForKey:[[self fileURL] absoluteString]];
if (savedEncoding) {
enc = [savedEncoding unsignedIntegerValue];
string = [[NSString alloc] initWithData:data encoding:enc];
}
if (string == nil) {
/* Try to auto-detect the encoding. */
enc = [[ViCharsetDetector defaultDetector] encodingForData:data];
if (enc == 0)
/* Try UTF-8 if auto-detecting fails. */
enc = NSUTF8StringEncoding;
string = [[NSString alloc] initWithData:data encoding:enc];
if (string == nil) {
/* If all else fails, use iso-8859-1. */
enc = NSISOLatin1StringEncoding;
string = [[NSString alloc] initWithData:data encoding:enc];
}
}
if (outEncoding)
*outEncoding = enc;
return string;
}
- (BOOL)addData:(NSData *)data
{
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSString *aString = nil;
if (_forcedEncoding != 0) {
aString = [[NSString alloc] initWithData:data encoding:_forcedEncoding];
if (aString == nil) {
NSString *description = [NSString stringWithFormat:
@"The file can't be interpreted in %@ encoding.",
[NSString localizedNameOfStringEncoding:_forcedEncoding]];
NSString *suggestion = [NSString stringWithFormat:@"Keeping the %@ encoding.",
[NSString localizedNameOfStringEncoding:_encoding]];
NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
description, NSLocalizedDescriptionKey,
suggestion, NSLocalizedRecoverySuggestionErrorKey,
nil];
NSError *err = [NSError errorWithDomain:ViErrorDomain code:2 userInfo:userInfo];
[self presentError:err];
aString = [[NSString alloc] initWithData:data encoding:_encoding];
} else {
_encoding = _forcedEncoding;
/* Save the user-overridden encoding in preferences. */
NSMutableDictionary *encodingOverride = [NSMutableDictionary dictionaryWithDictionary:
[userDefaults dictionaryForKey:@"encodingOverride"]];
[encodingOverride setObject:[NSNumber numberWithUnsignedInteger:_encoding]
forKey:[[self fileURL] absoluteString]];
[userDefaults setObject:encodingOverride
forKey:@"encodingOverride"];
}
_forcedEncoding = 0;
} else
aString = [self suggestEncoding:&_encoding forData:data];
NSUInteger len = [_textStorage length];
if (len == 0)
[self setString:aString];
else {
[_textStorage replaceCharactersInRange:NSMakeRange(len, 0) withString:aString];
NSRange r = NSMakeRange(len, [aString length]);
[_textStorage setAttributes:[self typingAttributes] range:r];
}
return YES;
}
- (void)setString:(NSString *)aString
{
/*
* Disable the processing in textStorageDidProcessEditing,
* otherwise we'll parse the document multiple times.
*/
_ignoreEditing = YES;
[[_textStorage mutableString] setString:aString ?: @""];
[_textStorage setAttributes:[self typingAttributes]
range:NSMakeRange(0, [aString length])];
/* Force incremental syntax parsing. */
[self setLanguage:nil];
[self configureSyntax];
}
- (void)setData:(NSData *)data
{
[self setString:@""];
[self addData:data];
}
- (void)setEncoding:(id)sender
{
_forcedEncoding = [[sender representedObject] unsignedIntegerValue];
[self revertDocumentToSaved:nil];
}
- (void)setDisplayName:(NSString *)displayNameOrNil
{
[super setDisplayName:displayNameOrNil];
[_windowController synchronizeWindowTitleWithDocumentName];
}
- (NSString *)title
{
NSString *displayName = [self displayName];
if ([displayName length] == 0) {
displayName = [[self fileURL] lastPathComponent];
if ([displayName length] == 0)
displayName = [[self fileURL] host];
}
return displayName;
}
- (void)updateChangeCount:(NSDocumentChangeType)changeType
{
DEBUG(@"called from %@", [NSThread callStackSymbols]);
if (_ignoreChangeCountNotification) {
DEBUG(@"%s", "ignoring change count notification");
_ignoreChangeCountNotification = NO;
return;
}
BOOL edited = [self isDocumentEdited];
[super updateChangeCount:changeType];
[self setModified:[self isDocumentEdited]];
if (edited != _modified)
[[NSNotificationCenter defaultCenter] postNotificationName:ViDocumentEditedChangedNotification
object:self
userInfo:nil];
}
- (void)setFileURL:(NSURL *)absoluteURL
{
DEBUG(@"set url %@ (was %@)", absoluteURL, [self fileURL]);
if ([absoluteURL isEqual:[self fileURL]])
return;
[[ViDocumentController sharedDocumentController] updateURL:absoluteURL ofDocument:self];
[[ViEventManager defaultManager] emit:ViEventWillChangeURL for:self with:self, absoluteURL, nil];
[self willChangeValueForKey:@"title"];
[super setFileURL:absoluteURL];
[self didChangeValueForKey:@"title"];
[self configureSyntax];
_localMarks.name = [NSString stringWithFormat:@"Local marks in %@", [self title]];
[[ViEventManager defaultManager] emit:ViEventDidChangeURL for:self with:self, absoluteURL, nil];
}
- (void)closeAndWindow:(BOOL)canCloseWindow
{
if (_closed) {
DEBUG(@"already closed document %@", self);
return;
}
int code = 1; /* not saved */
[[ViEventManager defaultManager] emit:ViEventWillCloseDocument for:self with:self, nil];
DEBUG(@"closing, w/window: %s", canCloseWindow ? "YES" : "NO");
if (_loader) {
DEBUG(@"cancelling load callback %@", _loader);