1 /* vi:set ts=8 sts=4 sw=4 ft=objc:
3 * VIM - Vi IMproved by Bram Moolenaar
4 * MacVim GUI port by Bjorn Winckler
6 * Do ":help uganda" in Vim to read copying and usage conditions.
7 * Do ":help credits" in Vim to see a list of people who contributed.
8 * See README.txt for an overview of the Vim source code.
13 * Contains code shared between the different text renderers. Unfortunately it
14 * is not possible to let the text renderers inherit from this class since
15 * MMTextView needs to inherit from NSTextView whereas MMAtsuiTextView needs to
16 * inherit from NSView.
19 #import "MMTextView.h"
20 #import "MMTextViewHelper.h"
21 #import "MMVimController.h"
22 #import "MMWindowController.h"
23 #import "Miscellaneous.h"
26 static char MMKeypadEnter[2] = { 'K', 'A' };
27 static NSString *MMKeypadEnterString = @"KA";
29 // The max/min drag timer interval in seconds
30 static NSTimeInterval MMDragTimerMaxInterval = 0.3;
31 static NSTimeInterval MMDragTimerMinInterval = 0.01;
33 // The number of pixels in which the drag timer interval changes
34 static float MMDragAreaSize = 73.0f;
37 @interface MMTextViewHelper (Private)
38 - (MMWindowController *)windowController;
39 - (MMVimController *)vimController;
40 - (void)dispatchKeyEvent:(NSEvent *)event;
41 - (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags
42 isARepeat:(BOOL)isARepeat;
43 - (void)hideMouseCursor;
44 - (void)startDragTimerWithInterval:(NSTimeInterval)t;
45 - (void)dragTimerFired:(NSTimer *)timer;
47 - (NSRect)trackingRect;
51 @implementation MMTextViewHelper
55 [insertionPointColor release]; insertionPointColor = nil;
56 [markedText release]; markedText = nil;
57 [markedTextAttributes release]; markedTextAttributes = nil;
62 - (void)setTextView:(id)view
64 // Only keep a weak reference to owning text view.
68 - (void)setInsertionPointColor:(NSColor *)color
70 if (color != insertionPointColor) {
71 [insertionPointColor release];
72 insertionPointColor = [color retain];
76 - (NSColor *)insertionPointColor
78 return insertionPointColor;
81 - (void)keyDown:(NSEvent *)event
83 //NSLog(@"%s %@", _cmd, event);
84 // HACK! If control modifier is held, don't pass the event along to
85 // interpretKeyEvents: since some keys are bound to multiple commands which
86 // means doCommandBySelector: is called several times. Do the same for
87 // Alt+Function key presses (Alt+Up and Alt+Down are bound to two
88 // commands). This hack may break input management, but unless we can
89 // figure out a way to disable key bindings there seems little else to do.
91 // TODO: Figure out a way to disable Cocoa key bindings entirely, without
92 // affecting input management.
94 // When the Input Method is activated, some special key inputs
95 // should be treated as key inputs for Input Method.
96 if ([textView hasMarkedText]) {
97 [textView interpretKeyEvents:[NSArray arrayWithObject:event]];
98 [textView setNeedsDisplay:YES];
102 int flags = [event modifierFlags];
103 if ((flags & NSControlKeyMask) ||
104 ((flags & NSAlternateKeyMask) && (flags & NSFunctionKeyMask))) {
105 BOOL unmodIsPrintable = YES;
106 NSString *unmod = [event charactersIgnoringModifiers];
107 if (unmod && [unmod length] > 0 && [unmod characterAtIndex:0] < 0x20)
108 unmodIsPrintable = NO;
110 NSString *chars = [event characters];
111 if ([chars length] == 1 && [chars characterAtIndex:0] < 0x20
112 && unmodIsPrintable) {
113 // HACK! Send unprintable characters (such as C-@, C-[, C-\, C-],
114 // C-^, C-_) as normal text to be added to the Vim input buffer.
115 // This must be done in order for the backend to be able to
116 // separate e.g. Ctrl-i and Ctrl-tab.
117 [self insertText:chars];
119 [self dispatchKeyEvent:event];
121 } else if ((flags & NSAlternateKeyMask) &&
122 [[[[self vimController] vimState] objectForKey:@"p_mmta"]
124 // If the 'macmeta' option is set, then send Alt+key presses directly
125 // to Vim without interpreting the key press.
126 NSString *unmod = [event charactersIgnoringModifiers];
127 int len = [unmod lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
128 const char *bytes = [unmod UTF8String];
130 [self sendKeyDown:bytes length:len modifiers:flags
131 isARepeat:[event isARepeat]];
133 [textView interpretKeyEvents:[NSArray arrayWithObject:event]];
137 - (void)insertText:(id)string
139 //NSLog(@"%s %@", _cmd, string);
140 // NOTE! This method is called for normal key presses but also for
141 // Option-key presses --- even when Ctrl is held as well as Option. When
142 // Ctrl is held, the AppKit translates the character to a Ctrl+key stroke,
143 // so 'string' need not be a printable character! In this case it still
144 // works to pass 'string' on to Vim as a printable character (since
145 // modifiers are already included and should not be added to the input
146 // buffer using CSI, K_MODIFIER).
148 if ([textView hasMarkedText]) {
149 [textView unmarkText];
152 NSEvent *event = [NSApp currentEvent];
154 // HACK! In order to be able to bind to <S-Space>, <S-M-Tab>, etc. we have
155 // to watch for them here.
156 if ([event type] == NSKeyDown
157 && [[event charactersIgnoringModifiers] length] > 0
158 && [event modifierFlags]
159 & (NSShiftKeyMask|NSControlKeyMask|NSAlternateKeyMask)) {
160 unichar c = [[event charactersIgnoringModifiers] characterAtIndex:0];
162 // <S-M-Tab> translates to 0x19
163 if (' ' == c || 0x19 == c) {
164 [self dispatchKeyEvent:event];
169 [self hideMouseCursor];
171 // NOTE: 'string' is either an NSString or an NSAttributedString. Since we
172 // do not support attributes, simply pass the corresponding NSString in the
174 if ([string isKindOfClass:[NSAttributedString class]])
175 string = [string string];
177 //NSLog(@"send InsertTextMsgID: %@", string);
179 NSMutableData *data = [NSMutableData data];
180 int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
181 int flags = [event modifierFlags] & 0xffff0000U;
182 if ([event type] == NSKeyDown && [event isARepeat])
185 [data appendBytes:&flags length:sizeof(int)];
186 [data appendBytes:&len length:sizeof(int)];
187 [data appendBytes:[string UTF8String] length:len];
189 [[self vimController] sendMessage:InsertTextMsgID data:data];
192 - (void)doCommandBySelector:(SEL)selector
194 //NSLog(@"%s %@", _cmd, NSStringFromSelector(selector));
195 // By ignoring the selector we effectively disable the key binding
196 // mechanism of Cocoa. Hopefully this is what the user will expect
197 // (pressing Ctrl+P would otherwise result in moveUp: instead of previous
200 // We usually end up here if the user pressed Ctrl+key (but not
203 NSEvent *event = [NSApp currentEvent];
205 if (selector == @selector(cancelOperation:)
206 || selector == @selector(insertNewline:)) {
207 // HACK! If there was marked text which got abandoned as a result of
208 // hitting escape or enter, then 'insertText:' is called with the
209 // abandoned text but '[event characters]' includes the abandoned text
210 // as well. Since 'dispatchKeyEvent:' looks at '[event characters]' we
211 // must intercept these keys here or the abandonded text gets inserted
213 NSString *key = [event charactersIgnoringModifiers];
214 const char *chars = [key UTF8String];
215 int len = [key lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
217 if (0x3 == chars[0]) {
218 // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
219 // handle it separately (else Ctrl-C doesn't work).
220 len = sizeof(MMKeypadEnter)/sizeof(MMKeypadEnter[0]);
221 chars = MMKeypadEnter;
224 [self sendKeyDown:chars length:len modifiers:[event modifierFlags]
225 isARepeat:[event isARepeat]];
227 [self dispatchKeyEvent:event];
231 - (BOOL)performKeyEquivalent:(NSEvent *)event
233 //NSLog(@"%s %@", _cmd, event);
234 // Called for Cmd+key keystrokes, function keys, arrow keys, page
235 // up/down, home, end.
237 // NOTE: This message cannot be ignored since Cmd+letter keys never are
238 // passed to keyDown:. It seems as if the main menu consumes Cmd-key
239 // strokes, unless the key is a function key.
241 // NOTE: If the event that triggered this method represents a function key
242 // down then we do nothing, otherwise the input method never gets the key
243 // stroke (some input methods use e.g. arrow keys). The function key down
244 // event will still reach Vim though (via keyDown:). The exceptions to
245 // this rule are: PageUp/PageDown (keycode 116/121).
246 int flags = [event modifierFlags] & 0xffff0000U;
247 if ([event type] != NSKeyDown || flags & NSFunctionKeyMask
248 && !(116 == [event keyCode] || 121 == [event keyCode]))
251 // HACK! KeyCode 50 represent the key which switches between windows
252 // within an application (like Cmd+Tab is used to switch between
253 // applications). Return NO here, else the window switching does not work.
254 if ([event keyCode] == 50)
257 // HACK! Let the main menu try to handle any key down event, before
258 // passing it on to vim, otherwise key equivalents for menus will
259 // effectively be disabled.
260 if ([[NSApp mainMenu] performKeyEquivalent:event])
263 // HACK! On Leopard Ctrl-key events end up here instead of keyDown:.
264 if (flags & NSControlKeyMask) {
265 [self keyDown:event];
269 // HACK! Don't handle Cmd-? or the "Help" menu does not work on Leopard.
270 NSString *unmodchars = [event charactersIgnoringModifiers];
271 if ([unmodchars isEqual:@"?"])
274 // Cmd-. is hard-wired to send SIGINT unlike Ctrl-C which is just another
275 // key press which Vim has to interpret. This means that Cmd-. always
276 // works to interrupt a Vim process whereas Ctrl-C can suffer from problems
277 // such as dropped DO messages (or if Vim is stuck in a loop without
278 // checking for keyboard input).
279 if ((flags & NSDeviceIndependentModifierFlagsMask) == NSCommandKeyMask &&
280 [unmodchars isEqual:@"."]) {
281 kill([[self vimController] pid], SIGINT);
285 //NSLog(@"%s%@", _cmd, event);
287 NSString *chars = [event characters];
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 if ([event isARepeat])
311 [data appendBytes:&flags length:sizeof(int)];
312 [data appendBytes:&len length:sizeof(int)];
313 [data appendBytes:[unmodchars UTF8String] length:len];
315 [[self vimController] sendMessage:CmdKeyMsgID data:data];
320 - (void)scrollWheel:(NSEvent *)event
322 if ([event deltaY] == 0)
326 NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
327 if ([textView convertPoint:pt toRow:&row column:&col]) {
328 int flags = [event modifierFlags];
329 float dy = [event deltaY];
330 NSMutableData *data = [NSMutableData data];
332 [data appendBytes:&row length:sizeof(int)];
333 [data appendBytes:&col length:sizeof(int)];
334 [data appendBytes:&flags length:sizeof(int)];
335 [data appendBytes:&dy length:sizeof(float)];
337 [[self vimController] sendMessage:ScrollWheelMsgID data:data];
341 - (void)mouseDown:(NSEvent *)event
344 NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
345 if (![textView convertPoint:pt toRow:&row column:&col])
348 int button = [event buttonNumber];
349 int flags = [event modifierFlags];
350 int count = [event clickCount];
351 NSMutableData *data = [NSMutableData data];
353 // If desired, intepret Ctrl-Click as a right mouse click.
354 BOOL translateCtrlClick = [[NSUserDefaults standardUserDefaults]
355 boolForKey:MMTranslateCtrlClickKey];
356 flags = flags & NSDeviceIndependentModifierFlagsMask;
357 if (translateCtrlClick && button == 0 &&
358 (flags == NSControlKeyMask ||
359 flags == (NSControlKeyMask|NSAlphaShiftKeyMask))) {
361 flags &= ~NSControlKeyMask;
364 [data appendBytes:&row length:sizeof(int)];
365 [data appendBytes:&col length:sizeof(int)];
366 [data appendBytes:&button length:sizeof(int)];
367 [data appendBytes:&flags length:sizeof(int)];
368 [data appendBytes:&count length:sizeof(int)];
370 [[self vimController] sendMessage:MouseDownMsgID data:data];
373 - (void)mouseUp:(NSEvent *)event
376 NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
377 if (![textView convertPoint:pt toRow:&row column:&col])
380 int flags = [event modifierFlags];
381 NSMutableData *data = [NSMutableData data];
383 [data appendBytes:&row length:sizeof(int)];
384 [data appendBytes:&col length:sizeof(int)];
385 [data appendBytes:&flags length:sizeof(int)];
387 [[self vimController] sendMessage:MouseUpMsgID data:data];
392 - (void)mouseDragged:(NSEvent *)event
394 int flags = [event modifierFlags];
396 NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
397 if (![textView convertPoint:pt toRow:&row column:&col])
400 // Autoscrolling is done in dragTimerFired:
401 if (!isAutoscrolling) {
402 NSMutableData *data = [NSMutableData data];
404 [data appendBytes:&row length:sizeof(int)];
405 [data appendBytes:&col length:sizeof(int)];
406 [data appendBytes:&flags length:sizeof(int)];
408 [[self vimController] sendMessage:MouseDraggedMsgID data:data];
417 [self startDragTimerWithInterval:.5];
422 - (void)mouseMoved:(NSEvent *)event
424 // HACK! NSTextView has a nasty habit of resetting the cursor to the
425 // default I-beam cursor at random moments. The only reliable way we know
426 // of to work around this is to set the cursor each time the mouse moves.
429 NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
431 if (![textView convertPoint:pt toRow:&row column:&col])
434 // HACK! It seems impossible to get the tracking rects set up before the
435 // view is visible, which means that the first mouseEntered: or
436 // mouseExited: events are never received. This forces us to check if the
437 // mouseMoved: event really happened over the text.
439 [textView getMaxRows:&rows columns:&cols];
440 if (row >= 0 && row < rows && col >= 0 && col < cols) {
441 NSMutableData *data = [NSMutableData data];
443 [data appendBytes:&row length:sizeof(int)];
444 [data appendBytes:&col length:sizeof(int)];
446 [[self vimController] sendMessage:MouseMovedMsgID data:data];
448 //NSLog(@"Moved %d %d\n", col, row);
452 - (void)mouseEntered:(NSEvent *)event
454 //NSLog(@"%s", _cmd);
456 // NOTE: This event is received even when the window is not key; thus we
457 // have to take care not to enable mouse moved events unless our window is
459 if ([[textView window] isKeyWindow]) {
460 [[textView window] setAcceptsMouseMovedEvents:YES];
464 - (void)mouseExited:(NSEvent *)event
466 //NSLog(@"%s", _cmd);
468 [[textView window] setAcceptsMouseMovedEvents:NO];
470 // NOTE: This event is received even when the window is not key; if the
471 // mouse shape is set when our window is not key, the hollow (unfocused)
472 // cursor will become a block (focused) cursor.
473 if ([[textView window] isKeyWindow]) {
475 NSMutableData *data = [NSMutableData data];
476 [data appendBytes:&shape length:sizeof(int)];
477 [[self vimController] sendMessage:SetMouseShapeMsgID data:data];
481 - (void)setFrame:(NSRect)frame
483 //NSLog(@"%s", _cmd);
485 // When the frame changes we also need to update the tracking rect.
486 [textView removeTrackingRect:trackingRectTag];
487 trackingRectTag = [textView addTrackingRect:[self trackingRect]
493 - (void)viewDidMoveToWindow
495 //NSLog(@"%s (window=%@)", _cmd, [self window]);
497 // Set a tracking rect which covers the text.
498 // NOTE: While the mouse cursor is in this rect the view will receive
499 // 'mouseMoved:' events so that Vim can take care of updating the mouse
501 if ([textView window]) {
502 [[textView window] setAcceptsMouseMovedEvents:YES];
503 trackingRectTag = [textView addTrackingRect:[self trackingRect]
510 - (void)viewWillMoveToWindow:(NSWindow *)newWindow
512 //NSLog(@"%s%@", _cmd, newWindow);
514 // Remove tracking rect if view moves or is removed.
515 if ([textView window] && trackingRectTag) {
516 [textView removeTrackingRect:trackingRectTag];
521 - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
523 NSPasteboard *pboard = [sender draggingPasteboard];
525 if ([[pboard types] containsObject:NSStringPboardType]) {
526 NSString *string = [pboard stringForType:NSStringPboardType];
527 [[self vimController] dropString:string];
529 } else if ([[pboard types] containsObject:NSFilenamesPboardType]) {
530 NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
531 [[self vimController] dropFiles:files forceOpen:NO];
538 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
540 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
541 NSPasteboard *pboard = [sender draggingPasteboard];
543 if ( [[pboard types] containsObject:NSFilenamesPboardType]
544 && (sourceDragMask & NSDragOperationCopy) )
545 return NSDragOperationCopy;
546 if ( [[pboard types] containsObject:NSStringPboardType]
547 && (sourceDragMask & NSDragOperationCopy) )
548 return NSDragOperationCopy;
550 return NSDragOperationNone;
553 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
555 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
556 NSPasteboard *pboard = [sender draggingPasteboard];
558 if ( [[pboard types] containsObject:NSFilenamesPboardType]
559 && (sourceDragMask & NSDragOperationCopy) )
560 return NSDragOperationCopy;
561 if ( [[pboard types] containsObject:NSStringPboardType]
562 && (sourceDragMask & NSDragOperationCopy) )
563 return NSDragOperationCopy;
565 return NSDragOperationNone;
568 - (void)setMouseShape:(int)shape
574 - (BOOL)hasMarkedText
576 return markedRange.length > 0 ? YES : NO;
579 - (NSRange)markedRange
581 if ([self hasMarkedText])
584 return NSMakeRange(NSNotFound, 0);
587 - (NSDictionary *)markedTextAttributes
589 return markedTextAttributes;
592 - (void)setMarkedTextAttributes:(NSDictionary *)attr
594 if (attr != markedTextAttributes) {
595 [markedTextAttributes release];
596 markedTextAttributes = [attr retain];
600 - (void)setMarkedText:(id)text selectedRange:(NSRange)range
604 if (!(text && [text length] > 0))
607 // HACK! Determine if the marked text is wide or normal width. This seems
608 // to always use 'wide' when there are both wide and normal width
610 NSString *string = text;
611 NSFont *theFont = [textView font];
612 if ([text isKindOfClass:[NSAttributedString class]]) {
613 theFont = [textView fontWide];
614 string = [text string];
617 // TODO: Use special colors for marked text.
618 [self setMarkedTextAttributes:
619 [NSDictionary dictionaryWithObjectsAndKeys:
620 theFont, NSFontAttributeName,
621 [textView defaultBackgroundColor], NSBackgroundColorAttributeName,
622 [textView defaultForegroundColor], NSForegroundColorAttributeName,
625 markedText = [[NSMutableAttributedString alloc]
626 initWithString:string
627 attributes:[self markedTextAttributes]];
629 markedRange = NSMakeRange(0, [markedText length]);
630 if (markedRange.length) {
631 [markedText addAttribute:NSUnderlineStyleAttributeName
632 value:[NSNumber numberWithInt:1]
637 [markedText addAttribute:NSUnderlineStyleAttributeName
638 value:[NSNumber numberWithInt:2]
642 [textView setNeedsDisplay:YES];
647 imRange = NSMakeRange(0, 0);
648 markedRange = NSMakeRange(NSNotFound, 0);
649 [markedText release];
653 - (NSMutableAttributedString *)markedText
658 - (void)setPreEditRow:(int)row column:(int)col
671 return preEditColumn;
674 - (void)setImRange:(NSRange)range
684 - (void)setMarkedRange:(NSRange)range
689 - (NSRect)firstRectForCharacterRange:(NSRange)range
691 // This method is called when the input manager wants to pop up an
692 // auxiliary window. The position where this should be is controlled by
693 // Vim by sending SetPreEditPositionMsgID so compute a position based on
694 // the pre-edit (row,column) pair.
695 int col = preEditColumn;
696 int row = preEditRow + 1;
698 NSFont *theFont = [[textView markedTextAttributes]
699 valueForKey:NSFontAttributeName];
700 if (theFont == [textView fontWide]) {
701 col += imRange.location * 2;
702 if (col >= [textView maxColumns] - 1) {
703 row += (col / [textView maxColumns]);
704 col = col % 2 ? col % [textView maxColumns] + 1 :
705 col % [textView maxColumns];
708 col += imRange.location;
709 if (col >= [textView maxColumns]) {
710 row += (col / [textView maxColumns]);
711 col = col % [textView maxColumns];
715 NSRect rect = [textView rectForRow:row
718 numColumns:range.length];
720 rect.origin = [textView convertPoint:rect.origin toView:nil];
721 rect.origin = [[textView window] convertBaseToScreen:rect.origin];
726 @end // MMTextViewHelper
731 @implementation MMTextViewHelper (Private)
733 - (MMWindowController *)windowController
735 id windowController = [[textView window] windowController];
736 if ([windowController isKindOfClass:[MMWindowController class]])
737 return (MMWindowController*)windowController;
741 - (MMVimController *)vimController
743 return [[self windowController] vimController];
746 - (void)dispatchKeyEvent:(NSEvent *)event
748 // Only handle the command if it came from a keyDown event
749 if ([event type] != NSKeyDown)
752 NSString *chars = [event characters];
753 NSString *unmodchars = [event charactersIgnoringModifiers];
754 unichar c = [chars characterAtIndex:0];
755 unichar imc = [unmodchars length] > 0 ? [unmodchars characterAtIndex:0] : 0;
757 const char *bytes = 0;
758 int mods = [event modifierFlags];
760 //NSLog(@"%s chars[0]=0x%x unmodchars[0]=0x%x (chars=%@ unmodchars=%@)",
761 // _cmd, c, imc, chars, unmodchars);
763 if (' ' == imc && 0xa0 != c) {
764 // HACK! The AppKit turns <C-Space> into <C-@> which is not standard
765 // Vim behaviour, so bypass this problem. (0xa0 is <M-Space>, which
766 // should be passed on as is.)
767 len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
768 bytes = [unmodchars UTF8String];
769 } else if (imc == c && '2' == c) {
770 // HACK! Translate Ctrl+2 to <C-@>.
771 static char ctrl_at = 0;
772 len = 1; bytes = &ctrl_at;
773 } else if (imc == c && '6' == c) {
774 // HACK! Translate Ctrl+6 to <C-^>.
775 static char ctrl_hat = 0x1e;
776 len = 1; bytes = &ctrl_hat;
777 } else if (c == 0x19 && imc == 0x19) {
778 // HACK! AppKit turns back tab into Ctrl-Y, so we need to handle it
779 // separately (else Ctrl-Y doesn't work).
780 static char tab = 0x9;
781 len = 1; bytes = &tab; mods |= NSShiftKeyMask;
783 len = [chars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
784 bytes = [chars UTF8String];
787 [self sendKeyDown:bytes length:len modifiers:mods
788 isARepeat:[event isARepeat]];
791 - (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags
792 isARepeat:(BOOL)isARepeat
794 if (chars && len > 0) {
795 NSMutableData *data = [NSMutableData data];
797 // The low 16 bits are not used for modifier flags by NSEvent. Use
798 // these bits for custom flags.
803 [data appendBytes:&flags length:sizeof(int)];
804 [data appendBytes:&len length:sizeof(int)];
805 [data appendBytes:chars length:len];
807 [self hideMouseCursor];
809 //NSLog(@"%s len=%d chars=0x%x", _cmd, len, chars[0]);
810 [[self vimController] sendMessage:KeyDownMsgID data:data];
814 - (void)hideMouseCursor
816 // Check 'mousehide' option
817 id mh = [[[self vimController] vimState] objectForKey:@"p_mh"];
818 if (mh && ![mh boolValue])
819 [NSCursor setHiddenUntilMouseMoves:NO];
821 [NSCursor setHiddenUntilMouseMoves:YES];
824 - (void)startDragTimerWithInterval:(NSTimeInterval)t
826 [NSTimer scheduledTimerWithTimeInterval:t target:self
827 selector:@selector(dragTimerFired:)
828 userInfo:nil repeats:NO];
831 - (void)dragTimerFired:(NSTimer *)timer
833 // TODO: Autoscroll in horizontal direction?
834 static unsigned tick = 1;
836 isAutoscrolling = NO;
838 if (isDragging && (dragRow < 0 || dragRow >= [textView maxRows])) {
839 // HACK! If the mouse cursor is outside the text area, then send a
840 // dragged event. However, if row&col hasn't changed since the last
841 // dragged event, Vim won't do anything (see gui_send_mouse_event()).
842 // Thus we fiddle with the column to make sure something happens.
843 int col = dragColumn + (dragRow < 0 ? -(tick % 2) : +(tick % 2));
844 NSMutableData *data = [NSMutableData data];
846 [data appendBytes:&dragRow length:sizeof(int)];
847 [data appendBytes:&col length:sizeof(int)];
848 [data appendBytes:&dragFlags length:sizeof(int)];
850 [[self vimController] sendMessage:MouseDraggedMsgID data:data];
852 isAutoscrolling = YES;
856 // Compute timer interval depending on how far away the mouse cursor is
857 // from the text view.
858 NSRect rect = [self trackingRect];
860 if (dragPoint.y < rect.origin.y) dy = rect.origin.y - dragPoint.y;
861 else if (dragPoint.y > NSMaxY(rect)) dy = dragPoint.y - NSMaxY(rect);
862 if (dy > MMDragAreaSize) dy = MMDragAreaSize;
864 NSTimeInterval t = MMDragTimerMaxInterval -
865 dy*(MMDragTimerMaxInterval-MMDragTimerMinInterval)/MMDragAreaSize;
867 [self startDragTimerWithInterval:t];
875 static NSCursor *customIbeamCursor = nil;
877 if (!customIbeamCursor) {
878 // Use a custom Ibeam cursor that has better contrast against dark
880 // TODO: Is the hotspot ok?
881 NSImage *ibeamImage = [NSImage imageNamed:@"ibeam"];
883 NSSize size = [ibeamImage size];
884 NSPoint hotSpot = { size.width*.5f, size.height*.5f };
886 customIbeamCursor = [[NSCursor alloc]
887 initWithImage:ibeamImage hotSpot:hotSpot];
889 if (!customIbeamCursor) {
890 NSLog(@"WARNING: Failed to load custom Ibeam cursor");
891 customIbeamCursor = [NSCursor IBeamCursor];
895 // This switch should match mshape_names[] in misc2.c.
897 // TODO: Add missing cursor shapes.
898 switch (mouseShape) {
899 case 2: [customIbeamCursor set]; break;
900 case 3: case 4: [[NSCursor resizeUpDownCursor] set]; break;
901 case 5: case 6: [[NSCursor resizeLeftRightCursor] set]; break;
902 case 9: [[NSCursor crosshairCursor] set]; break;
903 case 10: [[NSCursor pointingHandCursor] set]; break;
904 case 11: [[NSCursor openHandCursor] set]; break;
906 [[NSCursor arrowCursor] set]; break;
909 // Shape 1 indicates that the mouse cursor should be hidden.
911 [NSCursor setHiddenUntilMouseMoves:YES];
914 - (NSRect)trackingRect
916 NSRect rect = [textView frame];
917 NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
918 int left = [ud integerForKey:MMTextInsetLeftKey];
919 int top = [ud integerForKey:MMTextInsetTopKey];
920 int right = [ud integerForKey:MMTextInsetRightKey];
921 int bot = [ud integerForKey:MMTextInsetBottomKey];
923 rect.origin.x = left;
925 rect.size.width -= left + right - 1;
926 rect.size.height -= top + bot - 1;
931 @end // MMTextViewHelper (Private)