Add handling IM state
[MacVim/KaoriYa.git] / src / MacVim / MMTextViewHelper.m
blob946b5a98073f82068ac108002003ca26385625a5
1 /* vi:set ts=8 sts=4 sw=4 ft=objc:
2  *
3  * VIM - Vi IMproved            by Bram Moolenaar
4  *                              MacVim GUI port by Bjorn Winckler
5  *
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.
9  */
11  * MMTextViewHelper
12  *
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.
17  */
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)sendImState;
44 - (void)hideMouseCursor;
45 - (void)startDragTimerWithInterval:(NSTimeInterval)t;
46 - (void)dragTimerFired:(NSTimer *)timer;
47 - (void)setCursor;
48 - (NSRect)trackingRect;
49 @end
52 @implementation MMTextViewHelper
54 - (void)dealloc
56     [insertionPointColor release];  insertionPointColor = nil;
57     [markedText release];  markedText = nil;
58     [markedTextAttributes release];  markedTextAttributes = nil;
60     [super dealloc];
63 - (void)setTextView:(id)view
65     // Only keep a weak reference to owning text view.
66     textView = view;
69 - (void)setInsertionPointColor:(NSColor *)color
71     if (color != insertionPointColor) {
72         [insertionPointColor release];
73         insertionPointColor = [color retain];
74     }
77 - (NSColor *)insertionPointColor
79     return insertionPointColor;
82 - (void)keyDown:(NSEvent *)event
84     //NSLog(@"%s %@", _cmd, event);
85     // HACK! If control modifier is held, don't pass the event along to
86     // interpretKeyEvents: since some keys are bound to multiple commands which
87     // means doCommandBySelector: is called several times.  Do the same for
88     // Alt+Function key presses (Alt+Up and Alt+Down are bound to two
89     // commands).  This hack may break input management, but unless we can
90     // figure out a way to disable key bindings there seems little else to do.
91     //
92     // TODO: Figure out a way to disable Cocoa key bindings entirely, without
93     // affecting input management.
95     if (imControl)
96         [self sendImState];
98     // When the Input Method is activated, some special key inputs
99     // should be treated as key inputs for Input Method.
100     if ([textView hasMarkedText]) {
101         [textView interpretKeyEvents:[NSArray arrayWithObject:event]];
102         [textView setNeedsDisplay:YES];
103         return;
104     }
106     int flags = [event modifierFlags];
107     if ((flags & NSControlKeyMask) ||
108             ((flags & NSAlternateKeyMask) && (flags & NSFunctionKeyMask))) {
109         BOOL unmodIsPrintable = YES;
110         NSString *unmod = [event charactersIgnoringModifiers];
111         if (unmod && [unmod length] > 0 && [unmod characterAtIndex:0] < 0x20)
112             unmodIsPrintable = NO;
114         NSString *chars = [event characters];
115         if ([chars length] == 1 && [chars characterAtIndex:0] < 0x20
116                 && unmodIsPrintable) {
117             // HACK! Send unprintable characters (such as C-@, C-[, C-\, C-],
118             // C-^, C-_) as normal text to be added to the Vim input buffer.
119             // This must be done in order for the backend to be able to
120             // separate e.g. Ctrl-i and Ctrl-tab.
121             [self insertText:chars];
122         } else {
123             [self dispatchKeyEvent:event];
124         }
125     } else if ((flags & NSAlternateKeyMask) &&
126             [[[[self vimController] vimState] objectForKey:@"p_mmta"]
127                                                                 boolValue]) {
128         // If the 'macmeta' option is set, then send Alt+key presses directly
129         // to Vim without interpreting the key press.
130         NSString *unmod = [event charactersIgnoringModifiers];
131         int len = [unmod lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
132         const char *bytes = [unmod UTF8String];
134         [self sendKeyDown:bytes length:len modifiers:flags
135                 isARepeat:[event isARepeat]];
136     } else {
137         [textView interpretKeyEvents:[NSArray arrayWithObject:event]];
138     }
141 - (void)insertText:(id)string
143     //NSLog(@"%s %@", _cmd, string);
144     // NOTE!  This method is called for normal key presses but also for
145     // Option-key presses --- even when Ctrl is held as well as Option.  When
146     // Ctrl is held, the AppKit translates the character to a Ctrl+key stroke,
147     // so 'string' need not be a printable character!  In this case it still
148     // works to pass 'string' on to Vim as a printable character (since
149     // modifiers are already included and should not be added to the input
150     // buffer using CSI, K_MODIFIER).
152     if ([textView hasMarkedText]) {
153         [textView unmarkText];
154     }
156     NSEvent *event = [NSApp currentEvent];
158     if (imControl)
159         [self sendImState];
161     // HACK!  In order to be able to bind to <S-Space>, <S-M-Tab>, etc. we have
162     // to watch for them here.
163     if ([event type] == NSKeyDown
164             && [[event charactersIgnoringModifiers] length] > 0
165             && [event modifierFlags]
166                 & (NSShiftKeyMask|NSControlKeyMask|NSAlternateKeyMask)) {
167         unichar c = [[event charactersIgnoringModifiers] characterAtIndex:0];
169         // <S-M-Tab> translates to 0x19 
170         if (' ' == c || 0x19 == c) {
171             [self dispatchKeyEvent:event];
172             return;
173         }
174     }
176     [self hideMouseCursor];
178     // NOTE: 'string' is either an NSString or an NSAttributedString.  Since we
179     // do not support attributes, simply pass the corresponding NSString in the
180     // latter case.
181     if ([string isKindOfClass:[NSAttributedString class]])
182         string = [string string];
184     //NSLog(@"send InsertTextMsgID: %@", string);
186     NSMutableData *data = [NSMutableData data];
187     int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
188     int flags = [event modifierFlags] & 0xffff0000U;
189     if ([event type] == NSKeyDown && [event isARepeat])
190         flags |= 1;
192     [data appendBytes:&flags length:sizeof(int)];
193     [data appendBytes:&len length:sizeof(int)];
194     [data appendBytes:[string UTF8String] length:len];
196     [[self vimController] sendMessage:InsertTextMsgID data:data];
199 - (void)doCommandBySelector:(SEL)selector
201     //NSLog(@"%s %@", _cmd, NSStringFromSelector(selector));
202     // By ignoring the selector we effectively disable the key binding
203     // mechanism of Cocoa.  Hopefully this is what the user will expect
204     // (pressing Ctrl+P would otherwise result in moveUp: instead of previous
205     // match, etc.).
206     //
207     // We usually end up here if the user pressed Ctrl+key (but not
208     // Ctrl+Option+key).
210     NSEvent *event = [NSApp currentEvent];
212     if (imControl)
213         [self sendImState];
215     if (selector == @selector(cancelOperation:)
216             || selector == @selector(insertNewline:)) {
217         // HACK! If there was marked text which got abandoned as a result of
218         // hitting escape or enter, then 'insertText:' is called with the
219         // abandoned text but '[event characters]' includes the abandoned text
220         // as well.  Since 'dispatchKeyEvent:' looks at '[event characters]' we
221         // must intercept these keys here or the abandonded text gets inserted
222         // twice.
223         NSString *key = [event charactersIgnoringModifiers];
224         const char *chars = [key UTF8String];
225         int len = [key lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
227         if (0x3 == chars[0]) {
228             // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
229             // handle it separately (else Ctrl-C doesn't work).
230             len = sizeof(MMKeypadEnter)/sizeof(MMKeypadEnter[0]);
231             chars = MMKeypadEnter;
232         }
234         [self sendKeyDown:chars length:len modifiers:[event modifierFlags]
235                 isARepeat:[event isARepeat]];
236     } else {
237         [self dispatchKeyEvent:event];
238     }
241 - (BOOL)performKeyEquivalent:(NSEvent *)event
243     //NSLog(@"%s %@", _cmd, event);
244     // Called for Cmd+key keystrokes, function keys, arrow keys, page
245     // up/down, home, end.
246     //
247     // NOTE: This message cannot be ignored since Cmd+letter keys never are
248     // passed to keyDown:.  It seems as if the main menu consumes Cmd-key
249     // strokes, unless the key is a function key.
251     if (imControl)
252         [self sendImState];
254     // NOTE: If the event that triggered this method represents a function key
255     // down then we do nothing, otherwise the input method never gets the key
256     // stroke (some input methods use e.g. arrow keys).  The function key down
257     // event will still reach Vim though (via keyDown:).  The exceptions to
258     // this rule are: PageUp/PageDown (keycode 116/121).
259     int flags = [event modifierFlags] & 0xffff0000U;
260     if ([event type] != NSKeyDown || flags & NSFunctionKeyMask
261             && !(116 == [event keyCode] || 121 == [event keyCode]))
262         return NO;
264     // HACK!  KeyCode 50 represent the key which switches between windows
265     // within an application (like Cmd+Tab is used to switch between
266     // applications).  Return NO here, else the window switching does not work.
267     if ([event keyCode] == 50)
268         return NO;
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])
274         return YES;
276     // HACK!  On Leopard Ctrl-key events end up here instead of keyDown:.
277     if (flags & NSControlKeyMask) {
278         [self keyDown:event];
279         return YES;
280     }
282     // HACK!  Don't handle Cmd-? or the "Help" menu does not work on Leopard.
283     NSString *unmodchars = [event charactersIgnoringModifiers];
284     if ([unmodchars isEqual:@"?"])
285         return NO;
287     // Cmd-. is hard-wired to send SIGINT unlike Ctrl-C which is just another
288     // key press which Vim has to interpret.  This means that Cmd-. always
289     // works to interrupt a Vim process whereas Ctrl-C can suffer from problems
290     // such as dropped DO messages (or if Vim is stuck in a loop without
291     // checking for keyboard input).
292     if ((flags & NSDeviceIndependentModifierFlagsMask) == NSCommandKeyMask &&
293             [unmodchars isEqual:@"."]) {
294         kill([[self vimController] pid], SIGINT);
295         return YES;
296     }
298     //NSLog(@"%s%@", _cmd, event);
300     NSString *chars = [event characters];
301     int len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
302     NSMutableData *data = [NSMutableData data];
304     if (len <= 0)
305         return NO;
307     // If 'chars' and 'unmodchars' differs when shift flag is present, then we
308     // can clear the shift flag as it is already included in 'unmodchars'.
309     // Failing to clear the shift flag means <D-Bar> turns into <S-D-Bar> (on
310     // an English keyboard).
311     if (flags & NSShiftKeyMask && ![chars isEqual:unmodchars])
312         flags &= ~NSShiftKeyMask;
314     if (0x3 == [unmodchars characterAtIndex:0]) {
315         // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
316         // handle it separately (else Cmd-enter turns into Ctrl-C).
317         unmodchars = MMKeypadEnterString;
318         len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
319     }
321     if ([event isARepeat])
322         flags |= 1;
324     [data appendBytes:&flags length:sizeof(int)];
325     [data appendBytes:&len length:sizeof(int)];
326     [data appendBytes:[unmodchars UTF8String] length:len];
328     [[self vimController] sendMessage:CmdKeyMsgID data:data];
330     return YES;
333 - (void)scrollWheel:(NSEvent *)event
335     if ([event deltaY] == 0)
336         return;
338     int row, col;
339     NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
340     if ([textView convertPoint:pt toRow:&row column:&col]) {
341         int flags = [event modifierFlags];
342         float dy = [event deltaY];
343         NSMutableData *data = [NSMutableData data];
345         [data appendBytes:&row length:sizeof(int)];
346         [data appendBytes:&col length:sizeof(int)];
347         [data appendBytes:&flags length:sizeof(int)];
348         [data appendBytes:&dy length:sizeof(float)];
350         [[self vimController] sendMessage:ScrollWheelMsgID data:data];
351     }
354 - (void)mouseDown:(NSEvent *)event
356     int row, col;
357     NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
358     if (![textView convertPoint:pt toRow:&row column:&col])
359         return;
361     int button = [event buttonNumber];
362     int flags = [event modifierFlags];
363     int count = [event clickCount];
364     NSMutableData *data = [NSMutableData data];
366     // If desired, intepret Ctrl-Click as a right mouse click.
367     BOOL translateCtrlClick = [[NSUserDefaults standardUserDefaults]
368             boolForKey:MMTranslateCtrlClickKey];
369     flags = flags & NSDeviceIndependentModifierFlagsMask;
370     if (translateCtrlClick && button == 0 &&
371             (flags == NSControlKeyMask ||
372              flags == (NSControlKeyMask|NSAlphaShiftKeyMask))) {
373         button = 1;
374         flags &= ~NSControlKeyMask;
375     }
377     [data appendBytes:&row length:sizeof(int)];
378     [data appendBytes:&col length:sizeof(int)];
379     [data appendBytes:&button length:sizeof(int)];
380     [data appendBytes:&flags length:sizeof(int)];
381     [data appendBytes:&count length:sizeof(int)];
383     [[self vimController] sendMessage:MouseDownMsgID data:data];
386 - (void)mouseUp:(NSEvent *)event
388     int row, col;
389     NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
390     if (![textView convertPoint:pt toRow:&row column:&col])
391         return;
393     int flags = [event modifierFlags];
394     NSMutableData *data = [NSMutableData data];
396     [data appendBytes:&row length:sizeof(int)];
397     [data appendBytes:&col length:sizeof(int)];
398     [data appendBytes:&flags length:sizeof(int)];
400     [[self vimController] sendMessage:MouseUpMsgID data:data];
402     isDragging = NO;
405 - (void)mouseDragged:(NSEvent *)event
407     int flags = [event modifierFlags];
408     int row, col;
409     NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
410     if (![textView convertPoint:pt toRow:&row column:&col])
411         return;
413     // Autoscrolling is done in dragTimerFired:
414     if (!isAutoscrolling) {
415         NSMutableData *data = [NSMutableData data];
417         [data appendBytes:&row length:sizeof(int)];
418         [data appendBytes:&col length:sizeof(int)];
419         [data appendBytes:&flags length:sizeof(int)];
421         [[self vimController] sendMessage:MouseDraggedMsgID data:data];
422     }
424     dragPoint = pt;
425     dragRow = row;
426     dragColumn = col;
427     dragFlags = flags;
429     if (!isDragging) {
430         [self startDragTimerWithInterval:.5];
431         isDragging = YES;
432     }
435 - (void)mouseMoved:(NSEvent *)event
437     // HACK! NSTextView has a nasty habit of resetting the cursor to the
438     // default I-beam cursor at random moments.  The only reliable way we know
439     // of to work around this is to set the cursor each time the mouse moves.
440     [self setCursor];
442     NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
443     int row, col;
444     if (![textView convertPoint:pt toRow:&row column:&col])
445         return;
447     // HACK! It seems impossible to get the tracking rects set up before the
448     // view is visible, which means that the first mouseEntered: or
449     // mouseExited: events are never received.  This forces us to check if the
450     // mouseMoved: event really happened over the text.
451     int rows, cols;
452     [textView getMaxRows:&rows columns:&cols];
453     if (row >= 0 && row < rows && col >= 0 && col < cols) {
454         NSMutableData *data = [NSMutableData data];
456         [data appendBytes:&row length:sizeof(int)];
457         [data appendBytes:&col length:sizeof(int)];
459         [[self vimController] sendMessage:MouseMovedMsgID data:data];
461         //NSLog(@"Moved %d %d\n", col, row);
462     }
465 - (void)mouseEntered:(NSEvent *)event
467     //NSLog(@"%s", _cmd);
469     // NOTE: This event is received even when the window is not key; thus we
470     // have to take care not to enable mouse moved events unless our window is
471     // key.
472     if ([[textView window] isKeyWindow]) {
473         [[textView window] setAcceptsMouseMovedEvents:YES];
474     }
477 - (void)mouseExited:(NSEvent *)event
479     //NSLog(@"%s", _cmd);
481     [[textView window] setAcceptsMouseMovedEvents:NO];
483     // NOTE: This event is received even when the window is not key; if the
484     // mouse shape is set when our window is not key, the hollow (unfocused)
485     // cursor will become a block (focused) cursor.
486     if ([[textView window] isKeyWindow]) {
487         int shape = 0;
488         NSMutableData *data = [NSMutableData data];
489         [data appendBytes:&shape length:sizeof(int)];
490         [[self vimController] sendMessage:SetMouseShapeMsgID data:data];
491     }
494 - (void)setFrame:(NSRect)frame
496     //NSLog(@"%s", _cmd);
498     // When the frame changes we also need to update the tracking rect.
499     [textView removeTrackingRect:trackingRectTag];
500     trackingRectTag = [textView addTrackingRect:[self trackingRect]
501                                           owner:textView
502                                        userData:NULL
503                                    assumeInside:YES];
506 - (void)viewDidMoveToWindow
508     //NSLog(@"%s (window=%@)", _cmd, [self window]);
510     // Set a tracking rect which covers the text.
511     // NOTE: While the mouse cursor is in this rect the view will receive
512     // 'mouseMoved:' events so that Vim can take care of updating the mouse
513     // cursor.
514     if ([textView window]) {
515         [[textView window] setAcceptsMouseMovedEvents:YES];
516         trackingRectTag = [textView addTrackingRect:[self trackingRect]
517                                               owner:textView
518                                            userData:NULL
519                                        assumeInside:YES];
520     }
523 - (void)viewWillMoveToWindow:(NSWindow *)newWindow
525     //NSLog(@"%s%@", _cmd, newWindow);
527     // Remove tracking rect if view moves or is removed.
528     if ([textView window] && trackingRectTag) {
529         [textView removeTrackingRect:trackingRectTag];
530         trackingRectTag = 0;
531     }
534 - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
536     NSPasteboard *pboard = [sender draggingPasteboard];
538     if ([[pboard types] containsObject:NSStringPboardType]) {
539         NSString *string = [pboard stringForType:NSStringPboardType];
540         [[self vimController] dropString:string];
541         return YES;
542     } else if ([[pboard types] containsObject:NSFilenamesPboardType]) {
543         NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
544         [[self vimController] dropFiles:files forceOpen:NO];
545         return YES;
546     }
548     return NO;
551 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
553     NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
554     NSPasteboard *pboard = [sender draggingPasteboard];
556     if ( [[pboard types] containsObject:NSFilenamesPboardType]
557             && (sourceDragMask & NSDragOperationCopy) )
558         return NSDragOperationCopy;
559     if ( [[pboard types] containsObject:NSStringPboardType]
560             && (sourceDragMask & NSDragOperationCopy) )
561         return NSDragOperationCopy;
563     return NSDragOperationNone;
566 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
568     NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
569     NSPasteboard *pboard = [sender draggingPasteboard];
571     if ( [[pboard types] containsObject:NSFilenamesPboardType]
572             && (sourceDragMask & NSDragOperationCopy) )
573         return NSDragOperationCopy;
574     if ( [[pboard types] containsObject:NSStringPboardType]
575             && (sourceDragMask & NSDragOperationCopy) )
576         return NSDragOperationCopy;
578     return NSDragOperationNone;
581 - (void)setMouseShape:(int)shape
583     mouseShape = shape;
584     [self setCursor];
587 - (BOOL)hasMarkedText
589     return markedRange.length > 0 ? YES : NO;
592 - (NSRange)markedRange
594     if ([self hasMarkedText])
595         return markedRange;
596     else
597         return NSMakeRange(NSNotFound, 0);
600 - (NSDictionary *)markedTextAttributes
602     return markedTextAttributes;
605 - (void)setMarkedTextAttributes:(NSDictionary *)attr
607     if (attr != markedTextAttributes) {
608         [markedTextAttributes release];
609         markedTextAttributes = [attr retain];
610     }
613 - (void)setMarkedText:(id)text selectedRange:(NSRange)range
615     [self unmarkText];
617     if (!(text && [text length] > 0))
618         return;
620     // HACK! Determine if the marked text is wide or normal width.  This seems
621     // to always use 'wide' when there are both wide and normal width
622     // characters.
623     NSString *string = text;
624     NSFont *theFont = [textView font];
625     if ([text isKindOfClass:[NSAttributedString class]]) {
626         theFont = [textView fontWide];
627         string = [text string];
628     }
630     // TODO: Use special colors for marked text.
631     [self setMarkedTextAttributes:
632         [NSDictionary dictionaryWithObjectsAndKeys:
633             theFont, NSFontAttributeName,
634             [textView defaultBackgroundColor], NSBackgroundColorAttributeName,
635             [textView defaultForegroundColor], NSForegroundColorAttributeName,
636             nil]];
638     markedText = [[NSMutableAttributedString alloc]
639            initWithString:string
640                attributes:[self markedTextAttributes]];
642     markedRange = NSMakeRange(0, [markedText length]);
643     if (markedRange.length) {
644         [markedText addAttribute:NSUnderlineStyleAttributeName
645                            value:[NSNumber numberWithInt:1]
646                            range:markedRange];
647     }
648     imRange = range;
649     if (range.length) {
650         [markedText addAttribute:NSUnderlineStyleAttributeName
651                            value:[NSNumber numberWithInt:2]
652                            range:range];
653     }
655     [textView setNeedsDisplay:YES];
658 - (void)unmarkText
660     imRange = NSMakeRange(0, 0);
661     markedRange = NSMakeRange(NSNotFound, 0);
662     [markedText release];
663     markedText = nil;
666 - (NSMutableAttributedString *)markedText
668     return markedText;
671 - (void)setPreEditRow:(int)row column:(int)col
673     preEditRow = row;
674     preEditColumn = col;
677 - (int)preEditRow
679     return preEditRow;
682 - (int)preEditColumn
684     return preEditColumn;
687 - (void)setImRange:(NSRange)range
689     imRange = range;
692 - (NSRange)imRange
694     return imRange;
697 - (void)setMarkedRange:(NSRange)range
699     markedRange = range;
702 - (NSRect)firstRectForCharacterRange:(NSRange)range
704     // This method is called when the input manager wants to pop up an
705     // auxiliary window.  The position where this should be is controlled by
706     // Vim by sending SetPreEditPositionMsgID so compute a position based on
707     // the pre-edit (row,column) pair.
708     int col = preEditColumn;
709     int row = preEditRow + 1;
711     NSFont *theFont = [[textView markedTextAttributes]
712             valueForKey:NSFontAttributeName];
713     if (theFont == [textView fontWide]) {
714         col += imRange.location * 2;
715         if (col >= [textView maxColumns] - 1) {
716             row += (col / [textView maxColumns]);
717             col = col % 2 ? col % [textView maxColumns] + 1 :
718                             col % [textView maxColumns];
719         }
720     } else {
721         col += imRange.location;
722         if (col >= [textView maxColumns]) {
723             row += (col / [textView maxColumns]);
724             col = col % [textView maxColumns];
725         }
726     }
728     NSRect rect = [textView rectForRow:row
729                                 column:col
730                                numRows:1
731                             numColumns:range.length];
733     rect.origin = [textView convertPoint:rect.origin toView:nil];
734     rect.origin = [[textView window] convertBaseToScreen:rect.origin];
736     return rect;
739 - (void)setImControl:(BOOL)enable
741     imControl = enable;
744 - (void)sendImState
746     // IM is active whenever the current script is the system script and the
747     // system script isn't roman.  (Hence IM can only be active when using
748     // non-roman scripts.)
749     SInt32 currentScript = GetScriptManagerVariable(smKeyScript);
750     SInt32 systemScript = GetScriptManagerVariable(smSysScript);
751     BOOL state = currentScript != smRoman && currentScript == systemScript;
752     int msgid = state ? ActivatedImMsgID : DeactivatedImMsgID;
753     [[self vimController] sendMessage:msgid data:nil];
756 @end // MMTextViewHelper
761 @implementation MMTextViewHelper (Private)
763 - (MMWindowController *)windowController
765     id windowController = [[textView window] windowController];
766     if ([windowController isKindOfClass:[MMWindowController class]])
767         return (MMWindowController*)windowController;
768     return nil;
771 - (MMVimController *)vimController
773     return [[self windowController] vimController];
776 - (void)dispatchKeyEvent:(NSEvent *)event
778     // Only handle the command if it came from a keyDown event
779     if ([event type] != NSKeyDown)
780         return;
782     NSString *chars = [event characters];
783     NSString *unmodchars = [event charactersIgnoringModifiers];
784     unichar c = [chars characterAtIndex:0];
785     unichar imc = [unmodchars length] > 0 ? [unmodchars characterAtIndex:0] : 0;
786     int len = 0;
787     const char *bytes = 0;
788     int mods = [event modifierFlags];
790     //NSLog(@"%s chars[0]=0x%x unmodchars[0]=0x%x (chars=%@ unmodchars=%@)",
791     //        _cmd, c, imc, chars, unmodchars);
793     if (' ' == imc && 0xa0 != c) {
794         // HACK!  The AppKit turns <C-Space> into <C-@> which is not standard
795         // Vim behaviour, so bypass this problem.  (0xa0 is <M-Space>, which
796         // should be passed on as is.)
797         len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
798         bytes = [unmodchars UTF8String];
799     } else if (imc == c && '2' == c) {
800         // HACK!  Translate Ctrl+2 to <C-@>.
801         static char ctrl_at = 0;
802         len = 1;  bytes = &ctrl_at;
803     } else if (imc == c && '6' == c) {
804         // HACK!  Translate Ctrl+6 to <C-^>.
805         static char ctrl_hat = 0x1e;
806         len = 1;  bytes = &ctrl_hat;
807     } else if (c == 0x19 && imc == 0x19) {
808         // HACK! AppKit turns back tab into Ctrl-Y, so we need to handle it
809         // separately (else Ctrl-Y doesn't work).
810         static char tab = 0x9;
811         len = 1;  bytes = &tab;  mods |= NSShiftKeyMask;
812     } else {
813         len = [chars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
814         bytes = [chars UTF8String];
815     }
817     [self sendKeyDown:bytes length:len modifiers:mods
818             isARepeat:[event isARepeat]];
821 - (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags
822           isARepeat:(BOOL)isARepeat
824     if (chars && len > 0) {
825         NSMutableData *data = [NSMutableData data];
827         // The low 16 bits are not used for modifier flags by NSEvent.  Use
828         // these bits for custom flags.
829         flags &= 0xffff0000;
830         if (isARepeat)
831             flags |= 1;
833         [data appendBytes:&flags length:sizeof(int)];
834         [data appendBytes:&len length:sizeof(int)];
835         [data appendBytes:chars length:len];
837         [self hideMouseCursor];
839         //NSLog(@"%s len=%d chars=0x%x", _cmd, len, chars[0]);
840         [[self vimController] sendMessage:KeyDownMsgID data:data];
841     }
844 - (void)hideMouseCursor
846     // Check 'mousehide' option
847     id mh = [[[self vimController] vimState] objectForKey:@"p_mh"];
848     if (mh && ![mh boolValue])
849         [NSCursor setHiddenUntilMouseMoves:NO];
850     else
851         [NSCursor setHiddenUntilMouseMoves:YES];
854 - (void)startDragTimerWithInterval:(NSTimeInterval)t
856     [NSTimer scheduledTimerWithTimeInterval:t target:self
857                                    selector:@selector(dragTimerFired:)
858                                    userInfo:nil repeats:NO];
861 - (void)dragTimerFired:(NSTimer *)timer
863     // TODO: Autoscroll in horizontal direction?
864     static unsigned tick = 1;
866     isAutoscrolling = NO;
868     if (isDragging && (dragRow < 0 || dragRow >= [textView maxRows])) {
869         // HACK! If the mouse cursor is outside the text area, then send a
870         // dragged event.  However, if row&col hasn't changed since the last
871         // dragged event, Vim won't do anything (see gui_send_mouse_event()).
872         // Thus we fiddle with the column to make sure something happens.
873         int col = dragColumn + (dragRow < 0 ? -(tick % 2) : +(tick % 2));
874         NSMutableData *data = [NSMutableData data];
876         [data appendBytes:&dragRow length:sizeof(int)];
877         [data appendBytes:&col length:sizeof(int)];
878         [data appendBytes:&dragFlags length:sizeof(int)];
880         [[self vimController] sendMessage:MouseDraggedMsgID data:data];
882         isAutoscrolling = YES;
883     }
885     if (isDragging) {
886         // Compute timer interval depending on how far away the mouse cursor is
887         // from the text view.
888         NSRect rect = [self trackingRect];
889         float dy = 0;
890         if (dragPoint.y < rect.origin.y) dy = rect.origin.y - dragPoint.y;
891         else if (dragPoint.y > NSMaxY(rect)) dy = dragPoint.y - NSMaxY(rect);
892         if (dy > MMDragAreaSize) dy = MMDragAreaSize;
894         NSTimeInterval t = MMDragTimerMaxInterval -
895             dy*(MMDragTimerMaxInterval-MMDragTimerMinInterval)/MMDragAreaSize;
897         [self startDragTimerWithInterval:t];
898     }
900     ++tick;
903 - (void)setCursor
905     static NSCursor *customIbeamCursor = nil;
907     if (!customIbeamCursor) {
908         // Use a custom Ibeam cursor that has better contrast against dark
909         // backgrounds.
910         // TODO: Is the hotspot ok?
911         NSImage *ibeamImage = [NSImage imageNamed:@"ibeam"];
912         if (ibeamImage) {
913             NSSize size = [ibeamImage size];
914             NSPoint hotSpot = { size.width*.5f, size.height*.5f };
916             customIbeamCursor = [[NSCursor alloc]
917                     initWithImage:ibeamImage hotSpot:hotSpot];
918         }
919         if (!customIbeamCursor) {
920             NSLog(@"WARNING: Failed to load custom Ibeam cursor");
921             customIbeamCursor = [NSCursor IBeamCursor];
922         }
923     }
925     // This switch should match mshape_names[] in misc2.c.
926     //
927     // TODO: Add missing cursor shapes.
928     switch (mouseShape) {
929         case 2: [customIbeamCursor set]; break;
930         case 3: case 4: [[NSCursor resizeUpDownCursor] set]; break;
931         case 5: case 6: [[NSCursor resizeLeftRightCursor] set]; break;
932         case 9: [[NSCursor crosshairCursor] set]; break;
933         case 10: [[NSCursor pointingHandCursor] set]; break;
934         case 11: [[NSCursor openHandCursor] set]; break;
935         default:
936             [[NSCursor arrowCursor] set]; break;
937     }
939     // Shape 1 indicates that the mouse cursor should be hidden.
940     if (1 == mouseShape)
941         [NSCursor setHiddenUntilMouseMoves:YES];
944 - (NSRect)trackingRect
946     NSRect rect = [textView frame];
947     NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
948     int left = [ud integerForKey:MMTextInsetLeftKey];
949     int top = [ud integerForKey:MMTextInsetTopKey];
950     int right = [ud integerForKey:MMTextInsetRightKey];
951     int bot = [ud integerForKey:MMTextInsetBottomKey];
953     rect.origin.x = left;
954     rect.origin.y = top;
955     rect.size.width -= left + right - 1;
956     rect.size.height -= top + bot - 1;
958     return rect;
961 @end // MMTextViewHelper (Private)