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> etc. we have to watch
184 // for when space was pressed.
185 if ([event type] == NSKeyDown
186 && [[event charactersIgnoringModifiers] length] > 0
187 && [[event charactersIgnoringModifiers] characterAtIndex:0] == ' '
188 && [event modifierFlags]
189 & (NSShiftKeyMask|NSControlKeyMask|NSAlternateKeyMask))
191 [self dispatchKeyEvent:event];
195 // TODO: Support 'mousehide' (check p_mh)
196 [NSCursor setHiddenUntilMouseMoves:YES];
198 // NOTE: 'string' is either an NSString or an NSAttributedString. Since we
199 // do not support attributes, simply pass the corresponding NSString in the
201 if ([string isKindOfClass:[NSAttributedString class]])
202 string = [string string];
204 [[self vimController] sendMessage:InsertTextMsgID
205 data:[string dataUsingEncoding:NSUTF8StringEncoding]
210 - (void)doCommandBySelector:(SEL)selector
212 //NSLog(@"%s %@", _cmd, NSStringFromSelector(selector));
213 // By ignoring the selector we effectively disable the key binding
214 // mechanism of Cocoa. Hopefully this is what the user will expect
215 // (pressing Ctrl+P would otherwise result in moveUp: instead of previous
218 // We usually end up here if the user pressed Ctrl+key (but not
221 NSEvent *event = [NSApp currentEvent];
223 if (selector == @selector(cancelOperation:)
224 || selector == @selector(insertNewline:)) {
225 // HACK! If there was marked text which got abandoned as a result of
226 // hitting escape or enter, then 'insertText:' is called with the
227 // abandoned text but '[event characters]' includes the abandoned text
228 // as well. Since 'dispatchKeyEvent:' looks at '[event characters]' we
229 // must intercept these keys here or the abandonded text gets inserted
231 NSString *key = [event charactersIgnoringModifiers];
232 const char *chars = [key UTF8String];
233 int len = [key lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
235 if (0x3 == chars[0]) {
236 // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
237 // handle it separately (else Ctrl-C doesn't work).
238 len = sizeof(MMKeypadEnter)/sizeof(MMKeypadEnter[0]);
239 chars = MMKeypadEnter;
242 [self sendKeyDown:chars length:len modifiers:[event modifierFlags]];
244 [self dispatchKeyEvent:event];
248 - (BOOL)performKeyEquivalent:(NSEvent *)event
250 //NSLog(@"%s %@", _cmd, event);
251 // Called for Cmd+key keystrokes, function keys, arrow keys, page
252 // up/down, home, end.
254 // NOTE: This message cannot be ignored since Cmd+letter keys never are
255 // passed to keyDown:. It seems as if the main menu consumes Cmd-key
256 // strokes, unless the key is a function key.
258 // NOTE: If the event that triggered this method represents a function key
259 // down then we do nothing, otherwise the input method never gets the key
260 // stroke (some input methods use e.g. arrow keys). The function key down
261 // event will still reach Vim though (via keyDown:).
262 int flags = [event modifierFlags];
263 if ([event type] != NSKeyDown || flags & NSFunctionKeyMask)
266 // HACK! Let the main menu try to handle any key down event, before
267 // passing it on to vim, otherwise key equivalents for menus will
268 // effectively be disabled.
269 if ([[NSApp mainMenu] performKeyEquivalent:event])
272 // HACK! KeyCode 50 represent the key which switches between windows
273 // within an application (like Cmd+Tab is used to switch between
274 // applications). Return NO here, else the window switching does not work.
276 // Will this hack work for all languages / keyboard layouts?
277 if ([event keyCode] == 50)
280 //NSLog(@"%s%@", _cmd, event);
282 NSString *chars = [event characters];
283 NSString *unmodchars = [event charactersIgnoringModifiers];
284 int len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
285 NSMutableData *data = [NSMutableData data];
290 // If 'chars' and 'unmodchars' differs when shift flag is present, then we
291 // can clear the shift flag as it is already included in 'unmodchars'.
292 // Failing to clear the shift flag means <D-Bar> turns into <S-D-Bar> (on
293 // an English keyboard).
294 if (flags & NSShiftKeyMask && ![chars isEqual:unmodchars])
295 flags &= ~NSShiftKeyMask;
297 if (0x3 == [unmodchars characterAtIndex:0]) {
298 // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
299 // handle it separately (else Cmd-enter turns into Ctrl-C).
300 unmodchars = MMKeypadEnterString;
301 len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
304 [data appendBytes:&flags length:sizeof(int)];
305 [data appendBytes:&len length:sizeof(int)];
306 [data appendBytes:[unmodchars UTF8String] length:len];
308 [[self vimController] sendMessage:CmdKeyMsgID data:data wait:NO];
313 - (BOOL)hasMarkedText
315 //NSLog(@"%s", _cmd);
316 return markedTextField && [[markedTextField stringValue] length] > 0;
319 - (NSRange)markedRange
321 //NSLog(@"%s", _cmd);
322 // HACK! If a valid range is returned, then NSTextView changes the
323 // background color of the returned range. Since marked text is displayed
324 // in a separate popup window this behaviour is not wanted. By setting the
325 // location of the returned range to NSNotFound NSTextView does nothing.
326 // This hack is continued in 'firstRectForCharacterRange:'.
327 return NSMakeRange(NSNotFound, 0);
330 - (void)setMarkedText:(id)text selectedRange:(NSRange)range
332 //NSLog(@"setMarkedText:'%@' selectedRange:%@", text,
333 // NSStringFromRange(range));
335 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
338 if (!markedTextField) {
339 // Create a text field and put it inside a floating panel. This field
340 // is used to display marked text.
341 NSSize cellSize = [ts cellSize];
342 NSRect cellRect = { 0, 0, cellSize.width, cellSize.height };
344 markedTextField = [[NSTextField alloc] initWithFrame:cellRect];
345 [markedTextField setEditable:NO];
346 [markedTextField setSelectable:NO];
347 [markedTextField setBezeled:NO];
348 [markedTextField setBordered:YES];
350 NSPanel *panel = [[NSPanel alloc]
351 initWithContentRect:cellRect
352 styleMask:NSBorderlessWindowMask|NSUtilityWindowMask
353 backing:NSBackingStoreBuffered
356 //[panel setHidesOnDeactivate:NO];
357 [panel setFloatingPanel:YES];
358 [panel setBecomesKeyOnlyIfNeeded:YES];
359 [panel setContentView:markedTextField];
362 if (text && [text length] > 0) {
363 [markedTextField setFont:[ts font]];
364 if ([text isKindOfClass:[NSAttributedString class]])
365 [markedTextField setAttributedStringValue:text];
367 [markedTextField setStringValue:text];
369 [markedTextField sizeToFit];
370 NSSize size = [markedTextField frame].size;
372 // Convert coordinates (row,col) -> view -> window base -> screen
374 if (![self convertRow:insertionPointRow+1 column:insertionPointColumn
377 origin = [self convertPoint:origin toView:nil];
378 origin = [[self window] convertBaseToScreen:origin];
380 NSWindow *win = [markedTextField window];
381 [win setContentSize:size];
382 [win setFrameOrigin:origin];
383 [win orderFront:nil];
385 [self hideMarkedTextField];
391 //NSLog(@"%s", _cmd);
392 [self hideMarkedTextField];
395 - (NSRect)firstRectForCharacterRange:(NSRange)range
397 //NSLog(@"%s%@", _cmd, NSStringFromRange(range));
399 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
400 NSLayoutManager *lm = [self layoutManager];
401 NSTextContainer *tc = [self textContainer];
403 // HACK! Since we always return marked text to have location NSNotFound,
404 // this method will be called with 'range.location == NSNotFound' whenever
405 // the input manager tries to position a popup window near the insertion
406 // point. For this reason we compute where the insertion point is and
407 // return a rect which contains it.
408 if (!(ts && lm && tc) || NSNotFound != range.location)
409 return [super firstRectForCharacterRange:range];
411 unsigned charIdx = [ts characterIndexForRow:insertionPointRow
412 column:insertionPointColumn];
414 [lm glyphRangeForCharacterRange:NSMakeRange(charIdx,1)
415 actualCharacterRange:NULL];
416 NSRect ipRect = [lm boundingRectForGlyphRange:glyphRange
418 ipRect.origin.x += [self textContainerOrigin].x;
419 ipRect.origin.y += [self textContainerOrigin].y + [ts cellSize].height;
421 ipRect.origin = [self convertPoint:ipRect.origin toView:nil];
422 ipRect.origin = [[self window] convertBaseToScreen:ipRect.origin];
427 - (void)scrollWheel:(NSEvent *)event
429 if ([event deltaY] == 0)
433 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
434 if (![self convertPoint:pt toRow:&row column:&col])
437 int flags = [event modifierFlags];
438 float dy = [event deltaY];
439 NSMutableData *data = [NSMutableData data];
441 [data appendBytes:&row length:sizeof(int)];
442 [data appendBytes:&col length:sizeof(int)];
443 [data appendBytes:&flags length:sizeof(int)];
444 [data appendBytes:&dy length:sizeof(float)];
446 [[self vimController] sendMessage:ScrollWheelMsgID data:data wait:NO];
449 - (void)mouseDown:(NSEvent *)event
452 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
453 if (![self convertPoint:pt toRow:&row column:&col])
456 lastMouseDownEvent = [event copy];
458 int button = [event buttonNumber];
459 int flags = [event modifierFlags];
460 int count = [event clickCount];
461 NSMutableData *data = [NSMutableData data];
463 // If desired, intepret Ctrl-Click as a right mouse click.
464 if ([[NSUserDefaults standardUserDefaults]
465 boolForKey:MMTranslateCtrlClickKey]
466 && button == 0 && flags & NSControlKeyMask) {
468 flags &= ~NSControlKeyMask;
471 [data appendBytes:&row length:sizeof(int)];
472 [data appendBytes:&col length:sizeof(int)];
473 [data appendBytes:&button length:sizeof(int)];
474 [data appendBytes:&flags length:sizeof(int)];
475 [data appendBytes:&count length:sizeof(int)];
477 [[self vimController] sendMessage:MouseDownMsgID data:data wait:NO];
480 - (void)rightMouseDown:(NSEvent *)event
482 [self mouseDown:event];
485 - (void)otherMouseDown:(NSEvent *)event
487 [self mouseDown:event];
490 - (void)mouseUp:(NSEvent *)event
493 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
494 if (![self convertPoint:pt toRow:&row column:&col])
497 int flags = [event modifierFlags];
498 NSMutableData *data = [NSMutableData data];
500 [data appendBytes:&row length:sizeof(int)];
501 [data appendBytes:&col length:sizeof(int)];
502 [data appendBytes:&flags length:sizeof(int)];
504 [[self vimController] sendMessage:MouseUpMsgID data:data wait:NO];
509 - (void)rightMouseUp:(NSEvent *)event
511 [self mouseUp:event];
514 - (void)otherMouseUp:(NSEvent *)event
516 [self mouseUp:event];
519 - (void)mouseDragged:(NSEvent *)event
521 int flags = [event modifierFlags];
523 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
524 if (![self convertPoint:pt toRow:&row column:&col])
527 // Autoscrolling is done in dragTimerFired:
528 if (!isAutoscrolling) {
529 NSMutableData *data = [NSMutableData data];
531 [data appendBytes:&row length:sizeof(int)];
532 [data appendBytes:&col length:sizeof(int)];
533 [data appendBytes:&flags length:sizeof(int)];
535 [[self vimController] sendMessage:MouseDraggedMsgID data:data wait:NO];
539 dragRow = row; dragColumn = col; dragFlags = flags;
541 [self startDragTimerWithInterval:.5];
546 - (void)rightMouseDragged:(NSEvent *)event
548 [self mouseDragged:event];
551 - (void)otherMouseDragged:(NSEvent *)event
553 [self mouseDragged:event];
556 - (void)mouseMoved:(NSEvent *)event
558 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
561 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
563 if (![self convertPoint:pt toRow:&row column:&col])
566 // HACK! It seems impossible to get the tracking rects set up before the
567 // view is visible, which means that the first mouseEntered: or
568 // mouseExited: events are never received. This forces us to check if the
569 // mouseMoved: event really happened over the text.
571 [ts getMaxRows:&rows columns:&cols];
572 if (row >= 0 && row < rows && col >= 0 && col < cols) {
573 NSMutableData *data = [NSMutableData data];
575 [data appendBytes:&row length:sizeof(int)];
576 [data appendBytes:&col length:sizeof(int)];
578 [[self vimController] sendMessage:MouseMovedMsgID data:data wait:NO];
582 - (void)mouseEntered:(NSEvent *)event
584 //NSLog(@"%s", _cmd);
586 // NOTE: This event is received even when the window is not key; thus we
587 // have to take care not to enable mouse moved events unless our window is
589 if ([[self window] isKeyWindow])
590 [[self window] setAcceptsMouseMovedEvents:YES];
593 - (void)mouseExited:(NSEvent *)event
595 //NSLog(@"%s", _cmd);
597 [[self window] setAcceptsMouseMovedEvents:NO];
599 // NOTE: This event is received even when the window is not key; if the
600 // mouse shape is set when our window is not key, the hollow (unfocused)
601 // cursor will become a block (focused) cursor.
602 if ([[self window] isKeyWindow]) {
604 NSMutableData *data = [NSMutableData data];
605 [data appendBytes:&shape length:sizeof(int)];
606 [[self vimController] sendMessage:SetMouseShapeMsgID data:data wait:NO];
610 - (void)setFrame:(NSRect)frame
612 //NSLog(@"%s", _cmd);
614 // When the frame changes we also need to update the tracking rect.
615 [super setFrame:frame];
616 [self removeTrackingRect:trackingRectTag];
617 trackingRectTag = [self addTrackingRect:[self trackingRect] owner:self
618 userData:NULL assumeInside:YES];
621 - (void)viewDidMoveToWindow
623 //NSLog(@"%s (window=%@)", _cmd, [self window]);
625 // Set a tracking rect which covers the text.
626 // NOTE: While the mouse cursor is in this rect the view will receive
627 // 'mouseMoved:' events so that Vim can take care of updating the mouse
630 [[self window] setAcceptsMouseMovedEvents:YES];
631 trackingRectTag = [self addTrackingRect:[self trackingRect] owner:self
632 userData:NULL assumeInside:YES];
636 - (void)viewWillMoveToWindow:(NSWindow *)newWindow
638 //NSLog(@"%s%@", _cmd, newWindow);
640 // Remove tracking rect if view moves or is removed.
641 if ([self window] && trackingRectTag) {
642 [self removeTrackingRect:trackingRectTag];
647 - (NSMenu*)menuForEvent:(NSEvent *)event
649 // HACK! Return nil to disable NSTextView's popup menus (Vim provides its
650 // own). Called when user Ctrl-clicks in the view (this is already handled
651 // in rightMouseDown:).
655 - (NSArray *)acceptableDragTypes
657 return [NSArray arrayWithObjects:NSFilenamesPboardType,
658 NSStringPboardType, nil];
661 - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
663 NSPasteboard *pboard = [sender draggingPasteboard];
665 if ([[pboard types] containsObject:NSStringPboardType]) {
666 NSString *string = [pboard stringForType:NSStringPboardType];
667 [[self vimController] dropString:string];
669 } else if ([[pboard types] containsObject:NSFilenamesPboardType]) {
670 NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
671 [[self vimController] dropFiles:files];
678 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
680 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
681 NSPasteboard *pboard = [sender draggingPasteboard];
683 if ( [[pboard types] containsObject:NSFilenamesPboardType]
684 && (sourceDragMask & NSDragOperationCopy) )
685 return NSDragOperationCopy;
686 if ( [[pboard types] containsObject:NSStringPboardType]
687 && (sourceDragMask & NSDragOperationCopy) )
688 return NSDragOperationCopy;
690 return NSDragOperationNone;
693 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
695 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
696 NSPasteboard *pboard = [sender draggingPasteboard];
698 if ( [[pboard types] containsObject:NSFilenamesPboardType]
699 && (sourceDragMask & NSDragOperationCopy) )
700 return NSDragOperationCopy;
701 if ( [[pboard types] containsObject:NSStringPboardType]
702 && (sourceDragMask & NSDragOperationCopy) )
703 return NSDragOperationCopy;
705 return NSDragOperationNone;
708 - (void)changeFont:(id)sender
710 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
713 NSFont *oldFont = [ts font];
714 NSFont *newFont = [sender convertFont:oldFont];
717 NSString *name = [newFont displayName];
718 unsigned len = [name lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
720 NSMutableData *data = [NSMutableData data];
721 float pointSize = [newFont pointSize];
723 [data appendBytes:&pointSize length:sizeof(float)];
725 ++len; // include NUL byte
726 [data appendBytes:&len length:sizeof(unsigned)];
727 [data appendBytes:[name UTF8String] length:len];
729 [[self vimController] sendMessage:SetFontMsgID data:data wait:NO];
734 - (void)resetCursorRects
736 // No need to set up cursor rects since Vim handles cursor changes.
739 - (void)updateFontPanel
741 // The font panel is updated whenever the font is set.
749 @implementation MMTextView (Private)
751 - (BOOL)convertPoint:(NSPoint)point toRow:(int *)row column:(int *)column
754 NSLayoutManager *lm = [self layoutManager];
755 NSTextContainer *tc = [self textContainer];
756 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
758 if (!(lm && tc && ts))
761 unsigned glyphIdx = [lm glyphIndexForPoint:point inTextContainer:tc];
762 unsigned charIdx = [lm characterIndexForGlyphAtIndex:glyphIdx];
764 int mod = [ts maxColumns] + 1;
766 if (row) *row = (int)(charIdx / mod);
767 if (column) *column = (int)(charIdx % mod);
769 NSLog(@"convertPoint:%@ toRow:%d column:%d", NSStringFromPoint(point),
774 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
775 NSSize cellSize = [ts cellSize];
776 if (!(cellSize.width > 0 && cellSize.height > 0))
778 NSPoint origin = [self textContainerOrigin];
780 if (row) *row = floor((point.y-origin.y-1) / cellSize.height);
781 if (column) *column = floor((point.x-origin.x-1) / cellSize.width);
783 //NSLog(@"convertPoint:%@ toRow:%d column:%d", NSStringFromPoint(point),
790 - (BOOL)convertRow:(int)row column:(int)column toPoint:(NSPoint *)point
792 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
793 NSSize cellSize = [ts cellSize];
794 if (!(point && cellSize.width > 0 && cellSize.height > 0))
797 *point = [self textContainerOrigin];
798 point->x += column * cellSize.width;
799 point->y += row * cellSize.height;
804 - (NSRect)trackingRect
806 NSRect rect = [self frame];
807 NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
808 int left = [ud integerForKey:MMTextInsetLeftKey];
809 int top = [ud integerForKey:MMTextInsetTopKey];
810 int right = [ud integerForKey:MMTextInsetRightKey];
811 int bot = [ud integerForKey:MMTextInsetBottomKey];
813 rect.origin.x = left;
815 rect.size.width -= left + right - 1;
816 rect.size.height -= top + bot - 1;
821 - (void)dispatchKeyEvent:(NSEvent *)event
823 // Only handle the command if it came from a keyDown event
824 if ([event type] != NSKeyDown)
827 NSString *chars = [event characters];
828 NSString *unmodchars = [event charactersIgnoringModifiers];
829 unichar c = [chars characterAtIndex:0];
830 unichar imc = [unmodchars characterAtIndex:0];
832 const char *bytes = 0;
834 //NSLog(@"%s chars[0]=0x%x unmodchars[0]=0x%x (chars=%@ unmodchars=%@)",
835 // _cmd, c, imc, chars, unmodchars);
837 if (' ' == imc && 0xa0 != c) {
838 // HACK! The AppKit turns <C-Space> into <C-@> which is not standard
839 // Vim behaviour, so bypass this problem. (0xa0 is <M-Space>, which
840 // should be passed on as is.)
841 len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
842 bytes = [unmodchars UTF8String];
843 } else if (imc == c && '2' == c) {
844 // HACK! Translate Ctrl+2 to <C-@>.
845 static char ctrl_at = 0;
846 len = 1; bytes = &ctrl_at;
847 } else if (imc == c && '6' == c) {
848 // HACK! Translate Ctrl+6 to <C-^>.
849 static char ctrl_hat = 0x1e;
850 len = 1; bytes = &ctrl_hat;
851 } else if (c == 0x19 && imc == 0x19) {
852 // HACK! AppKit turns back tab into Ctrl-Y, so we need to handle it
853 // separately (else Ctrl-Y doesn't work).
854 static char back_tab[2] = { 'k', 'B' };
855 len = 2; bytes = back_tab;
857 len = [chars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
858 bytes = [chars UTF8String];
861 [self sendKeyDown:bytes length:len modifiers:[event modifierFlags]];
864 - (MMVimController *)vimController
866 id windowController = [[self window] windowController];
868 // TODO: Make sure 'windowController' is a MMWindowController before type
870 return [(MMWindowController*)windowController vimController];
873 - (void)startDragTimerWithInterval:(NSTimeInterval)t
875 [NSTimer scheduledTimerWithTimeInterval:t target:self
876 selector:@selector(dragTimerFired:)
877 userInfo:nil repeats:NO];
880 - (void)dragTimerFired:(NSTimer *)timer
882 // TODO: Autoscroll in horizontal direction?
883 static unsigned tick = 1;
884 MMTextStorage *ts = (MMTextStorage *)[self textStorage];
886 isAutoscrolling = NO;
888 if (isDragging && ts && (dragRow < 0 || dragRow >= [ts maxRows])) {
889 // HACK! If the mouse cursor is outside the text area, then send a
890 // dragged event. However, if row&col hasn't changed since the last
891 // dragged event, Vim won't do anything (see gui_send_mouse_event()).
892 // Thus we fiddle with the column to make sure something happens.
893 int col = dragColumn + (dragRow < 0 ? -(tick % 2) : +(tick % 2));
894 NSMutableData *data = [NSMutableData data];
896 [data appendBytes:&dragRow length:sizeof(int)];
897 [data appendBytes:&col length:sizeof(int)];
898 [data appendBytes:&dragFlags length:sizeof(int)];
900 [[self vimController] sendMessage:MouseDraggedMsgID data:data wait:NO];
902 isAutoscrolling = YES;
906 // Compute timer interval depending on how far away the mouse cursor is
907 // from the text view.
908 NSRect rect = [self trackingRect];
910 if (dragPoint.y < rect.origin.y) dy = rect.origin.y - dragPoint.y;
911 else if (dragPoint.y > NSMaxY(rect)) dy = dragPoint.y - NSMaxY(rect);
912 if (dy > MMDragAreaSize) dy = MMDragAreaSize;
914 NSTimeInterval t = MMDragTimerMaxInterval -
915 dy*(MMDragTimerMaxInterval-MMDragTimerMinInterval)/MMDragAreaSize;
917 [self startDragTimerWithInterval:t];
923 - (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags
925 if (chars && len > 0) {
926 NSMutableData *data = [NSMutableData data];
928 [data appendBytes:&flags length:sizeof(int)];
929 [data appendBytes:&len length:sizeof(int)];
930 [data appendBytes:chars length:len];
932 // TODO: Support 'mousehide' (check p_mh)
933 [NSCursor setHiddenUntilMouseMoves:YES];
935 //NSLog(@"%s len=%d chars=0x%x", _cmd, len, chars[0]);
936 [[self vimController] sendMessage:KeyDownMsgID data:data wait:NO];
940 @end // MMTextView (Private)