forked from macvim-dev/macvim
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMMTextStorage.m
1253 lines (1060 loc) · 40.6 KB
/
MMTextStorage.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
/* vi:set ts=8 sts=4 sw=4 ft=objc:
*
* VIM - Vi IMproved by Bram Moolenaar
* MacVim GUI port by Bjorn Winckler
*
* Do ":help uganda" in Vim to read copying and usage conditions.
* Do ":help credits" in Vim to see a list of people who contributed.
* See README.txt for an overview of the Vim source code.
*/
/*
* MMTextStorage
*
* Text rendering related code.
*
* Note that:
* - There are exactly 'actualRows' number of rows
* - Each row is terminated by an EOL character ('\n')
* - Each row must cover exactly 'actualColumns' display cells
* - The attribute "MMWideChar" denotes a character that covers two cells, a
* character without this attribute covers one cell
* - Unicode line (U+2028) and paragraph (U+2029) terminators are considered
* invalid and are replaced by spaces
* - Spaces are used to fill out blank spaces
*
* In order to locate a (row,col) pair it is in general necessary to search one
* character at a time. To speed things up we cache the length of each row, as
* well as the offset of the last column searched within each row.
*
* If each character in the text storage has length 1 and is not wide, then
* there is no need to search for a (row, col) pair since it can easily be
* computed.
*/
#import "MMTextStorage.h"
#import "MacVim.h"
#import "Miscellaneous.h"
// Enable debug log messages for situations that should never occur.
#define MM_TS_PARANOIA_LOG 1
// TODO: What does DRAW_TRANSP flag do? If the background isn't drawn when
// this flag is set, then sometimes the character after the cursor becomes
// blank. Everything seems to work fine by just ignoring this flag.
#define DRAW_TRANSP 0x01 // draw with transparent bg
#define DRAW_BOLD 0x02 // draw bold text
#define DRAW_UNDERL 0x04 // draw underline text
#define DRAW_UNDERC 0x08 // draw undercurl text
#define DRAW_ITALIC 0x10 // draw italic text
#define DRAW_CURSOR 0x20
#define DRAW_STRIKE 0x40 // draw strikethrough text
#define DRAW_UNDERDOUBLE 0x80 // draw double underline
#define DRAW_UNDERDOTTED 0x100 // draw dotted underline
#define DRAW_UNDERDASHED 0x200 // draw dashed underline
#define DRAW_WIDE 0x1000 // (MacVim only) draw wide text
#define DRAW_COMP 0x2000 // (MacVim only) drawing composing char
static NSString *MMWideCharacterAttributeName = @"MMWideChar";
@interface MMTextStorage (Private)
- (void)lazyResize:(BOOL)force;
- (NSRange)charRangeForRow:(int)row column:(int*)col cells:(int*)cells;
- (void)fixInvalidCharactersInRange:(NSRange)range;
@end
@implementation MMTextStorage
- (id)init
{
if ((self = [super init])) {
backingStore = [[NSTextStorage alloc] init];
// NOTE! It does not matter which font is set here, Vim will set its
// own font on startup anyway. Just set some bogus values.
font = [[NSFont userFixedPitchFontOfSize:0] retain];
cellSize.height = 16.0;
cellSize.width = 6.0;
}
return self;
}
- (void)dealloc
{
ASLogDebug(@"");
#if MM_USE_ROW_CACHE
if (rowCache) {
free(rowCache);
rowCache = NULL;
}
#endif
[emptyRowString release]; emptyRowString = nil;
[boldItalicFontWide release]; boldItalicFontWide = nil;
[italicFontWide release]; italicFontWide = nil;
[boldFontWide release]; boldFontWide = nil;
[fontWide release]; fontWide = nil;
[boldItalicFont release]; boldItalicFont = nil;
[italicFont release]; italicFont = nil;
[boldFont release]; boldFont = nil;
[font release]; font = nil;
[defaultBackgroundColor release]; defaultBackgroundColor = nil;
[defaultForegroundColor release]; defaultForegroundColor = nil;
[backingStore release]; backingStore = nil;
[super dealloc];
}
- (NSString *)string
{
return [backingStore string];
}
- (NSDictionary *)attributesAtIndex:(NSUInteger)index
effectiveRange:(NSRangePointer)range
{
return [backingStore attributesAtIndex:index effectiveRange:range];
}
- (void)replaceCharactersInRange:(NSRange)range
withString:(NSString *)string
{
#if MM_TS_PARANOIA_LOG
ASLogWarn(@"Calling %@ on MMTextStorage is unsupported",
NSStringFromSelector(_cmd));
#endif
//[backingStore replaceCharactersInRange:range withString:string];
}
- (void)setAttributes:(NSDictionary *)attributes range:(NSRange)range
{
// NOTE! This method must be implemented since the text system calls it
// constantly to 'fix attributes', apply font substitution, etc.
#if 0
[backingStore setAttributes:attributes range:range];
#elif 1
// HACK! If the font attribute is being modified, then ensure that the new
// font has a fixed advancement which is either the same as the current
// font or twice that, depending on whether it is a 'wide' character that
// is being fixed or not.
//
// TODO: This code assumes that the characters in 'range' all have the same
// width.
NSFont *newFont = [attributes objectForKey:NSFontAttributeName];
if (newFont) {
// Allow disabling of font substitution via a user default. Not
// recommended since the typesetter hides the corresponding glyphs and
// the display gets messed up.
if ([[NSUserDefaults standardUserDefaults]
boolForKey:MMNoFontSubstitutionKey])
return;
float adv = cellSize.width;
if ([backingStore attribute:MMWideCharacterAttributeName
atIndex:range.location
effectiveRange:NULL])
adv += adv;
// Create a new font which has the 'fixed advance attribute' set.
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithFloat:adv], NSFontFixedAdvanceAttribute, nil];
NSFontDescriptor *desc = [newFont fontDescriptor];
desc = [desc fontDescriptorByAddingAttributes:dict];
newFont = [NSFont fontWithDescriptor:desc size:[newFont pointSize]];
// Now modify the 'attributes' dictionary to hold the new font.
NSMutableDictionary *newAttr = [NSMutableDictionary
dictionaryWithDictionary:attributes];
[newAttr setObject:newFont forKey:NSFontAttributeName];
[backingStore setAttributes:newAttr range:range];
} else {
[backingStore setAttributes:attributes range:range];
}
#endif
}
- (int)maxRows
{
return maxRows;
}
- (int)maxColumns
{
return maxColumns;
}
- (int)actualRows
{
return actualRows;
}
- (int)actualColumns
{
return actualColumns;
}
- (float)linespace
{
return linespace;
}
- (float)columnspace
{
return columnspace;
}
- (void)setLinespace:(float)newLinespace
{
NSLayoutManager *lm = [[self layoutManagers] objectAtIndex:0];
if (!lm) {
ASLogWarn(@"No layout manager available");
return;
}
linespace = newLinespace;
// NOTE: The linespace is added to the cell height in order for a multiline
// selection not to have white (background color) gaps between lines. Also
// this simplifies the code a lot because there is no need to check the
// linespace when calculating the size of the text view etc. When the
// linespace is non-zero the baseline will be adjusted as well; check
// MMTypesetter.
cellSize.height = linespace + [lm defaultLineHeightForFont:font];
}
- (void)setColumnspace:(float)newColumnspace
{
NSLayoutManager *lm = [[self layoutManagers] objectAtIndex:0];
if (!lm) {
ASLogWarn(@"No layout manager available");
return;
}
columnspace = newColumnspace;
float em = [@"m" sizeWithAttributes:
[NSDictionary dictionaryWithObject:font
forKey:NSFontAttributeName]].width;
float cellWidthMultiplier = [[NSUserDefaults standardUserDefaults]
floatForKey:MMCellWidthMultiplierKey];
cellSize.width = columnspace + ceilf(em * cellWidthMultiplier);
}
- (void)getMaxRows:(int*)rows columns:(int*)cols
{
if (rows) *rows = maxRows;
if (cols) *cols = maxColumns;
}
- (void)setMaxRows:(int)rows columns:(int)cols
{
// NOTE: Just remember the new values, the actual resizing is done lazily.
maxRows = rows;
maxColumns = cols;
}
- (void)drawString:(NSString *)string atRow:(int)row column:(int)col
cells:(int)cells withFlags:(int)flags
foregroundColor:(NSColor *)fg backgroundColor:(NSColor *)bg
specialColor:(NSColor *)sp
{
[self lazyResize:NO];
if (row < 0 || row >= maxRows || col < 0 || col >= maxColumns
|| col+cells > maxColumns || !string || !(fg && bg && sp))
return;
BOOL hasControlChars = [string rangeOfCharacterFromSet:
[NSCharacterSet controlCharacterSet]].location != NSNotFound;
if (hasControlChars) {
// HACK! If a string for some reason contains control characters, then
// draw blanks instead (otherwise charRangeForRow::: fails).
NSRange subRange = { 0, cells };
flags &= ~DRAW_WIDE;
string = [[emptyRowString string] substringWithRange:subRange];
}
// Find range of characters in text storage to replace.
int acol = col;
int acells = cells;
NSRange range = [self charRangeForRow:row column:&acol cells:&acells];
if (NSNotFound == range.location) {
#if MM_TS_PARANOIA_LOG
ASLogErr(@"INTERNAL ERROR: Out of bounds");
#endif
return;
}
// Create dictionary of attributes to apply to the new characters.
NSFont *theFont = font;
if (flags & DRAW_WIDE) {
if (flags & DRAW_BOLD)
theFont = flags & DRAW_ITALIC ? boldItalicFontWide : boldFontWide;
else if (flags & DRAW_ITALIC)
theFont = italicFontWide;
else
theFont = fontWide;
} else {
if (flags & DRAW_BOLD)
theFont = flags & DRAW_ITALIC ? boldItalicFont : boldFont;
else if (flags & DRAW_ITALIC)
theFont = italicFont;
}
NSMutableDictionary *attributes =
[NSMutableDictionary dictionaryWithObjectsAndKeys:
theFont, NSFontAttributeName,
bg, NSBackgroundColorAttributeName,
fg, NSForegroundColorAttributeName,
sp, NSUnderlineColorAttributeName,
[NSNumber numberWithInt:0], NSLigatureAttributeName,
nil];
if (flags & DRAW_UNDERL) {
NSNumber *value = [NSNumber numberWithInt:(NSUnderlineStyleSingle
| NSUnderlinePatternSolid)]; // | NSUnderlineByWordMask
[attributes setObject:value forKey:NSUnderlineStyleAttributeName];
}
if (flags & DRAW_STRIKE) {
NSNumber *value = [NSNumber numberWithInt:(NSUnderlineStyleSingle
| NSUnderlinePatternSolid)]; // | NSUnderlineByWordMask
[attributes setObject:value forKey:NSStrikethroughStyleAttributeName];
}
if (flags & DRAW_UNDERC) {
// TODO: figure out how do draw proper undercurls
NSNumber *value = [NSNumber numberWithInt:(NSUnderlineStyleThick
| NSUnderlinePatternDot)]; // | NSUnderlineByWordMask
[attributes setObject:value forKey:NSUnderlineStyleAttributeName];
}
// Mark these characters as wide. This attribute is subsequently checked
// when translating (row,col) pairs to offsets within 'backingStore'.
if (flags & DRAW_WIDE)
[attributes setObject:[NSNull null]
forKey:MMWideCharacterAttributeName];
// Replace characters in text storage and apply new attributes.
NSRange r = NSMakeRange(range.location, [string length]);
[backingStore replaceCharactersInRange:range withString:string];
[backingStore setAttributes:attributes range:r];
NSInteger changeInLength = [string length] - range.length;
if (acells != cells || acol != col) {
if (acells == cells + 1) {
// NOTE: A normal width character replaced a double width
// character. To maintain the invariant that each row covers the
// same amount of cells, we compensate by adding an empty column.
[backingStore replaceCharactersInRange:NSMakeRange(NSMaxRange(r),0)
withAttributedString:[emptyRowString
attributedSubstringFromRange:NSMakeRange(0,1)]];
++changeInLength;
#if 0
} else if (acol == col - 1) {
[backingStore replaceCharactersInRange:NSMakeRange(r.location,0)
withAttributedString:[emptyRowString
attributedSubstringFromRange:NSMakeRange(0,1)]];
++changeInLength;
} else if (acol == col + 1) {
[backingStore replaceCharactersInRange:NSMakeRange(r.location-1,1)
withAttributedString:[emptyRowString
attributedSubstringFromRange:NSMakeRange(0,2)]];
++changeInLength;
#endif
} else {
// NOTE: It seems that this never gets called. If it ever does,
// then there is another case to treat.
#if MM_TS_PARANOIA_LOG
ASLogWarn(@"row=%d col=%d acol=%d cells=%d acells=%d", row, col,
acol, cells, acells);
#endif
}
}
if ((flags & DRAW_WIDE) || [string length] != cells)
characterEqualsColumn = NO;
[self fixInvalidCharactersInRange:r];
#if 0
ASLogDebug(@"length=%d row=%d col=%d cells=%d replaceRange=%@ change=%d",
[string length], row, col, cells,
NSStringFromRange(r), changeInLength);
#endif
[self edited:(NSTextStorageEditedCharacters|NSTextStorageEditedAttributes)
range:range changeInLength:changeInLength];
#if MM_USE_ROW_CACHE
rowCache[row].length += changeInLength;
#endif
}
/*
* Delete 'count' lines from 'row' and insert 'count' empty lines at the bottom
* of the scroll region.
*/
- (void)deleteLinesFromRow:(int)row lineCount:(int)count
scrollBottom:(int)bottom left:(int)left right:(int)right
color:(NSColor *)color
{
[self lazyResize:NO];
if (row < 0 || row+count > maxRows || bottom > maxRows || left < 0
|| right > maxColumns)
return;
int total = 1 + bottom - row;
int move = total - count;
int width = right - left + 1;
int destRow = row;
NSRange destRange, srcRange;
int i;
for (i = 0; i < move; ++i, ++destRow) {
int acol = left;
int acells = width;
destRange = [self charRangeForRow:destRow column:&acol cells:&acells];
#if MM_TS_PARANOIA_LOG
if (acells != width || acol != left)
ASLogErr(@"INTERNAL ERROR");
#endif
acol = left; acells = width;
srcRange = [self charRangeForRow:(destRow+count) column:&acol
cells:&acells];
#if MM_TS_PARANOIA_LOG
if (acells != width || acol != left)
ASLogErr(@"INTERNAL ERROR");
#endif
if (NSNotFound == destRange.location || NSNotFound == srcRange.location)
{
#if MM_TS_PARANOIA_LOG
ASLogErr(@"INTERNAL ERROR: Out of bounds");
#endif
return;
}
NSAttributedString *srcString = [backingStore
attributedSubstringFromRange:srcRange];
[backingStore replaceCharactersInRange:destRange
withAttributedString:srcString];
[self edited:(NSTextStorageEditedCharacters
| NSTextStorageEditedAttributes) range:destRange
changeInLength:([srcString length]-destRange.length)];
#if MM_USE_ROW_CACHE
rowCache[destRow].length += [srcString length] - destRange.length;
#endif
}
NSRange emptyRange = {0,width};
NSAttributedString *emptyString =
[emptyRowString attributedSubstringFromRange:emptyRange];
NSDictionary *attribs = [NSDictionary dictionaryWithObjectsAndKeys:
font, NSFontAttributeName,
color, NSBackgroundColorAttributeName, nil];
for (i = 0; i < count; ++i, ++destRow) {
int acol = left;
int acells = width;
destRange = [self charRangeForRow:destRow column:&acol cells:&acells];
#if MM_TS_PARANOIA_LOG
if (acells != width || acol != left)
ASLogErr(@"INTERNAL ERROR");
#endif
if (NSNotFound == destRange.location) {
#if MM_TS_PARANOIA_LOG
ASLogErr(@"INTERNAL ERROR: Out of bounds");
#endif
return;
}
[backingStore replaceCharactersInRange:destRange
withAttributedString:emptyString];
[backingStore setAttributes:attribs
range:NSMakeRange(destRange.location, width)];
[self edited:(NSTextStorageEditedAttributes
| NSTextStorageEditedCharacters) range:destRange
changeInLength:([emptyString length]-destRange.length)];
#if MM_USE_ROW_CACHE
rowCache[destRow].length += [emptyString length] - destRange.length;
#endif
}
}
/*
* Insert 'count' empty lines at 'row' and delete 'count' lines from the bottom
* of the scroll region.
*/
- (void)insertLinesAtRow:(int)row lineCount:(int)count
scrollBottom:(int)bottom left:(int)left right:(int)right
color:(NSColor *)color
{
[self lazyResize:NO];
if (row < 0 || row+count > maxRows || bottom > maxRows || left < 0
|| right > maxColumns)
return;
int total = 1 + bottom - row;
int move = total - count;
int width = right - left + 1;
int destRow = bottom;
int srcRow = row + move - 1;
NSRange destRange, srcRange;
int i;
for (i = 0; i < move; ++i, --destRow, --srcRow) {
int acol = left;
int acells = width;
destRange = [self charRangeForRow:destRow column:&acol cells:&acells];
#if MM_TS_PARANOIA_LOG
if (acells != width || acol != left)
ASLogErr(@"INTERNAL ERROR");
#endif
acol = left; acells = width;
srcRange = [self charRangeForRow:srcRow column:&acol cells:&acells];
#if MM_TS_PARANOIA_LOG
if (acells != width || acol != left)
ASLogErr(@"INTERNAL ERROR");
#endif
if (NSNotFound == destRange.location || NSNotFound == srcRange.location)
{
#if MM_TS_PARANOIA_LOG
ASLogErr(@"INTERNAL ERROR: Out of bounds");
#endif
return;
}
NSAttributedString *srcString = [backingStore
attributedSubstringFromRange:srcRange];
[backingStore replaceCharactersInRange:destRange
withAttributedString:srcString];
[self edited:(NSTextStorageEditedCharacters
| NSTextStorageEditedAttributes) range:destRange
changeInLength:([srcString length]-destRange.length)];
#if MM_USE_ROW_CACHE
rowCache[destRow].length += [srcString length] - destRange.length;
#endif
}
NSRange emptyRange = {0,width};
NSAttributedString *emptyString =
[emptyRowString attributedSubstringFromRange:emptyRange];
NSDictionary *attribs = [NSDictionary dictionaryWithObjectsAndKeys:
font, NSFontAttributeName,
color, NSBackgroundColorAttributeName, nil];
for (i = 0; i < count; ++i, --destRow) {
int acol = left;
int acells = width;
destRange = [self charRangeForRow:destRow column:&acol cells:&acells];
#if MM_TS_PARANOIA_LOG
if (acells != width || acol != left)
ASLogErr(@"INTERNAL ERROR");
#endif
if (NSNotFound == destRange.location) {
#if MM_TS_PARANOIA_LOG
ASLogErr(@"INTERNAL ERROR: Out of bounds");
#endif
return;
}
[backingStore replaceCharactersInRange:destRange
withAttributedString:emptyString];
[backingStore setAttributes:attribs
range:NSMakeRange(destRange.location, width)];
[self edited:(NSTextStorageEditedAttributes
| NSTextStorageEditedCharacters) range:destRange
changeInLength:([emptyString length]-destRange.length)];
#if MM_USE_ROW_CACHE
rowCache[destRow].length += [emptyString length] - destRange.length;
#endif
}
}
- (void)clearBlockFromRow:(int)row1 column:(int)col1 toRow:(int)row2
column:(int)col2 color:(NSColor *)color
{
[self lazyResize:NO];
if (row1 < 0 || row2 >= maxRows || col1 < 0 || col2 > maxColumns)
return;
NSDictionary *attribs = [NSDictionary dictionaryWithObjectsAndKeys:
font, NSFontAttributeName,
color, NSBackgroundColorAttributeName, nil];
int cells = col2 - col1 + 1;
NSRange range, emptyRange = {0, cells};
NSAttributedString *emptyString =
[emptyRowString attributedSubstringFromRange:emptyRange];
int r;
for (r=row1; r<=row2; ++r) {
int acol = col1;
int acells = cells;
range = [self charRangeForRow:r column:&acol cells:&acells];
#if MM_TS_PARANOIA_LOG
if (acells != cells || acol != col1)
ASLogErr(@"INTERNAL ERROR");
#endif
if (NSNotFound == range.location) {
#if MM_TS_PARANOIA_LOG
ASLogErr(@"INTERNAL ERROR: Out of bounds");
#endif
return;
}
[backingStore replaceCharactersInRange:range
withAttributedString:emptyString];
[backingStore setAttributes:attribs
range:NSMakeRange(range.location, cells)];
[self edited:(NSTextStorageEditedAttributes
| NSTextStorageEditedCharacters) range:range
changeInLength:cells-range.length];
#if MM_USE_ROW_CACHE
rowCache[r].length += cells - range.length;
#endif
}
}
- (void)clearAll
{
[self lazyResize:YES];
}
- (void)setDefaultColorsBackground:(NSColor *)bgColor
foreground:(NSColor *)fgColor
{
if (defaultBackgroundColor != bgColor) {
[defaultBackgroundColor release];
defaultBackgroundColor = bgColor ? [bgColor retain] : nil;
}
// NOTE: The default foreground color isn't actually used for anything, but
// other class instances might want to be able to access it so it is stored
// here.
if (defaultForegroundColor != fgColor) {
[defaultForegroundColor release];
defaultForegroundColor = fgColor ? [fgColor retain] : nil;
}
}
- (void)setFont:(NSFont*)newFont
{
if (newFont && font != newFont) {
[boldItalicFont release]; boldItalicFont = nil;
[italicFont release]; italicFont = nil;
[boldFont release]; boldFont = nil;
[font release]; font = nil;
// NOTE! When setting a new font we make sure that the advancement of
// each glyph is fixed.
float em = [@"m" sizeWithAttributes:
[NSDictionary dictionaryWithObject:newFont
forKey:NSFontAttributeName]].width;
float cellWidthMultiplier = [[NSUserDefaults standardUserDefaults]
floatForKey:MMCellWidthMultiplierKey];
// NOTE! Even though NSFontFixedAdvanceAttribute is a float, it will
// only render at integer sizes. Hence, we restrict the cell width to
// an integer here, otherwise the window width and the actual text
// width will not match.
cellSize.width = ceilf(em * cellWidthMultiplier);
float pointSize = [newFont pointSize];
NSDictionary *dict = [NSDictionary
dictionaryWithObject:[NSNumber numberWithFloat:cellSize.width]
forKey:NSFontFixedAdvanceAttribute];
NSFontDescriptor *desc = [newFont fontDescriptor];
desc = [desc fontDescriptorByAddingAttributes:dict];
font = [NSFont fontWithDescriptor:desc size:pointSize];
[font retain];
NSLayoutManager *lm = [[self layoutManagers] objectAtIndex:0];
if (lm) {
cellSize.height = linespace + [lm defaultLineHeightForFont:font];
cellSize.width = columnspace + ceilf(em * cellWidthMultiplier);
} else {
// Should never happen, set some bogus value for cell height.
ASLogWarn(@"No layout manager available");
cellSize.height = linespace + 16.0;
}
// NOTE: The font manager does not care about the 'font fixed advance'
// attribute, so after converting the font we have to add this
// attribute again.
boldFont = [[NSFontManager sharedFontManager]
convertFont:font toHaveTrait:NSBoldFontMask];
desc = [boldFont fontDescriptor];
desc = [desc fontDescriptorByAddingAttributes:dict];
boldFont = [NSFont fontWithDescriptor:desc size:pointSize];
[boldFont retain];
italicFont = [[NSFontManager sharedFontManager]
convertFont:font toHaveTrait:NSItalicFontMask];
desc = [italicFont fontDescriptor];
desc = [desc fontDescriptorByAddingAttributes:dict];
italicFont = [NSFont fontWithDescriptor:desc size:pointSize];
[italicFont retain];
boldItalicFont = [[NSFontManager sharedFontManager]
convertFont:italicFont toHaveTrait:NSBoldFontMask];
desc = [boldItalicFont fontDescriptor];
desc = [desc fontDescriptorByAddingAttributes:dict];
boldItalicFont = [NSFont fontWithDescriptor:desc size:pointSize];
[boldItalicFont retain];
}
}
- (void)setWideFont:(NSFont *)newFont
{
if (!newFont) {
// Use the normal font as the wide font (note that the normal font may
// very well include wide characters.)
if (font) [self setWideFont:font];
} else if (newFont != fontWide) {
[boldItalicFontWide release]; boldItalicFontWide = nil;
[italicFontWide release]; italicFontWide = nil;
[boldFontWide release]; boldFontWide = nil;
[fontWide release]; fontWide = nil;
float pointSize = [newFont pointSize];
NSFontDescriptor *desc = [newFont fontDescriptor];
NSDictionary *dictWide = [NSDictionary
dictionaryWithObject:[NSNumber numberWithFloat:2*cellSize.width]
forKey:NSFontFixedAdvanceAttribute];
desc = [desc fontDescriptorByAddingAttributes:dictWide];
fontWide = [NSFont fontWithDescriptor:desc size:pointSize];
[fontWide retain];
boldFontWide = [[NSFontManager sharedFontManager]
convertFont:fontWide toHaveTrait:NSBoldFontMask];
desc = [boldFontWide fontDescriptor];
desc = [desc fontDescriptorByAddingAttributes:dictWide];
boldFontWide = [NSFont fontWithDescriptor:desc size:pointSize];
[boldFontWide retain];
italicFontWide = [[NSFontManager sharedFontManager]
convertFont:fontWide toHaveTrait:NSItalicFontMask];
desc = [italicFontWide fontDescriptor];
desc = [desc fontDescriptorByAddingAttributes:dictWide];
italicFontWide = [NSFont fontWithDescriptor:desc size:pointSize];
[italicFontWide retain];
boldItalicFontWide = [[NSFontManager sharedFontManager]
convertFont:italicFontWide toHaveTrait:NSBoldFontMask];
desc = [boldItalicFontWide fontDescriptor];
desc = [desc fontDescriptorByAddingAttributes:dictWide];
boldItalicFontWide = [NSFont fontWithDescriptor:desc size:pointSize];
[boldItalicFontWide retain];
}
}
- (NSFont*)font
{
return font;
}
- (NSFont*)fontWide
{
return fontWide;
}
- (NSColor *)defaultBackgroundColor
{
return defaultBackgroundColor;
}
- (NSColor *)defaultForegroundColor
{
return defaultForegroundColor;
}
- (NSSize)size
{
return NSMakeSize(maxColumns*cellSize.width, maxRows*cellSize.height);
}
- (NSSize)cellSize
{
return cellSize;
}
- (NSRect)rectForRowsInRange:(NSRange)range
{
NSRect rect = { {0, 0}, {0, 0} };
NSUInteger start = range.location > maxRows ? maxRows : range.location;
NSUInteger length = range.length;
if (start+length > maxRows)
length = maxRows - start;
rect.origin.y = cellSize.height * start;
rect.size.height = cellSize.height * length;
return rect;
}
- (NSRect)rectForColumnsInRange:(NSRange)range
{
NSRect rect = { {0, 0}, {0, 0} };
NSUInteger start = range.location > maxColumns ? maxColumns : range.location;
NSUInteger length = range.length;
if (start+length > maxColumns)
length = maxColumns - start;
rect.origin.x = cellSize.width * start;
rect.size.width = cellSize.width * length;
return rect;
}
- (NSUInteger)characterIndexForRow:(int)row column:(int)col
{
int cells = 1;
NSRange range = [self charRangeForRow:row column:&col cells:&cells];
return range.location != NSNotFound ? range.location : 0;
}
// XXX: unused at the moment
- (BOOL)resizeToFitSize:(NSSize)size
{
int rows = maxRows, cols = maxColumns;
[self fitToSize:size rows:&rows columns:&cols];
if (rows != maxRows || cols != maxColumns) {
[self setMaxRows:rows columns:cols];
return YES;
}
// Return NO only if dimensions did not change.
return NO;
}
- (NSSize)fitToSize:(NSSize)size
{
return [self fitToSize:size rows:NULL columns:NULL];
}
- (NSSize)fitToSize:(NSSize)size rows:(int *)rows columns:(int *)columns
{
NSSize curSize = [self size];
NSSize fitSize = curSize;
int fitRows = maxRows;
int fitCols = maxColumns;
if (size.height < curSize.height) {
// Remove lines until the height of the text storage fits inside
// 'size'. However, always make sure there are at least 3 lines in the
// text storage. (Why 3? It seem Vim never allows less than 3 lines.)
//
// TODO: No need to search since line height is fixed, just calculate
// the new height.
int rowCount = maxRows;
int rowsToRemove;
for (rowsToRemove = 0; rowsToRemove < maxRows-3; ++rowsToRemove) {
float height = cellSize.height*rowCount;
if (height <= size.height) {
fitSize.height = height;
break;
}
--rowCount;
}
fitRows -= rowsToRemove;
} else if (size.height > curSize.height) {
float fh = cellSize.height;
if (fh < 1.0f) fh = 1.0f;
fitRows = floor(size.height/fh);
// Sanity checking in case unusual window sizes lead to degenerate results
if (fitRows < 1)
fitRows = 1;
fitSize.height = fh*fitRows;
}
if (size.width != curSize.width) {
float fw = cellSize.width;
if (fw < 1.0f) fw = 1.0f;
fitCols = floor(size.width/fw);
// Sanity checking in case unusual window sizes lead to degenerate results
if (fitCols < 1)
fitCols = 1;
fitSize.width = fw*fitCols;
}
if (rows) *rows = fitRows;
if (columns) *columns = fitCols;
return fitSize;
}
- (NSRect)boundingRectForCharacterAtRow:(int)row column:(int)col
{
#if 1
// This properly computes the position of where Vim expects the glyph to be
// drawn. Had the typesetter actually computed the right position of each
// character and not hidden some, this code would be correct.
NSRect rect = NSZeroRect;
rect.origin.x = col*cellSize.width;
rect.origin.y = row*cellSize.height;
rect.size = cellSize;
// Wide character take up twice the width of a normal character.
int cells = 1;
NSRange r = [self charRangeForRow:row column:&col cells:&cells];
if (NSNotFound != r.location
&& [backingStore attribute:MMWideCharacterAttributeName
atIndex:r.location
effectiveRange:nil])
rect.size.width += rect.size.width;
return rect;
#else
// Use layout manager to compute bounding rect. This works in situations
// where the layout manager decides to hide glyphs (Vim assumes all glyphs
// are drawn).
NSLayoutManager *lm = [[self layoutManagers] objectAtIndex:0];
NSTextContainer *tc = [[lm textContainers] objectAtIndex:0];
int cells = 1;
NSRange range = [self charRangeForRow:row column:&col cells:&cells];
NSRange glyphRange = [lm glyphRangeForCharacterRange:range
actualCharacterRange:NULL];
return [lm boundingRectForGlyphRange:glyphRange inTextContainer:tc];
#endif
}
#if MM_USE_ROW_CACHE
- (MMRowCacheEntry *)rowCache
{
return rowCache;
}
#endif
@end // MMTextStorage
@implementation MMTextStorage (Private)
- (void)lazyResize:(BOOL)force
{
// Do nothing if the dimensions are already right.
if (!force && actualRows == maxRows && actualColumns == maxColumns)
return;
NSRange oldRange = NSMakeRange(0, [backingStore length]);
actualRows = maxRows;
actualColumns = maxColumns;
characterEqualsColumn = YES;
#if MM_USE_ROW_CACHE
free(rowCache);
rowCache = (MMRowCacheEntry*)calloc(actualRows, sizeof(MMRowCacheEntry));
#endif
NSDictionary *dict;
if (defaultBackgroundColor) {
dict = [NSDictionary dictionaryWithObjectsAndKeys:
font, NSFontAttributeName,
defaultBackgroundColor, NSBackgroundColorAttributeName, nil];
} else {
dict = [NSDictionary dictionaryWithObjectsAndKeys:
font, NSFontAttributeName, nil];
}
NSMutableString *rowString = [NSMutableString string];
int i;