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.
11 #import "MMTextView.h"
12 #import "MMTextStorage.h"
13 #import "MMWindowController.h"
14 #import "MMVimController.h"
19 // The max/min drag timer interval in seconds
20 static NSTimeInterval MMDragTimerMaxInterval = .3f;
21 static NSTimeInterval MMDragTimerMinInterval = .01f;
23 // The number of pixels in which the drag timer interval changes
24 static float MMDragAreaSize = 73.0f;
29 @interface MMTextView (Private)
30 - (BOOL)convertPoint:(NSPoint)point toRow:(int *)row column:(int *)column;
31 - (BOOL)convertRow:(int)row column:(int)column toPoint:(NSPoint *)point;
32 - (NSRect)trackingRect;
33 - (void)dispatchKeyEvent:(NSEvent *)event;
34 - (MMVimController *)vimController;
35 - (void)startDragTimerWithInterval:(NSTimeInterval)t;
36 - (void)dragTimerFired:(NSTimer *)timer;
37 - (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags;
42 @implementation MMTextView
46 if (markedTextField) {
47 [[markedTextField window] autorelease];
48 [markedTextField release];
49 markedTextField = nil;
52 [lastMouseDownEvent release];
56 - (NSEvent *)lastMouseDownEvent
58 return lastMouseDownEvent;
61 - (BOOL)shouldDrawInsertionPoint
63 // NOTE: The insertion point is drawn manually in drawRect:. It would be
64 // nice to be able to use the insertion point related methods of
65 // NSTextView, but it seems impossible to get them to work properly (search
66 // the cocoabuilder archives).
70 - (void)setShouldDrawInsertionPoint:(BOOL)on
72 shouldDrawInsertionPoint = on;
75 - (void)drawInsertionPointAtRow:(int)row column:(int)col shape:(int)shape
76 fraction:(int)percent color:(NSColor *)color
78 //NSLog(@"drawInsertionPointAtRow:%d column:%d shape:%d color:%@",
79 // row, col, shape, color);
81 // This only stores where to draw the insertion point, the actual drawing
82 // is done in drawRect:.
83 shouldDrawInsertionPoint = YES;
84 insertionPointRow = row;
85 insertionPointColumn = col;
86 insertionPointShape = shape;
87 insertionPointFraction = percent;
89 [self setInsertionPointColor:color];
92 - (void)hideMarkedTextField
94 if (markedTextField) {
95 NSWindow *win = [markedTextField window];
97 [markedTextField setStringValue:@""];
101 - (void)drawRect:(NSRect)rect
103 [super drawRect:rect];
105 if (shouldDrawInsertionPoint) {
106 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
107 NSLayoutManager *lm = [self layoutManager];
108 NSTextContainer *tc = [self textContainer];
110 // Given (row,column), calculate the bounds of the glyph at that spot.
111 // We use the layout manager because this gives us exactly the size and
112 // location of the glyph so that we can match the insertion point to
114 unsigned charIdx = [ts characterIndexForRow:insertionPointRow
115 column:insertionPointColumn];
117 [lm glyphRangeForCharacterRange:NSMakeRange(charIdx,1)
118 actualCharacterRange:NULL];
119 NSRect ipRect = [lm boundingRectForGlyphRange:glyphRange
121 ipRect.origin.x += [self textContainerOrigin].x;
122 ipRect.origin.y += [self textContainerOrigin].y;
124 if (MMInsertionPointHorizontal == insertionPointShape) {
125 int frac = ([ts cellSize].height * insertionPointFraction + 99)/100;
126 ipRect.origin.y += ipRect.size.height - frac;
127 ipRect.size.height = frac;
128 } else if (MMInsertionPointVertical == insertionPointShape) {
129 int frac = ([ts cellSize].width* insertionPointFraction + 99)/100;
130 ipRect.size.width = frac;
133 [[self insertionPointColor] set];
134 if (MMInsertionPointHollow == insertionPointShape) {
140 // NOTE: We only draw the cursor once and rely on Vim to say when it
141 // should be drawn again.
142 shouldDrawInsertionPoint = NO;
144 //NSLog(@"%s draw insertion point %@ shape=%d color=%@", _cmd,
145 // NSStringFromRect(ipRect), insertionPointShape,
146 // [self insertionPointColor]);
150 - (void)keyDown:(NSEvent *)event
152 //NSLog(@"%s %@", _cmd, event);
153 // HACK! If a modifier is held, don't pass the event along to
154 // interpretKeyEvents: since some keys are bound to multiple commands which
155 // means doCommandBySelector: is called several times.
157 // TODO: Figure out a way to disable Cocoa key bindings entirely, without
158 // affecting input management.
160 if ([event modifierFlags] & NSControlKeyMask)
161 [self dispatchKeyEvent:event];
163 [super keyDown:event];
166 - (void)insertText:(id)string
168 //NSLog(@"%s %@", _cmd, string);
169 // NOTE! This method is called for normal key presses but also for
170 // Option-key presses --- even when Ctrl is held as well as Option. When
171 // Ctrl is held, the AppKit translates the character to a Ctrl+key stroke,
172 // so 'string' need not be a printable character! In this case it still
173 // works to pass 'string' on to Vim as a printable character (since
174 // modifiers are already included and should not be added to the input
175 // buffer using CSI, K_MODIFIER).
177 [self hideMarkedTextField];
179 NSEvent *event = [NSApp currentEvent];
181 // HACK! In order to be able to bind to <S-Space> etc. we have to watch
182 // for when space was pressed.
183 if ([event type] == NSKeyDown
184 && [[event charactersIgnoringModifiers] length] > 0
185 && [[event charactersIgnoringModifiers] characterAtIndex:0] == ' '
186 && [event modifierFlags]
187 & (NSShiftKeyMask|NSControlKeyMask|NSAlternateKeyMask))
189 [self dispatchKeyEvent:event];
193 // TODO: Support 'mousehide' (check p_mh)
194 [NSCursor setHiddenUntilMouseMoves:YES];
196 [[self vimController] sendMessage:InsertTextMsgID
197 data:[string dataUsingEncoding:NSUTF8StringEncoding]
202 - (void)doCommandBySelector:(SEL)selector
204 //NSLog(@"%s %@", _cmd, NSStringFromSelector(selector));
205 // By ignoring the selector we effectively disable the key binding
206 // mechanism of Cocoa. Hopefully this is what the user will expect
207 // (pressing Ctrl+P would otherwise result in moveUp: instead of previous
210 // We usually end up here if the user pressed Ctrl+key (but not
213 NSEvent *event = [NSApp currentEvent];
215 if (selector == @selector(cancelOperation:)
216 || selector == @selector(insertNewline:)) {
217 // HACK! If there was marked text which got abandoned as a result of
218 // hitting escape or enter, then 'insertText:' is called with the
219 // abandoned text but '[event characters]' includes the abandoned text
220 // as well. Since 'dispatchKeyEvent:' looks at '[event characters]' we
221 // must intercept these keys here or the abandonded text gets inserted
223 NSString *key = [event charactersIgnoringModifiers];
224 const char *chars = [key UTF8String];
225 int len = [key lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
227 if (0x3 == chars[0]) {
228 // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
229 // handle it separately (else Ctrl-C doesn't work).
230 static char keypadEnter[2] = { 'K', 'A' };
231 len = 2; chars = keypadEnter;
234 [self sendKeyDown:chars length:len modifiers:[event modifierFlags]];
236 [self dispatchKeyEvent:event];
241 // Confused note to self: Why did I implement this in the first place? Will
242 // something break if I don't? Input methods that use arrow keys do not work
243 // properly with this implementation, so it is disabled for now.
244 - (BOOL)performKeyEquivalent:(NSEvent *)event
246 NSLog(@"%s %@", _cmd, event);
247 // Called for Cmd+key keystrokes, function keys, arrow keys, page
248 // up/down, home, end.
250 if ([event type] != NSKeyDown)
253 // HACK! Let the main menu try to handle any key down event, before
254 // passing it on to vim, otherwise key equivalents for menus will
255 // effectively be disabled.
256 if ([[NSApp mainMenu] performKeyEquivalent:event])
259 // HACK! KeyCode 50 represent the key which switches between windows
260 // within an application (like Cmd+Tab is used to switch between
261 // applications). Return NO here, else the window switching does not work.
263 // Will this hack work for all languages / keyboard layouts?
264 if ([event keyCode] == 50)
267 //NSLog(@"%s%@", _cmd, event);
269 NSString *string = [event charactersIgnoringModifiers];
270 int flags = [event modifierFlags];
271 int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
272 NSMutableData *data = [NSMutableData data];
274 [data appendBytes:&flags length:sizeof(int)];
275 [data appendBytes:&len length:sizeof(int)];
276 [data appendBytes:[string UTF8String] length:len];
278 [[self vimController] sendMessage:CmdKeyMsgID data:data wait:NO];
284 - (BOOL)hasMarkedText
286 //NSLog(@"%s", _cmd);
287 return markedTextField && [[markedTextField stringValue] length] > 0;
290 - (NSRange)markedRange
292 //NSLog(@"%s", _cmd);
293 // HACK! If a valid range is returned, then NSTextView changes the
294 // background color of the returned range. Since marked text is displayed
295 // in a separate popup window this behaviour is not wanted. By setting the
296 // location of the returned range to NSNotFound NSTextView does nothing.
297 // This hack is continued in 'firstRectForCharacterRange:'.
298 return NSMakeRange(NSNotFound, 0);
301 - (void)setMarkedText:(id)text selectedRange:(NSRange)range
303 //NSLog(@"setMarkedText:'%@' selectedRange:%@", text,
304 // NSStringFromRange(range));
306 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
309 if (!markedTextField) {
310 // Create a text field and put it inside a floating panel. This field
311 // is used to display marked text.
312 NSSize cellSize = [ts cellSize];
313 NSRect cellRect = { 0, 0, cellSize.width, cellSize.height };
315 markedTextField = [[NSTextField alloc] initWithFrame:cellRect];
316 [markedTextField setEditable:NO];
317 [markedTextField setSelectable:NO];
318 [markedTextField setBezeled:NO];
319 [markedTextField setBordered:YES];
321 NSPanel *panel = [[NSPanel alloc]
322 initWithContentRect:cellRect
323 styleMask:NSBorderlessWindowMask|NSUtilityWindowMask
324 backing:NSBackingStoreBuffered
327 //[panel setHidesOnDeactivate:NO];
328 [panel setFloatingPanel:YES];
329 [panel setBecomesKeyOnlyIfNeeded:YES];
330 [panel setContentView:markedTextField];
333 if (text && [text length] > 0) {
334 [markedTextField setFont:[ts font]];
335 if ([text isKindOfClass:[NSAttributedString class]])
336 [markedTextField setAttributedStringValue:text];
338 [markedTextField setStringValue:text];
340 [markedTextField sizeToFit];
341 NSSize size = [markedTextField frame].size;
343 // Convert coordinates (row,col) -> view -> window base -> screen
345 if (![self convertRow:insertionPointRow+1 column:insertionPointColumn
348 origin = [self convertPoint:origin toView:nil];
349 origin = [[self window] convertBaseToScreen:origin];
351 NSWindow *win = [markedTextField window];
352 [win setContentSize:size];
353 [win setFrameOrigin:origin];
354 [win orderFront:nil];
356 [self hideMarkedTextField];
362 //NSLog(@"%s", _cmd);
363 [self hideMarkedTextField];
366 - (NSRect)firstRectForCharacterRange:(NSRange)range
368 //NSLog(@"%s%@", _cmd, NSStringFromRange(range));
370 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
371 NSLayoutManager *lm = [self layoutManager];
372 NSTextContainer *tc = [self textContainer];
374 // HACK! Since we always return marked text to have location NSNotFound,
375 // this method will be called with 'range.location == NSNotFound' whenever
376 // the input manager tries to position a popup window near the insertion
377 // point. For this reason we compute where the insertion point is and
378 // return a rect which contains it.
379 if (!(ts && lm && tc) || NSNotFound != range.location)
380 return [super firstRectForCharacterRange:range];
382 unsigned charIdx = [ts characterIndexForRow:insertionPointRow
383 column:insertionPointColumn];
385 [lm glyphRangeForCharacterRange:NSMakeRange(charIdx,1)
386 actualCharacterRange:NULL];
387 NSRect ipRect = [lm boundingRectForGlyphRange:glyphRange
389 ipRect.origin.x += [self textContainerOrigin].x;
390 ipRect.origin.y += [self textContainerOrigin].y + [ts cellSize].height;
392 ipRect.origin = [self convertPoint:ipRect.origin toView:nil];
393 ipRect.origin = [[self window] convertBaseToScreen:ipRect.origin];
398 - (void)scrollWheel:(NSEvent *)event
400 if ([event deltaY] == 0)
404 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
405 if (![self convertPoint:pt toRow:&row column:&col])
408 int flags = [event modifierFlags];
409 float dy = [event deltaY];
410 NSMutableData *data = [NSMutableData data];
412 [data appendBytes:&row length:sizeof(int)];
413 [data appendBytes:&col length:sizeof(int)];
414 [data appendBytes:&flags length:sizeof(int)];
415 [data appendBytes:&dy length:sizeof(float)];
417 [[self vimController] sendMessage:ScrollWheelMsgID data:data wait:NO];
420 - (void)mouseDown:(NSEvent *)event
423 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
424 if (![self convertPoint:pt toRow:&row column:&col])
427 lastMouseDownEvent = [event copy];
429 int button = [event buttonNumber];
430 int flags = [event modifierFlags];
431 int count = [event clickCount];
432 NSMutableData *data = [NSMutableData data];
434 // If desired, intepret Ctrl-Click as a right mouse click.
435 if ([[NSUserDefaults standardUserDefaults]
436 boolForKey:MMTranslateCtrlClickKey]
437 && button == 0 && flags & NSControlKeyMask) {
439 flags &= ~NSControlKeyMask;
442 [data appendBytes:&row length:sizeof(int)];
443 [data appendBytes:&col length:sizeof(int)];
444 [data appendBytes:&button length:sizeof(int)];
445 [data appendBytes:&flags length:sizeof(int)];
446 [data appendBytes:&count length:sizeof(int)];
448 [[self vimController] sendMessage:MouseDownMsgID data:data wait:NO];
451 - (void)rightMouseDown:(NSEvent *)event
453 [self mouseDown:event];
456 - (void)otherMouseDown:(NSEvent *)event
458 [self mouseDown:event];
461 - (void)mouseUp:(NSEvent *)event
464 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
465 if (![self convertPoint:pt toRow:&row column:&col])
468 int flags = [event modifierFlags];
469 NSMutableData *data = [NSMutableData data];
471 [data appendBytes:&row length:sizeof(int)];
472 [data appendBytes:&col length:sizeof(int)];
473 [data appendBytes:&flags length:sizeof(int)];
475 [[self vimController] sendMessage:MouseUpMsgID data:data wait:NO];
480 - (void)rightMouseUp:(NSEvent *)event
482 [self mouseUp:event];
485 - (void)otherMouseUp:(NSEvent *)event
487 [self mouseUp:event];
490 - (void)mouseDragged:(NSEvent *)event
492 int flags = [event modifierFlags];
494 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
495 if (![self convertPoint:pt toRow:&row column:&col])
498 // Autoscrolling is done in dragTimerFired:
499 if (!isAutoscrolling) {
500 NSMutableData *data = [NSMutableData data];
502 [data appendBytes:&row length:sizeof(int)];
503 [data appendBytes:&col length:sizeof(int)];
504 [data appendBytes:&flags length:sizeof(int)];
506 [[self vimController] sendMessage:MouseDraggedMsgID data:data wait:NO];
510 dragRow = row; dragColumn = col; dragFlags = flags;
512 [self startDragTimerWithInterval:.5];
517 - (void)rightMouseDragged:(NSEvent *)event
519 [self mouseDragged:event];
522 - (void)otherMouseDragged:(NSEvent *)event
524 [self mouseDragged:event];
527 - (void)mouseMoved:(NSEvent *)event
529 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
532 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
534 if (![self convertPoint:pt toRow:&row column:&col])
537 // HACK! It seems impossible to get the tracking rects set up before the
538 // view is visible, which means that the first mouseEntered: or
539 // mouseExited: events are never received. This forces us to check if the
540 // mouseMoved: event really happened over the text.
542 [ts getMaxRows:&rows columns:&cols];
543 if (row >= 0 && row < rows && col >= 0 && col < cols) {
544 NSMutableData *data = [NSMutableData data];
546 [data appendBytes:&row length:sizeof(int)];
547 [data appendBytes:&col length:sizeof(int)];
549 [[self vimController] sendMessage:MouseMovedMsgID data:data wait:NO];
553 - (void)mouseEntered:(NSEvent *)event
555 //NSLog(@"%s", _cmd);
557 // NOTE: This event is received even when the window is not key; thus we
558 // have to take care not to enable mouse moved events unless our window is
560 if ([[self window] isKeyWindow])
561 [[self window] setAcceptsMouseMovedEvents:YES];
564 - (void)mouseExited:(NSEvent *)event
566 //NSLog(@"%s", _cmd);
568 [[self window] setAcceptsMouseMovedEvents:NO];
570 // NOTE: This event is received even when the window is not key; if the
571 // mouse shape is set when our window is not key, the hollow (unfocused)
572 // cursor will become a block (focused) cursor.
573 if ([[self window] isKeyWindow]) {
575 NSMutableData *data = [NSMutableData data];
576 [data appendBytes:&shape length:sizeof(int)];
577 [[self vimController] sendMessage:SetMouseShapeMsgID data:data wait:NO];
581 - (void)setFrame:(NSRect)frame
583 //NSLog(@"%s", _cmd);
585 // When the frame changes we also need to update the tracking rect.
586 [super setFrame:frame];
587 [self removeTrackingRect:trackingRectTag];
588 trackingRectTag = [self addTrackingRect:[self trackingRect] owner:self
589 userData:NULL assumeInside:YES];
592 - (void)viewDidMoveToWindow
594 //NSLog(@"%s (window=%@)", _cmd, [self window]);
596 // Set a tracking rect which covers the text.
597 // NOTE: While the mouse cursor is in this rect the view will receive
598 // 'mouseMoved:' events so that Vim can take care of updating the mouse
601 [[self window] setAcceptsMouseMovedEvents:YES];
602 trackingRectTag = [self addTrackingRect:[self trackingRect] owner:self
603 userData:NULL assumeInside:YES];
607 - (void)viewWillMoveToWindow:(NSWindow *)newWindow
609 //NSLog(@"%s%@", _cmd, newWindow);
611 // Remove tracking rect if view moves or is removed.
612 if ([self window] && trackingRectTag) {
613 [self removeTrackingRect:trackingRectTag];
618 - (NSMenu*)menuForEvent:(NSEvent *)event
620 // HACK! Return nil to disable NSTextView's popup menus (Vim provides its
621 // own). Called when user Ctrl-clicks in the view (this is already handled
622 // in rightMouseDown:).
626 - (NSArray *)acceptableDragTypes
628 return [NSArray arrayWithObjects:NSFilenamesPboardType,
629 NSStringPboardType, nil];
632 - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
634 NSPasteboard *pboard = [sender draggingPasteboard];
636 if ([[pboard types] containsObject:NSStringPboardType]) {
637 NSString *string = [pboard stringForType:NSStringPboardType];
638 [[self vimController] dropString:string];
640 } else if ([[pboard types] containsObject:NSFilenamesPboardType]) {
641 NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
642 [[self vimController] dropFiles:files];
649 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
651 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
652 NSPasteboard *pboard = [sender draggingPasteboard];
654 if ( [[pboard types] containsObject:NSFilenamesPboardType]
655 && (sourceDragMask & NSDragOperationCopy) )
656 return NSDragOperationCopy;
657 if ( [[pboard types] containsObject:NSStringPboardType]
658 && (sourceDragMask & NSDragOperationCopy) )
659 return NSDragOperationCopy;
661 return NSDragOperationNone;
664 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
666 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
667 NSPasteboard *pboard = [sender draggingPasteboard];
669 if ( [[pboard types] containsObject:NSFilenamesPboardType]
670 && (sourceDragMask & NSDragOperationCopy) )
671 return NSDragOperationCopy;
672 if ( [[pboard types] containsObject:NSStringPboardType]
673 && (sourceDragMask & NSDragOperationCopy) )
674 return NSDragOperationCopy;
676 return NSDragOperationNone;
679 - (void)changeFont:(id)sender
681 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
684 NSFont *oldFont = [ts font];
685 NSFont *newFont = [sender convertFont:oldFont];
688 NSString *name = [newFont displayName];
689 unsigned len = [name lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
691 NSMutableData *data = [NSMutableData data];
692 float pointSize = [newFont pointSize];
694 [data appendBytes:&pointSize length:sizeof(float)];
696 ++len; // include NUL byte
697 [data appendBytes:&len length:sizeof(unsigned)];
698 [data appendBytes:[name UTF8String] length:len];
700 [[self vimController] sendMessage:SetFontMsgID data:data wait:NO];
705 - (void)resetCursorRects
707 // No need to set up cursor rects since Vim handles cursor changes.
710 - (void)updateFontPanel
712 // The font panel is updated whenever the font is set.
720 @implementation MMTextView (Private)
722 - (BOOL)convertPoint:(NSPoint)point toRow:(int *)row column:(int *)column
725 NSLayoutManager *lm = [self layoutManager];
726 NSTextContainer *tc = [self textContainer];
727 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
729 if (!(lm && tc && ts))
732 unsigned glyphIdx = [lm glyphIndexForPoint:point inTextContainer:tc];
733 unsigned charIdx = [lm characterIndexForGlyphAtIndex:glyphIdx];
735 int mod = [ts maxColumns] + 1;
737 if (row) *row = (int)(charIdx / mod);
738 if (column) *column = (int)(charIdx % mod);
740 NSLog(@"convertPoint:%@ toRow:%d column:%d", NSStringFromPoint(point),
745 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
746 NSSize cellSize = [ts cellSize];
747 if (!(cellSize.width > 0 && cellSize.height > 0))
749 NSPoint origin = [self textContainerOrigin];
751 if (row) *row = floor((point.y-origin.y-1) / cellSize.height);
752 if (column) *column = floor((point.x-origin.x-1) / cellSize.width);
754 //NSLog(@"convertPoint:%@ toRow:%d column:%d", NSStringFromPoint(point),
761 - (BOOL)convertRow:(int)row column:(int)column toPoint:(NSPoint *)point
763 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
764 NSSize cellSize = [ts cellSize];
765 if (!(point && cellSize.width > 0 && cellSize.height > 0))
768 *point = [self textContainerOrigin];
769 point->x += column * cellSize.width;
770 point->y += row * cellSize.height;
775 - (NSRect)trackingRect
777 NSRect rect = [self frame];
778 NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
779 int left = [ud integerForKey:MMTextInsetLeftKey];
780 int top = [ud integerForKey:MMTextInsetTopKey];
781 int right = [ud integerForKey:MMTextInsetRightKey];
782 int bot = [ud integerForKey:MMTextInsetBottomKey];
784 rect.origin.x = left;
786 rect.size.width -= left + right - 1;
787 rect.size.height -= top + bot - 1;
792 - (void)dispatchKeyEvent:(NSEvent *)event
794 // Only handle the command if it came from a keyDown event
795 if ([event type] != NSKeyDown)
798 NSString *chars = [event characters];
799 NSString *unmodchars = [event charactersIgnoringModifiers];
800 unichar c = [chars characterAtIndex:0];
801 unichar imc = [unmodchars characterAtIndex:0];
803 const char *bytes = 0;
805 //NSLog(@"%s chars[0]=0x%x unmodchars[0]=0x%x (chars=%@ unmodchars=%@)",
806 // _cmd, c, imc, chars, unmodchars);
808 if (' ' == imc && 0xa0 != c) {
809 // HACK! The AppKit turns <C-Space> into <C-@> which is not standard
810 // Vim behaviour, so bypass this problem. (0xa0 is <M-Space>, which
811 // should be passed on as is.)
812 len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
813 bytes = [unmodchars UTF8String];
814 } else if (imc == c && '2' == c) {
815 // HACK! Translate Ctrl+2 to <C-@>.
816 static char ctrl_at = 0;
817 len = 1; bytes = &ctrl_at;
818 } else if (imc == c && '6' == c) {
819 // HACK! Translate Ctrl+6 to <C-^>.
820 static char ctrl_hat = 0x1e;
821 len = 1; bytes = &ctrl_hat;
822 } else if (c == 0x19 && imc == 0x19) {
823 // HACK! AppKit turns back tab into Ctrl-Y, so we need to handle it
824 // separately (else Ctrl-Y doesn't work).
825 static char back_tab[2] = { 'k', 'B' };
826 len = 2; bytes = back_tab;
828 len = [chars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
829 bytes = [chars UTF8String];
832 [self sendKeyDown:bytes length:len modifiers:[event modifierFlags]];
835 - (MMVimController *)vimController
837 id windowController = [[self window] windowController];
839 // TODO: Make sure 'windowController' is a MMWindowController before type
841 return [(MMWindowController*)windowController vimController];
844 - (void)startDragTimerWithInterval:(NSTimeInterval)t
846 [NSTimer scheduledTimerWithTimeInterval:t target:self
847 selector:@selector(dragTimerFired:)
848 userInfo:nil repeats:NO];
851 - (void)dragTimerFired:(NSTimer *)timer
853 // TODO: Autoscroll in horizontal direction?
854 static unsigned tick = 1;
855 MMTextStorage *ts = (MMTextStorage *)[self textStorage];
857 isAutoscrolling = NO;
859 if (isDragging && ts && (dragRow < 0 || dragRow >= [ts maxRows])) {
860 // HACK! If the mouse cursor is outside the text area, then send a
861 // dragged event. However, if row&col hasn't changed since the last
862 // dragged event, Vim won't do anything (see gui_send_mouse_event()).
863 // Thus we fiddle with the column to make sure something happens.
864 int col = dragColumn + (dragRow < 0 ? -(tick % 2) : +(tick % 2));
865 NSMutableData *data = [NSMutableData data];
867 [data appendBytes:&dragRow length:sizeof(int)];
868 [data appendBytes:&col length:sizeof(int)];
869 [data appendBytes:&dragFlags length:sizeof(int)];
871 [[self vimController] sendMessage:MouseDraggedMsgID data:data wait:NO];
873 isAutoscrolling = YES;
877 // Compute timer interval depending on how far away the mouse cursor is
878 // from the text view.
879 NSRect rect = [self trackingRect];
881 if (dragPoint.y < rect.origin.y) dy = rect.origin.y - dragPoint.y;
882 else if (dragPoint.y > NSMaxY(rect)) dy = dragPoint.y - NSMaxY(rect);
883 if (dy > MMDragAreaSize) dy = MMDragAreaSize;
885 NSTimeInterval t = MMDragTimerMaxInterval -
886 dy*(MMDragTimerMaxInterval-MMDragTimerMinInterval)/MMDragAreaSize;
888 [self startDragTimerWithInterval:t];
894 - (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags
896 if (chars && len > 0) {
897 NSMutableData *data = [NSMutableData data];
899 [data appendBytes:&flags length:sizeof(int)];
900 [data appendBytes:&len length:sizeof(int)];
901 [data appendBytes:chars length:len];
903 // TODO: Support 'mousehide' (check p_mh)
904 [NSCursor setHiddenUntilMouseMoves:YES];
906 //NSLog(@"%s len=%d chars=0x%x", _cmd, len, chars[0]);
907 [[self vimController] sendMessage:KeyDownMsgID data:data wait:NO];
911 @end // MMTextView (Private)