Inline IM Patch
[MacVim.git] / src / MacVim / MMTextStorage.m
blobb0b61d5f1fb6a48e253de91070fdd3f810c615a9
1 /* vi:set ts=8 sts=4 sw=4 ft=objc:
2  *
3  * VIM - Vi IMproved            by Bram Moolenaar
4  *                              MacVim GUI port by Bjorn Winckler
5  *
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.
9  */
11  * MMTextStorage
12  *
13  * Text rendering related code.
14  *
15  * Note that:
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
24  *
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.
28  *
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
31  * computed.
32  */
34 #import "MMTextStorage.h"
35 #import "MacVim.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;
65 @end
69 @implementation MMTextStorage
71 - (id)init
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];
80     }
82     return self;
85 - (void)dealloc
87     //NSLog(@"MMTextStorage dealloc");
89 #if MM_USE_ROW_CACHE
90     if (rowCache) {
91         free(rowCache);
92         rowCache = NULL;
93     }
94 #endif
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;
107     [super dealloc];
110 - (NSString *)string
112     return [attribString string];
115 - (NSDictionary *)attributesAtIndex:(unsigned)index
116                      effectiveRange:(NSRangePointer)range
118     if (index >= [attribString length]) {
119         if (range)
120             *range = NSMakeRange(NSNotFound, 0);
122         return [NSDictionary dictionary];
123     }
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);
139 #endif
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.
149 #if 0
150     [attribString setAttributes:attributes range:range];
151 #elif 1
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.
156     //
157     // TODO: This code assumes that the characters in 'range' all have the same
158     // width.
159     NSFont *newFont = [attributes objectForKey:NSFontAttributeName];
160     if (newFont) {
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])
166             return;
168         float adv = cellSize.width;
169         if ([attribString attribute:MMWideCharacterAttributeName
170                             atIndex:range.location
171                      effectiveRange:NULL])
172             adv += adv;
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];
187     } else {
188         //NSLog(@"NOT fixing font attribute!");
189         [attribString setAttributes:attributes range:range];
190     }
191 #endif
194 - (int)maxRows
196     return maxRows;
199 - (int)maxColumns
201     return maxColumns;
204 - (int)actualRows
206     return actualRows;
209 - (int)actualColumns
211     return actualColumns;
214 - (float)linespace
216     return linespace;
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
230     // MMTypesetter.
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.
244     maxRows = rows;
245     maxColumns = cols;
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))
260         return;
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 };
268         flags &= ~DRAW_WIDE;
269         string = [[emptyRowString string] substringWithRange:subRange];
270     }
272     // Find range of characters in text storage to replace.
273     int acol = col;
274     int acells = cells;
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);
279 #endif
280         return;
281     }
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;
290         else
291             theFont = fontWide;
292     } else {
293         if (flags & DRAW_BOLD)
294             theFont = flags & DRAW_ITALIC ? boldItalicFont : boldFont;
295         else if (flags & DRAW_ITALIC)
296             theFont = italicFont;
297     }
299     NSMutableDictionary *attributes =
300         [NSMutableDictionary dictionaryWithObjectsAndKeys:
301             theFont, NSFontAttributeName,
302             bg, NSBackgroundColorAttributeName,
303             fg, NSForegroundColorAttributeName,
304             sp, NSUnderlineColorAttributeName,
305             nil];
307     if (flags & DRAW_UNDERL) {
308         NSNumber *value = [NSNumber numberWithInt:(NSUnderlineStyleSingle
309                 | NSUnderlinePatternSolid)]; // | NSUnderlineByWordMask
310         [attributes setObject:value forKey:NSUnderlineStyleAttributeName];
311     }
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];
318     }
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)]];
340             ++changeInLength;
341 #if 0
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)]];
347             ++changeInLength;
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)]];
353             ++changeInLength;
354 #endif
355         } else {
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,
360                     cells, acells);
361 #endif
362         }
363     }
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];
373 #if MM_USE_ROW_CACHE
374     rowCache[row].length += changeInLength;
375 #endif
379  * Delete 'count' lines from 'row' and insert 'count' empty lines at the bottom
380  * of the scroll region.
381  */
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)
390         return;
392     int total = 1 + bottom - row;
393     int move = total - count;
394     int width = right - left + 1;
395     int destRow = row;
396     NSRange destRange, srcRange;
397     int i;
399     for (i = 0; i < move; ++i, ++destRow) {
400         int acol = left;
401         int acells = width;
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);
406 #endif
408         acol = left; acells = width;
409         srcRange = [self charRangeForRow:(destRow+count) column:&acol
410                                    cells:&acells];
411 #if MM_TS_PARANOIA_LOG
412         if (acells != width || acol != left)
413             NSLog(@"INTERNAL ERROR [%s]", _cmd);
414 #endif
416         if (NSNotFound == destRange.location || NSNotFound == srcRange.location)
417         {
418 #if MM_TS_PARANOIA_LOG
419             NSLog(@"INTERNAL ERROR [%s] Out of bounds", _cmd);
420 #endif
421             return;
422         }
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)];
433 #if MM_USE_ROW_CACHE
434         rowCache[destRow].length += [srcString length] - destRange.length;
435 #endif
436     }
437     
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) {
446         int acol = left;
447         int acells = width;
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);
452 #endif
453         if (NSNotFound == destRange.location) {
454 #if MM_TS_PARANOIA_LOG
455             NSLog(@"INTERNAL ERROR [%s] Out of bounds", _cmd);
456 #endif
457             return;
458         }
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)];
469 #if MM_USE_ROW_CACHE
470         rowCache[destRow].length += [emptyString length] - destRange.length;
471 #endif
472     }
476  * Insert 'count' empty lines at 'row' and delete 'count' lines from the bottom
477  * of the scroll region.
478  */
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)
487         return;
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;
495     int i;
497     for (i = 0; i < move; ++i, --destRow, --srcRow) {
498         int acol = left;
499         int acells = width;
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);
504 #endif
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);
511 #endif
512         if (NSNotFound == destRange.location || NSNotFound == srcRange.location)
513         {
514 #if MM_TS_PARANOIA_LOG
515             NSLog(@"INTERNAL ERROR [%s] Out of bounds", _cmd);
516 #endif
517             return;
518         }
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)];
528 #if MM_USE_ROW_CACHE
529         rowCache[destRow].length += [srcString length] - destRange.length;
530 #endif
531     }
532     
533     NSRange emptyRange = {0,width};
534     NSAttributedString *emptyString =
535             [emptyRowString attributedSubstringFromRange:emptyRange];
536     NSDictionary *attribs = [NSDictionary dictionaryWithObjectsAndKeys:
537             font, NSFontAttributeName,
538             color, NSBackgroundColorAttributeName, nil];
539     
540     for (i = 0; i < count; ++i, --destRow) {
541         int acol = left;
542         int acells = width;
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);
547 #endif
548         if (NSNotFound == destRange.location) {
549 #if MM_TS_PARANOIA_LOG
550             NSLog(@"INTERNAL ERROR [%s] Out of bounds", _cmd);
551 #endif
552             return;
553         }
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)];
564 #if MM_USE_ROW_CACHE
565         rowCache[destRow].length += [emptyString length] - destRange.length;
566 #endif
567     }
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)
578         return;
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];
587     int r;
589     for (r=row1; r<=row2; ++r) {
590         int acol = col1;
591         int acells = cells;
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);
596 #endif
597         if (NSNotFound == range.location) {
598 #if MM_TS_PARANOIA_LOG
599             NSLog(@"INTERNAL ERROR [%s] Out of bounds", _cmd);
600 #endif
601             return;
602         }
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];
613 #if MM_USE_ROW_CACHE
614         rowCache[r].length += cells - range.length;
615 #endif
616     }
619 - (void)clearAll
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;
631     }
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
635     // here.
636     if (defaultForegroundColor != fgColor) {
637         [defaultForegroundColor release];
638         defaultForegroundColor = fgColor ? [fgColor retain] : nil;
639     }
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];
671         [font retain];
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
679         // attribute again.
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];
685         [boldFont retain];
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];
692         [italicFont retain];
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];
700     }
703 - (void)setWideFont:(NSFont *)newFont
705     if (!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];
723         [fontWide retain];
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];
745     }
748 - (NSFont*)font
750     return font;
753 - (NSFont*)fontWide
755     return fontWide;
758 - (NSColor *)defaultBackgroundColor
760     return defaultBackgroundColor;
763 - (NSColor *)defaultForegroundColor
765     return defaultForegroundColor;
768 - (NSSize)size
770     return NSMakeSize(maxColumns*cellSize.width, maxRows*cellSize.height);
773 - (NSSize)cellSize
775     return cellSize;
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;
790     return rect;
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;
805     return rect;
808 - (unsigned)characterIndexForRow:(int)row column:(int)col
810     int cells = 1;
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];
823         return YES;
824     }
826     // Return NO only if dimensions did not change.
827     return NO;
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.)
846         //
847         // TODO: No need to search since line height is fixed, just calculate
848         // the new height.
849         int rowCount = maxRows;
850         int rowsToRemove;
851         for (rowsToRemove = 0; rowsToRemove < maxRows-3; ++rowsToRemove) {
852             float height = cellSize.height*rowCount;
854             if (height <= size.height) {
855                 fitSize.height = height;
856                 break;
857             }
859             --rowCount;
860         }
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;
869     }
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;
877     }
879     if (rows) *rows = fitRows;
880     if (columns) *columns = fitCols;
882     return fitSize;
885 - (NSRect)boundingRectForCharacterAtRow:(int)row column:(int)col
887 #if 1
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.
898     int cells = 1;
899     NSRange r = [self charRangeForRow:row column:&col cells:&cells];
900     if (NSNotFound != r.location
901             && [attribString attribute:MMWideCharacterAttributeName
902                                atIndex:r.location
903                         effectiveRange:nil])
904         rect.size.width += rect.size.width;
906     return rect;
907 #else
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
910     // are drawn).
911     NSLayoutManager *lm = [[self layoutManagers] objectAtIndex:0];
912     NSTextContainer *tc = [[lm textContainers] objectAtIndex:0];
913     int cells = 1;
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];
919 #endif
922 #if MM_USE_ROW_CACHE
923 - (MMRowCacheEntry *)rowCache
925     return rowCache;
927 #endif
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)
940         return;
942     NSRange oldRange = NSMakeRange(0, [attribString length]);
944     actualRows = maxRows;
945     actualColumns = maxColumns;
946     characterEqualsColumn = YES;
948 #if MM_USE_ROW_CACHE
949     free(rowCache);
950     rowCache = (MMRowCacheEntry*)calloc(actualRows, sizeof(MMRowCacheEntry));
951 #endif
953     NSDictionary *dict;
954     if (defaultBackgroundColor) {
955         dict = [NSDictionary dictionaryWithObjectsAndKeys:
956                 font, NSFontAttributeName,
957                 defaultBackgroundColor, NSBackgroundColorAttributeName, nil];
958     } else {
959         dict = [NSDictionary dictionaryWithObjectsAndKeys:
960                 font, NSFontAttributeName, nil];
961     }
962             
963     NSMutableString *rowString = [NSMutableString string];
964     int i;
965     for (i = 0; i < maxColumns; ++i) {
966         [rowString appendString:@" "];
967     }
968     [rowString appendString:@"\n"];
970     [emptyRowString release];
971     emptyRowString = [[NSAttributedString alloc] initWithString:rowString
972                                                      attributes:dict];
974     [attribString release];
975     attribString = [[NSMutableAttributedString alloc] init];
976     for (i=0; i<maxRows; ++i) {
977 #if MM_USE_ROW_CACHE
978         rowCache[i].length = actualColumns + 1;
979 #endif
980         [attribString appendAttributedString:emptyRowString];
981     }
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
990     int col = *pcol;
991     int cells = *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;
1001     int i;
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]);
1008 #endif
1009         return range;
1010     }
1012 #if MM_USE_ROW_CACHE
1013     // Locate the beginning of the row
1014     MMRowCacheEntry *cache = rowCache;
1015     idx = 0;
1016     for (i = 0; i < row; ++i, ++cache)
1017         idx += cache->length;
1019     rowEnd = idx + cache->length;
1020 #else
1021     // Locate the beginning of the row by scanning for EOL characters.
1022     r.location = 0;
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)
1027             return range;
1028         ++r.location;
1029     }
1030 #endif
1032     // Locate the column
1033 #if MM_USE_ROW_CACHE
1034     cache = &rowCache[row];
1036     i = cache->col;
1037     if (col == i) {
1038         // Cache hit
1039         idx += cache->colOffset;
1040     } else {
1041         range.location = idx;
1043 #if 0  // Backward search seems to be broken...
1044         // Cache miss
1045         if (col < i - col) {
1046             // Search forward from beginning of line.
1047             i = 0;
1048         } else if (actualColumns - col < col - i) {
1049             // Search backward from end of line.
1050             i = actualColumns - 1;
1051             idx += cache->length - 2;
1052         } else {
1053             // Search from cache spot (forward or backward).
1054             idx += cache->colOffset;
1055         }
1057         if (col > i) {
1058             // Forward search
1059             while (col > i) {
1060                 r = [string rangeOfComposedCharacterSequenceAtIndex:idx];
1062                 // Wide chars take up two display cells.
1063                 if ([attribString attribute:MMWideCharacterAttributeName
1064                                     atIndex:idx
1065                              effectiveRange:nil])
1066                     ++i;
1068                 idx += r.length;
1069                 ++i;
1070             }
1071         } else if (col < i) {
1072             // Backward search
1073             while (col < i) {
1074                 r = [string rangeOfComposedCharacterSequenceAtIndex:idx-1];
1075                 idx -= r.length;
1076                 --i;
1078                 // Wide chars take up two display cells.
1079                 if ([attribString attribute:MMWideCharacterAttributeName
1080                                     atIndex:idx
1081                              effectiveRange:nil])
1082                     --i;
1083             }
1084         }
1086         *pcol = i;
1087         cache->col = i;
1088         cache->colOffset = idx - range.location;
1089 #else
1090         // Cache miss
1091         if (col < i) {
1092             // Search forward from beginning of line.
1093             i = 0;
1094         } else {
1095             // Search forward from cache spot.
1096             idx += cache->colOffset;
1097         }
1099         // Forward search
1100         while (col > i) {
1101             r = [string rangeOfComposedCharacterSequenceAtIndex:idx];
1103             // Wide chars take up two display cells.
1104             if ([attribString attribute:MMWideCharacterAttributeName
1105                                 atIndex:idx
1106                          effectiveRange:nil])
1107                 ++i;
1109             idx += r.length;
1110             ++i;
1111         }
1113         *pcol = i;
1114         cache->col = i;
1115         cache->colOffset = idx - range.location;
1116 #endif
1117     }
1118 #else
1119     idx = r.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
1125                             atIndex:idx
1126                      effectiveRange:nil])
1127             ++i;
1129         idx += r.length;
1130     }
1131 #endif
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
1140                             atIndex:idx
1141                      effectiveRange:nil])
1142             ++i;
1144         idx += r.length;
1145         range.length += r.length;
1146     }
1148     *pcells = i;
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;
1156         range.length = 1;
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;
1161     }
1162 #endif
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;
1168         range.length = 0;
1169     }
1170 #endif
1172     return range;
1175 - (void)fixInvalidCharactersInRange:(NSRange)range
1177     static NSCharacterSet *invalidCharacterSet = nil;
1178     NSRange invalidRange;
1179     unsigned end;
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.
1187     //
1188     // TODO: Treat these separately inside of Vim so we don't have to bother
1189     // here.
1190     while (range.length > 0) {
1191         invalidRange = [[attribString string]
1192             rangeOfCharacterFromSet:invalidCharacterSet
1193                             options:NSLiteralSearch
1194                               range:range];
1195         if (NSNotFound == invalidRange.location)
1196             break;
1198         [attribString replaceCharactersInRange:invalidRange withString:@" "];
1200         end = NSMaxRange(invalidRange);
1201         range.length -= end - range.location;
1202         range.location = end;
1203     }
1206 @end // MMTextStorage (Private)