First version of macvim help file
[MacVim/jjgod.git] / MMTextView.m
blob4e9c984799bacc88cd5f8a727d5a6e24ad288944
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 #import "MMTextView.h"
12 #import "MMTextStorage.h"
13 #import "MMWindowController.h"
14 #import "MMVimController.h"
15 #import "MacVim.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;
29 @interface MMTextView (Private)
30 - (BOOL)convertPoint:(NSPoint)point toRow:(int *)row column:(int *)column;
31 - (BOOL)convertRow:(int)row column:(int)column toPoint:(NSPoint *)point;
32 - (NSRect)trackingRect;
33 - (void)dispatchKeyEvent:(NSEvent *)event;
34 - (MMVimController *)vimController;
35 - (void)startDragTimerWithInterval:(NSTimeInterval)t;
36 - (void)dragTimerFired:(NSTimer *)timer;
37 - (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags;
38 @end
42 @implementation MMTextView
44 - (void)dealloc
46     if (markedTextField) {
47         [[markedTextField window] autorelease];
48         [markedTextField release];
49         markedTextField = nil;
50     }
52     [lastMouseDownEvent release];
53     [super dealloc];
56 - (NSEvent *)lastMouseDownEvent
58     return lastMouseDownEvent;
61 - (BOOL)shouldDrawInsertionPoint
63     // NOTE: The insertion point is drawn manually in drawRect:.  It would be
64     // nice to be able to use the insertion point related methods of
65     // NSTextView, but it seems impossible to get them to work properly (search
66     // the cocoabuilder archives).
67     return NO;
70 - (void)setShouldDrawInsertionPoint:(BOOL)on
72     shouldDrawInsertionPoint = on;
75 - (void)drawInsertionPointAtRow:(int)row column:(int)col shape:(int)shape
76                        fraction:(int)percent color:(NSColor *)color
78     //NSLog(@"drawInsertionPointAtRow:%d column:%d shape:%d color:%@",
79     //        row, col, shape, color);
81     // This only stores where to draw the insertion point, the actual drawing
82     // is done in drawRect:.
83     shouldDrawInsertionPoint = YES;
84     insertionPointRow = row;
85     insertionPointColumn = col;
86     insertionPointShape = shape;
87     insertionPointFraction = percent;
89     [self setInsertionPointColor:color];
92 - (void)hideMarkedTextField
94     if (markedTextField) {
95         NSWindow *win = [markedTextField window];
96         [win close];
97         [markedTextField setStringValue:@""];
98     }
101 - (void)drawRect:(NSRect)rect
103     [super drawRect:rect];
105     if (shouldDrawInsertionPoint) {
106         MMTextStorage *ts = (MMTextStorage*)[self textStorage];
107         NSLayoutManager *lm = [self layoutManager];
108         NSTextContainer *tc = [self textContainer];
110         // Given (row,column), calculate the bounds of the glyph at that spot.
111         // We use the layout manager because this gives us exactly the size and
112         // location of the glyph so that we can match the insertion point to
113         // it.
114         unsigned charIdx = [ts characterIndexForRow:insertionPointRow
115                                              column:insertionPointColumn];
116         NSRange glyphRange =
117             [lm glyphRangeForCharacterRange:NSMakeRange(charIdx,1)
118                        actualCharacterRange:NULL];
119         NSRect ipRect = [lm boundingRectForGlyphRange:glyphRange
120                                       inTextContainer:tc];
121         ipRect.origin.x += [self textContainerOrigin].x;
122         ipRect.origin.y += [self textContainerOrigin].y;
124         if (MMInsertionPointHorizontal == insertionPointShape) {
125             int frac = ([ts cellSize].height * insertionPointFraction + 99)/100;
126             ipRect.origin.y += ipRect.size.height - frac;
127             ipRect.size.height = frac;
128         } else if (MMInsertionPointVertical == insertionPointShape) {
129             int frac = ([ts cellSize].width* insertionPointFraction + 99)/100;
130             ipRect.size.width = frac;
131         }
133         [[self insertionPointColor] set];
134         if (MMInsertionPointHollow == insertionPointShape) {
135             NSFrameRect(ipRect);
136         } else {
137             NSRectFill(ipRect);
138         }
140         // NOTE: We only draw the cursor once and rely on Vim to say when it
141         // should be drawn again.
142         shouldDrawInsertionPoint = NO;
144         //NSLog(@"%s draw insertion point %@ shape=%d color=%@", _cmd,
145         //        NSStringFromRect(ipRect), insertionPointShape,
146         //        [self insertionPointColor]);
147     }
150 - (void)keyDown:(NSEvent *)event
152     //NSLog(@"%s %@", _cmd, event);
153     // HACK! If a modifier is held, don't pass the event along to
154     // interpretKeyEvents: since some keys are bound to multiple commands which
155     // means doCommandBySelector: is called several times.
156     //
157     // TODO: Figure out a way to disable Cocoa key bindings entirely, without
158     // affecting input management.
160     if ([event modifierFlags] & NSControlKeyMask)
161         [self dispatchKeyEvent:event];
162     else
163         [super keyDown:event];
166 - (void)insertText:(id)string
168     //NSLog(@"%s %@", _cmd, string);
169     // NOTE!  This method is called for normal key presses but also for
170     // Option-key presses --- even when Ctrl is held as well as Option.  When
171     // Ctrl is held, the AppKit translates the character to a Ctrl+key stroke,
172     // so 'string' need not be a printable character!  In this case it still
173     // works to pass 'string' on to Vim as a printable character (since
174     // modifiers are already included and should not be added to the input
175     // buffer using CSI, K_MODIFIER).
177     [self hideMarkedTextField];
179     NSEvent *event = [NSApp currentEvent];
181     // HACK!  In order to be able to bind to <S-Space> etc. we have to watch
182     // for when space was pressed.
183     if ([event type] == NSKeyDown
184             && [[event charactersIgnoringModifiers] length] > 0
185             && [[event charactersIgnoringModifiers] characterAtIndex:0] == ' '
186             && [event modifierFlags]
187                 & (NSShiftKeyMask|NSControlKeyMask|NSAlternateKeyMask))
188     {
189         [self dispatchKeyEvent:event];
190         return;
191     }
193     // TODO: Support 'mousehide' (check p_mh)
194     [NSCursor setHiddenUntilMouseMoves:YES];
196     // NOTE: 'string' is either an NSString or an NSAttributedString.  Since we
197     // do not support attributes, simply pass the corresponding NSString in the
198     // latter case.
199     if ([string isKindOfClass:[NSAttributedString class]])
200         string = [string string];
202     [[self vimController] sendMessage:InsertTextMsgID
203                  data:[string dataUsingEncoding:NSUTF8StringEncoding]
204                  wait:NO];
208 - (void)doCommandBySelector:(SEL)selector
210     //NSLog(@"%s %@", _cmd, NSStringFromSelector(selector));
211     // By ignoring the selector we effectively disable the key binding
212     // mechanism of Cocoa.  Hopefully this is what the user will expect
213     // (pressing Ctrl+P would otherwise result in moveUp: instead of previous
214     // match, etc.).
215     //
216     // We usually end up here if the user pressed Ctrl+key (but not
217     // Ctrl+Option+key).
219     NSEvent *event = [NSApp currentEvent];
221     if (selector == @selector(cancelOperation:)
222             || selector == @selector(insertNewline:)) {
223         // HACK! If there was marked text which got abandoned as a result of
224         // hitting escape or enter, then 'insertText:' is called with the
225         // abandoned text but '[event characters]' includes the abandoned text
226         // as well.  Since 'dispatchKeyEvent:' looks at '[event characters]' we
227         // must intercept these keys here or the abandonded text gets inserted
228         // twice.
229         NSString *key = [event charactersIgnoringModifiers];
230         const char *chars = [key UTF8String];
231         int len = [key lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
233         if (0x3 == chars[0]) {
234             // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
235             // handle it separately (else Ctrl-C doesn't work).
236             static char keypadEnter[2] = { 'K', 'A' };
237             len = 2; chars = keypadEnter;
238         }
240         [self sendKeyDown:chars length:len modifiers:[event modifierFlags]];
241     } else {
242         [self dispatchKeyEvent:event];
243     }
246 #if 0
247 // Confused note to self: Why did I implement this in the first place?  Will
248 // something break if I don't?
250 // Answer: Cmd-letter key strokes are consumed by the menu (regardless if they
251 // are bound to a menu item or not) and never passed on to Vim.
253 // Input methods that use arrow keys do not work
254 // properly with this implementation, so it is disabled for now.
255 - (BOOL)performKeyEquivalent:(NSEvent *)event
257     NSLog(@"%s %@", _cmd, event);
258     // Called for Cmd+key keystrokes, function keys, arrow keys, page
259     // up/down, home, end.
261     if ([event type] != NSKeyDown)
262         return NO;
264     // HACK!  Let the main menu try to handle any key down event, before
265     // passing it on to vim, otherwise key equivalents for menus will
266     // effectively be disabled.
267     if ([[NSApp mainMenu] performKeyEquivalent:event])
268         return YES;
270     // HACK!  KeyCode 50 represent the key which switches between windows
271     // within an application (like Cmd+Tab is used to switch between
272     // applications).  Return NO here, else the window switching does not work.
273     //
274     // Will this hack work for all languages / keyboard layouts?
275     if ([event keyCode] == 50)
276         return NO;
278     //NSLog(@"%s%@", _cmd, event);
280     NSString *string = [event charactersIgnoringModifiers];
281     int flags = [event modifierFlags];
282     int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
283     NSMutableData *data = [NSMutableData data];
285     [data appendBytes:&flags length:sizeof(int)];
286     [data appendBytes:&len length:sizeof(int)];
287     [data appendBytes:[string UTF8String] length:len];
289     [[self vimController] sendMessage:CmdKeyMsgID data:data wait:NO];
291     return YES;
293 #endif
295 - (BOOL)hasMarkedText
297     //NSLog(@"%s", _cmd);
298     return markedTextField && [[markedTextField stringValue] length] > 0;
301 - (NSRange)markedRange
303     //NSLog(@"%s", _cmd);
304     // HACK! If a valid range is returned, then NSTextView changes the
305     // background color of the returned range.  Since marked text is displayed
306     // in a separate popup window this behaviour is not wanted.  By setting the
307     // location of the returned range to NSNotFound NSTextView does nothing.
308     // This hack is continued in 'firstRectForCharacterRange:'.
309     return NSMakeRange(NSNotFound, 0);
312 - (void)setMarkedText:(id)text selectedRange:(NSRange)range
314     //NSLog(@"setMarkedText:'%@' selectedRange:%@", text,
315     //        NSStringFromRange(range));
317     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
318     if (!ts) return;
320     if (!markedTextField) {
321         // Create a text field and put it inside a floating panel.  This field
322         // is used to display marked text.
323         NSSize cellSize = [ts cellSize];
324         NSRect cellRect = { 0, 0, cellSize.width, cellSize.height };
326         markedTextField = [[NSTextField alloc] initWithFrame:cellRect];
327         [markedTextField setEditable:NO];
328         [markedTextField setSelectable:NO];
329         [markedTextField setBezeled:NO];
330         [markedTextField setBordered:YES];
332         NSPanel *panel = [[NSPanel alloc]
333             initWithContentRect:cellRect
334                       styleMask:NSBorderlessWindowMask|NSUtilityWindowMask
335                         backing:NSBackingStoreBuffered
336                           defer:YES];
338         //[panel setHidesOnDeactivate:NO];
339         [panel setFloatingPanel:YES];
340         [panel setBecomesKeyOnlyIfNeeded:YES];
341         [panel setContentView:markedTextField];
342     }
344     if (text && [text length] > 0) {
345         [markedTextField setFont:[ts font]];
346         if ([text isKindOfClass:[NSAttributedString class]])
347             [markedTextField setAttributedStringValue:text];
348         else
349             [markedTextField setStringValue:text];
351         [markedTextField sizeToFit];
352         NSSize size = [markedTextField frame].size;
354         // Convert coordinates (row,col) -> view -> window base -> screen
355         NSPoint origin;
356         if (![self convertRow:insertionPointRow+1 column:insertionPointColumn
357                      toPoint:&origin])
358             return;
359         origin = [self convertPoint:origin toView:nil];
360         origin = [[self window] convertBaseToScreen:origin];
362         NSWindow *win = [markedTextField window];
363         [win setContentSize:size];
364         [win setFrameOrigin:origin];
365         [win orderFront:nil];
366     } else {
367         [self hideMarkedTextField];
368     }
371 - (void)unmarkText
373     //NSLog(@"%s", _cmd);
374     [self hideMarkedTextField];
377 - (NSRect)firstRectForCharacterRange:(NSRange)range
379     //NSLog(@"%s%@", _cmd, NSStringFromRange(range));
381     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
382     NSLayoutManager *lm = [self layoutManager];
383     NSTextContainer *tc = [self textContainer];
385     // HACK! Since we always return marked text to have location NSNotFound,
386     // this method will be called with 'range.location == NSNotFound' whenever
387     // the input manager tries to position a popup window near the insertion
388     // point.  For this reason we compute where the insertion point is and
389     // return a rect which contains it.
390     if (!(ts && lm && tc) || NSNotFound != range.location)
391         return [super firstRectForCharacterRange:range];
393     unsigned charIdx = [ts characterIndexForRow:insertionPointRow
394                                          column:insertionPointColumn];
395     NSRange glyphRange =
396         [lm glyphRangeForCharacterRange:NSMakeRange(charIdx,1)
397                    actualCharacterRange:NULL];
398     NSRect ipRect = [lm boundingRectForGlyphRange:glyphRange
399                                   inTextContainer:tc];
400     ipRect.origin.x += [self textContainerOrigin].x;
401     ipRect.origin.y += [self textContainerOrigin].y + [ts cellSize].height;
403     ipRect.origin = [self convertPoint:ipRect.origin toView:nil];
404     ipRect.origin = [[self window] convertBaseToScreen:ipRect.origin];
406     return ipRect;
409 - (void)scrollWheel:(NSEvent *)event
411     if ([event deltaY] == 0)
412         return;
414     int row, col;
415     NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
416     if (![self convertPoint:pt toRow:&row column:&col])
417         return;
419     int flags = [event modifierFlags];
420     float dy = [event deltaY];
421     NSMutableData *data = [NSMutableData data];
423     [data appendBytes:&row length:sizeof(int)];
424     [data appendBytes:&col length:sizeof(int)];
425     [data appendBytes:&flags length:sizeof(int)];
426     [data appendBytes:&dy length:sizeof(float)];
428     [[self vimController] sendMessage:ScrollWheelMsgID data:data wait:NO];
431 - (void)mouseDown:(NSEvent *)event
433     int row, col;
434     NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
435     if (![self convertPoint:pt toRow:&row column:&col])
436         return;
438     lastMouseDownEvent = [event copy];
440     int button = [event buttonNumber];
441     int flags = [event modifierFlags];
442     int count = [event clickCount];
443     NSMutableData *data = [NSMutableData data];
445     // If desired, intepret Ctrl-Click as a right mouse click.
446     if ([[NSUserDefaults standardUserDefaults]
447             boolForKey:MMTranslateCtrlClickKey]
448             && button == 0 && flags & NSControlKeyMask) {
449         button = 1;
450         flags &= ~NSControlKeyMask;
451     }
453     [data appendBytes:&row length:sizeof(int)];
454     [data appendBytes:&col length:sizeof(int)];
455     [data appendBytes:&button length:sizeof(int)];
456     [data appendBytes:&flags length:sizeof(int)];
457     [data appendBytes:&count length:sizeof(int)];
459     [[self vimController] sendMessage:MouseDownMsgID data:data wait:NO];
462 - (void)rightMouseDown:(NSEvent *)event
464     [self mouseDown:event];
467 - (void)otherMouseDown:(NSEvent *)event
469     [self mouseDown:event];
472 - (void)mouseUp:(NSEvent *)event
474     int row, col;
475     NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
476     if (![self convertPoint:pt toRow:&row column:&col])
477         return;
479     int flags = [event modifierFlags];
480     NSMutableData *data = [NSMutableData data];
482     [data appendBytes:&row length:sizeof(int)];
483     [data appendBytes:&col length:sizeof(int)];
484     [data appendBytes:&flags length:sizeof(int)];
486     [[self vimController] sendMessage:MouseUpMsgID data:data wait:NO];
488     isDragging = NO;
491 - (void)rightMouseUp:(NSEvent *)event
493     [self mouseUp:event];
496 - (void)otherMouseUp:(NSEvent *)event
498     [self mouseUp:event];
501 - (void)mouseDragged:(NSEvent *)event
503     int flags = [event modifierFlags];
504     int row, col;
505     NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
506     if (![self convertPoint:pt toRow:&row column:&col])
507         return;
509     // Autoscrolling is done in dragTimerFired:
510     if (!isAutoscrolling) {
511         NSMutableData *data = [NSMutableData data];
513         [data appendBytes:&row length:sizeof(int)];
514         [data appendBytes:&col length:sizeof(int)];
515         [data appendBytes:&flags length:sizeof(int)];
517         [[self vimController] sendMessage:MouseDraggedMsgID data:data wait:NO];
518     }
520     dragPoint = pt;
521     dragRow = row; dragColumn = col; dragFlags = flags;
522     if (!isDragging) {
523         [self startDragTimerWithInterval:.5];
524         isDragging = YES;
525     }
528 - (void)rightMouseDragged:(NSEvent *)event
530     [self mouseDragged:event];
533 - (void)otherMouseDragged:(NSEvent *)event
535     [self mouseDragged:event];
538 - (void)mouseMoved:(NSEvent *)event
540     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
541     if (!ts) return;
543     NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
544     int row, col;
545     if (![self convertPoint:pt toRow:&row column:&col])
546         return;
548     // HACK! It seems impossible to get the tracking rects set up before the
549     // view is visible, which means that the first mouseEntered: or
550     // mouseExited: events are never received.  This forces us to check if the
551     // mouseMoved: event really happened over the text.
552     int rows, cols;
553     [ts getMaxRows:&rows columns:&cols];
554     if (row >= 0 && row < rows && col >= 0 && col < cols) {
555         NSMutableData *data = [NSMutableData data];
557         [data appendBytes:&row length:sizeof(int)];
558         [data appendBytes:&col length:sizeof(int)];
560         [[self vimController] sendMessage:MouseMovedMsgID data:data wait:NO];
561     }
564 - (void)mouseEntered:(NSEvent *)event
566     //NSLog(@"%s", _cmd);
568     // NOTE: This event is received even when the window is not key; thus we
569     // have to take care not to enable mouse moved events unless our window is
570     // key.
571     if ([[self window] isKeyWindow])
572         [[self window] setAcceptsMouseMovedEvents:YES];
575 - (void)mouseExited:(NSEvent *)event
577     //NSLog(@"%s", _cmd);
579     [[self window] setAcceptsMouseMovedEvents:NO];
581     // NOTE: This event is received even when the window is not key; if the
582     // mouse shape is set when our window is not key, the hollow (unfocused)
583     // cursor will become a block (focused) cursor.
584     if ([[self window] isKeyWindow]) {
585         int shape = 0;
586         NSMutableData *data = [NSMutableData data];
587         [data appendBytes:&shape length:sizeof(int)];
588         [[self vimController] sendMessage:SetMouseShapeMsgID data:data wait:NO];
589     }
592 - (void)setFrame:(NSRect)frame
594     //NSLog(@"%s", _cmd);
596     // When the frame changes we also need to update the tracking rect.
597     [super setFrame:frame];
598     [self removeTrackingRect:trackingRectTag];
599     trackingRectTag = [self addTrackingRect:[self trackingRect] owner:self
600                                    userData:NULL assumeInside:YES];
603 - (void)viewDidMoveToWindow
605     //NSLog(@"%s (window=%@)", _cmd, [self window]);
607     // Set a tracking rect which covers the text.
608     // NOTE: While the mouse cursor is in this rect the view will receive
609     // 'mouseMoved:' events so that Vim can take care of updating the mouse
610     // cursor.
611     if ([self window]) {
612         [[self window] setAcceptsMouseMovedEvents:YES];
613         trackingRectTag = [self addTrackingRect:[self trackingRect] owner:self
614                                        userData:NULL assumeInside:YES];
615     }
618 - (void)viewWillMoveToWindow:(NSWindow *)newWindow
620     //NSLog(@"%s%@", _cmd, newWindow);
622     // Remove tracking rect if view moves or is removed.
623     if ([self window] && trackingRectTag) {
624         [self removeTrackingRect:trackingRectTag];
625         trackingRectTag = 0;
626     }
629 - (NSMenu*)menuForEvent:(NSEvent *)event
631     // HACK! Return nil to disable NSTextView's popup menus (Vim provides its
632     // own).  Called when user Ctrl-clicks in the view (this is already handled
633     // in rightMouseDown:).
634     return nil;
637 - (NSArray *)acceptableDragTypes
639     return [NSArray arrayWithObjects:NSFilenamesPboardType,
640            NSStringPboardType, nil];
643 - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
645     NSPasteboard *pboard = [sender draggingPasteboard];
647     if ([[pboard types] containsObject:NSStringPboardType]) {
648         NSString *string = [pboard stringForType:NSStringPboardType];
649         [[self vimController] dropString:string];
650         return YES;
651     } else if ([[pboard types] containsObject:NSFilenamesPboardType]) {
652         NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
653         [[self vimController] dropFiles:files];
654         return YES;
655     }
657     return NO;
660 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
662     NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
663     NSPasteboard *pboard = [sender draggingPasteboard];
665     if ( [[pboard types] containsObject:NSFilenamesPboardType]
666             && (sourceDragMask & NSDragOperationCopy) )
667         return NSDragOperationCopy;
668     if ( [[pboard types] containsObject:NSStringPboardType]
669             && (sourceDragMask & NSDragOperationCopy) )
670         return NSDragOperationCopy;
672     return NSDragOperationNone;
675 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
677     NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
678     NSPasteboard *pboard = [sender draggingPasteboard];
680     if ( [[pboard types] containsObject:NSFilenamesPboardType]
681             && (sourceDragMask & NSDragOperationCopy) )
682         return NSDragOperationCopy;
683     if ( [[pboard types] containsObject:NSStringPboardType]
684             && (sourceDragMask & NSDragOperationCopy) )
685         return NSDragOperationCopy;
687     return NSDragOperationNone;
690 - (void)changeFont:(id)sender
692     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
693     if (!ts) return;
695     NSFont *oldFont = [ts font];
696     NSFont *newFont = [sender convertFont:oldFont];
698     if (newFont) {
699         NSString *name = [newFont displayName];
700         unsigned len = [name lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
701         if (len > 0) {
702             NSMutableData *data = [NSMutableData data];
703             float pointSize = [newFont pointSize];
705             [data appendBytes:&pointSize length:sizeof(float)];
707             ++len;  // include NUL byte
708             [data appendBytes:&len length:sizeof(unsigned)];
709             [data appendBytes:[name UTF8String] length:len];
711             [[self vimController] sendMessage:SetFontMsgID data:data wait:NO];
712         }
713     }
716 - (void)resetCursorRects
718     // No need to set up cursor rects since Vim handles cursor changes.
721 - (void)updateFontPanel
723     // The font panel is updated whenever the font is set.
726 @end // MMTextView
731 @implementation MMTextView (Private)
733 - (BOOL)convertPoint:(NSPoint)point toRow:(int *)row column:(int *)column
735 #if 0
736     NSLayoutManager *lm = [self layoutManager];
737     NSTextContainer *tc = [self textContainer];
738     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
740     if (!(lm && tc && ts))
741         return NO;
743     unsigned glyphIdx = [lm glyphIndexForPoint:point inTextContainer:tc];
744     unsigned charIdx = [lm characterIndexForGlyphAtIndex:glyphIdx];
746     int mod = [ts maxColumns] + 1;
748     if (row) *row = (int)(charIdx / mod);
749     if (column) *column = (int)(charIdx % mod);
751     NSLog(@"convertPoint:%@ toRow:%d column:%d", NSStringFromPoint(point),
752             *row, *column);
754     return YES;
755 #else
756     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
757     NSSize cellSize = [ts cellSize];
758     if (!(cellSize.width > 0 && cellSize.height > 0))
759         return NO;
760     NSPoint origin = [self textContainerOrigin];
762     if (row) *row = floor((point.y-origin.y-1) / cellSize.height);
763     if (column) *column = floor((point.x-origin.x-1) / cellSize.width);
765     //NSLog(@"convertPoint:%@ toRow:%d column:%d", NSStringFromPoint(point),
766     //        *row, *column);
768     return YES;
769 #endif
772 - (BOOL)convertRow:(int)row column:(int)column toPoint:(NSPoint *)point
774     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
775     NSSize cellSize = [ts cellSize];
776     if (!(point && cellSize.width > 0 && cellSize.height > 0))
777         return NO;
779     *point = [self textContainerOrigin];
780     point->x += column * cellSize.width;
781     point->y += row * cellSize.height;
783     return YES;
786 - (NSRect)trackingRect
788     NSRect rect = [self frame];
789     NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
790     int left = [ud integerForKey:MMTextInsetLeftKey];
791     int top = [ud integerForKey:MMTextInsetTopKey];
792     int right = [ud integerForKey:MMTextInsetRightKey];
793     int bot = [ud integerForKey:MMTextInsetBottomKey];
795     rect.origin.x = left;
796     rect.origin.y = top;
797     rect.size.width -= left + right - 1;
798     rect.size.height -= top + bot - 1;
800     return rect;
803 - (void)dispatchKeyEvent:(NSEvent *)event
805     // Only handle the command if it came from a keyDown event
806     if ([event type] != NSKeyDown)
807         return;
809     NSString *chars = [event characters];
810     NSString *unmodchars = [event charactersIgnoringModifiers];
811     unichar c = [chars characterAtIndex:0];
812     unichar imc = [unmodchars characterAtIndex:0];
813     int len = 0;
814     const char *bytes = 0;
816     //NSLog(@"%s chars[0]=0x%x unmodchars[0]=0x%x (chars=%@ unmodchars=%@)",
817     //        _cmd, c, imc, chars, unmodchars);
819     if (' ' == imc && 0xa0 != c) {
820         // HACK!  The AppKit turns <C-Space> into <C-@> which is not standard
821         // Vim behaviour, so bypass this problem.  (0xa0 is <M-Space>, which
822         // should be passed on as is.)
823         len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
824         bytes = [unmodchars UTF8String];
825     } else if (imc == c && '2' == c) {
826         // HACK!  Translate Ctrl+2 to <C-@>.
827         static char ctrl_at = 0;
828         len = 1;  bytes = &ctrl_at;
829     } else if (imc == c && '6' == c) {
830         // HACK!  Translate Ctrl+6 to <C-^>.
831         static char ctrl_hat = 0x1e;
832         len = 1;  bytes = &ctrl_hat;
833     } else if (c == 0x19 && imc == 0x19) {
834         // HACK! AppKit turns back tab into Ctrl-Y, so we need to handle it
835         // separately (else Ctrl-Y doesn't work).
836         static char back_tab[2] = { 'k', 'B' };
837         len = 2; bytes = back_tab;
838     } else {
839         len = [chars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
840         bytes = [chars UTF8String];
841     }
843     [self sendKeyDown:bytes length:len modifiers:[event modifierFlags]];
846 - (MMVimController *)vimController
848     id windowController = [[self window] windowController];
850     // TODO: Make sure 'windowController' is a MMWindowController before type
851     // casting.
852     return [(MMWindowController*)windowController vimController];
855 - (void)startDragTimerWithInterval:(NSTimeInterval)t
857     [NSTimer scheduledTimerWithTimeInterval:t target:self
858                                    selector:@selector(dragTimerFired:)
859                                    userInfo:nil repeats:NO];
862 - (void)dragTimerFired:(NSTimer *)timer
864     // TODO: Autoscroll in horizontal direction?
865     static unsigned tick = 1;
866     MMTextStorage *ts = (MMTextStorage *)[self textStorage];
868     isAutoscrolling = NO;
870     if (isDragging && ts && (dragRow < 0 || dragRow >= [ts maxRows])) {
871         // HACK! If the mouse cursor is outside the text area, then send a
872         // dragged event.  However, if row&col hasn't changed since the last
873         // dragged event, Vim won't do anything (see gui_send_mouse_event()).
874         // Thus we fiddle with the column to make sure something happens.
875         int col = dragColumn + (dragRow < 0 ? -(tick % 2) : +(tick % 2));
876         NSMutableData *data = [NSMutableData data];
878         [data appendBytes:&dragRow length:sizeof(int)];
879         [data appendBytes:&col length:sizeof(int)];
880         [data appendBytes:&dragFlags length:sizeof(int)];
882         [[self vimController] sendMessage:MouseDraggedMsgID data:data wait:NO];
884         isAutoscrolling = YES;
885     }
887     if (isDragging) {
888         // Compute timer interval depending on how far away the mouse cursor is
889         // from the text view.
890         NSRect rect = [self trackingRect];
891         float dy = 0;
892         if (dragPoint.y < rect.origin.y) dy = rect.origin.y - dragPoint.y;
893         else if (dragPoint.y > NSMaxY(rect)) dy = dragPoint.y - NSMaxY(rect);
894         if (dy > MMDragAreaSize) dy = MMDragAreaSize;
896         NSTimeInterval t = MMDragTimerMaxInterval -
897             dy*(MMDragTimerMaxInterval-MMDragTimerMinInterval)/MMDragAreaSize;
899         [self startDragTimerWithInterval:t];
900     }
902     ++tick;
905 - (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags
907     if (chars && len > 0) {
908         NSMutableData *data = [NSMutableData data];
910         [data appendBytes:&flags length:sizeof(int)];
911         [data appendBytes:&len length:sizeof(int)];
912         [data appendBytes:chars length:len];
914         // TODO: Support 'mousehide' (check p_mh)
915         [NSCursor setHiddenUntilMouseMoves:YES];
917         //NSLog(@"%s len=%d chars=0x%x", _cmd, len, chars[0]);
918         [[self vimController] sendMessage:KeyDownMsgID data:data wait:NO];
919     }
922 @end // MMTextView (Private)