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 * Dispatches keyboard and mouse input to the backend. Handles drag-n-drop of
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.
21 #import "MMAppController.h"
22 #import "MMTextStorage.h"
23 #import "MMTextView.h"
24 #import "MMTypesetter.h"
25 #import "MMVimController.h"
26 #import "MMWindowController.h"
27 #import "Miscellaneous.h"
31 // This is taken from gui.h
32 #define DRAW_CURSOR 0x20
34 // The max/min drag timer interval in seconds
35 static NSTimeInterval MMDragTimerMaxInterval = .3f;
36 static NSTimeInterval MMDragTimerMinInterval = .01f;
38 // The number of pixels in which the drag timer interval changes
39 static float MMDragAreaSize = 73.0f;
41 static char MMKeypadEnter[2] = { 'K', 'A' };
42 static NSString *MMKeypadEnterString = @"KA";
50 @interface MMTextView (Private)
52 - (BOOL)convertPoint:(NSPoint)point toRow:(int *)row column:(int *)column;
53 - (BOOL)convertRow:(int)row column:(int)column toPoint:(NSPoint *)point;
54 - (BOOL)convertRow:(int)row column:(int)column numRows:(int)nr
55 numColumns:(int)nc toRect:(NSRect *)rect;
56 - (NSRect)trackingRect;
57 - (void)dispatchKeyEvent:(NSEvent *)event;
58 - (MMWindowController *)windowController;
59 - (MMVimController *)vimController;
60 - (void)startDragTimerWithInterval:(NSTimeInterval)t;
61 - (void)dragTimerFired:(NSTimer *)timer;
62 - (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags;
63 - (void)hideMouseCursor;
64 - (void)drawInsertionPointAtRow:(int)row column:(int)col shape:(int)shape
65 fraction:(int)percent color:(NSColor *)color;
66 - (void)drawInvertedRectAtRow:(int)row column:(int)col numRows:(int)nrows
67 numColumns:(int)ncols invert:(int)invert;
72 @implementation MMTextView
74 - (id)initWithFrame:(NSRect)frame
76 // Set up a Cocoa text system. Note that the textStorage is released in
77 // -[MMVimView dealloc].
78 MMTextStorage *textStorage = [[MMTextStorage alloc] init];
79 NSLayoutManager *lm = [[NSLayoutManager alloc] init];
80 NSTextContainer *tc = [[NSTextContainer alloc] initWithContainerSize:
81 NSMakeSize(1.0e7,1.0e7)];
83 NSString *typesetterString = [[NSUserDefaults standardUserDefaults]
84 stringForKey:MMTypesetterKey];
85 if ([typesetterString isEqual:@"MMTypesetter"]) {
86 NSTypesetter *typesetter = [[MMTypesetter alloc] init];
87 [lm setTypesetter:typesetter];
89 } else if ([typesetterString isEqual:@"MMTypesetter2"]) {
90 NSTypesetter *typesetter = [[MMTypesetter2 alloc] init];
91 [lm setTypesetter:typesetter];
94 // Only MMTypesetter supports different cell width multipliers.
95 [[NSUserDefaults standardUserDefaults]
96 setFloat:1.0 forKey:MMCellWidthMultiplierKey];
99 // The characters in the text storage are in display order, so disable
100 // bidirectional text processing (this call is 10.4 only).
101 [[lm typesetter] setBidiProcessingEnabled:NO];
103 [tc setWidthTracksTextView:NO];
104 [tc setHeightTracksTextView:NO];
105 [tc setLineFragmentPadding:0];
107 [textStorage addLayoutManager:lm];
108 [lm addTextContainer:tc];
110 // The text storage retains the layout manager which in turn retains
111 // the text container.
115 // NOTE: This will make the text storage the principal owner of the text
116 // system. Releasing the text storage will in turn release the layout
117 // manager, the text container, and finally the text view (self). This
118 // complicates deallocation somewhat, see -[MMVimView dealloc].
119 if (![super initWithFrame:frame textContainer:tc]) {
120 [textStorage release];
124 imRange = NSMakeRange(0, 0);
125 markedRange = NSMakeRange(0, 0);
126 // NOTE: If the default changes to 'NO' then the intialization of
127 // p_antialias in option.c must change as well.
137 imRange = NSMakeRange(0, 0);
138 [markedText release];
151 - (BOOL)shouldDrawInsertionPoint
153 // NOTE: The insertion point is drawn manually in drawRect:. It would be
154 // nice to be able to use the insertion point related methods of
155 // NSTextView, but it seems impossible to get them to work properly (search
156 // the cocoabuilder archives).
160 - (void)setShouldDrawInsertionPoint:(BOOL)on
162 shouldDrawInsertionPoint = on;
165 - (void)setPreEditRow:(int)row column:(int)col
171 #define MM_DEBUG_DRAWING 0
173 - (void)performBatchDrawWithData:(NSData *)data
175 MMTextStorage *textStorage = (MMTextStorage *)[self textStorage];
179 const void *bytes = [data bytes];
180 const void *end = bytes + [data length];
181 int cursorRow = -1, cursorCol = 0;
184 NSLog(@"====> BEGIN %s", _cmd);
186 [textStorage beginEditing];
188 // TODO: Sanity check input
190 while (bytes < end) {
191 int type = *((int*)bytes); bytes += sizeof(int);
193 if (ClearAllDrawType == type) {
195 NSLog(@" Clear all");
197 [textStorage clearAll];
198 } else if (ClearBlockDrawType == type) {
199 unsigned color = *((unsigned*)bytes); bytes += sizeof(unsigned);
200 int row1 = *((int*)bytes); bytes += sizeof(int);
201 int col1 = *((int*)bytes); bytes += sizeof(int);
202 int row2 = *((int*)bytes); bytes += sizeof(int);
203 int col2 = *((int*)bytes); bytes += sizeof(int);
206 NSLog(@" Clear block (%d,%d) -> (%d,%d)", row1, col1,
209 [textStorage clearBlockFromRow:row1 column:col1
210 toRow:row2 column:col2
211 color:[NSColor colorWithArgbInt:color]];
212 } else if (DeleteLinesDrawType == type) {
213 unsigned color = *((unsigned*)bytes); bytes += sizeof(unsigned);
214 int row = *((int*)bytes); bytes += sizeof(int);
215 int count = *((int*)bytes); bytes += sizeof(int);
216 int bot = *((int*)bytes); bytes += sizeof(int);
217 int left = *((int*)bytes); bytes += sizeof(int);
218 int right = *((int*)bytes); bytes += sizeof(int);
221 NSLog(@" Delete %d line(s) from %d", count, row);
223 [textStorage deleteLinesFromRow:row lineCount:count
224 scrollBottom:bot left:left right:right
225 color:[NSColor colorWithArgbInt:color]];
226 } else if (DrawStringDrawType == type) {
227 int bg = *((int*)bytes); bytes += sizeof(int);
228 int fg = *((int*)bytes); bytes += sizeof(int);
229 int sp = *((int*)bytes); bytes += sizeof(int);
230 int row = *((int*)bytes); bytes += sizeof(int);
231 int col = *((int*)bytes); bytes += sizeof(int);
232 int cells = *((int*)bytes); bytes += sizeof(int);
233 int flags = *((int*)bytes); bytes += sizeof(int);
234 int len = *((int*)bytes); bytes += sizeof(int);
235 NSString *string = [[NSString alloc]
236 initWithBytes:(void*)bytes length:len
237 encoding:NSUTF8StringEncoding];
241 NSLog(@" Draw string at (%d,%d) length=%d flags=%d fg=0x%x "
242 "bg=0x%x sp=0x%x (%@)", row, col, len, flags, fg, bg, sp,
243 len > 0 ? [string substringToIndex:1] : @"");
245 // NOTE: If this is a call to draw the (block) cursor, then cancel
246 // any previous request to draw the insertion point, or it might
247 // get drawn as well.
248 if (flags & DRAW_CURSOR) {
249 [self setShouldDrawInsertionPoint:NO];
250 //NSColor *color = [NSColor colorWithRgbInt:bg];
251 //[self drawInsertionPointAtRow:row column:col
252 // shape:MMInsertionPointBlock
256 [textStorage drawString:string
257 atRow:row column:col cells:cells
259 foregroundColor:[NSColor colorWithRgbInt:fg]
260 backgroundColor:[NSColor colorWithArgbInt:bg]
261 specialColor:[NSColor colorWithRgbInt:sp]];
264 } else if (InsertLinesDrawType == type) {
265 unsigned color = *((unsigned*)bytes); bytes += sizeof(unsigned);
266 int row = *((int*)bytes); bytes += sizeof(int);
267 int count = *((int*)bytes); bytes += sizeof(int);
268 int bot = *((int*)bytes); bytes += sizeof(int);
269 int left = *((int*)bytes); bytes += sizeof(int);
270 int right = *((int*)bytes); bytes += sizeof(int);
273 NSLog(@" Insert %d line(s) at row %d", count, row);
275 [textStorage insertLinesAtRow:row lineCount:count
276 scrollBottom:bot left:left right:right
277 color:[NSColor colorWithArgbInt:color]];
278 } else if (DrawCursorDrawType == type) {
279 unsigned color = *((unsigned*)bytes); bytes += sizeof(unsigned);
280 int row = *((int*)bytes); bytes += sizeof(int);
281 int col = *((int*)bytes); bytes += sizeof(int);
282 int shape = *((int*)bytes); bytes += sizeof(int);
283 int percent = *((int*)bytes); bytes += sizeof(int);
286 NSLog(@" Draw cursor at (%d,%d)", row, col);
288 [self drawInsertionPointAtRow:row column:col shape:shape
290 color:[NSColor colorWithRgbInt:color]];
291 } else if (DrawInvertedRectDrawType == type) {
292 int row = *((int*)bytes); bytes += sizeof(int);
293 int col = *((int*)bytes); bytes += sizeof(int);
294 int nr = *((int*)bytes); bytes += sizeof(int);
295 int nc = *((int*)bytes); bytes += sizeof(int);
296 int invert = *((int*)bytes); bytes += sizeof(int);
299 NSLog(@" Draw inverted rect: row=%d col=%d nrows=%d ncols=%d",
302 [self drawInvertedRectAtRow:row column:col numRows:nr numColumns:nc
304 } else if (SetCursorPosDrawType == type) {
305 cursorRow = *((int*)bytes); bytes += sizeof(int);
306 cursorCol = *((int*)bytes); bytes += sizeof(int);
308 NSLog(@"WARNING: Unknown draw type (type=%d)", type);
312 [textStorage endEditing];
314 if (cursorRow >= 0) {
315 unsigned off = [textStorage characterIndexForRow:cursorRow
317 unsigned maxoff = [[textStorage string] length];
318 if (off > maxoff) off = maxoff;
320 [self setSelectedRange:NSMakeRange(off, 0)];
323 // NOTE: During resizing, Cocoa only sends draw messages before Vim's rows
324 // and columns are changed (due to ipc delays). Force a redraw here.
325 [self displayIfNeeded];
328 NSLog(@"<==== END %s", _cmd);
332 - (void)setMouseShape:(int)shape
338 - (void)setAntialias:(BOOL)state
345 return [(MMTextStorage*)[self textStorage] font];
348 - (void)setFont:(NSFont *)newFont
350 [(MMTextStorage*)[self textStorage] setFont:newFont];
353 - (void)setWideFont:(NSFont *)newFont
355 [(MMTextStorage*)[self textStorage] setWideFont:newFont];
360 return [(MMTextStorage*)[self textStorage] cellSize];
363 - (void)setLinespace:(float)newLinespace
365 return [(MMTextStorage*)[self textStorage] setLinespace:newLinespace];
368 - (void)getMaxRows:(int*)rows columns:(int*)cols
370 return [(MMTextStorage*)[self textStorage] getMaxRows:rows columns:cols];
373 - (void)setMaxRows:(int)rows columns:(int)cols
375 return [(MMTextStorage*)[self textStorage] setMaxRows:rows columns:cols];
378 - (NSRect)rectForRowsInRange:(NSRange)range
380 return [(MMTextStorage*)[self textStorage] rectForRowsInRange:range];
383 - (NSRect)rectForColumnsInRange:(NSRange)range
385 return [(MMTextStorage*)[self textStorage] rectForColumnsInRange:range];
388 - (void)setDefaultColorsBackground:(NSColor *)bgColor
389 foreground:(NSColor *)fgColor
391 [self setBackgroundColor:bgColor];
392 return [(MMTextStorage*)[self textStorage]
393 setDefaultColorsBackground:bgColor foreground:fgColor];
396 - (NSSize)constrainRows:(int *)rows columns:(int *)cols toSize:(NSSize)size
398 NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
399 int right = [ud integerForKey:MMTextInsetRightKey];
400 int bot = [ud integerForKey:MMTextInsetBottomKey];
402 size.width -= [self textContainerOrigin].x + right;
403 size.height -= [self textContainerOrigin].y + bot;
405 NSSize newSize = [(MMTextStorage*)[self textStorage] fitToSize:size
409 newSize.width += [self textContainerOrigin].x + right;
410 newSize.height += [self textContainerOrigin].y + bot;
415 - (NSSize)desiredSize
417 NSSize size = [(MMTextStorage*)[self textStorage] size];
419 NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
420 int right = [ud integerForKey:MMTextInsetRightKey];
421 int bot = [ud integerForKey:MMTextInsetBottomKey];
423 size.width += [self textContainerOrigin].x + right;
424 size.height += [self textContainerOrigin].y + bot;
431 NSSize cellSize = [(MMTextStorage*)[self textStorage] cellSize];
432 NSSize size = { MMMinColumns*cellSize.width, MMMinRows*cellSize.height };
434 NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
435 int right = [ud integerForKey:MMTextInsetRightKey];
436 int bot = [ud integerForKey:MMTextInsetBottomKey];
438 size.width += [self textContainerOrigin].x + right;
439 size.height += [self textContainerOrigin].y + bot;
449 - (void)drawRect:(NSRect)rect
451 NSGraphicsContext *context = [NSGraphicsContext currentContext];
452 [context setShouldAntialias:antialias];
454 [super drawRect:rect];
457 CGContextRef cgctx = (CGContextRef)[context graphicsPort];
458 CGContextSaveGState(cgctx);
459 CGContextSetBlendMode(cgctx, kCGBlendModeDifference);
460 CGContextSetRGBFillColor(cgctx, 1.0, 1.0, 1.0, 1.0);
463 CGRect *rect = (CGRect*)invertRects;
464 for (i = 0; i < numInvertRects; ++i)
465 CGContextFillRect(cgctx, rect[i]);
467 CGContextRestoreGState(cgctx);
474 if ([self hasMarkedText]) {
475 shouldDrawInsertionPoint = YES;
476 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
477 NSSize inset = [self textContainerInset];
479 // HACK! Get the baseline of the zeroth glyph and use that as the
480 // baseline for the marked text. (Is there a better way to figure out
481 // what baseline NSTextView uses?)
482 NSLayoutManager *lm = [self layoutManager];
483 NSTypesetter *tsr = [lm typesetter];
484 float baseline = [tsr baselineOffsetInLayoutManager:lm glyphIndex:0];
486 // Also adjust for 'linespace' option (TODO: Why not .5*linespace?)
487 baseline -= floor([ts linespace]);
489 inset.height -= baseline;
491 int len = [markedText length];
492 // The following implementation should be re-written with
493 // more efficient way...
495 // Calculate how many wide-font characters can be inserted at
496 // a first line, and draw those characters.
497 int cols = ([ts actualColumns] - insertionPointColumn);
498 NSFont *theFont = [[self markedTextAttributes]
499 valueForKey:NSFontAttributeName];
500 if (theFont == [ts fontWide])
503 int lend = cols > len ? len : cols;
504 NSAttributedString *aString = [markedText attributedSubstringFromRange:
505 NSMakeRange(done, lend)];
506 [aString drawAtPoint:NSMakePoint(
507 preEditColumn*[ts cellSize].width + inset.width,
508 preEditRow*[ts cellSize].height + inset.height)];
511 // Check whether there're charecters that aren't drawn at
512 // the first line. If everything is already done, the follow
516 // Calculate How many rows are needed to draw all the left
518 int rows = (len - done) / ([ts actualColumns] / 2) + 1;
519 for (r = 1; r <= rows; r++) {
520 lend = len - done > [ts actualColumns] / 2
521 ? [ts actualColumns] / 2 : len - done;
522 aString = [markedText attributedSubstringFromRange:
523 NSMakeRange(done, lend)];
524 [aString drawAtPoint:NSMakePoint(
526 (preEditRow + r)*[ts cellSize].height
533 if (shouldDrawInsertionPoint) {
534 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
536 NSRect ipRect = [ts boundingRectForCharacterAtRow:preEditRow
537 column:preEditColumn];
538 ipRect.origin.x += [self textContainerOrigin].x;
539 ipRect.origin.y += [self textContainerOrigin].y;
541 // Draw insertion point inside marked text.
542 if ([self hasMarkedText]) {
543 NSFont *theFont = [[self markedTextAttributes]
544 valueForKey:NSFontAttributeName];
545 if (theFont == [ts font])
546 ipRect.origin.x += [ts cellSize].width *
547 (imRange.location + imRange.length);
549 ipRect.origin.x += [ts cellSize].width * 2 *
550 (imRange.location + imRange.length);
553 if (MMInsertionPointHorizontal == insertionPointShape) {
554 int frac = ([ts cellSize].height * insertionPointFraction + 99)/100;
555 ipRect.origin.y += ipRect.size.height - frac;
556 ipRect.size.height = frac;
557 } else if (MMInsertionPointVertical == insertionPointShape) {
558 int frac = ([ts cellSize].width * insertionPointFraction + 99)/100;
559 ipRect.size.width = frac;
560 } else if (MMInsertionPointVerticalRight == insertionPointShape) {
561 int frac = ([ts cellSize].width * insertionPointFraction + 99)/100;
562 ipRect.origin.x += ipRect.size.width - frac;
563 ipRect.size.width = frac;
566 [[self insertionPointColor] set];
567 if (MMInsertionPointHollow == insertionPointShape) {
573 // NOTE: We only draw the cursor once and rely on Vim to say when it
574 // should be drawn again.
575 shouldDrawInsertionPoint = NO;
577 //NSLog(@"%s draw insertion point %@ shape=%d color=%@", _cmd,
578 // NSStringFromRect(ipRect), insertionPointShape,
579 // [self insertionPointColor]);
583 // this code invalidates the shadow, so we don't
584 // get shifting ghost text on scroll and resize
585 // but makes speed unusable
586 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
587 if ([ts defaultBackgroundAlpha] < 1.0f) {
588 if (floor(NSAppKitVersionNumber) <= NSAppKitVersionNumber10_1)
590 [[self window] setHasShadow:NO];
591 [[self window] setHasShadow:YES];
594 [[self window] invalidateShadow];
600 - (void)keyDown:(NSEvent *)event
602 //NSLog(@"%s %@", _cmd, event);
603 // HACK! If control modifier is held, don't pass the event along to
604 // interpretKeyEvents: since some keys are bound to multiple commands which
605 // means doCommandBySelector: is called several times. Do the same for
606 // Alt+Function key presses (Alt+Up and Alt+Down are bound to two
607 // commands). This hack may break input management, but unless we can
608 // figure out a way to disable key bindings there seems little else to do.
610 // TODO: Figure out a way to disable Cocoa key bindings entirely, without
611 // affecting input management.
613 // When the Input Method is activated, some special key inputs
614 // should be treated as key inputs for Input Method.
615 if ([self hasMarkedText]) {
616 [self interpretKeyEvents:[NSArray arrayWithObject:event]];
617 [self setNeedsDisplay:YES];
621 int flags = [event modifierFlags];
622 if ((flags & NSControlKeyMask) ||
623 ((flags & NSAlternateKeyMask) && (flags & NSFunctionKeyMask))) {
624 NSString *unmod = [event charactersIgnoringModifiers];
625 if ([unmod length] == 1 && [unmod characterAtIndex:0] <= 0x7f
626 && [unmod characterAtIndex:0] >= 0x60) {
627 // HACK! Send Ctrl-letter keys (and C-@, C-[, C-\, C-], C-^, C-_)
628 // as normal text to be added to the Vim input buffer. This must
629 // be done in order for the backend to be able to separate e.g.
630 // Ctrl-i and Ctrl-tab.
631 [self insertText:[event characters]];
633 [self dispatchKeyEvent:event];
636 [super keyDown:event];
640 - (void)insertText:(id)string
642 //NSLog(@"%s %@", _cmd, string);
643 // NOTE! This method is called for normal key presses but also for
644 // Option-key presses --- even when Ctrl is held as well as Option. When
645 // Ctrl is held, the AppKit translates the character to a Ctrl+key stroke,
646 // so 'string' need not be a printable character! In this case it still
647 // works to pass 'string' on to Vim as a printable character (since
648 // modifiers are already included and should not be added to the input
649 // buffer using CSI, K_MODIFIER).
651 if ([self hasMarkedText]) {
655 NSEvent *event = [NSApp currentEvent];
657 // HACK! In order to be able to bind to <S-Space>, <S-M-Tab>, etc. we have
658 // to watch for them here.
659 if ([event type] == NSKeyDown
660 && [[event charactersIgnoringModifiers] length] > 0
661 && [event modifierFlags]
662 & (NSShiftKeyMask|NSControlKeyMask|NSAlternateKeyMask)) {
663 unichar c = [[event charactersIgnoringModifiers] characterAtIndex:0];
665 // <S-M-Tab> translates to 0x19
666 if (' ' == c || 0x19 == c) {
667 [self dispatchKeyEvent:event];
672 [self hideMouseCursor];
674 // NOTE: 'string' is either an NSString or an NSAttributedString. Since we
675 // do not support attributes, simply pass the corresponding NSString in the
677 if ([string isKindOfClass:[NSAttributedString class]])
678 string = [string string];
680 //NSLog(@"send InsertTextMsgID: %@", string);
682 [[self vimController] sendMessage:InsertTextMsgID
683 data:[string dataUsingEncoding:NSUTF8StringEncoding]];
687 - (void)doCommandBySelector:(SEL)selector
689 //NSLog(@"%s %@", _cmd, NSStringFromSelector(selector));
690 // By ignoring the selector we effectively disable the key binding
691 // mechanism of Cocoa. Hopefully this is what the user will expect
692 // (pressing Ctrl+P would otherwise result in moveUp: instead of previous
695 // We usually end up here if the user pressed Ctrl+key (but not
698 NSEvent *event = [NSApp currentEvent];
700 if (selector == @selector(cancelOperation:)
701 || selector == @selector(insertNewline:)) {
702 // HACK! If there was marked text which got abandoned as a result of
703 // hitting escape or enter, then 'insertText:' is called with the
704 // abandoned text but '[event characters]' includes the abandoned text
705 // as well. Since 'dispatchKeyEvent:' looks at '[event characters]' we
706 // must intercept these keys here or the abandonded text gets inserted
708 NSString *key = [event charactersIgnoringModifiers];
709 const char *chars = [key UTF8String];
710 int len = [key lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
712 if (0x3 == chars[0]) {
713 // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
714 // handle it separately (else Ctrl-C doesn't work).
715 len = sizeof(MMKeypadEnter)/sizeof(MMKeypadEnter[0]);
716 chars = MMKeypadEnter;
719 [self sendKeyDown:chars length:len modifiers:[event modifierFlags]];
721 [self dispatchKeyEvent:event];
725 - (BOOL)performKeyEquivalent:(NSEvent *)event
727 //NSLog(@"%s %@", _cmd, event);
728 // Called for Cmd+key keystrokes, function keys, arrow keys, page
729 // up/down, home, end.
731 // NOTE: This message cannot be ignored since Cmd+letter keys never are
732 // passed to keyDown:. It seems as if the main menu consumes Cmd-key
733 // strokes, unless the key is a function key.
735 // NOTE: If the event that triggered this method represents a function key
736 // down then we do nothing, otherwise the input method never gets the key
737 // stroke (some input methods use e.g. arrow keys). The function key down
738 // event will still reach Vim though (via keyDown:). The exceptions to
739 // this rule are: PageUp/PageDown (keycode 116/121).
740 int flags = [event modifierFlags];
741 if ([event type] != NSKeyDown || flags & NSFunctionKeyMask
742 && !(116 == [event keyCode] || 121 == [event keyCode]))
745 // HACK! KeyCode 50 represent the key which switches between windows
746 // within an application (like Cmd+Tab is used to switch between
747 // applications). Return NO here, else the window switching does not work.
748 if ([event keyCode] == 50)
751 // HACK! Let the main menu try to handle any key down event, before
752 // passing it on to vim, otherwise key equivalents for menus will
753 // effectively be disabled.
754 if ([[NSApp mainMenu] performKeyEquivalent:event])
757 // HACK! On Leopard Ctrl-key events end up here instead of keyDown:.
758 if (flags & NSControlKeyMask) {
759 [self keyDown:event];
763 // HACK! Don't handle Cmd-? or the "Help" menu does not work on Leopard.
764 NSString *unmodchars = [event charactersIgnoringModifiers];
765 if ([unmodchars isEqual:@"?"])
768 //NSLog(@"%s%@", _cmd, event);
770 NSString *chars = [event characters];
771 int len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
772 NSMutableData *data = [NSMutableData data];
777 // If 'chars' and 'unmodchars' differs when shift flag is present, then we
778 // can clear the shift flag as it is already included in 'unmodchars'.
779 // Failing to clear the shift flag means <D-Bar> turns into <S-D-Bar> (on
780 // an English keyboard).
781 if (flags & NSShiftKeyMask && ![chars isEqual:unmodchars])
782 flags &= ~NSShiftKeyMask;
784 if (0x3 == [unmodchars characterAtIndex:0]) {
785 // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
786 // handle it separately (else Cmd-enter turns into Ctrl-C).
787 unmodchars = MMKeypadEnterString;
788 len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
791 [data appendBytes:&flags length:sizeof(int)];
792 [data appendBytes:&len length:sizeof(int)];
793 [data appendBytes:[unmodchars UTF8String] length:len];
795 [[self vimController] sendMessage:CmdKeyMsgID data:data];
800 - (BOOL)hasMarkedText
802 //NSLog(@"%s", _cmd);
803 //return markedText && [markedText length] > 0;
804 return markedRange.length > 0 ? YES : NO;
807 - (NSRange)markedRange
809 if ([self hasMarkedText]) {
812 return NSMakeRange(NSNotFound, 0);
815 - (NSDictionary *)markedTextAttributes
817 return markedTextAttributes;
820 - (void)setMarkedTextAttributes:(NSDictionary *)attr
822 if (attr != markedTextAttributes) {
823 [markedTextAttributes release];
824 markedTextAttributes = [attr retain];
829 - (void)setMarkedText:(id)text selectedRange:(NSRange)range
831 //NSLog(@"setMarkedText:'%@' selectedRange:%@", text,
832 // NSStringFromRange(range));
834 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
839 if (text && [text length] > 0) {
840 if ([text isKindOfClass:[NSAttributedString class]]) {
841 [self setMarkedTextAttributes:
842 [NSDictionary dictionaryWithObjectsAndKeys:
843 [ts fontWide], NSFontAttributeName,
844 [ts defaultBackgroundColor], NSBackgroundColorAttributeName,
845 [ts defaultForegroundColor], NSForegroundColorAttributeName,
847 markedText = [[NSMutableAttributedString alloc]
848 initWithString:[text string]
849 attributes:[self markedTextAttributes]];
851 [self setMarkedTextAttributes:
852 [NSDictionary dictionaryWithObjectsAndKeys:
853 [ts font], NSFontAttributeName,
854 [ts defaultBackgroundColor], NSBackgroundColorAttributeName,
855 [ts defaultForegroundColor], NSForegroundColorAttributeName,
857 markedText = [[NSMutableAttributedString alloc]
859 attributes:[self markedTextAttributes]];
862 markedRange = NSMakeRange(0, [markedText length]);
863 if (markedRange.length) {
864 [markedText addAttribute:NSUnderlineStyleAttributeName
865 value:[NSNumber numberWithInt:1]
870 [markedText addAttribute:NSUnderlineStyleAttributeName
871 value:[NSNumber numberWithInt:2]
875 [self setNeedsDisplay: YES];
880 //NSLog(@"%s", _cmd);
881 imRange = NSMakeRange(0, 0);
882 markedRange = NSMakeRange(NSNotFound, 0);
883 [markedText release];
887 - (NSRect)firstRectForCharacterRange:(NSRange)range
889 //NSLog(@"%s%@", _cmd, NSStringFromRange(range));
890 // HACK! This method is called when the input manager wants to pop up an
891 // auxiliary window. The position where this should be is controller by
892 // Vim by sending SetPreEditPositionMsgID so compute a position based on
893 // the pre-edit (row,column) pair.
894 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
896 NSRect rect = [ts boundingRectForCharacterAtRow:preEditRow
897 column:preEditColumn];
898 rect.origin.x += [self textContainerOrigin].x;
899 rect.origin.y += [self textContainerOrigin].y + [ts cellSize].height;
901 rect.origin = [self convertPoint:rect.origin toView:nil];
902 rect.origin = [[self window] convertBaseToScreen:rect.origin];
907 - (void)scrollWheel:(NSEvent *)event
909 if ([event deltaY] == 0)
913 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
914 if (![self convertPoint:pt toRow:&row column:&col])
917 int flags = [event modifierFlags];
918 float dy = [event deltaY];
919 NSMutableData *data = [NSMutableData data];
921 [data appendBytes:&row length:sizeof(int)];
922 [data appendBytes:&col length:sizeof(int)];
923 [data appendBytes:&flags length:sizeof(int)];
924 [data appendBytes:&dy length:sizeof(float)];
926 [[self vimController] sendMessage:ScrollWheelMsgID data:data];
929 - (void)mouseDown:(NSEvent *)event
932 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
933 if (![self convertPoint:pt toRow:&row column:&col])
936 int button = [event buttonNumber];
937 int flags = [event modifierFlags];
938 int count = [event clickCount];
939 NSMutableData *data = [NSMutableData data];
941 // If desired, intepret Ctrl-Click as a right mouse click.
942 BOOL translateCtrlClick = [[NSUserDefaults standardUserDefaults]
943 boolForKey:MMTranslateCtrlClickKey];
944 flags = flags & NSDeviceIndependentModifierFlagsMask;
945 if (translateCtrlClick && button == 0 &&
946 (flags == NSControlKeyMask ||
947 flags == (NSControlKeyMask|NSAlphaShiftKeyMask))) {
949 flags &= ~NSControlKeyMask;
952 [data appendBytes:&row length:sizeof(int)];
953 [data appendBytes:&col length:sizeof(int)];
954 [data appendBytes:&button length:sizeof(int)];
955 [data appendBytes:&flags length:sizeof(int)];
956 [data appendBytes:&count length:sizeof(int)];
958 [[self vimController] sendMessage:MouseDownMsgID data:data];
961 - (void)rightMouseDown:(NSEvent *)event
963 [self mouseDown:event];
966 - (void)otherMouseDown:(NSEvent *)event
968 [self mouseDown:event];
971 - (void)mouseUp:(NSEvent *)event
974 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
975 if (![self convertPoint:pt toRow:&row column:&col])
978 int flags = [event modifierFlags];
979 NSMutableData *data = [NSMutableData data];
981 [data appendBytes:&row length:sizeof(int)];
982 [data appendBytes:&col length:sizeof(int)];
983 [data appendBytes:&flags length:sizeof(int)];
985 [[self vimController] sendMessage:MouseUpMsgID data:data];
990 - (void)rightMouseUp:(NSEvent *)event
992 [self mouseUp:event];
995 - (void)otherMouseUp:(NSEvent *)event
997 [self mouseUp:event];
1000 - (void)mouseDragged:(NSEvent *)event
1002 int flags = [event modifierFlags];
1004 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
1005 if (![self convertPoint:pt toRow:&row column:&col])
1008 // Autoscrolling is done in dragTimerFired:
1009 if (!isAutoscrolling) {
1010 NSMutableData *data = [NSMutableData data];
1012 [data appendBytes:&row length:sizeof(int)];
1013 [data appendBytes:&col length:sizeof(int)];
1014 [data appendBytes:&flags length:sizeof(int)];
1016 [[self vimController] sendMessage:MouseDraggedMsgID data:data];
1020 dragRow = row; dragColumn = col; dragFlags = flags;
1022 [self startDragTimerWithInterval:.5];
1027 - (void)rightMouseDragged:(NSEvent *)event
1029 [self mouseDragged:event];
1032 - (void)otherMouseDragged:(NSEvent *)event
1034 [self mouseDragged:event];
1037 - (void)mouseMoved:(NSEvent *)event
1039 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
1042 // HACK! NSTextView has a nasty habit of resetting the cursor to the
1043 // default I-beam cursor at random moments. The only reliable way we know
1044 // of to work around this is to set the cursor each time the mouse moves.
1047 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
1049 if (![self convertPoint:pt toRow:&row column:&col])
1052 // HACK! It seems impossible to get the tracking rects set up before the
1053 // view is visible, which means that the first mouseEntered: or
1054 // mouseExited: events are never received. This forces us to check if the
1055 // mouseMoved: event really happened over the text.
1057 [ts getMaxRows:&rows columns:&cols];
1058 if (row >= 0 && row < rows && col >= 0 && col < cols) {
1059 NSMutableData *data = [NSMutableData data];
1061 [data appendBytes:&row length:sizeof(int)];
1062 [data appendBytes:&col length:sizeof(int)];
1064 [[self vimController] sendMessage:MouseMovedMsgID data:data];
1066 //NSLog(@"Moved %d %d\n", col, row);
1070 - (void)mouseEntered:(NSEvent *)event
1072 //NSLog(@"%s", _cmd);
1074 // NOTE: This event is received even when the window is not key; thus we
1075 // have to take care not to enable mouse moved events unless our window is
1077 if ([[self window] isKeyWindow]) {
1078 [[self window] setAcceptsMouseMovedEvents:YES];
1082 - (void)mouseExited:(NSEvent *)event
1084 //NSLog(@"%s", _cmd);
1086 [[self window] setAcceptsMouseMovedEvents:NO];
1088 // NOTE: This event is received even when the window is not key; if the
1089 // mouse shape is set when our window is not key, the hollow (unfocused)
1090 // cursor will become a block (focused) cursor.
1091 if ([[self window] isKeyWindow]) {
1093 NSMutableData *data = [NSMutableData data];
1094 [data appendBytes:&shape length:sizeof(int)];
1095 [[self vimController] sendMessage:SetMouseShapeMsgID data:data];
1099 - (void)setFrame:(NSRect)frame
1101 //NSLog(@"%s", _cmd);
1103 // When the frame changes we also need to update the tracking rect.
1104 [super setFrame:frame];
1105 [self removeTrackingRect:trackingRectTag];
1106 trackingRectTag = [self addTrackingRect:[self trackingRect] owner:self
1107 userData:NULL assumeInside:YES];
1110 - (void)viewDidMoveToWindow
1112 //NSLog(@"%s (window=%@)", _cmd, [self window]);
1114 // Set a tracking rect which covers the text.
1115 // NOTE: While the mouse cursor is in this rect the view will receive
1116 // 'mouseMoved:' events so that Vim can take care of updating the mouse
1118 if ([self window]) {
1119 [[self window] setAcceptsMouseMovedEvents:YES];
1120 trackingRectTag = [self addTrackingRect:[self trackingRect] owner:self
1121 userData:NULL assumeInside:YES];
1125 - (void)viewWillMoveToWindow:(NSWindow *)newWindow
1127 //NSLog(@"%s%@", _cmd, newWindow);
1129 // Remove tracking rect if view moves or is removed.
1130 if ([self window] && trackingRectTag) {
1131 [self removeTrackingRect:trackingRectTag];
1132 trackingRectTag = 0;
1136 - (NSMenu*)menuForEvent:(NSEvent *)event
1138 // HACK! Return nil to disable NSTextView's popup menus (Vim provides its
1139 // own). Called when user Ctrl-clicks in the view (this is already handled
1140 // in rightMouseDown:).
1144 - (NSArray *)acceptableDragTypes
1146 return [NSArray arrayWithObjects:NSFilenamesPboardType,
1147 NSStringPboardType, nil];
1150 - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
1152 NSPasteboard *pboard = [sender draggingPasteboard];
1154 if ([[pboard types] containsObject:NSStringPboardType]) {
1155 NSString *string = [pboard stringForType:NSStringPboardType];
1156 [[self vimController] dropString:string];
1158 } else if ([[pboard types] containsObject:NSFilenamesPboardType]) {
1159 NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
1160 [[self vimController] dropFiles:files forceOpen:NO];
1167 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
1169 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
1170 NSPasteboard *pboard = [sender draggingPasteboard];
1172 if ( [[pboard types] containsObject:NSFilenamesPboardType]
1173 && (sourceDragMask & NSDragOperationCopy) )
1174 return NSDragOperationCopy;
1175 if ( [[pboard types] containsObject:NSStringPboardType]
1176 && (sourceDragMask & NSDragOperationCopy) )
1177 return NSDragOperationCopy;
1179 return NSDragOperationNone;
1182 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
1184 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
1185 NSPasteboard *pboard = [sender draggingPasteboard];
1187 if ( [[pboard types] containsObject:NSFilenamesPboardType]
1188 && (sourceDragMask & NSDragOperationCopy) )
1189 return NSDragOperationCopy;
1190 if ( [[pboard types] containsObject:NSStringPboardType]
1191 && (sourceDragMask & NSDragOperationCopy) )
1192 return NSDragOperationCopy;
1194 return NSDragOperationNone;
1197 - (void)changeFont:(id)sender
1199 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
1202 NSFont *oldFont = [ts font];
1203 NSFont *newFont = [sender convertFont:oldFont];
1206 NSString *name = [newFont displayName];
1207 unsigned len = [name lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1209 NSMutableData *data = [NSMutableData data];
1210 float pointSize = [newFont pointSize];
1212 [data appendBytes:&pointSize length:sizeof(float)];
1214 ++len; // include NUL byte
1215 [data appendBytes:&len length:sizeof(unsigned)];
1216 [data appendBytes:[name UTF8String] length:len];
1218 [[self vimController] sendMessage:SetFontMsgID data:data];
1223 - (void)resetCursorRects
1225 // No need to set up cursor rects since Vim handles cursor changes.
1228 - (void)updateFontPanel
1230 // The font panel is updated whenever the font is set.
1235 // NOTE: The menu items cut/copy/paste/undo/redo/select all/... must be bound
1236 // to the same actions as in IB otherwise they will not work with dialogs. All
1237 // we do here is forward these actions to the Vim process.
1239 - (IBAction)cut:(id)sender
1241 [[self windowController] vimMenuItemAction:sender];
1244 - (IBAction)copy:(id)sender
1246 [[self windowController] vimMenuItemAction:sender];
1249 - (IBAction)paste:(id)sender
1251 [[self windowController] vimMenuItemAction:sender];
1254 - (IBAction)undo:(id)sender
1256 [[self windowController] vimMenuItemAction:sender];
1259 - (IBAction)redo:(id)sender
1261 [[self windowController] vimMenuItemAction:sender];
1264 - (IBAction)selectAll:(id)sender
1266 [[self windowController] vimMenuItemAction:sender];
1269 - (BOOL)validateMenuItem:(NSMenuItem *)item
1271 if ([item action] == @selector(cut:)
1272 || [item action] == @selector(copy:)
1273 || [item action] == @selector(paste:)
1274 || [item action] == @selector(undo:)
1275 || [item action] == @selector(redo:)
1276 || [item action] == @selector(selectAll:))
1286 @implementation MMTextView (Private)
1290 static NSCursor *customIbeamCursor = nil;
1292 if (!customIbeamCursor) {
1293 // Use a custom Ibeam cursor that has better contrast against dark
1295 // TODO: Is the hotspot ok?
1296 NSImage *ibeamImage = [NSImage imageNamed:@"ibeam"];
1298 NSSize size = [ibeamImage size];
1299 NSPoint hotSpot = { size.width*.5f, size.height*.5f };
1301 customIbeamCursor = [[NSCursor alloc]
1302 initWithImage:ibeamImage hotSpot:hotSpot];
1304 if (!customIbeamCursor) {
1305 NSLog(@"WARNING: Failed to load custom Ibeam cursor");
1306 customIbeamCursor = [NSCursor IBeamCursor];
1310 // This switch should match mshape_names[] in misc2.c.
1312 // TODO: Add missing cursor shapes.
1313 switch (mouseShape) {
1314 case 2: [customIbeamCursor set]; break;
1315 case 3: case 4: [[NSCursor resizeUpDownCursor] set]; break;
1316 case 5: case 6: [[NSCursor resizeLeftRightCursor] set]; break;
1317 case 9: [[NSCursor crosshairCursor] set]; break;
1318 case 10: [[NSCursor pointingHandCursor] set]; break;
1319 case 11: [[NSCursor openHandCursor] set]; break;
1321 [[NSCursor arrowCursor] set]; break;
1324 // Shape 1 indicates that the mouse cursor should be hidden.
1325 if (1 == mouseShape)
1326 [NSCursor setHiddenUntilMouseMoves:YES];
1329 - (BOOL)convertPoint:(NSPoint)point toRow:(int *)row column:(int *)column
1331 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
1332 NSSize cellSize = [ts cellSize];
1333 if (!(cellSize.width > 0 && cellSize.height > 0))
1335 NSPoint origin = [self textContainerOrigin];
1337 if (row) *row = floor((point.y-origin.y-1) / cellSize.height);
1338 if (column) *column = floor((point.x-origin.x-1) / cellSize.width);
1340 //NSLog(@"convertPoint:%@ toRow:%d column:%d", NSStringFromPoint(point),
1346 - (BOOL)convertRow:(int)row column:(int)column toPoint:(NSPoint *)point
1348 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
1349 NSSize cellSize = [ts cellSize];
1350 if (!(point && cellSize.width > 0 && cellSize.height > 0))
1353 *point = [self textContainerOrigin];
1354 point->x += column * cellSize.width;
1355 point->y += row * cellSize.height;
1360 - (BOOL)convertRow:(int)row column:(int)column numRows:(int)nr
1361 numColumns:(int)nc toRect:(NSRect *)rect
1363 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
1364 NSSize cellSize = [ts cellSize];
1365 if (!(rect && cellSize.width > 0 && cellSize.height > 0))
1368 rect->origin = [self textContainerOrigin];
1369 rect->origin.x += column * cellSize.width;
1370 rect->origin.y += row * cellSize.height;
1371 rect->size.width = cellSize.width * nc;
1372 rect->size.height = cellSize.height * nr;
1377 - (NSRect)trackingRect
1379 NSRect rect = [self frame];
1380 NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
1381 int left = [ud integerForKey:MMTextInsetLeftKey];
1382 int top = [ud integerForKey:MMTextInsetTopKey];
1383 int right = [ud integerForKey:MMTextInsetRightKey];
1384 int bot = [ud integerForKey:MMTextInsetBottomKey];
1386 rect.origin.x = left;
1387 rect.origin.y = top;
1388 rect.size.width -= left + right - 1;
1389 rect.size.height -= top + bot - 1;
1394 - (void)dispatchKeyEvent:(NSEvent *)event
1396 // Only handle the command if it came from a keyDown event
1397 if ([event type] != NSKeyDown)
1400 NSString *chars = [event characters];
1401 NSString *unmodchars = [event charactersIgnoringModifiers];
1402 unichar c = [chars characterAtIndex:0];
1403 unichar imc = [unmodchars characterAtIndex:0];
1405 const char *bytes = 0;
1406 int mods = [event modifierFlags];
1408 //NSLog(@"%s chars[0]=0x%x unmodchars[0]=0x%x (chars=%@ unmodchars=%@)",
1409 // _cmd, c, imc, chars, unmodchars);
1411 if (' ' == imc && 0xa0 != c) {
1412 // HACK! The AppKit turns <C-Space> into <C-@> which is not standard
1413 // Vim behaviour, so bypass this problem. (0xa0 is <M-Space>, which
1414 // should be passed on as is.)
1415 len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1416 bytes = [unmodchars UTF8String];
1417 } else if (imc == c && '2' == c) {
1418 // HACK! Translate Ctrl+2 to <C-@>.
1419 static char ctrl_at = 0;
1420 len = 1; bytes = &ctrl_at;
1421 } else if (imc == c && '6' == c) {
1422 // HACK! Translate Ctrl+6 to <C-^>.
1423 static char ctrl_hat = 0x1e;
1424 len = 1; bytes = &ctrl_hat;
1425 } else if (c == 0x19 && imc == 0x19) {
1426 // HACK! AppKit turns back tab into Ctrl-Y, so we need to handle it
1427 // separately (else Ctrl-Y doesn't work).
1428 static char tab = 0x9;
1429 len = 1; bytes = &tab; mods |= NSShiftKeyMask;
1431 len = [chars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1432 bytes = [chars UTF8String];
1435 [self sendKeyDown:bytes length:len modifiers:mods];
1438 - (MMWindowController *)windowController
1440 id windowController = [[self window] windowController];
1441 if ([windowController isKindOfClass:[MMWindowController class]])
1442 return (MMWindowController*)windowController;
1446 - (MMVimController *)vimController
1448 return [[self windowController] vimController];
1451 - (void)startDragTimerWithInterval:(NSTimeInterval)t
1453 [NSTimer scheduledTimerWithTimeInterval:t target:self
1454 selector:@selector(dragTimerFired:)
1455 userInfo:nil repeats:NO];
1458 - (void)dragTimerFired:(NSTimer *)timer
1460 // TODO: Autoscroll in horizontal direction?
1461 static unsigned tick = 1;
1462 MMTextStorage *ts = (MMTextStorage *)[self textStorage];
1464 isAutoscrolling = NO;
1466 if (isDragging && ts && (dragRow < 0 || dragRow >= [ts maxRows])) {
1467 // HACK! If the mouse cursor is outside the text area, then send a
1468 // dragged event. However, if row&col hasn't changed since the last
1469 // dragged event, Vim won't do anything (see gui_send_mouse_event()).
1470 // Thus we fiddle with the column to make sure something happens.
1471 int col = dragColumn + (dragRow < 0 ? -(tick % 2) : +(tick % 2));
1472 NSMutableData *data = [NSMutableData data];
1474 [data appendBytes:&dragRow length:sizeof(int)];
1475 [data appendBytes:&col length:sizeof(int)];
1476 [data appendBytes:&dragFlags length:sizeof(int)];
1478 [[self vimController] sendMessage:MouseDraggedMsgID data:data];
1480 isAutoscrolling = YES;
1484 // Compute timer interval depending on how far away the mouse cursor is
1485 // from the text view.
1486 NSRect rect = [self trackingRect];
1488 if (dragPoint.y < rect.origin.y) dy = rect.origin.y - dragPoint.y;
1489 else if (dragPoint.y > NSMaxY(rect)) dy = dragPoint.y - NSMaxY(rect);
1490 if (dy > MMDragAreaSize) dy = MMDragAreaSize;
1492 NSTimeInterval t = MMDragTimerMaxInterval -
1493 dy*(MMDragTimerMaxInterval-MMDragTimerMinInterval)/MMDragAreaSize;
1495 [self startDragTimerWithInterval:t];
1501 - (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags
1503 if (chars && len > 0) {
1504 NSMutableData *data = [NSMutableData data];
1506 [data appendBytes:&flags length:sizeof(int)];
1507 [data appendBytes:&len length:sizeof(int)];
1508 [data appendBytes:chars length:len];
1510 [self hideMouseCursor];
1512 //NSLog(@"%s len=%d chars=0x%x", _cmd, len, chars[0]);
1513 [[self vimController] sendMessage:KeyDownMsgID data:data];
1517 - (void)hideMouseCursor
1519 // Check 'mousehide' option
1520 id mh = [[[self vimController] vimState] objectForKey:@"p_mh"];
1521 if (mh && ![mh boolValue])
1522 [NSCursor setHiddenUntilMouseMoves:NO];
1524 [NSCursor setHiddenUntilMouseMoves:YES];
1527 - (void)drawInsertionPointAtRow:(int)row column:(int)col shape:(int)shape
1528 fraction:(int)percent color:(NSColor *)color
1530 //NSLog(@"drawInsertionPointAtRow:%d column:%d shape:%d color:%@",
1531 // row, col, shape, color);
1533 // This only stores where to draw the insertion point, the actual drawing
1534 // is done in drawRect:.
1535 shouldDrawInsertionPoint = YES;
1536 insertionPointRow = row;
1537 insertionPointColumn = col;
1538 insertionPointShape = shape;
1539 insertionPointFraction = percent;
1541 [self setInsertionPointColor:color];
1544 - (void)drawInvertedRectAtRow:(int)row column:(int)col numRows:(int)nrows
1545 numColumns:(int)ncols invert:(int)invert
1548 // The result should be inverted.
1549 int n = numInvertRects++;
1550 invertRects = reallocf(invertRects,
1551 numInvertRects*sizeof(NSRect));
1552 if (NULL != invertRects) {
1553 [self convertRow:row column:col numRows:nrows numColumns:ncols
1554 toRect:&invertRects[n]];
1555 [self setNeedsDisplayInRect:invertRects[n]];
1557 n = numInvertRects = 0;
1560 // The result should look normal; all we need to do is to mark
1561 // the rect for redrawing and Cocoa will redraw the text.
1563 [self convertRow:row column:col numRows:nrows numColumns:ncols
1565 [self setNeedsDisplayInRect:rect];
1569 @end // MMTextView (Private)