1 /* vi:set ts=8 sts=4 sw=4 ft=objc:
3 * VIM - Vi IMproved by Bram Moolenaar
4 * MacVim GUI port by Bjorn Winckler
6 * Do ":help uganda" in Vim to read copying and usage conditions.
7 * Do ":help credits" in Vim to see a list of people who contributed.
8 * See README.txt for an overview of the Vim source code.
13 * Text rendering related code.
16 * - There are exactly 'actualRows' number of rows
17 * - Each row is terminated by an EOL character ('\n')
18 * - Each row must cover exactly 'actualColumns' display cells
19 * - The attribute "MMWideChar" denotes a character that covers two cells, a
20 * character without this attribute covers one cell
21 * - Unicode line (U+2028) and paragraph (U+2029) terminators are considered
22 * invalid and are replaced by spaces
23 * - Spaces are used to fill out blank spaces
25 * In order to locate a (row,col) pair it is in general necessary to search one
26 * character at a time. To speed things up we cache the length of each row, as
27 * well as the offset of the last column searched within each row.
29 * If each character in the text storage has length 1 and is not wide, then
30 * there is no need to search for a (row, col) pair since it can easily be
34 #import "MMTextStorage.h"
36 #import "Miscellaneous.h"
40 // Enable debug log messages for situations that should never occur.
41 #define MM_TS_PARANOIA_LOG 1
45 // TODO: What does DRAW_TRANSP flag do? If the background isn't drawn when
46 // this flag is set, then sometimes the character after the cursor becomes
47 // blank. Everything seems to work fine by just ignoring this flag.
48 #define DRAW_TRANSP 0x01 /* draw with transparant bg */
49 #define DRAW_BOLD 0x02 /* draw bold text */
50 #define DRAW_UNDERL 0x04 /* draw underline text */
51 #define DRAW_UNDERC 0x08 /* draw undercurl text */
52 #define DRAW_ITALIC 0x10 /* draw italic text */
53 #define DRAW_CURSOR 0x20
56 static NSString *MMWideCharacterAttributeName = @"MMWideChar";
61 @interface MMTextStorage (Private)
62 - (void)lazyResize:(BOOL)force;
63 - (NSRange)charRangeForRow:(int)row column:(int*)col cells:(int*)cells;
64 - (void)fixInvalidCharactersInRange:(NSRange)range;
69 @implementation MMTextStorage
73 if ((self = [super init])) {
74 attribString = [[NSMutableAttributedString alloc] initWithString:@""];
75 // NOTE! It does not matter which font is set here, Vim will set its
76 // own font on startup anyway. Just set some bogus values.
77 font = [[NSFont userFixedPitchFontOfSize:0] retain];
78 cellSize.height = [font pointSize];
79 cellSize.width = [font defaultLineHeightForFont];
87 //NSLog(@"MMTextStorage dealloc");
95 [emptyRowString release]; emptyRowString = nil;
96 [boldItalicFontWide release]; boldItalicFontWide = nil;
97 [italicFontWide release]; italicFontWide = nil;
98 [boldFontWide release]; boldFontWide = nil;
99 [fontWide release]; fontWide = nil;
100 [boldItalicFont release]; boldItalicFont = nil;
101 [italicFont release]; italicFont = nil;
102 [boldFont release]; boldFont = nil;
103 [font release]; font = nil;
104 [defaultBackgroundColor release]; defaultBackgroundColor = nil;
105 [defaultForegroundColor release]; defaultForegroundColor = nil;
106 [attribString release]; attribString = nil;
112 return [attribString string];
115 - (NSDictionary *)attributesAtIndex:(unsigned)index
116 effectiveRange:(NSRangePointer)range
118 if (index >= [attribString length]) {
120 *range = NSMakeRange(NSNotFound, 0);
122 return [NSDictionary dictionary];
125 return [attribString attributesAtIndex:index effectiveRange:range];
128 - (id)attribute:(NSString *)attrib atIndex:(unsigned)index
129 effectiveRange:(NSRangePointer)range
131 return [attribString attribute:attrib atIndex:index effectiveRange:range];
134 - (void)replaceCharactersInRange:(NSRange)range
135 withString:(NSString *)string
137 #if MM_TS_PARANOIA_LOG
138 NSLog(@"WARNING: calling %s on MMTextStorage is unsupported", _cmd);
140 //[attribString replaceCharactersInRange:range withString:string];
143 - (void)setAttributes:(NSDictionary *)attributes range:(NSRange)range
145 //NSLog(@"%s%@", _cmd, NSStringFromRange(range));
147 // NOTE! This method must be implemented since the text system calls it
148 // constantly to 'fix attributes', apply font substitution, etc.
150 [attribString setAttributes:attributes range:range];
152 // HACK! If the font attribute is being modified, then ensure that the new
153 // font has a fixed advancement which is either the same as the current
154 // font or twice that, depending on whether it is a 'wide' character that
155 // is being fixed or not.
157 // TODO: This code assumes that the characters in 'range' all have the same
159 NSFont *newFont = [attributes objectForKey:NSFontAttributeName];
161 // Allow disabling of font substitution via a user default. Not
162 // recommended since the typesetter hides the corresponding glyphs and
163 // the display gets messed up.
164 if ([[NSUserDefaults standardUserDefaults]
165 boolForKey:MMNoFontSubstitutionKey])
168 float adv = cellSize.width;
169 if ([attribString attribute:MMWideCharacterAttributeName
170 atIndex:range.location
171 effectiveRange:NULL])
174 // Create a new font which has the 'fixed advance attribute' set.
175 NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
176 [NSNumber numberWithFloat:adv], NSFontFixedAdvanceAttribute, nil];
177 NSFontDescriptor *desc = [newFont fontDescriptor];
178 desc = [desc fontDescriptorByAddingAttributes:dict];
179 newFont = [NSFont fontWithDescriptor:desc size:[newFont pointSize]];
181 // Now modify the 'attributes' dictionary to hold the new font.
182 NSMutableDictionary *newAttr = [NSMutableDictionary
183 dictionaryWithDictionary:attributes];
184 [newAttr setObject:newFont forKey:NSFontAttributeName];
186 [attribString setAttributes:newAttr range:range];
188 //NSLog(@"NOT fixing font attribute!");
189 [attribString setAttributes:attributes range:range];
211 return actualColumns;
219 - (void)setLinespace:(float)newLinespace
221 NSLayoutManager *lm = [[self layoutManagers] objectAtIndex:0];
223 linespace = newLinespace;
225 // NOTE: The linespace is added to the cell height in order for a multiline
226 // selection not to have white (background color) gaps between lines. Also
227 // this simplifies the code a lot because there is no need to check the
228 // linespace when calculating the size of the text view etc. When the
229 // linespace is non-zero the baseline will be adjusted as well; check
231 cellSize.height = linespace + (lm ? [lm defaultLineHeightForFont:font]
232 : [font defaultLineHeightForFont]);
235 - (void)getMaxRows:(int*)rows columns:(int*)cols
237 if (rows) *rows = maxRows;
238 if (cols) *cols = maxColumns;
241 - (void)setMaxRows:(int)rows columns:(int)cols
243 // NOTE: Just remember the new values, the actual resizing is done lazily.
248 - (void)drawString:(NSString *)string atRow:(int)row column:(int)col
249 cells:(int)cells withFlags:(int)flags
250 foregroundColor:(NSColor *)fg backgroundColor:(NSColor *)bg
251 specialColor:(NSColor *)sp
253 //NSLog(@"replaceString:atRow:%d column:%d withFlags:%d "
254 // "foreground:%@ background:%@ special:%@",
255 // row, col, flags, fg, bg, sp);
256 [self lazyResize:NO];
258 if (row < 0 || row >= maxRows || col < 0 || col >= maxColumns
259 || col+cells > maxColumns || !string || !(fg && bg && sp))
262 BOOL hasControlChars = [string rangeOfCharacterFromSet:
263 [NSCharacterSet controlCharacterSet]].location != NSNotFound;
264 if (hasControlChars) {
265 // HACK! If a string for some reason contains control characters, then
266 // draw blanks instead (otherwise charRangeForRow::: fails).
267 NSRange subRange = { 0, cells };
269 string = [[emptyRowString string] substringWithRange:subRange];
272 // Find range of characters in text storage to replace.
275 NSRange range = [self charRangeForRow:row column:&acol cells:&acells];
276 if (NSNotFound == range.location) {
277 #if MM_TS_PARANOIA_LOG
278 NSLog(@"INTERNAL ERROR [%s] Out of bounds", _cmd);
283 // Create dictionary of attributes to apply to the new characters.
284 NSFont *theFont = font;
285 if (flags & DRAW_WIDE) {
286 if (flags & DRAW_BOLD)
287 theFont = flags & DRAW_ITALIC ? boldItalicFontWide : boldFontWide;
288 else if (flags & DRAW_ITALIC)
289 theFont = italicFontWide;
293 if (flags & DRAW_BOLD)
294 theFont = flags & DRAW_ITALIC ? boldItalicFont : boldFont;
295 else if (flags & DRAW_ITALIC)
296 theFont = italicFont;
299 NSMutableDictionary *attributes =
300 [NSMutableDictionary dictionaryWithObjectsAndKeys:
301 theFont, NSFontAttributeName,
302 bg, NSBackgroundColorAttributeName,
303 fg, NSForegroundColorAttributeName,
304 sp, NSUnderlineColorAttributeName,
307 if (flags & DRAW_UNDERL) {
308 NSNumber *value = [NSNumber numberWithInt:(NSUnderlineStyleSingle
309 | NSUnderlinePatternSolid)]; // | NSUnderlineByWordMask
310 [attributes setObject:value forKey:NSUnderlineStyleAttributeName];
313 if (flags & DRAW_UNDERC) {
314 // TODO: figure out how do draw proper undercurls
315 NSNumber *value = [NSNumber numberWithInt:(NSUnderlineStyleThick
316 | NSUnderlinePatternDot)]; // | NSUnderlineByWordMask
317 [attributes setObject:value forKey:NSUnderlineStyleAttributeName];
320 // Mark these characters as wide. This attribute is subsequently checked
321 // when translating (row,col) pairs to offsets within 'attribString'.
322 if (flags & DRAW_WIDE)
323 [attributes setObject:[NSNull null]
324 forKey:MMWideCharacterAttributeName];
326 // Replace characters in text storage and apply new attributes.
327 NSRange r = NSMakeRange(range.location, [string length]);
328 [attribString replaceCharactersInRange:range withString:string];
329 [attribString setAttributes:attributes range:r];
331 unsigned changeInLength = [string length] - range.length;
332 if (acells != cells || acol != col) {
333 if (acells == cells + 1) {
334 // NOTE: A normal width character replaced a double width
335 // character. To maintain the invariant that each row covers the
336 // same amount of cells, we compensate by adding an empty column.
337 [attribString replaceCharactersInRange:NSMakeRange(NSMaxRange(r),0)
338 withAttributedString:[emptyRowString
339 attributedSubstringFromRange:NSMakeRange(0,1)]];
342 } else if (acol == col - 1) {
343 NSLog(@"acol == col - 1");
344 [attribString replaceCharactersInRange:NSMakeRange(r.location,0)
345 withAttributedString:[emptyRowString
346 attributedSubstringFromRange:NSMakeRange(0,1)]];
348 } else if (acol == col + 1) {
349 NSLog(@"acol == col + 1");
350 [attribString replaceCharactersInRange:NSMakeRange(r.location-1,1)
351 withAttributedString:[emptyRowString
352 attributedSubstringFromRange:NSMakeRange(0,2)]];
356 // NOTE: It seems that this never gets called. If it ever does,
357 // then there is another case to treat.
358 #if MM_TS_PARANOIA_LOG
359 NSLog(@"row=%d col=%d acol=%d cells=%d acells=%d", row, col, acol,
365 if ((flags & DRAW_WIDE) || [string length] != cells)
366 characterEqualsColumn = NO;
368 [self fixInvalidCharactersInRange:r];
370 [self edited:(NSTextStorageEditedCharacters|NSTextStorageEditedAttributes)
371 range:range changeInLength:changeInLength];
374 rowCache[row].length += changeInLength;
379 * Delete 'count' lines from 'row' and insert 'count' empty lines at the bottom
380 * of the scroll region.
382 - (void)deleteLinesFromRow:(int)row lineCount:(int)count
383 scrollBottom:(int)bottom left:(int)left right:(int)right
384 color:(NSColor *)color
386 //NSLog(@"deleteLinesFromRow:%d lineCount:%d color:%@", row, count, color);
387 [self lazyResize:NO];
389 if (row < 0 || row+count > maxRows)
392 int total = 1 + bottom - row;
393 int move = total - count;
394 int width = right - left + 1;
396 NSRange destRange, srcRange;
399 for (i = 0; i < move; ++i, ++destRow) {
402 destRange = [self charRangeForRow:destRow column:&acol cells:&acells];
403 #if MM_TS_PARANOIA_LOG
404 if (acells != width || acol != left)
405 NSLog(@"INTERNAL ERROR [%s]", _cmd);
408 acol = left; acells = width;
409 srcRange = [self charRangeForRow:(destRow+count) column:&acol
411 #if MM_TS_PARANOIA_LOG
412 if (acells != width || acol != left)
413 NSLog(@"INTERNAL ERROR [%s]", _cmd);
416 if (NSNotFound == destRange.location || NSNotFound == srcRange.location)
418 #if MM_TS_PARANOIA_LOG
419 NSLog(@"INTERNAL ERROR [%s] Out of bounds", _cmd);
424 NSAttributedString *srcString = [attribString
425 attributedSubstringFromRange:srcRange];
427 [attribString replaceCharactersInRange:destRange
428 withAttributedString:srcString];
429 [self edited:(NSTextStorageEditedCharacters
430 | NSTextStorageEditedAttributes) range:destRange
431 changeInLength:([srcString length]-destRange.length)];
434 rowCache[destRow].length += [srcString length] - destRange.length;
438 NSRange emptyRange = {0,width};
439 NSAttributedString *emptyString =
440 [emptyRowString attributedSubstringFromRange:emptyRange];
441 NSDictionary *attribs = [NSDictionary dictionaryWithObjectsAndKeys:
442 font, NSFontAttributeName,
443 color, NSBackgroundColorAttributeName, nil];
445 for (i = 0; i < count; ++i, ++destRow) {
448 destRange = [self charRangeForRow:destRow column:&acol cells:&acells];
449 #if MM_TS_PARANOIA_LOG
450 if (acells != width || acol != left)
451 NSLog(@"INTERNAL ERROR [%s]", _cmd);
453 if (NSNotFound == destRange.location) {
454 #if MM_TS_PARANOIA_LOG
455 NSLog(@"INTERNAL ERROR [%s] Out of bounds", _cmd);
460 [attribString replaceCharactersInRange:destRange
461 withAttributedString:emptyString];
462 [attribString setAttributes:attribs
463 range:NSMakeRange(destRange.location, width)];
465 [self edited:(NSTextStorageEditedAttributes
466 | NSTextStorageEditedCharacters) range:destRange
467 changeInLength:([emptyString length]-destRange.length)];
470 rowCache[destRow].length += [emptyString length] - destRange.length;
476 * Insert 'count' empty lines at 'row' and delete 'count' lines from the bottom
477 * of the scroll region.
479 - (void)insertLinesAtRow:(int)row lineCount:(int)count
480 scrollBottom:(int)bottom left:(int)left right:(int)right
481 color:(NSColor *)color
483 //NSLog(@"insertLinesAtRow:%d lineCount:%d color:%@", row, count, color);
484 [self lazyResize:NO];
486 if (row < 0 || row+count > maxRows)
489 int total = 1 + bottom - row;
490 int move = total - count;
491 int width = right - left + 1;
492 int destRow = bottom;
493 int srcRow = row + move - 1;
494 NSRange destRange, srcRange;
497 for (i = 0; i < move; ++i, --destRow, --srcRow) {
500 destRange = [self charRangeForRow:destRow column:&acol cells:&acells];
501 #if MM_TS_PARANOIA_LOG
502 if (acells != width || acol != left)
503 NSLog(@"INTERNAL ERROR [%s]", _cmd);
506 acol = left; acells = width;
507 srcRange = [self charRangeForRow:srcRow column:&acol cells:&acells];
508 #if MM_TS_PARANOIA_LOG
509 if (acells != width || acol != left)
510 NSLog(@"INTERNAL ERROR [%s]", _cmd);
512 if (NSNotFound == destRange.location || NSNotFound == srcRange.location)
514 #if MM_TS_PARANOIA_LOG
515 NSLog(@"INTERNAL ERROR [%s] Out of bounds", _cmd);
520 NSAttributedString *srcString = [attribString
521 attributedSubstringFromRange:srcRange];
522 [attribString replaceCharactersInRange:destRange
523 withAttributedString:srcString];
524 [self edited:(NSTextStorageEditedCharacters
525 | NSTextStorageEditedAttributes) range:destRange
526 changeInLength:([srcString length]-destRange.length)];
529 rowCache[destRow].length += [srcString length] - destRange.length;
533 NSRange emptyRange = {0,width};
534 NSAttributedString *emptyString =
535 [emptyRowString attributedSubstringFromRange:emptyRange];
536 NSDictionary *attribs = [NSDictionary dictionaryWithObjectsAndKeys:
537 font, NSFontAttributeName,
538 color, NSBackgroundColorAttributeName, nil];
540 for (i = 0; i < count; ++i, --destRow) {
543 destRange = [self charRangeForRow:destRow column:&acol cells:&acells];
544 #if MM_TS_PARANOIA_LOG
545 if (acells != width || acol != left)
546 NSLog(@"INTERNAL ERROR [%s]", _cmd);
548 if (NSNotFound == destRange.location) {
549 #if MM_TS_PARANOIA_LOG
550 NSLog(@"INTERNAL ERROR [%s] Out of bounds", _cmd);
555 [attribString replaceCharactersInRange:destRange
556 withAttributedString:emptyString];
557 [attribString setAttributes:attribs
558 range:NSMakeRange(destRange.location, width)];
560 [self edited:(NSTextStorageEditedAttributes
561 | NSTextStorageEditedCharacters) range:destRange
562 changeInLength:([emptyString length]-destRange.length)];
565 rowCache[destRow].length += [emptyString length] - destRange.length;
570 - (void)clearBlockFromRow:(int)row1 column:(int)col1 toRow:(int)row2
571 column:(int)col2 color:(NSColor *)color
573 //NSLog(@"clearBlockFromRow:%d column:%d toRow:%d column:%d color:%@",
574 // row1, col1, row2, col2, color);
575 [self lazyResize:NO];
577 if (row1 < 0 || row2 >= maxRows || col1 < 0 || col2 > maxColumns)
580 NSDictionary *attribs = [NSDictionary dictionaryWithObjectsAndKeys:
581 font, NSFontAttributeName,
582 color, NSBackgroundColorAttributeName, nil];
583 int cells = col2 - col1 + 1;
584 NSRange range, emptyRange = {0, cells};
585 NSAttributedString *emptyString =
586 [emptyRowString attributedSubstringFromRange:emptyRange];
589 for (r=row1; r<=row2; ++r) {
592 range = [self charRangeForRow:r column:&acol cells:&acells];
593 #if MM_TS_PARANOIA_LOG
594 if (acells != cells || acol != col1)
595 NSLog(@"INTERNAL ERROR [%s]", _cmd);
597 if (NSNotFound == range.location) {
598 #if MM_TS_PARANOIA_LOG
599 NSLog(@"INTERNAL ERROR [%s] Out of bounds", _cmd);
604 [attribString replaceCharactersInRange:range
605 withAttributedString:emptyString];
606 [attribString setAttributes:attribs
607 range:NSMakeRange(range.location, cells)];
609 [self edited:(NSTextStorageEditedAttributes
610 | NSTextStorageEditedCharacters) range:range
611 changeInLength:cells-range.length];
614 rowCache[r].length += cells - range.length;
621 //NSLog(@"%s", _cmd);
622 [self lazyResize:YES];
625 - (void)setDefaultColorsBackground:(NSColor *)bgColor
626 foreground:(NSColor *)fgColor
628 if (defaultBackgroundColor != bgColor) {
629 [defaultBackgroundColor release];
630 defaultBackgroundColor = bgColor ? [bgColor retain] : nil;
633 // NOTE: The default foreground color isn't actually used for anything, but
634 // other class instances might want to be able to access it so it is stored
636 if (defaultForegroundColor != fgColor) {
637 [defaultForegroundColor release];
638 defaultForegroundColor = fgColor ? [fgColor retain] : nil;
642 - (void)setFont:(NSFont*)newFont
644 if (newFont && font != newFont) {
645 [boldItalicFont release]; boldItalicFont = nil;
646 [italicFont release]; italicFont = nil;
647 [boldFont release]; boldFont = nil;
648 [font release]; font = nil;
650 // NOTE! When setting a new font we make sure that the advancement of
651 // each glyph is fixed.
653 float em = [newFont widthOfString:@"m"];
654 float cellWidthMultiplier = [[NSUserDefaults standardUserDefaults]
655 floatForKey:MMCellWidthMultiplierKey];
657 // NOTE! Even though NSFontFixedAdvanceAttribute is a float, it will
658 // only render at integer sizes. Hence, we restrict the cell width to
659 // an integer here, otherwise the window width and the actual text
660 // width will not match.
661 cellSize.width = ceilf(em * cellWidthMultiplier);
663 float pointSize = [newFont pointSize];
664 NSDictionary *dict = [NSDictionary
665 dictionaryWithObject:[NSNumber numberWithFloat:cellSize.width]
666 forKey:NSFontFixedAdvanceAttribute];
668 NSFontDescriptor *desc = [newFont fontDescriptor];
669 desc = [desc fontDescriptorByAddingAttributes:dict];
670 font = [NSFont fontWithDescriptor:desc size:pointSize];
673 NSLayoutManager *lm = [[self layoutManagers] objectAtIndex:0];
674 cellSize.height = linespace + (lm ? [lm defaultLineHeightForFont:font]
675 : [font defaultLineHeightForFont]);
677 // NOTE: The font manager does not care about the 'font fixed advance'
678 // attribute, so after converting the font we have to add this
680 boldFont = [[NSFontManager sharedFontManager]
681 convertFont:font toHaveTrait:NSBoldFontMask];
682 desc = [boldFont fontDescriptor];
683 desc = [desc fontDescriptorByAddingAttributes:dict];
684 boldFont = [NSFont fontWithDescriptor:desc size:pointSize];
687 italicFont = [[NSFontManager sharedFontManager]
688 convertFont:font toHaveTrait:NSItalicFontMask];
689 desc = [italicFont fontDescriptor];
690 desc = [desc fontDescriptorByAddingAttributes:dict];
691 italicFont = [NSFont fontWithDescriptor:desc size:pointSize];
694 boldItalicFont = [[NSFontManager sharedFontManager]
695 convertFont:italicFont toHaveTrait:NSBoldFontMask];
696 desc = [boldItalicFont fontDescriptor];
697 desc = [desc fontDescriptorByAddingAttributes:dict];
698 boldItalicFont = [NSFont fontWithDescriptor:desc size:pointSize];
699 [boldItalicFont retain];
703 - (void)setWideFont:(NSFont *)newFont
706 // Use the normal font as the wide font (note that the normal font may
707 // very well include wide characters.)
708 if (font) [self setWideFont:font];
709 } else if (newFont != fontWide) {
710 [boldItalicFontWide release]; boldItalicFontWide = nil;
711 [italicFontWide release]; italicFontWide = nil;
712 [boldFontWide release]; boldFontWide = nil;
713 [fontWide release]; fontWide = nil;
715 float pointSize = [newFont pointSize];
716 NSFontDescriptor *desc = [newFont fontDescriptor];
717 NSDictionary *dictWide = [NSDictionary
718 dictionaryWithObject:[NSNumber numberWithFloat:2*cellSize.width]
719 forKey:NSFontFixedAdvanceAttribute];
721 desc = [desc fontDescriptorByAddingAttributes:dictWide];
722 fontWide = [NSFont fontWithDescriptor:desc size:pointSize];
725 boldFontWide = [[NSFontManager sharedFontManager]
726 convertFont:fontWide toHaveTrait:NSBoldFontMask];
727 desc = [boldFontWide fontDescriptor];
728 desc = [desc fontDescriptorByAddingAttributes:dictWide];
729 boldFontWide = [NSFont fontWithDescriptor:desc size:pointSize];
730 [boldFontWide retain];
732 italicFontWide = [[NSFontManager sharedFontManager]
733 convertFont:fontWide toHaveTrait:NSItalicFontMask];
734 desc = [italicFontWide fontDescriptor];
735 desc = [desc fontDescriptorByAddingAttributes:dictWide];
736 italicFontWide = [NSFont fontWithDescriptor:desc size:pointSize];
737 [italicFontWide retain];
739 boldItalicFontWide = [[NSFontManager sharedFontManager]
740 convertFont:italicFontWide toHaveTrait:NSBoldFontMask];
741 desc = [boldItalicFontWide fontDescriptor];
742 desc = [desc fontDescriptorByAddingAttributes:dictWide];
743 boldItalicFontWide = [NSFont fontWithDescriptor:desc size:pointSize];
744 [boldItalicFontWide retain];
758 - (NSColor *)defaultBackgroundColor
760 return defaultBackgroundColor;
763 - (NSColor *)defaultForegroundColor
765 return defaultForegroundColor;
770 return NSMakeSize(maxColumns*cellSize.width, maxRows*cellSize.height);
778 - (NSRect)rectForRowsInRange:(NSRange)range
780 NSRect rect = { 0, 0, 0, 0 };
781 unsigned start = range.location > maxRows ? maxRows : range.location;
782 unsigned length = range.length;
784 if (start+length > maxRows)
785 length = maxRows - start;
787 rect.origin.y = cellSize.height * start;
788 rect.size.height = cellSize.height * length;
793 - (NSRect)rectForColumnsInRange:(NSRange)range
795 NSRect rect = { 0, 0, 0, 0 };
796 unsigned start = range.location > maxColumns ? maxColumns : range.location;
797 unsigned length = range.length;
799 if (start+length > maxColumns)
800 length = maxColumns - start;
802 rect.origin.x = cellSize.width * start;
803 rect.size.width = cellSize.width * length;
808 - (unsigned)characterIndexForRow:(int)row column:(int)col
811 NSRange range = [self charRangeForRow:row column:&col cells:&cells];
812 return range.location != NSNotFound ? range.location : 0;
815 // XXX: unused at the moment
816 - (BOOL)resizeToFitSize:(NSSize)size
818 int rows = maxRows, cols = maxColumns;
820 [self fitToSize:size rows:&rows columns:&cols];
821 if (rows != maxRows || cols != maxColumns) {
822 [self setMaxRows:rows columns:cols];
826 // Return NO only if dimensions did not change.
830 - (NSSize)fitToSize:(NSSize)size
832 return [self fitToSize:size rows:NULL columns:NULL];
835 - (NSSize)fitToSize:(NSSize)size rows:(int *)rows columns:(int *)columns
837 NSSize curSize = [self size];
838 NSSize fitSize = curSize;
839 int fitRows = maxRows;
840 int fitCols = maxColumns;
842 if (size.height < curSize.height) {
843 // Remove lines until the height of the text storage fits inside
844 // 'size'. However, always make sure there are at least 3 lines in the
845 // text storage. (Why 3? It seem Vim never allows less than 3 lines.)
847 // TODO: No need to search since line height is fixed, just calculate
849 int rowCount = maxRows;
851 for (rowsToRemove = 0; rowsToRemove < maxRows-3; ++rowsToRemove) {
852 float height = cellSize.height*rowCount;
854 if (height <= size.height) {
855 fitSize.height = height;
862 fitRows -= rowsToRemove;
863 } else if (size.height > curSize.height) {
864 float fh = cellSize.height;
865 if (fh < 1.0f) fh = 1.0f;
867 fitRows = floor(size.height/fh);
868 fitSize.height = fh*fitRows;
871 if (size.width != curSize.width) {
872 float fw = cellSize.width;
873 if (fw < 1.0f) fw = 1.0f;
875 fitCols = floor(size.width/fw);
876 fitSize.width = fw*fitCols;
879 if (rows) *rows = fitRows;
880 if (columns) *columns = fitCols;
885 - (NSRect)boundingRectForCharacterAtRow:(int)row column:(int)col
888 // This properly computes the position of where Vim expects the glyph to be
889 // drawn. Had the typesetter actually computed the right position of each
890 // character and not hidden some, this code would be correct.
891 NSRect rect = NSZeroRect;
893 rect.origin.x = col*cellSize.width;
894 rect.origin.y = row*cellSize.height;
895 rect.size = cellSize;
897 // Wide character take up twice the width of a normal character.
899 NSRange r = [self charRangeForRow:row column:&col cells:&cells];
900 if (NSNotFound != r.location
901 && [attribString attribute:MMWideCharacterAttributeName
904 rect.size.width += rect.size.width;
908 // Use layout manager to compute bounding rect. This works in situations
909 // where the layout manager decides to hide glyphs (Vim assumes all glyphs
911 NSLayoutManager *lm = [[self layoutManagers] objectAtIndex:0];
912 NSTextContainer *tc = [[lm textContainers] objectAtIndex:0];
914 NSRange range = [self charRangeForRow:row column:&col cells:&cells];
915 NSRange glyphRange = [lm glyphRangeForCharacterRange:range
916 actualCharacterRange:NULL];
918 return [lm boundingRectForGlyphRange:glyphRange inTextContainer:tc];
923 - (MMRowCacheEntry *)rowCache
929 @end // MMTextStorage
934 @implementation MMTextStorage (Private)
936 - (void)lazyResize:(BOOL)force
938 // Do nothing if the dimensions are already right.
939 if (!force && actualRows == maxRows && actualColumns == maxColumns)
942 NSRange oldRange = NSMakeRange(0, [attribString length]);
944 actualRows = maxRows;
945 actualColumns = maxColumns;
946 characterEqualsColumn = YES;
950 rowCache = (MMRowCacheEntry*)calloc(actualRows, sizeof(MMRowCacheEntry));
954 if (defaultBackgroundColor) {
955 dict = [NSDictionary dictionaryWithObjectsAndKeys:
956 font, NSFontAttributeName,
957 defaultBackgroundColor, NSBackgroundColorAttributeName, nil];
959 dict = [NSDictionary dictionaryWithObjectsAndKeys:
960 font, NSFontAttributeName, nil];
963 NSMutableString *rowString = [NSMutableString string];
965 for (i = 0; i < maxColumns; ++i) {
966 [rowString appendString:@" "];
968 [rowString appendString:@"\n"];
970 [emptyRowString release];
971 emptyRowString = [[NSAttributedString alloc] initWithString:rowString
974 [attribString release];
975 attribString = [[NSMutableAttributedString alloc] init];
976 for (i=0; i<maxRows; ++i) {
978 rowCache[i].length = actualColumns + 1;
980 [attribString appendAttributedString:emptyRowString];
983 NSRange fullRange = NSMakeRange(0, [attribString length]);
984 [self edited:(NSTextStorageEditedCharacters|NSTextStorageEditedAttributes)
985 range:oldRange changeInLength:fullRange.length-oldRange.length];
988 - (NSRange)charRangeForRow:(int)row column:(int*)pcol cells:(int*)pcells
993 // If no wide chars are used and if every char has length 1 (no composing
994 // characters, no > 16 bit characters), then we can compute the range.
995 if (characterEqualsColumn)
996 return NSMakeRange(row*(actualColumns+1) + col, cells);
998 NSString *string = [attribString string];
999 NSRange r, range = { NSNotFound, 0 };
1000 unsigned idx, rowEnd;
1003 if (row < 0 || row >= actualRows || col < 0 || col >= actualColumns
1004 || col+cells > actualColumns) {
1005 #if MM_TS_PARANOIA_LOG
1006 NSLog(@"%s row=%d col=%d cells=%d is out of range (length=%d)",
1007 _cmd, row, col, cells, [string length]);
1012 #if MM_USE_ROW_CACHE
1013 // Locate the beginning of the row
1014 MMRowCacheEntry *cache = rowCache;
1016 for (i = 0; i < row; ++i, ++cache)
1017 idx += cache->length;
1019 rowEnd = idx + cache->length;
1021 // Locate the beginning of the row by scanning for EOL characters.
1023 for (i = 0; i < row; ++i) {
1024 r.length = [string length] - r.location;
1025 r = [string rangeOfString:@"\n" options:NSLiteralSearch range:r];
1026 if (NSNotFound == r.location)
1032 // Locate the column
1033 #if MM_USE_ROW_CACHE
1034 cache = &rowCache[row];
1039 idx += cache->colOffset;
1041 range.location = idx;
1043 #if 0 // Backward search seems to be broken...
1045 if (col < i - col) {
1046 // Search forward from beginning of line.
1048 } else if (actualColumns - col < col - i) {
1049 // Search backward from end of line.
1050 i = actualColumns - 1;
1051 idx += cache->length - 2;
1053 // Search from cache spot (forward or backward).
1054 idx += cache->colOffset;
1060 r = [string rangeOfComposedCharacterSequenceAtIndex:idx];
1062 // Wide chars take up two display cells.
1063 if ([attribString attribute:MMWideCharacterAttributeName
1065 effectiveRange:nil])
1071 } else if (col < i) {
1074 r = [string rangeOfComposedCharacterSequenceAtIndex:idx-1];
1078 // Wide chars take up two display cells.
1079 if ([attribString attribute:MMWideCharacterAttributeName
1081 effectiveRange:nil])
1088 cache->colOffset = idx - range.location;
1092 // Search forward from beginning of line.
1095 // Search forward from cache spot.
1096 idx += cache->colOffset;
1101 r = [string rangeOfComposedCharacterSequenceAtIndex:idx];
1103 // Wide chars take up two display cells.
1104 if ([attribString attribute:MMWideCharacterAttributeName
1106 effectiveRange:nil])
1115 cache->colOffset = idx - range.location;
1120 for (i = 0; i < col; ++i) {
1121 r = [string rangeOfComposedCharacterSequenceAtIndex:idx];
1123 // Wide chars take up two display cells.
1124 if ([attribString attribute:MMWideCharacterAttributeName
1126 effectiveRange:nil])
1133 // Count the number of characters that cover the cells.
1134 range.location = idx;
1135 for (i = 0; i < cells; ++i) {
1136 r = [string rangeOfComposedCharacterSequenceAtIndex:idx];
1138 // Wide chars take up two display cells.
1139 if ([attribString attribute:MMWideCharacterAttributeName
1141 effectiveRange:nil])
1145 range.length += r.length;
1150 #if MM_TS_PARANOIA_LOG
1151 #if MM_USE_ROW_CACHE
1152 if (range.location >= rowEnd-1) {
1153 NSLog(@"INTERNAL ERROR [%s] : row=%d col=%d cells=%d --> range=%@",
1154 _cmd, row, col, cells, NSStringFromRange(range));
1155 range.location = rowEnd - 2;
1157 } else if (NSMaxRange(range) >= rowEnd) {
1158 NSLog(@"INTERNAL ERROR [%s] : row=%d col=%d cells=%d --> range=%@",
1159 _cmd, row, col, cells, NSStringFromRange(range));
1160 range.length = rowEnd - range.location - 1;
1164 if (NSMaxRange(range) > [string length]) {
1165 NSLog(@"INTERNAL ERROR [%s] : row=%d col=%d cells=%d --> range=%@",
1166 _cmd, row, col, cells, NSStringFromRange(range));
1167 range.location = NSNotFound;
1175 - (void)fixInvalidCharactersInRange:(NSRange)range
1177 static NSCharacterSet *invalidCharacterSet = nil;
1178 NSRange invalidRange;
1181 if (!invalidCharacterSet)
1182 invalidCharacterSet = [[NSCharacterSet characterSetWithRange:
1183 NSMakeRange(0x2028, 2)] retain];
1185 // HACK! Replace characters that the text system can't handle (currently
1186 // LINE SEPARATOR U+2028 and PARAGRAPH SEPARATOR U+2029) with space.
1188 // TODO: Treat these separately inside of Vim so we don't have to bother
1190 while (range.length > 0) {
1191 invalidRange = [[attribString string]
1192 rangeOfCharacterFromSet:invalidCharacterSet
1193 options:NSLiteralSearch
1195 if (NSNotFound == invalidRange.location)
1198 [attribString replaceCharactersInRange:invalidRange withString:@" "];
1200 end = NSMaxRange(invalidRange);
1201 range.length -= end - range.location;
1202 range.location = end;
1206 @end // MMTextStorage (Private)