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;
26 static char MMKeypadEnter[2] = { 'K', 'A' };
27 static NSString *MMKeypadEnterString = @"KA";
31 @interface MMTextView (Private)
32 - (BOOL)convertPoint:(NSPoint)point toRow:(int *)row column:(int *)column;
33 - (BOOL)convertRow:(int)row column:(int)column toPoint:(NSPoint *)point;
34 - (NSRect)trackingRect;
35 - (void)dispatchKeyEvent:(NSEvent *)event;
36 - (MMVimController *)vimController;
37 - (void)startDragTimerWithInterval:(NSTimeInterval)t;
38 - (void)dragTimerFired:(NSTimer *)timer;
39 - (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags;
44 @implementation MMTextView
48 if (markedTextField) {
49 [[markedTextField window] autorelease];
50 [markedTextField release];
51 markedTextField = nil;
54 [lastMouseDownEvent release];
58 - (NSEvent *)lastMouseDownEvent
60 return lastMouseDownEvent;
63 - (BOOL)shouldDrawInsertionPoint
65 // NOTE: The insertion point is drawn manually in drawRect:. It would be
66 // nice to be able to use the insertion point related methods of
67 // NSTextView, but it seems impossible to get them to work properly (search
68 // the cocoabuilder archives).
72 - (void)setShouldDrawInsertionPoint:(BOOL)on
74 shouldDrawInsertionPoint = on;
77 - (void)drawInsertionPointAtRow:(int)row column:(int)col shape:(int)shape
78 fraction:(int)percent color:(NSColor *)color
80 //NSLog(@"drawInsertionPointAtRow:%d column:%d shape:%d color:%@",
81 // row, col, shape, color);
83 // This only stores where to draw the insertion point, the actual drawing
84 // is done in drawRect:.
85 shouldDrawInsertionPoint = YES;
86 insertionPointRow = row;
87 insertionPointColumn = col;
88 insertionPointShape = shape;
89 insertionPointFraction = percent;
91 [self setInsertionPointColor:color];
94 - (void)hideMarkedTextField
96 if (markedTextField) {
97 NSWindow *win = [markedTextField window];
99 [markedTextField setStringValue:@""];
103 - (void)drawRect:(NSRect)rect
105 [super drawRect:rect];
107 if (shouldDrawInsertionPoint) {
108 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
109 NSLayoutManager *lm = [self layoutManager];
110 NSTextContainer *tc = [self textContainer];
112 // Given (row,column), calculate the bounds of the glyph at that spot.
113 // We use the layout manager because this gives us exactly the size and
114 // location of the glyph so that we can match the insertion point to
116 unsigned charIdx = [ts characterIndexForRow:insertionPointRow
117 column:insertionPointColumn];
119 [lm glyphRangeForCharacterRange:NSMakeRange(charIdx,1)
120 actualCharacterRange:NULL];
121 NSRect ipRect = [lm boundingRectForGlyphRange:glyphRange
123 ipRect.origin.x += [self textContainerOrigin].x;
124 ipRect.origin.y += [self textContainerOrigin].y;
126 if (MMInsertionPointHorizontal == insertionPointShape) {
127 int frac = ([ts cellSize].height * insertionPointFraction + 99)/100;
128 ipRect.origin.y += ipRect.size.height - frac;
129 ipRect.size.height = frac;
130 } else if (MMInsertionPointVertical == insertionPointShape) {
131 int frac = ([ts cellSize].width* insertionPointFraction + 99)/100;
132 ipRect.size.width = frac;
135 [[self insertionPointColor] set];
136 if (MMInsertionPointHollow == insertionPointShape) {
142 // NOTE: We only draw the cursor once and rely on Vim to say when it
143 // should be drawn again.
144 shouldDrawInsertionPoint = NO;
146 //NSLog(@"%s draw insertion point %@ shape=%d color=%@", _cmd,
147 // NSStringFromRect(ipRect), insertionPointShape,
148 // [self insertionPointColor]);
152 - (void)keyDown:(NSEvent *)event
154 //NSLog(@"%s %@", _cmd, event);
155 // HACK! If a modifier is held, don't pass the event along to
156 // interpretKeyEvents: since some keys are bound to multiple commands which
157 // means doCommandBySelector: is called several times.
159 // TODO: Figure out a way to disable Cocoa key bindings entirely, without
160 // affecting input management.
162 if ([event modifierFlags] & NSControlKeyMask)
163 [self dispatchKeyEvent:event];
165 [super keyDown:event];
168 - (void)insertText:(id)string
170 //NSLog(@"%s %@", _cmd, string);
171 // NOTE! This method is called for normal key presses but also for
172 // Option-key presses --- even when Ctrl is held as well as Option. When
173 // Ctrl is held, the AppKit translates the character to a Ctrl+key stroke,
174 // so 'string' need not be a printable character! In this case it still
175 // works to pass 'string' on to Vim as a printable character (since
176 // modifiers are already included and should not be added to the input
177 // buffer using CSI, K_MODIFIER).
179 [self hideMarkedTextField];
181 NSEvent *event = [NSApp currentEvent];
183 // HACK! In order to be able to bind to <S-Space>, <S-M-Tab>, etc. we have
184 // to watch for them here.
185 if ([event type] == NSKeyDown
186 && [[event charactersIgnoringModifiers] length] > 0
187 && [event modifierFlags]
188 & (NSShiftKeyMask|NSControlKeyMask|NSAlternateKeyMask)) {
189 unichar c = [[event charactersIgnoringModifiers] characterAtIndex:0];
191 // <S-M-Tab> translates to 0x19
192 if (' ' == c || 0x19 == c) {
193 [self dispatchKeyEvent:event];
198 // TODO: Support 'mousehide' (check p_mh)
199 [NSCursor setHiddenUntilMouseMoves:YES];
201 // NOTE: 'string' is either an NSString or an NSAttributedString. Since we
202 // do not support attributes, simply pass the corresponding NSString in the
204 if ([string isKindOfClass:[NSAttributedString class]])
205 string = [string string];
207 [[self vimController] sendMessage:InsertTextMsgID
208 data:[string dataUsingEncoding:NSUTF8StringEncoding]];
212 - (void)doCommandBySelector:(SEL)selector
214 //NSLog(@"%s %@", _cmd, NSStringFromSelector(selector));
215 // By ignoring the selector we effectively disable the key binding
216 // mechanism of Cocoa. Hopefully this is what the user will expect
217 // (pressing Ctrl+P would otherwise result in moveUp: instead of previous
220 // We usually end up here if the user pressed Ctrl+key (but not
223 NSEvent *event = [NSApp currentEvent];
225 if (selector == @selector(cancelOperation:)
226 || selector == @selector(insertNewline:)) {
227 // HACK! If there was marked text which got abandoned as a result of
228 // hitting escape or enter, then 'insertText:' is called with the
229 // abandoned text but '[event characters]' includes the abandoned text
230 // as well. Since 'dispatchKeyEvent:' looks at '[event characters]' we
231 // must intercept these keys here or the abandonded text gets inserted
233 NSString *key = [event charactersIgnoringModifiers];
234 const char *chars = [key UTF8String];
235 int len = [key lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
237 if (0x3 == chars[0]) {
238 // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
239 // handle it separately (else Ctrl-C doesn't work).
240 len = sizeof(MMKeypadEnter)/sizeof(MMKeypadEnter[0]);
241 chars = MMKeypadEnter;
244 [self sendKeyDown:chars length:len modifiers:[event modifierFlags]];
246 [self dispatchKeyEvent:event];
250 - (BOOL)performKeyEquivalent:(NSEvent *)event
252 //NSLog(@"%s %@", _cmd, event);
253 // Called for Cmd+key keystrokes, function keys, arrow keys, page
254 // up/down, home, end.
256 // NOTE: This message cannot be ignored since Cmd+letter keys never are
257 // passed to keyDown:. It seems as if the main menu consumes Cmd-key
258 // strokes, unless the key is a function key.
260 // NOTE: If the event that triggered this method represents a function key
261 // down then we do nothing, otherwise the input method never gets the key
262 // stroke (some input methods use e.g. arrow keys). The function key down
263 // event will still reach Vim though (via keyDown:). The exceptions to
264 // this rule are: PageUp/PageDown (keycode 116/121).
265 int flags = [event modifierFlags];
266 if ([event type] != NSKeyDown || flags & NSFunctionKeyMask
267 && !(116 == [event keyCode] || 121 == [event keyCode]))
270 // HACK! Let the main menu try to handle any key down event, before
271 // passing it on to vim, otherwise key equivalents for menus will
272 // effectively be disabled.
273 if ([[NSApp mainMenu] performKeyEquivalent:event])
276 // HACK! KeyCode 50 represent the key which switches between windows
277 // within an application (like Cmd+Tab is used to switch between
278 // applications). Return NO here, else the window switching does not work.
280 // Will this hack work for all languages / keyboard layouts?
281 if ([event keyCode] == 50)
284 //NSLog(@"%s%@", _cmd, event);
286 NSString *chars = [event characters];
287 NSString *unmodchars = [event charactersIgnoringModifiers];
288 int len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
289 NSMutableData *data = [NSMutableData data];
294 // If 'chars' and 'unmodchars' differs when shift flag is present, then we
295 // can clear the shift flag as it is already included in 'unmodchars'.
296 // Failing to clear the shift flag means <D-Bar> turns into <S-D-Bar> (on
297 // an English keyboard).
298 if (flags & NSShiftKeyMask && ![chars isEqual:unmodchars])
299 flags &= ~NSShiftKeyMask;
301 if (0x3 == [unmodchars characterAtIndex:0]) {
302 // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
303 // handle it separately (else Cmd-enter turns into Ctrl-C).
304 unmodchars = MMKeypadEnterString;
305 len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
308 [data appendBytes:&flags length:sizeof(int)];
309 [data appendBytes:&len length:sizeof(int)];
310 [data appendBytes:[unmodchars UTF8String] length:len];
312 [[self vimController] sendMessage:CmdKeyMsgID data:data];
317 - (BOOL)hasMarkedText
319 //NSLog(@"%s", _cmd);
320 return markedTextField && [[markedTextField stringValue] length] > 0;
323 - (NSRange)markedRange
325 //NSLog(@"%s", _cmd);
326 // HACK! If a valid range is returned, then NSTextView changes the
327 // background color of the returned range. Since marked text is displayed
328 // in a separate popup window this behaviour is not wanted. By setting the
329 // location of the returned range to NSNotFound NSTextView does nothing.
330 // This hack is continued in 'firstRectForCharacterRange:'.
331 return NSMakeRange(NSNotFound, 0);
334 - (void)setMarkedText:(id)text selectedRange:(NSRange)range
336 //NSLog(@"setMarkedText:'%@' selectedRange:%@", text,
337 // NSStringFromRange(range));
339 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
342 if (!markedTextField) {
343 // Create a text field and put it inside a floating panel. This field
344 // is used to display marked text.
345 NSSize cellSize = [ts cellSize];
346 NSRect cellRect = { 0, 0, cellSize.width, cellSize.height };
348 markedTextField = [[NSTextField alloc] initWithFrame:cellRect];
349 [markedTextField setEditable:NO];
350 [markedTextField setSelectable:NO];
351 [markedTextField setBezeled:NO];
352 [markedTextField setBordered:YES];
354 NSPanel *panel = [[NSPanel alloc]
355 initWithContentRect:cellRect
356 styleMask:NSBorderlessWindowMask|NSUtilityWindowMask
357 backing:NSBackingStoreBuffered
360 //[panel setHidesOnDeactivate:NO];
361 [panel setFloatingPanel:YES];
362 [panel setBecomesKeyOnlyIfNeeded:YES];
363 [panel setContentView:markedTextField];
366 if (text && [text length] > 0) {
367 [markedTextField setFont:[ts font]];
368 if ([text isKindOfClass:[NSAttributedString class]])
369 [markedTextField setAttributedStringValue:text];
371 [markedTextField setStringValue:text];
373 [markedTextField sizeToFit];
374 NSSize size = [markedTextField frame].size;
376 // Convert coordinates (row,col) -> view -> window base -> screen
378 if (![self convertRow:insertionPointRow+1 column:insertionPointColumn
381 origin = [self convertPoint:origin toView:nil];
382 origin = [[self window] convertBaseToScreen:origin];
384 NSWindow *win = [markedTextField window];
385 [win setContentSize:size];
386 [win setFrameOrigin:origin];
387 [win orderFront:nil];
389 [self hideMarkedTextField];
395 //NSLog(@"%s", _cmd);
396 [self hideMarkedTextField];
399 - (NSRect)firstRectForCharacterRange:(NSRange)range
401 //NSLog(@"%s%@", _cmd, NSStringFromRange(range));
403 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
404 NSLayoutManager *lm = [self layoutManager];
405 NSTextContainer *tc = [self textContainer];
407 // HACK! Since we always return marked text to have location NSNotFound,
408 // this method will be called with 'range.location == NSNotFound' whenever
409 // the input manager tries to position a popup window near the insertion
410 // point. For this reason we compute where the insertion point is and
411 // return a rect which contains it.
412 if (!(ts && lm && tc) || NSNotFound != range.location)
413 return [super firstRectForCharacterRange:range];
415 unsigned charIdx = [ts characterIndexForRow:insertionPointRow
416 column:insertionPointColumn];
418 [lm glyphRangeForCharacterRange:NSMakeRange(charIdx,1)
419 actualCharacterRange:NULL];
420 NSRect ipRect = [lm boundingRectForGlyphRange:glyphRange
422 ipRect.origin.x += [self textContainerOrigin].x;
423 ipRect.origin.y += [self textContainerOrigin].y + [ts cellSize].height;
425 ipRect.origin = [self convertPoint:ipRect.origin toView:nil];
426 ipRect.origin = [[self window] convertBaseToScreen:ipRect.origin];
431 - (void)scrollWheel:(NSEvent *)event
433 if ([event deltaY] == 0)
437 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
438 if (![self convertPoint:pt toRow:&row column:&col])
441 int flags = [event modifierFlags];
442 float dy = [event deltaY];
443 NSMutableData *data = [NSMutableData data];
445 [data appendBytes:&row length:sizeof(int)];
446 [data appendBytes:&col length:sizeof(int)];
447 [data appendBytes:&flags length:sizeof(int)];
448 [data appendBytes:&dy length:sizeof(float)];
450 [[self vimController] sendMessage:ScrollWheelMsgID data:data];
453 - (void)mouseDown:(NSEvent *)event
456 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
457 if (![self convertPoint:pt toRow:&row column:&col])
460 lastMouseDownEvent = [event copy];
462 int button = [event buttonNumber];
463 int flags = [event modifierFlags];
464 int count = [event clickCount];
465 NSMutableData *data = [NSMutableData data];
467 // If desired, intepret Ctrl-Click as a right mouse click.
468 if ([[NSUserDefaults standardUserDefaults]
469 boolForKey:MMTranslateCtrlClickKey]
470 && button == 0 && flags & NSControlKeyMask) {
472 flags &= ~NSControlKeyMask;
475 [data appendBytes:&row length:sizeof(int)];
476 [data appendBytes:&col length:sizeof(int)];
477 [data appendBytes:&button length:sizeof(int)];
478 [data appendBytes:&flags length:sizeof(int)];
479 [data appendBytes:&count length:sizeof(int)];
481 [[self vimController] sendMessage:MouseDownMsgID data:data];
484 - (void)rightMouseDown:(NSEvent *)event
486 [self mouseDown:event];
489 - (void)otherMouseDown:(NSEvent *)event
491 [self mouseDown:event];
494 - (void)mouseUp:(NSEvent *)event
497 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
498 if (![self convertPoint:pt toRow:&row column:&col])
501 int flags = [event modifierFlags];
502 NSMutableData *data = [NSMutableData data];
504 [data appendBytes:&row length:sizeof(int)];
505 [data appendBytes:&col length:sizeof(int)];
506 [data appendBytes:&flags length:sizeof(int)];
508 [[self vimController] sendMessage:MouseUpMsgID data:data];
513 - (void)rightMouseUp:(NSEvent *)event
515 [self mouseUp:event];
518 - (void)otherMouseUp:(NSEvent *)event
520 [self mouseUp:event];
523 - (void)mouseDragged:(NSEvent *)event
525 int flags = [event modifierFlags];
527 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
528 if (![self convertPoint:pt toRow:&row column:&col])
531 // Autoscrolling is done in dragTimerFired:
532 if (!isAutoscrolling) {
533 NSMutableData *data = [NSMutableData data];
535 [data appendBytes:&row length:sizeof(int)];
536 [data appendBytes:&col length:sizeof(int)];
537 [data appendBytes:&flags length:sizeof(int)];
539 [[self vimController] sendMessage:MouseDraggedMsgID data:data];
543 dragRow = row; dragColumn = col; dragFlags = flags;
545 [self startDragTimerWithInterval:.5];
550 - (void)rightMouseDragged:(NSEvent *)event
552 [self mouseDragged:event];
555 - (void)otherMouseDragged:(NSEvent *)event
557 [self mouseDragged:event];
560 - (void)mouseMoved:(NSEvent *)event
562 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
565 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
567 if (![self convertPoint:pt toRow:&row column:&col])
570 // HACK! It seems impossible to get the tracking rects set up before the
571 // view is visible, which means that the first mouseEntered: or
572 // mouseExited: events are never received. This forces us to check if the
573 // mouseMoved: event really happened over the text.
575 [ts getMaxRows:&rows columns:&cols];
576 if (row >= 0 && row < rows && col >= 0 && col < cols) {
577 NSMutableData *data = [NSMutableData data];
579 [data appendBytes:&row length:sizeof(int)];
580 [data appendBytes:&col length:sizeof(int)];
582 [[self vimController] sendMessage:MouseMovedMsgID data:data];
586 - (void)mouseEntered:(NSEvent *)event
588 //NSLog(@"%s", _cmd);
590 // NOTE: This event is received even when the window is not key; thus we
591 // have to take care not to enable mouse moved events unless our window is
593 if ([[self window] isKeyWindow])
594 [[self window] setAcceptsMouseMovedEvents:YES];
597 - (void)mouseExited:(NSEvent *)event
599 //NSLog(@"%s", _cmd);
601 [[self window] setAcceptsMouseMovedEvents:NO];
603 // NOTE: This event is received even when the window is not key; if the
604 // mouse shape is set when our window is not key, the hollow (unfocused)
605 // cursor will become a block (focused) cursor.
606 if ([[self window] isKeyWindow]) {
608 NSMutableData *data = [NSMutableData data];
609 [data appendBytes:&shape length:sizeof(int)];
610 [[self vimController] sendMessage:SetMouseShapeMsgID data:data];
614 - (void)setFrame:(NSRect)frame
616 //NSLog(@"%s", _cmd);
618 // When the frame changes we also need to update the tracking rect.
619 [super setFrame:frame];
620 [self removeTrackingRect:trackingRectTag];
621 trackingRectTag = [self addTrackingRect:[self trackingRect] owner:self
622 userData:NULL assumeInside:YES];
625 - (void)viewDidMoveToWindow
627 //NSLog(@"%s (window=%@)", _cmd, [self window]);
629 // Set a tracking rect which covers the text.
630 // NOTE: While the mouse cursor is in this rect the view will receive
631 // 'mouseMoved:' events so that Vim can take care of updating the mouse
634 [[self window] setAcceptsMouseMovedEvents:YES];
635 trackingRectTag = [self addTrackingRect:[self trackingRect] owner:self
636 userData:NULL assumeInside:YES];
640 - (void)viewWillMoveToWindow:(NSWindow *)newWindow
642 //NSLog(@"%s%@", _cmd, newWindow);
644 // Remove tracking rect if view moves or is removed.
645 if ([self window] && trackingRectTag) {
646 [self removeTrackingRect:trackingRectTag];
651 - (NSMenu*)menuForEvent:(NSEvent *)event
653 // HACK! Return nil to disable NSTextView's popup menus (Vim provides its
654 // own). Called when user Ctrl-clicks in the view (this is already handled
655 // in rightMouseDown:).
659 - (NSArray *)acceptableDragTypes
661 return [NSArray arrayWithObjects:NSFilenamesPboardType,
662 NSStringPboardType, nil];
665 - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
667 NSPasteboard *pboard = [sender draggingPasteboard];
669 if ([[pboard types] containsObject:NSStringPboardType]) {
670 NSString *string = [pboard stringForType:NSStringPboardType];
671 [[self vimController] dropString:string];
673 } else if ([[pboard types] containsObject:NSFilenamesPboardType]) {
674 NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
675 [[self vimController] dropFiles:files];
682 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
684 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
685 NSPasteboard *pboard = [sender draggingPasteboard];
687 if ( [[pboard types] containsObject:NSFilenamesPboardType]
688 && (sourceDragMask & NSDragOperationCopy) )
689 return NSDragOperationCopy;
690 if ( [[pboard types] containsObject:NSStringPboardType]
691 && (sourceDragMask & NSDragOperationCopy) )
692 return NSDragOperationCopy;
694 return NSDragOperationNone;
697 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
699 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
700 NSPasteboard *pboard = [sender draggingPasteboard];
702 if ( [[pboard types] containsObject:NSFilenamesPboardType]
703 && (sourceDragMask & NSDragOperationCopy) )
704 return NSDragOperationCopy;
705 if ( [[pboard types] containsObject:NSStringPboardType]
706 && (sourceDragMask & NSDragOperationCopy) )
707 return NSDragOperationCopy;
709 return NSDragOperationNone;
712 - (void)changeFont:(id)sender
714 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
717 NSFont *oldFont = [ts font];
718 NSFont *newFont = [sender convertFont:oldFont];
721 NSString *name = [newFont displayName];
722 unsigned len = [name lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
724 NSMutableData *data = [NSMutableData data];
725 float pointSize = [newFont pointSize];
727 [data appendBytes:&pointSize length:sizeof(float)];
729 ++len; // include NUL byte
730 [data appendBytes:&len length:sizeof(unsigned)];
731 [data appendBytes:[name UTF8String] length:len];
733 [[self vimController] sendMessage:SetFontMsgID data:data];
738 - (void)resetCursorRects
740 // No need to set up cursor rects since Vim handles cursor changes.
743 - (void)updateFontPanel
745 // The font panel is updated whenever the font is set.
748 - (void)viewDidEndLiveResize
750 id windowController = [[self window] windowController];
751 [windowController liveResizeDidEnd];
759 @implementation MMTextView (Private)
761 - (BOOL)convertPoint:(NSPoint)point toRow:(int *)row column:(int *)column
764 NSLayoutManager *lm = [self layoutManager];
765 NSTextContainer *tc = [self textContainer];
766 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
768 if (!(lm && tc && ts))
771 unsigned glyphIdx = [lm glyphIndexForPoint:point inTextContainer:tc];
772 unsigned charIdx = [lm characterIndexForGlyphAtIndex:glyphIdx];
774 int mod = [ts maxColumns] + 1;
776 if (row) *row = (int)(charIdx / mod);
777 if (column) *column = (int)(charIdx % mod);
779 NSLog(@"convertPoint:%@ toRow:%d column:%d", NSStringFromPoint(point),
784 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
785 NSSize cellSize = [ts cellSize];
786 if (!(cellSize.width > 0 && cellSize.height > 0))
788 NSPoint origin = [self textContainerOrigin];
790 if (row) *row = floor((point.y-origin.y-1) / cellSize.height);
791 if (column) *column = floor((point.x-origin.x-1) / cellSize.width);
793 //NSLog(@"convertPoint:%@ toRow:%d column:%d", NSStringFromPoint(point),
800 - (BOOL)convertRow:(int)row column:(int)column toPoint:(NSPoint *)point
802 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
803 NSSize cellSize = [ts cellSize];
804 if (!(point && cellSize.width > 0 && cellSize.height > 0))
807 *point = [self textContainerOrigin];
808 point->x += column * cellSize.width;
809 point->y += row * cellSize.height;
814 - (NSRect)trackingRect
816 NSRect rect = [self frame];
817 NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
818 int left = [ud integerForKey:MMTextInsetLeftKey];
819 int top = [ud integerForKey:MMTextInsetTopKey];
820 int right = [ud integerForKey:MMTextInsetRightKey];
821 int bot = [ud integerForKey:MMTextInsetBottomKey];
823 rect.origin.x = left;
825 rect.size.width -= left + right - 1;
826 rect.size.height -= top + bot - 1;
831 - (void)dispatchKeyEvent:(NSEvent *)event
833 // Only handle the command if it came from a keyDown event
834 if ([event type] != NSKeyDown)
837 NSString *chars = [event characters];
838 NSString *unmodchars = [event charactersIgnoringModifiers];
839 unichar c = [chars characterAtIndex:0];
840 unichar imc = [unmodchars characterAtIndex:0];
842 const char *bytes = 0;
843 int mods = [event modifierFlags];
845 //NSLog(@"%s chars[0]=0x%x unmodchars[0]=0x%x (chars=%@ unmodchars=%@)",
846 // _cmd, c, imc, chars, unmodchars);
848 if (' ' == imc && 0xa0 != c) {
849 // HACK! The AppKit turns <C-Space> into <C-@> which is not standard
850 // Vim behaviour, so bypass this problem. (0xa0 is <M-Space>, which
851 // should be passed on as is.)
852 len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
853 bytes = [unmodchars UTF8String];
854 } else if (imc == c && '2' == c) {
855 // HACK! Translate Ctrl+2 to <C-@>.
856 static char ctrl_at = 0;
857 len = 1; bytes = &ctrl_at;
858 } else if (imc == c && '6' == c) {
859 // HACK! Translate Ctrl+6 to <C-^>.
860 static char ctrl_hat = 0x1e;
861 len = 1; bytes = &ctrl_hat;
862 } else if (c == 0x19 && imc == 0x19) {
863 // HACK! AppKit turns back tab into Ctrl-Y, so we need to handle it
864 // separately (else Ctrl-Y doesn't work).
865 static char tab = 0x9;
866 len = 1; bytes = &tab; mods |= NSShiftKeyMask;
868 len = [chars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
869 bytes = [chars UTF8String];
872 [self sendKeyDown:bytes length:len modifiers:mods];
875 - (MMVimController *)vimController
877 id windowController = [[self window] windowController];
879 // TODO: Make sure 'windowController' is a MMWindowController before type
881 return [(MMWindowController*)windowController vimController];
884 - (void)startDragTimerWithInterval:(NSTimeInterval)t
886 [NSTimer scheduledTimerWithTimeInterval:t target:self
887 selector:@selector(dragTimerFired:)
888 userInfo:nil repeats:NO];
891 - (void)dragTimerFired:(NSTimer *)timer
893 // TODO: Autoscroll in horizontal direction?
894 static unsigned tick = 1;
895 MMTextStorage *ts = (MMTextStorage *)[self textStorage];
897 isAutoscrolling = NO;
899 if (isDragging && ts && (dragRow < 0 || dragRow >= [ts maxRows])) {
900 // HACK! If the mouse cursor is outside the text area, then send a
901 // dragged event. However, if row&col hasn't changed since the last
902 // dragged event, Vim won't do anything (see gui_send_mouse_event()).
903 // Thus we fiddle with the column to make sure something happens.
904 int col = dragColumn + (dragRow < 0 ? -(tick % 2) : +(tick % 2));
905 NSMutableData *data = [NSMutableData data];
907 [data appendBytes:&dragRow length:sizeof(int)];
908 [data appendBytes:&col length:sizeof(int)];
909 [data appendBytes:&dragFlags length:sizeof(int)];
911 [[self vimController] sendMessage:MouseDraggedMsgID data:data];
913 isAutoscrolling = YES;
917 // Compute timer interval depending on how far away the mouse cursor is
918 // from the text view.
919 NSRect rect = [self trackingRect];
921 if (dragPoint.y < rect.origin.y) dy = rect.origin.y - dragPoint.y;
922 else if (dragPoint.y > NSMaxY(rect)) dy = dragPoint.y - NSMaxY(rect);
923 if (dy > MMDragAreaSize) dy = MMDragAreaSize;
925 NSTimeInterval t = MMDragTimerMaxInterval -
926 dy*(MMDragTimerMaxInterval-MMDragTimerMinInterval)/MMDragAreaSize;
928 [self startDragTimerWithInterval:t];
934 - (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags
936 if (chars && len > 0) {
937 NSMutableData *data = [NSMutableData data];
939 [data appendBytes:&flags length:sizeof(int)];
940 [data appendBytes:&len length:sizeof(int)];
941 [data appendBytes:chars length:len];
943 // TODO: Support 'mousehide' (check p_mh)
944 [NSCursor setHiddenUntilMouseMoves:YES];
946 //NSLog(@"%s len=%d chars=0x%x", _cmd, len, chars[0]);
947 [[self vimController] sendMessage:KeyDownMsgID data:data];
951 @end // MMTextView (Private)