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;
28 @interface MMTextView (Private)
29 - (BOOL)convertPoint:(NSPoint)point toRow:(int *)row column:(int *)column;
30 - (NSRect)trackingRect;
31 - (void)dispatchKeyEvent:(NSEvent *)event;
32 - (MMVimController *)vimController;
33 - (void)startDragTimerWithInterval:(NSTimeInterval)t;
34 - (void)dragTimerFired:(NSTimer *)timer;
39 @implementation MMTextView
43 [lastMouseDownEvent release];
47 - (NSEvent *)lastMouseDownEvent
49 return lastMouseDownEvent;
52 - (BOOL)shouldDrawInsertionPoint
54 // NOTE: The insertion point is drawn manually in drawRect:. It would be
55 // nice to be able to use the insertion point related methods of
56 // NSTextView, but it seems impossible to get them to work properly (search
57 // the cocoabuilder archives).
61 - (void)setShouldDrawInsertionPoint:(BOOL)on
63 shouldDrawInsertionPoint = on;
66 - (void)drawInsertionPointAtRow:(int)row column:(int)col shape:(int)shape
67 fraction:(int)percent color:(NSColor *)color
69 //NSLog(@"drawInsertionPointAtRow:%d column:%d shape:%d color:%@",
70 // row, col, shape, color);
72 // This only stores where to draw the insertion point, the actual drawing
73 // is done in drawRect:.
74 shouldDrawInsertionPoint = YES;
75 insertionPointRow = row;
76 insertionPointColumn = col;
77 insertionPointShape = shape;
78 insertionPointFraction = percent;
80 [self setInsertionPointColor:color];
83 - (void)drawRect:(NSRect)rect
85 [super drawRect:rect];
87 if (shouldDrawInsertionPoint) {
88 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
89 NSLayoutManager *lm = [self layoutManager];
90 NSTextContainer *tc = [self textContainer];
92 // Given (row,column), calculate the bounds of the glyph at that spot.
93 // We use the layout manager because this gives us exactly the size and
94 // location of the glyph so that we can match the insertion point to
96 unsigned charIdx = [ts characterIndexForRow:insertionPointRow
97 column:insertionPointColumn];
99 [lm glyphRangeForCharacterRange:NSMakeRange(charIdx,1)
100 actualCharacterRange:NULL];
101 NSRect ipRect = [lm boundingRectForGlyphRange:glyphRange
103 ipRect.origin.x += [self textContainerOrigin].x;
104 ipRect.origin.y += [self textContainerOrigin].y;
106 if (MMInsertionPointHorizontal == insertionPointShape) {
107 int frac = (ipRect.size.height * insertionPointFraction + 99)/100;
108 ipRect.origin.y += ipRect.size.height - frac;
109 ipRect.size.height = frac;
110 } else if (MMInsertionPointVertical == insertionPointShape) {
111 int frac = (ipRect.size.width * insertionPointFraction + 99)/100;
112 ipRect.size.width = frac;
115 [[self insertionPointColor] set];
116 if (MMInsertionPointHollow == insertionPointShape) {
122 // NOTE: We only draw the cursor once and rely on Vim to say when it
123 // should be drawn again.
124 shouldDrawInsertionPoint = NO;
126 //NSLog(@"%s draw insertion point %@ shape=%d color=%@", _cmd,
127 // NSStringFromRect(ipRect), insertionPointShape,
128 // [self insertionPointColor]);
132 - (void)keyDown:(NSEvent *)event
134 // HACK! If a modifier is held, don't pass the event along to
135 // interpretKeyEvents: since some keys are bound to multiple commands which
136 // means doCommandBySelector: is called several times.
138 // TODO: Figure out a way to disable Cocoa key bindings entirely, without
139 // affecting input management.
141 if ([event modifierFlags] & NSControlKeyMask)
142 [self dispatchKeyEvent:event];
144 [super keyDown:event];
147 - (void)insertText:(id)string
149 // NOTE! This method is called for normal key presses but also for
150 // Option-key presses --- even when Ctrl is held as well as Option. When
151 // Ctrl is held, the AppKit translates the character to a Ctrl+key stroke,
152 // so 'string' need not be a printable character! In this case it still
153 // works to pass 'string' on to Vim as a printable character (since
154 // modifiers are already included and should not be added to the input
155 // buffer using CSI, K_MODIFIER).
157 NSEvent *event = [NSApp currentEvent];
158 //NSLog(@"%s%@ (event=%@)", _cmd, string, event);
160 // HACK! In order to be able to bind to <S-Space> etc. we have to watch
161 // for when space was pressed.
162 if ([event type] == NSKeyDown
163 && [[event charactersIgnoringModifiers] length] > 0
164 && [[event charactersIgnoringModifiers] characterAtIndex:0] == ' '
165 && [event modifierFlags]
166 & (NSShiftKeyMask|NSControlKeyMask|NSAlternateKeyMask))
168 [self dispatchKeyEvent:event];
172 // TODO: Support 'mousehide' (check p_mh)
173 [NSCursor setHiddenUntilMouseMoves:YES];
175 [[self vimController] sendMessage:InsertTextMsgID
176 data:[string dataUsingEncoding:NSUTF8StringEncoding]
181 - (void)doCommandBySelector:(SEL)selector
183 // By ignoring the selector we effectively disable the key binding
184 // mechanism of Cocoa. Hopefully this is what the user will expect
185 // (pressing Ctrl+P would otherwise result in moveUp: instead of previous
188 // We usually end up here if the user pressed Ctrl+key (but not
191 //NSLog(@"%s%@", _cmd, NSStringFromSelector(selector));
192 [self dispatchKeyEvent:[NSApp currentEvent]];
195 - (BOOL)performKeyEquivalent:(NSEvent *)event
197 // Called for Cmd+key keystrokes, function keys, arrow keys, page
198 // up/down, home, end.
200 if ([event type] != NSKeyDown)
203 // HACK! Let the main menu try to handle any key down event, before
204 // passing it on to vim, otherwise key equivalents for menus will
205 // effectively be disabled.
206 if ([[NSApp mainMenu] performKeyEquivalent:event])
209 // HACK! KeyCode 50 represent the key which switches between windows
210 // within an application (like Cmd+Tab is used to switch between
211 // applications). Return NO here, else the window switching does not work.
213 // Will this hack work for all languages / keyboard layouts?
214 if ([event keyCode] == 50)
217 //NSLog(@"%s%@", _cmd, event);
219 NSString *string = [event charactersIgnoringModifiers];
220 int flags = [event modifierFlags];
221 int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
222 NSMutableData *data = [NSMutableData data];
224 [data appendBytes:&flags length:sizeof(int)];
225 [data appendBytes:&len length:sizeof(int)];
226 [data appendBytes:[string UTF8String] length:len];
228 [[self vimController] sendMessage:CmdKeyMsgID data:data wait:NO];
233 - (void)setMarkedText:(id)text selectedRange:(NSRange)range
235 // TODO: Figure out a way to handle marked text, at the moment the user
236 // has no way of knowing what has been added so far in a multi-stroke key.
237 // E.g. hitting Option-e and then e will result in an 'e' with acute, but
238 // nothing is displayed immediately after hitting Option-e.
240 NSLog(@"setMarkedText:'%@' selectedRange:(%d,%d)", text, range.location,
244 - (void)scrollWheel:(NSEvent *)event
246 if ([event deltaY] == 0)
250 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
251 if (![self convertPoint:pt toRow:&row column:&col])
254 int flags = [event modifierFlags];
255 float dy = [event deltaY];
256 NSMutableData *data = [NSMutableData data];
258 [data appendBytes:&row length:sizeof(int)];
259 [data appendBytes:&col length:sizeof(int)];
260 [data appendBytes:&flags length:sizeof(int)];
261 [data appendBytes:&dy length:sizeof(float)];
263 [[self vimController] sendMessage:ScrollWheelMsgID data:data wait:NO];
266 - (void)mouseDown:(NSEvent *)event
269 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
270 if (![self convertPoint:pt toRow:&row column:&col])
273 lastMouseDownEvent = [event copy];
275 int button = [event buttonNumber];
276 int flags = [event modifierFlags];
277 int count = [event clickCount];
278 NSMutableData *data = [NSMutableData data];
280 // If desired, intepret Ctrl-Click as a right mouse click.
281 if ([[NSUserDefaults standardUserDefaults]
282 boolForKey:MMTranslateCtrlClickKey]
283 && button == 0 && flags & NSControlKeyMask) {
285 flags &= ~NSControlKeyMask;
288 [data appendBytes:&row length:sizeof(int)];
289 [data appendBytes:&col length:sizeof(int)];
290 [data appendBytes:&button length:sizeof(int)];
291 [data appendBytes:&flags length:sizeof(int)];
292 [data appendBytes:&count length:sizeof(int)];
294 [[self vimController] sendMessage:MouseDownMsgID data:data wait:NO];
297 - (void)rightMouseDown:(NSEvent *)event
299 [self mouseDown:event];
302 - (void)otherMouseDown:(NSEvent *)event
304 [self mouseDown:event];
307 - (void)mouseUp:(NSEvent *)event
310 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
311 if (![self convertPoint:pt toRow:&row column:&col])
314 int flags = [event modifierFlags];
315 NSMutableData *data = [NSMutableData data];
317 [data appendBytes:&row length:sizeof(int)];
318 [data appendBytes:&col length:sizeof(int)];
319 [data appendBytes:&flags length:sizeof(int)];
321 [[self vimController] sendMessage:MouseUpMsgID data:data wait:NO];
326 - (void)rightMouseUp:(NSEvent *)event
328 [self mouseUp:event];
331 - (void)otherMouseUp:(NSEvent *)event
333 [self mouseUp:event];
336 - (void)mouseDragged:(NSEvent *)event
338 int flags = [event modifierFlags];
340 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
341 if (![self convertPoint:pt toRow:&row column:&col])
344 // Autoscrolling is done in dragTimerFired:
345 if (!isAutoscrolling) {
346 NSMutableData *data = [NSMutableData data];
348 [data appendBytes:&row length:sizeof(int)];
349 [data appendBytes:&col length:sizeof(int)];
350 [data appendBytes:&flags length:sizeof(int)];
352 [[self vimController] sendMessage:MouseDraggedMsgID data:data wait:NO];
356 dragRow = row; dragColumn = col; dragFlags = flags;
358 [self startDragTimerWithInterval:.5];
363 - (void)rightMouseDragged:(NSEvent *)event
365 [self mouseDragged:event];
368 - (void)otherMouseDragged:(NSEvent *)event
370 [self mouseDragged:event];
373 - (void)mouseMoved:(NSEvent *)event
375 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
378 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
380 if (![self convertPoint:pt toRow:&row column:&col])
383 // HACK! It seems impossible to get the tracking rects set up before the
384 // view is visible, which means that the first mouseEntered: or
385 // mouseExited: events are never received. This forces us to check if the
386 // mouseMoved: event really happened over the text.
388 [ts getMaxRows:&rows columns:&cols];
389 if (row >= 0 && row < rows && col >= 0 && col < cols) {
390 NSMutableData *data = [NSMutableData data];
392 [data appendBytes:&row length:sizeof(int)];
393 [data appendBytes:&col length:sizeof(int)];
395 [[self vimController] sendMessage:MouseMovedMsgID data:data wait:NO];
399 - (void)mouseEntered:(NSEvent *)event
401 //NSLog(@"%s", _cmd);
403 // NOTE: This event is received even when the window is not key; thus we
404 // have to take care not to enable mouse moved events unless our window is
406 if ([[self window] isKeyWindow])
407 [[self window] setAcceptsMouseMovedEvents:YES];
410 - (void)mouseExited:(NSEvent *)event
412 //NSLog(@"%s", _cmd);
414 [[self window] setAcceptsMouseMovedEvents:NO];
416 // NOTE: This event is received even when the window is not key; if the
417 // mouse shape is set when our window is not key, the hollow (unfocused)
418 // cursor will become a block (focused) cursor.
419 if ([[self window] isKeyWindow]) {
421 NSMutableData *data = [NSMutableData data];
422 [data appendBytes:&shape length:sizeof(int)];
423 [[self vimController] sendMessage:SetMouseShapeMsgID data:data wait:NO];
427 - (void)setFrame:(NSRect)frame
429 //NSLog(@"%s", _cmd);
431 // When the frame changes we also need to update the tracking rect.
432 [super setFrame:frame];
433 [self removeTrackingRect:trackingRectTag];
434 trackingRectTag = [self addTrackingRect:[self trackingRect] owner:self
435 userData:NULL assumeInside:YES];
438 - (void)viewDidMoveToWindow
440 //NSLog(@"%s (window=%@)", _cmd, [self window]);
442 // Set a tracking rect which covers the text.
443 // NOTE: While the mouse cursor is in this rect the view will receive
444 // 'mouseMoved:' events so that Vim can take care of updating the mouse
447 [[self window] setAcceptsMouseMovedEvents:YES];
448 trackingRectTag = [self addTrackingRect:[self trackingRect] owner:self
449 userData:NULL assumeInside:YES];
453 - (void)viewWillMoveToWindow:(NSWindow *)newWindow
455 //NSLog(@"%s%@", _cmd, newWindow);
457 // Remove tracking rect if view moves or is removed.
458 if ([self window] && trackingRectTag) {
459 [self removeTrackingRect:trackingRectTag];
464 - (NSMenu*)menuForEvent:(NSEvent *)event
466 // HACK! Return nil to disable NSTextView's popup menus (Vim provides its
467 // own). Called when user Ctrl-clicks in the view (this is already handled
468 // in rightMouseDown:).
472 - (NSArray *)acceptableDragTypes
474 return [NSArray arrayWithObjects:NSFilenamesPboardType,
475 NSStringPboardType, nil];
478 - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
480 NSPasteboard *pboard = [sender draggingPasteboard];
482 if ([[pboard types] containsObject:NSStringPboardType]) {
483 NSString *string = [pboard stringForType:NSStringPboardType];
484 [[self vimController] dropString:string];
486 } else if ([[pboard types] containsObject:NSFilenamesPboardType]) {
487 NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
488 [[self vimController] dropFiles:files];
495 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
497 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
498 NSPasteboard *pboard = [sender draggingPasteboard];
500 if ( [[pboard types] containsObject:NSFilenamesPboardType]
501 && (sourceDragMask & NSDragOperationCopy) )
502 return NSDragOperationCopy;
503 if ( [[pboard types] containsObject:NSStringPboardType]
504 && (sourceDragMask & NSDragOperationCopy) )
505 return NSDragOperationCopy;
507 return NSDragOperationNone;
510 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
512 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
513 NSPasteboard *pboard = [sender draggingPasteboard];
515 if ( [[pboard types] containsObject:NSFilenamesPboardType]
516 && (sourceDragMask & NSDragOperationCopy) )
517 return NSDragOperationCopy;
518 if ( [[pboard types] containsObject:NSStringPboardType]
519 && (sourceDragMask & NSDragOperationCopy) )
520 return NSDragOperationCopy;
522 return NSDragOperationNone;
525 - (void)changeFont:(id)sender
527 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
530 NSFont *oldFont = [ts font];
531 NSFont *newFont = [sender convertFont:oldFont];
534 NSString *name = [newFont displayName];
535 unsigned len = [name lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
537 NSMutableData *data = [NSMutableData data];
538 float pointSize = [newFont pointSize];
540 [data appendBytes:&pointSize length:sizeof(float)];
542 ++len; // include NUL byte
543 [data appendBytes:&len length:sizeof(unsigned)];
544 [data appendBytes:[name UTF8String] length:len];
546 [[self vimController] sendMessage:SetFontMsgID data:data wait:NO];
551 - (void)resetCursorRects
553 // No need to set up cursor rects since Vim handles cursor changes.
556 - (void)updateFontPanel
558 // The font panel is updated whenever the font is set.
566 @implementation MMTextView (Private)
568 - (BOOL)convertPoint:(NSPoint)point toRow:(int *)row column:(int *)column
571 NSLayoutManager *lm = [self layoutManager];
572 NSTextContainer *tc = [self textContainer];
573 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
575 if (!(lm && tc && ts))
578 unsigned glyphIdx = [lm glyphIndexForPoint:point inTextContainer:tc];
579 unsigned charIdx = [lm characterIndexForGlyphAtIndex:glyphIdx];
581 int mod = [ts maxColumns] + 1;
583 if (row) *row = (int)(charIdx / mod);
584 if (column) *column = (int)(charIdx % mod);
586 NSLog(@"convertPoint:%@ toRow:%d column:%d", NSStringFromPoint(point),
591 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
592 NSSize cellSize = [ts cellSize];
593 if (!(cellSize.width > 0 && cellSize.height > 0))
595 NSPoint origin = [self textContainerOrigin];
597 if (row) *row = floor((point.y-origin.y-1) / cellSize.height);
598 if (column) *column = floor((point.x-origin.x-1) / cellSize.width);
600 //NSLog(@"convertPoint:%@ toRow:%d column:%d", NSStringFromPoint(point),
607 - (NSRect)trackingRect
609 NSRect rect = [self frame];
610 NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
611 int left = [ud integerForKey:MMTextInsetLeftKey];
612 int top = [ud integerForKey:MMTextInsetTopKey];
613 int right = [ud integerForKey:MMTextInsetRightKey];
614 int bot = [ud integerForKey:MMTextInsetBottomKey];
616 rect.origin.x = left;
618 rect.size.width -= left + right - 1;
619 rect.size.height -= top + bot - 1;
624 - (void)dispatchKeyEvent:(NSEvent *)event
626 // Only handle the command if it came from a keyDown event
627 if ([event type] != NSKeyDown)
630 NSString *chars = [event characters];
631 NSString *imchars = [event charactersIgnoringModifiers];
632 unichar c = [chars characterAtIndex:0];
633 unichar imc = [imchars characterAtIndex:0];
635 const char *bytes = 0;
637 //NSLog(@"%s chars=0x%x unmodchars=0x%x", _cmd, c, imc);
639 if (' ' == imc && 0xa0 != c) {
640 // HACK! The AppKit turns <C-Space> into <C-@> which is not standard
641 // Vim behaviour, so bypass this problem. (0xa0 is <M-Space>, which
642 // should be passed on as is.)
643 len = [imchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
644 bytes = [imchars UTF8String];
645 } else if (imc == c && '2' == c) {
646 // HACK! Translate Ctrl+2 to <C-@>.
647 static char ctrl_at = 0;
648 len = 1; bytes = &ctrl_at;
649 } else if (imc == c && '6' == c) {
650 // HACK! Translate Ctrl+6 to <C-^>.
651 static char ctrl_hat = 0x1e;
652 len = 1; bytes = &ctrl_hat;
653 } else if (c == 0x19 && imc == 0x19) {
654 // HACK! AppKit turns back tab into Ctrl-Y, so we need to handle it
655 // separately (else Ctrl-Y doesn't work).
656 static char back_tab[2] = { 'k', 'B' };
657 len = 2; bytes = back_tab;
658 } else if (c == 0x3 && imc == 0x3) {
659 // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
660 // handle it separately (else Ctrl-C doesn't work).
661 static char enter[2] = { 'K', 'A' };
662 len = 2; bytes = enter;
664 len = [chars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
665 bytes = [chars UTF8String];
668 if (len > 0 && bytes) {
669 NSMutableData *data = [NSMutableData data];
670 int flags = [event modifierFlags];
672 [data appendBytes:&flags length:sizeof(int)];
673 [data appendBytes:&len length:sizeof(int)];
674 [data appendBytes:bytes length:len];
676 // TODO: Support 'mousehide' (check p_mh)
677 [NSCursor setHiddenUntilMouseMoves:YES];
679 //NSLog(@"%s len=%d bytes=0x%x", _cmd, len, bytes[0]);
680 [[self vimController] sendMessage:KeyDownMsgID data:data wait:NO];
684 - (MMVimController *)vimController
686 id windowController = [[self window] windowController];
688 // TODO: Make sure 'windowController' is a MMWindowController before type
690 return [(MMWindowController*)windowController vimController];
693 - (void)startDragTimerWithInterval:(NSTimeInterval)t
695 [NSTimer scheduledTimerWithTimeInterval:t target:self
696 selector:@selector(dragTimerFired:)
697 userInfo:nil repeats:NO];
700 - (void)dragTimerFired:(NSTimer *)timer
702 // TODO: Autoscroll in horizontal direction?
703 static unsigned tick = 1;
704 MMTextStorage *ts = (MMTextStorage *)[self textStorage];
706 isAutoscrolling = NO;
708 if (isDragging && ts && (dragRow < 0 || dragRow >= [ts maxRows])) {
709 // HACK! If the mouse cursor is outside the text area, then send a
710 // dragged event. However, if row&col hasn't changed since the last
711 // dragged event, Vim won't do anything (see gui_send_mouse_event()).
712 // Thus we fiddle with the column to make sure something happens.
713 int col = dragColumn + (dragRow < 0 ? -(tick % 2) : +(tick % 2));
714 NSMutableData *data = [NSMutableData data];
716 [data appendBytes:&dragRow length:sizeof(int)];
717 [data appendBytes:&col length:sizeof(int)];
718 [data appendBytes:&dragFlags length:sizeof(int)];
720 [[self vimController] sendMessage:MouseDraggedMsgID data:data wait:NO];
722 isAutoscrolling = YES;
726 // Compute timer interval depending on how far away the mouse cursor is
727 // from the text view.
728 NSRect rect = [self trackingRect];
730 if (dragPoint.y < rect.origin.y) dy = rect.origin.y - dragPoint.y;
731 else if (dragPoint.y > NSMaxY(rect)) dy = dragPoint.y - NSMaxY(rect);
732 if (dy > MMDragAreaSize) dy = MMDragAreaSize;
734 NSTimeInterval t = MMDragTimerMaxInterval -
735 dy*(MMDragTimerMaxInterval-MMDragTimerMinInterval)/MMDragAreaSize;
737 [self startDragTimerWithInterval:t];
743 @end // MMTextView (Private)