Add Vimball (vba) as supported filetype
[MacVim.git] / src / MacVim / MMTextView.m
blob62240b18be1130c2a7d93254522d76c81ede8067
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  * MMTextView
12  *
13  * Dispatches keyboard and mouse input to the backend.  Handles drag-n-drop of
14  * files onto window.
15  *
16  * Support for input managers is somewhat hacked together.  Marked text is
17  * drawn "pseudo-inline"; it will simply draw on top of existing text and it
18  * does not respect Vim-window boundaries.
19  */
21 #import "MMAppController.h"
22 #import "MMTextStorage.h"
23 #import "MMTextView.h"
24 #import "MMTextViewHelper.h"
25 #import "MMTypesetter.h"
26 #import "MMVimController.h"
27 #import "MMWindowController.h"
28 #import "Miscellaneous.h"
32 // This is taken from gui.h
33 #define DRAW_CURSOR 0x20
37 @interface MMTextView (Private)
38 - (MMWindowController *)windowController;
39 - (MMVimController *)vimController;
40 - (void)setShouldDrawInsertionPoint:(BOOL)on;
41 - (void)drawInsertionPointAtRow:(int)row column:(int)col shape:(int)shape
42                        fraction:(int)percent;
43 - (void)drawInvertedRectAtRow:(int)row column:(int)col numRows:(int)nrows
44                    numColumns:(int)ncols invert:(int)invert;
45 @end
49 @implementation MMTextView
51 - (id)initWithFrame:(NSRect)frame
53     // Set up a Cocoa text system.  Note that the textStorage is released in
54     // -[MMVimView dealloc].
55     MMTextStorage *textStorage = [[MMTextStorage alloc] init];
56     NSLayoutManager *lm = [[NSLayoutManager alloc] init];
57     NSTextContainer *tc = [[NSTextContainer alloc] initWithContainerSize:
58                     NSMakeSize(1.0e7,1.0e7)];
60     NSString *typesetterString = [[NSUserDefaults standardUserDefaults]
61             stringForKey:MMTypesetterKey];
62     if ([typesetterString isEqual:@"MMTypesetter"]) {
63         NSTypesetter *typesetter = [[MMTypesetter alloc] init];
64         [lm setTypesetter:typesetter];
65         [typesetter release];
66 #if MM_USE_ROW_CACHE
67     } else if ([typesetterString isEqual:@"MMTypesetter2"]) {
68         NSTypesetter *typesetter = [[MMTypesetter2 alloc] init];
69         [lm setTypesetter:typesetter];
70         [typesetter release];
71 #endif // MM_USE_ROW_CACHE
72     } else {
73         // Only MMTypesetter supports different cell width multipliers.
74         [[NSUserDefaults standardUserDefaults]
75                 setFloat:1.0 forKey:MMCellWidthMultiplierKey];
76     }
78     // The characters in the text storage are in display order, so disable
79     // bidirectional text processing (this call is 10.4 only).
80     [[lm typesetter] setBidiProcessingEnabled:NO];
82     [tc setWidthTracksTextView:NO];
83     [tc setHeightTracksTextView:NO];
84     [tc setLineFragmentPadding:0];
86     [textStorage addLayoutManager:lm];
87     [lm addTextContainer:tc];
89     // The text storage retains the layout manager which in turn retains
90     // the text container.
91     [tc autorelease];
92     [lm autorelease];
94     // NOTE: This will make the text storage the principal owner of the text
95     // system.  Releasing the text storage will in turn release the layout
96     // manager, the text container, and finally the text view (self).  This
97     // complicates deallocation somewhat, see -[MMVimView dealloc].
98     if (![super initWithFrame:frame textContainer:tc]) {
99         [textStorage release];
100         return nil;
101     }
103     helper = [[MMTextViewHelper alloc] init];
104     [helper setTextView:self];
106     // NOTE: If the default changes to 'NO' then the intialization of
107     // p_antialias in option.c must change as well.
108     antialias = YES;
110     return self;
113 - (void)dealloc
115     ASLogDebug(@"");
117     if (invertRects) {
118         free(invertRects);
119         invertRects = NULL;
120         numInvertRects = 0;
121     }
123     [helper setTextView:nil];
124     [helper dealloc];  helper = nil;
126     [super dealloc];
129 - (BOOL)shouldDrawInsertionPoint
131     // NOTE: The insertion point is drawn manually in drawRect:.  It would be
132     // nice to be able to use the insertion point related methods of
133     // NSTextView, but it seems impossible to get them to work properly (search
134     // the cocoabuilder archives).
135     return NO;
138 - (void)setPreEditRow:(int)row column:(int)col
140     [helper setPreEditRow:row column:col];
143 #define MM_DEBUG_DRAWING 0
145 - (void)performBatchDrawWithData:(NSData *)data
147     MMTextStorage *textStorage = (MMTextStorage *)[self textStorage];
148     if (!textStorage)
149         return;
151     const void *bytes = [data bytes];
152     const void *end = bytes + [data length];
153     int cursorRow = -1, cursorCol = 0;
155 #if MM_DEBUG_DRAWING
156     ASLogDebug(@"====> BEGIN %s", _cmd);
157 #endif
158     [textStorage beginEditing];
160     // TODO: Sanity check input
162     while (bytes < end) {
163         int type = *((int*)bytes);  bytes += sizeof(int);
165         if (ClearAllDrawType == type) {
166 #if MM_DEBUG_DRAWING
167             ASLogDebug(@"   Clear all");
168 #endif
169             [textStorage clearAll];
170         } else if (ClearBlockDrawType == type) {
171             unsigned color = *((unsigned*)bytes);  bytes += sizeof(unsigned);
172             int row1 = *((int*)bytes);  bytes += sizeof(int);
173             int col1 = *((int*)bytes);  bytes += sizeof(int);
174             int row2 = *((int*)bytes);  bytes += sizeof(int);
175             int col2 = *((int*)bytes);  bytes += sizeof(int);
177 #if MM_DEBUG_DRAWING
178             ASLogDebug(@"   Clear block (%d,%d) -> (%d,%d)", row1, col1,
179                        row2,col2);
180 #endif
181             [textStorage clearBlockFromRow:row1 column:col1
182                     toRow:row2 column:col2
183                     color:[NSColor colorWithArgbInt:color]];
184         } else if (DeleteLinesDrawType == type) {
185             unsigned color = *((unsigned*)bytes);  bytes += sizeof(unsigned);
186             int row = *((int*)bytes);  bytes += sizeof(int);
187             int count = *((int*)bytes);  bytes += sizeof(int);
188             int bot = *((int*)bytes);  bytes += sizeof(int);
189             int left = *((int*)bytes);  bytes += sizeof(int);
190             int right = *((int*)bytes);  bytes += sizeof(int);
192 #if MM_DEBUG_DRAWING
193             ASLogDebug(@"   Delete %d line(s) from %d", count, row);
194 #endif
195             [textStorage deleteLinesFromRow:row lineCount:count
196                     scrollBottom:bot left:left right:right
197                            color:[NSColor colorWithArgbInt:color]];
198         } else if (DrawStringDrawType == type) {
199             int bg = *((int*)bytes);  bytes += sizeof(int);
200             int fg = *((int*)bytes);  bytes += sizeof(int);
201             int sp = *((int*)bytes);  bytes += sizeof(int);
202             int row = *((int*)bytes);  bytes += sizeof(int);
203             int col = *((int*)bytes);  bytes += sizeof(int);
204             int cells = *((int*)bytes);  bytes += sizeof(int);
205             int flags = *((int*)bytes);  bytes += sizeof(int);
206             int len = *((int*)bytes);  bytes += sizeof(int);
207             NSString *string = [[NSString alloc]
208                     initWithBytes:(void*)bytes length:len
209                          encoding:NSUTF8StringEncoding];
210             bytes += len;
212 #if MM_DEBUG_DRAWING
213             ASLogDebug(@"   Draw string at (%d,%d) length=%d flags=%d fg=0x%x "
214                        "bg=0x%x sp=0x%x (%@)", row, col, len, flags, fg, bg, sp,
215                        len > 0 ? [string substringToIndex:1] : @"");
216 #endif
217             // NOTE: If this is a call to draw the (block) cursor, then cancel
218             // any previous request to draw the insertion point, or it might
219             // get drawn as well.
220             if (flags & DRAW_CURSOR)
221                 [self setShouldDrawInsertionPoint:NO];
223             [textStorage drawString:string
224                               atRow:row column:col cells:cells
225                           withFlags:flags
226                     foregroundColor:[NSColor colorWithRgbInt:fg]
227                     backgroundColor:[NSColor colorWithArgbInt:bg]
228                        specialColor:[NSColor colorWithRgbInt:sp]];
230             [string release];
231         } else if (InsertLinesDrawType == type) {
232             unsigned color = *((unsigned*)bytes);  bytes += sizeof(unsigned);
233             int row = *((int*)bytes);  bytes += sizeof(int);
234             int count = *((int*)bytes);  bytes += sizeof(int);
235             int bot = *((int*)bytes);  bytes += sizeof(int);
236             int left = *((int*)bytes);  bytes += sizeof(int);
237             int right = *((int*)bytes);  bytes += sizeof(int);
239 #if MM_DEBUG_DRAWING
240             ASLogDebug(@"   Insert %d line(s) at row %d", count, row);
241 #endif
242             [textStorage insertLinesAtRow:row lineCount:count
243                              scrollBottom:bot left:left right:right
244                                     color:[NSColor colorWithArgbInt:color]];
245         } else if (DrawCursorDrawType == type) {
246             unsigned color = *((unsigned*)bytes);  bytes += sizeof(unsigned);
247             int row = *((int*)bytes);  bytes += sizeof(int);
248             int col = *((int*)bytes);  bytes += sizeof(int);
249             int shape = *((int*)bytes);  bytes += sizeof(int);
250             int percent = *((int*)bytes);  bytes += sizeof(int);
252 #if MM_DEBUG_DRAWING
253             ASLogDebug(@"   Draw cursor at (%d,%d)", row, col);
254 #endif
255             [helper setInsertionPointColor:[NSColor colorWithRgbInt:color]];
256             [self drawInsertionPointAtRow:row column:col shape:shape
257                                  fraction:percent];
258         } else if (DrawInvertedRectDrawType == type) {
259             int row = *((int*)bytes);  bytes += sizeof(int);
260             int col = *((int*)bytes);  bytes += sizeof(int);
261             int nr = *((int*)bytes);  bytes += sizeof(int);
262             int nc = *((int*)bytes);  bytes += sizeof(int);
263             int invert = *((int*)bytes);  bytes += sizeof(int);
265 #if MM_DEBUG_DRAWING
266             ASLogDebug(@"   Draw inverted rect: row=%d col=%d nrows=%d "
267                        "ncols=%d", row, col, nr, nc);
268 #endif
269             [self drawInvertedRectAtRow:row column:col numRows:nr numColumns:nc
270                                  invert:invert];
271         } else if (SetCursorPosDrawType == type) {
272             cursorRow = *((int*)bytes);  bytes += sizeof(int);
273             cursorCol = *((int*)bytes);  bytes += sizeof(int);
274         } else {
275             ASLogWarn(@"Unknown draw type (type=%d)", type);
276         }
277     }
279     [textStorage endEditing];
281     if (cursorRow >= 0) {
282         unsigned off = [textStorage characterIndexForRow:cursorRow
283                                                   column:cursorCol];
284         unsigned maxoff = [[textStorage string] length];
285         if (off > maxoff) off = maxoff;
287         [self setSelectedRange:NSMakeRange(off, 0)];
288     }
290     // NOTE: During resizing, Cocoa only sends draw messages before Vim's rows
291     // and columns are changed (due to ipc delays). Force a redraw here.
292     if ([self inLiveResize])
293         [self display];
295 #if MM_DEBUG_DRAWING
296     ASLogDebug(@"<==== END   %s", _cmd);
297 #endif
300 - (void)setMouseShape:(int)shape
302     [helper setMouseShape:shape];
305 - (void)setAntialias:(BOOL)state
307     antialias = state;
310 - (void)setImControl:(BOOL)enable
312     [helper setImControl:enable];
315 - (NSFont *)font
317     return [(MMTextStorage*)[self textStorage] font];
320 - (void)setFont:(NSFont *)newFont
322     [(MMTextStorage*)[self textStorage] setFont:newFont];
325 - (NSFont *)fontWide
327     return [(MMTextStorage*)[self textStorage] fontWide];
330 - (void)setWideFont:(NSFont *)newFont
332     [(MMTextStorage*)[self textStorage] setWideFont:newFont];
335 - (NSSize)cellSize
337     return [(MMTextStorage*)[self textStorage] cellSize];
340 - (void)setLinespace:(float)newLinespace
342     return [(MMTextStorage*)[self textStorage] setLinespace:newLinespace];
345 - (int)maxRows
347     MMTextStorage *ts = (MMTextStorage *)[self textStorage];
348     return [ts maxRows];
351 - (int)maxColumns
353     MMTextStorage *ts = (MMTextStorage *)[self textStorage];
354     return [ts maxColumns];
357 - (void)getMaxRows:(int*)rows columns:(int*)cols
359     return [(MMTextStorage*)[self textStorage] getMaxRows:rows columns:cols];
362 - (void)setMaxRows:(int)rows columns:(int)cols
364     return [(MMTextStorage*)[self textStorage] setMaxRows:rows columns:cols];
367 - (NSRect)rectForRowsInRange:(NSRange)range
369     return [(MMTextStorage*)[self textStorage] rectForRowsInRange:range];
372 - (NSRect)rectForColumnsInRange:(NSRange)range
374     return [(MMTextStorage*)[self textStorage] rectForColumnsInRange:range];
377 - (void)setDefaultColorsBackground:(NSColor *)bgColor
378                         foreground:(NSColor *)fgColor
380     [self setBackgroundColor:bgColor];
381     return [(MMTextStorage*)[self textStorage]
382             setDefaultColorsBackground:bgColor foreground:fgColor];
385 - (NSColor *)defaultBackgroundColor
387     return [(MMTextStorage*)[self textStorage] defaultBackgroundColor];
390 - (NSColor *)defaultForegroundColor
392     return [(MMTextStorage*)[self textStorage] defaultForegroundColor];
395 - (NSSize)constrainRows:(int *)rows columns:(int *)cols toSize:(NSSize)size
397     NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
398     int right = [ud integerForKey:MMTextInsetRightKey];
399     int bot = [ud integerForKey:MMTextInsetBottomKey];
401     size.width -= [self textContainerOrigin].x + right;
402     size.height -= [self textContainerOrigin].y + bot;
404     NSSize newSize = [(MMTextStorage*)[self textStorage] fitToSize:size
405                                                               rows:rows
406                                                            columns:cols];
408     newSize.width += [self textContainerOrigin].x + right;
409     newSize.height += [self textContainerOrigin].y + bot;
411     return newSize;
414 - (NSSize)desiredSize
416     NSSize size = [(MMTextStorage*)[self textStorage] size];
418     NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
419     int right = [ud integerForKey:MMTextInsetRightKey];
420     int bot = [ud integerForKey:MMTextInsetBottomKey];
422     size.width += [self textContainerOrigin].x + right;
423     size.height += [self textContainerOrigin].y + bot;
425     return size;
428 - (NSSize)minSize
430     NSSize cellSize = [(MMTextStorage*)[self textStorage] cellSize];
431     NSSize size = { MMMinColumns*cellSize.width, MMMinRows*cellSize.height };
433     NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
434     int right = [ud integerForKey:MMTextInsetRightKey];
435     int bot = [ud integerForKey:MMTextInsetBottomKey];
437     size.width += [self textContainerOrigin].x + right;
438     size.height += [self textContainerOrigin].y + bot;
440     return size;
443 - (BOOL)convertPoint:(NSPoint)point toRow:(int *)row column:(int *)column
445     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
446     NSSize cellSize = [ts cellSize];
447     if (!(cellSize.width > 0 && cellSize.height > 0))
448         return NO;
449     NSPoint origin = [self textContainerOrigin];
451     if (row) *row = floor((point.y-origin.y-1) / cellSize.height);
452     if (column) *column = floor((point.x-origin.x-1) / cellSize.width);
454     return YES;
457 - (NSPoint)pointForRow:(int)row column:(int)col
459     // Return the upper-left coordinate for (row,column).
460     // NOTE: The coordinate system is flipped!
461     NSPoint pt = [self textContainerOrigin];
462     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
463     NSSize cellSize = [ts cellSize];
465     pt.x += col * cellSize.width;
466     pt.y += row * cellSize.height;
468     return pt;
471 - (NSRect)rectForRow:(int)row column:(int)col numRows:(int)nr
472           numColumns:(int)nc
474     // Return the rect for the block which covers the specified rows and
475     // columns.  The upper-left corner is the origin of this rect.
476     // NOTE: The coordinate system is flipped!
477     NSRect rect;
478     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
479     NSSize cellSize = [ts cellSize];
481     rect.origin = [self textContainerOrigin];
482     rect.origin.x += col * cellSize.width;
483     rect.origin.y += row * cellSize.height;
484     rect.size.width = cellSize.width * nc;
485     rect.size.height = cellSize.height * nr;
487     return rect;
490 - (BOOL)isOpaque
492     return NO;
495 - (void)drawRect:(NSRect)rect
497     NSGraphicsContext *context = [NSGraphicsContext currentContext];
498     [context setShouldAntialias:antialias];
500     [super drawRect:rect];
502     if (invertRects) {
503         CGContextRef cgctx = (CGContextRef)[context graphicsPort];
504         CGContextSaveGState(cgctx);
505         CGContextSetBlendMode(cgctx, kCGBlendModeDifference);
506         CGContextSetRGBFillColor(cgctx, 1.0, 1.0, 1.0, 1.0);
508         int i;
509         CGRect *rect = (CGRect*)invertRects;
510         for (i = 0; i < numInvertRects; ++i)
511             CGContextFillRect(cgctx, rect[i]);
513         CGContextRestoreGState(cgctx);
515         free(invertRects);
516         invertRects = NULL;
517         numInvertRects = 0;
518     }
520     if ([self hasMarkedText]) {
521         shouldDrawInsertionPoint = YES;
522         MMTextStorage *ts = (MMTextStorage*)[self textStorage];
523         NSSize inset = [self textContainerInset];
525         // HACK! Get the baseline of the zeroth glyph and use that as the
526         // baseline for the marked text.  (Is there a better way to figure out
527         // what baseline NSTextView uses?)
528         NSLayoutManager *lm = [self layoutManager];
529         NSTypesetter *tsr = [lm typesetter];
530         float baseline = [tsr baselineOffsetInLayoutManager:lm glyphIndex:0];
532         // Also adjust for 'linespace' option (TODO: Why not .5*linespace?)
533         baseline -= floor([ts linespace]);
535         inset.height -= baseline;
537         int len = [[helper markedText] length];
538         // The following implementation should be re-written with
539         // more efficient way...
541         // Calculate how many wide-font characters can be inserted at
542         // a first line, and draw those characters.
543         int cols = ([ts actualColumns] - insertionPointColumn);
544         NSFont *theFont = [[self markedTextAttributes]
545                 valueForKey:NSFontAttributeName];
546         if (theFont == [ts fontWide])
547             cols = cols / 2;
548         int done = 0;
549         int lend = cols > len ? len : cols;
550         NSAttributedString *aString = [[helper markedText]
551                 attributedSubstringFromRange:NSMakeRange(done, lend)];
552         [aString drawAtPoint:NSMakePoint(
553                 [helper preEditColumn]*[ts cellSize].width + inset.width,
554                 [helper preEditRow]*[ts cellSize].height + inset.height)];
556         done = lend;
557         // Check whether there're charecters that aren't drawn at
558         // the first line. If everything is already done, the follow
559         // check fails.
560         if (done != len) {
561             int r;
562             // Calculate How many rows are needed to draw all the left
563             // characters.
564             int rows = (len - done) / ([ts actualColumns] / 2) + 1;
565             for (r = 1; r <= rows; r++) {
566                 lend = len - done > [ts actualColumns] / 2
567                         ? [ts actualColumns] / 2 : len - done;
568                 aString = [[helper markedText] attributedSubstringFromRange:
569                         NSMakeRange(done, lend)];
570                 [aString drawAtPoint:NSMakePoint(
571                         inset.width,
572                         ([helper preEditRow] + r)*[ts cellSize].height
573                             + inset.height)];
574                 done += lend;
575             }
576         }
577     }
579     if (shouldDrawInsertionPoint) {
580         MMTextStorage *ts = (MMTextStorage*)[self textStorage];
582         NSRect ipRect = [ts boundingRectForCharacterAtRow:[helper preEditRow]
583                                                    column:[helper preEditColumn]];
584         ipRect.origin.x += [self textContainerOrigin].x;
585         ipRect.origin.y += [self textContainerOrigin].y;
587         // Draw insertion point inside marked text.
588         if ([self hasMarkedText]) {
589             NSFont *theFont = [[self markedTextAttributes]
590                     valueForKey:NSFontAttributeName];
591             if (theFont == [ts font])
592                 ipRect.origin.x += [ts cellSize].width *
593                                    ([helper imRange].location +
594                                    [helper imRange].length);
595             else
596                 ipRect.origin.x += [ts cellSize].width * 2 *
597                                    ([helper imRange].location +
598                                    [helper imRange].length);
599         }
601         if (MMInsertionPointHorizontal == insertionPointShape) {
602             int frac = ([ts cellSize].height * insertionPointFraction + 99)/100;
603             ipRect.origin.y += ipRect.size.height - frac;
604             ipRect.size.height = frac;
605         } else if (MMInsertionPointVertical == insertionPointShape) {
606             int frac = ([ts cellSize].width * insertionPointFraction + 99)/100;
607             ipRect.size.width = frac;
608         } else if (MMInsertionPointVerticalRight == insertionPointShape) {
609             int frac = ([ts cellSize].width * insertionPointFraction + 99)/100;
610             ipRect.origin.x += ipRect.size.width - frac;
611             ipRect.size.width = frac;
612         }
614         [[helper insertionPointColor] set];
615         if (MMInsertionPointHollow == insertionPointShape) {
616             NSFrameRect(ipRect);
617         } else {
618             NSRectFill(ipRect);
619         }
621         // NOTE: We only draw the cursor once and rely on Vim to say when it
622         // should be drawn again.
623         shouldDrawInsertionPoint = NO;
624     }
626 #if 0
627     // this code invalidates the shadow, so we don't 
628     // get shifting ghost text on scroll and resize
629     // but makes speed unusable
630     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
631     if ([ts defaultBackgroundAlpha] < 1.0f) {
632         if (floor(NSAppKitVersionNumber) <= NSAppKitVersionNumber10_1)
633         {
634             [[self window] setHasShadow:NO];
635             [[self window] setHasShadow:YES];
636         }
637         else
638             [[self window] invalidateShadow];
640     }
641 #endif
644 - (void)keyDown:(NSEvent *)event
646     [helper keyDown:event];
649 - (void)insertText:(id)string
651     [helper insertText:string];
654 - (void)doCommandBySelector:(SEL)selector
656     [helper doCommandBySelector:selector];
659 - (BOOL)performKeyEquivalent:(NSEvent *)event
661     return [helper performKeyEquivalent:event];
664 - (BOOL)hasMarkedText
666     return [helper hasMarkedText];
669 - (NSRange)markedRange
671     return [helper markedRange];
674 - (NSDictionary *)markedTextAttributes
676     return [helper markedTextAttributes];
679 - (void)setMarkedTextAttributes:(NSDictionary *)attr
681     [helper setMarkedTextAttributes:attr];
684 - (void)setMarkedText:(id)text selectedRange:(NSRange)range
686     [helper setMarkedText:text selectedRange:range];
689 - (void)unmarkText
691     [helper unmarkText];
694 - (NSRect)firstRectForCharacterRange:(NSRange)range
696     return [helper firstRectForCharacterRange:range];
699 - (void)scrollWheel:(NSEvent *)event
701     [helper scrollWheel:event];
704 - (void)mouseDown:(NSEvent *)event
706     [helper mouseDown:event];
709 - (void)rightMouseDown:(NSEvent *)event
711     [helper mouseDown:event];
714 - (void)otherMouseDown:(NSEvent *)event
716     [helper mouseDown:event];
719 - (void)mouseUp:(NSEvent *)event
721     [helper mouseUp:event];
724 - (void)rightMouseUp:(NSEvent *)event
726     [helper mouseUp:event];
729 - (void)otherMouseUp:(NSEvent *)event
731     [helper mouseUp:event];
734 - (void)mouseDragged:(NSEvent *)event
736     [helper mouseDragged:event];
739 - (void)rightMouseDragged:(NSEvent *)event
741     [helper mouseDragged:event];
744 - (void)otherMouseDragged:(NSEvent *)event
746     [helper mouseDragged:event];
749 - (void)mouseMoved:(NSEvent *)event
751     [helper mouseMoved:event];
754 - (void)mouseEntered:(NSEvent *)event
756     [helper mouseEntered:event];
759 - (void)mouseExited:(NSEvent *)event
761     [helper mouseExited:event];
764 - (void)setFrame:(NSRect)frame
766     [super setFrame:frame];
767     [helper setFrame:frame];
770 - (void)viewDidMoveToWindow
772     [helper viewDidMoveToWindow];
775 - (void)viewWillMoveToWindow:(NSWindow *)newWindow
777     [helper viewWillMoveToWindow:newWindow];
780 - (NSMenu*)menuForEvent:(NSEvent *)event
782     // HACK! Return nil to disable NSTextView's popup menus (Vim provides its
783     // own).  Called when user Ctrl-clicks in the view (this is already handled
784     // in rightMouseDown:).
785     return nil;
788 - (NSArray *)acceptableDragTypes
790     return [NSArray arrayWithObjects:NSFilenamesPboardType,
791            NSStringPboardType, nil];
794 - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
796     return [helper performDragOperation:sender];
799 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
801     return [helper draggingEntered:sender];
804 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
806     return [helper draggingUpdated:sender];
809 - (void)changeFont:(id)sender
811     [helper changeFont:sender];
814 - (void)resetCursorRects
816     // No need to set up cursor rects since Vim handles cursor changes.
819 - (void)updateFontPanel
821     // The font panel is updated whenever the font is set.
826 // NOTE: The menu items cut/copy/paste/undo/redo/select all/... must be bound
827 // to the same actions as in IB otherwise they will not work with dialogs.  All
828 // we do here is forward these actions to the Vim process.
830 - (IBAction)cut:(id)sender
832     [[self windowController] vimMenuItemAction:sender];
835 - (IBAction)copy:(id)sender
837     [[self windowController] vimMenuItemAction:sender];
840 - (IBAction)paste:(id)sender
842     [[self windowController] vimMenuItemAction:sender];
845 - (IBAction)undo:(id)sender
847     [[self windowController] vimMenuItemAction:sender];
850 - (IBAction)redo:(id)sender
852     [[self windowController] vimMenuItemAction:sender];
855 - (IBAction)selectAll:(id)sender
857     [[self windowController] vimMenuItemAction:sender];
860 - (BOOL)validateMenuItem:(NSMenuItem *)item
862     if ([item action] == @selector(cut:)
863             || [item action] == @selector(copy:)
864             || [item action] == @selector(paste:)
865             || [item action] == @selector(undo:)
866             || [item action] == @selector(redo:)
867             || [item action] == @selector(selectAll:))
868         return [item tag];
870     return YES;
873 @end // MMTextView
878 @implementation MMTextView (Private)
880 - (MMWindowController *)windowController
882     id windowController = [[self window] windowController];
883     if ([windowController isKindOfClass:[MMWindowController class]])
884         return (MMWindowController*)windowController;
885     return nil;
888 - (MMVimController *)vimController
890     return [[self windowController] vimController];
893 - (void)setShouldDrawInsertionPoint:(BOOL)on
895     shouldDrawInsertionPoint = on;
898 - (void)drawInsertionPointAtRow:(int)row column:(int)col shape:(int)shape
899                        fraction:(int)percent
901     // This only stores where to draw the insertion point, the actual drawing
902     // is done in drawRect:.
903     shouldDrawInsertionPoint = YES;
904     insertionPointRow = row;
905     insertionPointColumn = col;
906     insertionPointShape = shape;
907     insertionPointFraction = percent;
910 - (void)drawInvertedRectAtRow:(int)row column:(int)col numRows:(int)nrows
911                    numColumns:(int)ncols invert:(int)invert
913     if (invert) {
914         // The result should be inverted.
915         int n = numInvertRects++;
916         invertRects = reallocf(invertRects,
917                                numInvertRects*sizeof(NSRect));
918         if (NULL != invertRects) {
919             invertRects[n] = [self rectForRow:row column:col numRows:nrows
920                                    numColumns:ncols];
921             [self setNeedsDisplayInRect:invertRects[n]];
922         } else {
923             n = numInvertRects = 0;
924         }
925     } else {
926         // The result should look normal; all we need to do is to mark
927         // the rect for redrawing and Cocoa will redraw the text.
928         NSRect rect = [self rectForRow:row column:col numRows:nrows
929                             numColumns:ncols];
930         [self setNeedsDisplayInRect:rect];
931     }
934 @end // MMTextView (Private)