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 * Hooks for the Vim gui code. Mainly passes control on to MMBackend.
19 #import <Foundation/Foundation.h>
23 // NOTE: The default font is bundled with the application.
24 static NSString *MMDefaultFontName = @"DejaVu Sans Mono";
25 static int MMDefaultFontSize = 12;
26 static int MMMinFontSize = 6;
27 static int MMMaxFontSize = 100;
28 static BOOL gui_mch_init_has_finished = NO;
31 static GuiFont gui_macvim_font_with_name(char_u *name);
32 static int specialKeyToNSKey(int key);
33 static int vimModMaskToEventModifierFlags(int mods);
35 NSArray *descriptor_for_menu(vimmenu_T *menu);
36 vimmenu_T *menu_for_descriptor(NSArray *desc);
40 // -- Initialization --------------------------------------------------------
43 * Parse the GUI related command-line arguments. Any arguments used are
44 * deleted from argv, and *argc is decremented accordingly. This is called
45 * when vim is started, whether or not the GUI has been started.
48 gui_mch_prepare(int *argc, char **argv)
50 //NSLog(@"gui_mch_prepare(argc=%d)", *argc);
52 // Set environment variables $VIM and $VIMRUNTIME
53 // NOTE! If vim_getenv is called with one of these as parameters before
54 // they have been set here, they will most likely end up with the wrong
58 // - ensure this is called first to avoid above problem
61 NSString *path = [[[NSBundle mainBundle] resourcePath]
62 stringByAppendingPathComponent:@"vim"];
63 vim_setenv((char_u*)"VIM", (char_u*)[path UTF8String]);
65 path = [path stringByAppendingPathComponent:@"runtime"];
66 vim_setenv((char_u*)"VIMRUNTIME", (char_u*)[path UTF8String]);
69 for (i = 0; i < *argc; ++i) {
70 if (strncmp(argv[i], "--mmwaitforack", 14) == 0) {
71 [[MMBackend sharedInstance] setWaitForAck:YES];
74 mch_memmove(&argv[i], &argv[i+1], (*argc-i) * sizeof(char*));
82 * Check if the GUI can be started. Called before gvimrc is sourced.
86 gui_mch_init_check(void)
88 //NSLog(@"gui_mch_init_check()");
94 * Initialise the GUI. Create all the windows, set up all the call-backs etc.
95 * Returns OK for success, FAIL when the GUI can't be started.
100 //NSLog(@"gui_mch_init()");
102 // NOTE! Because OS X has to exec after fork we effectively end up doing
103 // the initialization twice (because this function is called before the
104 // fork). To avoid all this extra work we check if Vim is about to fork,
105 // and if so do nothing for now.
107 // TODO: Is this check 100% foolproof?
108 if (gui.dofork && (vim_strchr(p_go, GO_FORG) == NULL))
111 if (![[MMBackend sharedInstance] checkin]) {
112 // TODO: Kill the process if there is no terminal to fall back on,
113 // otherwise the process will run outputting to the console.
117 // Force 'termencoding' to utf-8 (changes to 'tenc' are disallowed in
118 // 'option.c', so that ':set termencoding=...' is impossible).
119 set_option_value((char_u *)"termencoding", 0L, (char_u *)"utf-8", 0);
121 // Set values so that pixels and characters are in one-to-one
122 // correspondence (assuming all characters have the same dimensions).
123 gui.scrollbar_width = gui.scrollbar_height = 0;
129 gui_mch_def_colors();
131 [[MMBackend sharedInstance]
132 setDefaultColorsBackground:gui.back_pixel foreground:gui.norm_pixel];
133 [[MMBackend sharedInstance] setBackgroundColor:gui.back_pixel];
134 [[MMBackend sharedInstance] setForegroundColor:gui.norm_pixel];
136 // NOTE: If this call is left out the cursor is opaque.
137 highlight_gui_started();
139 // Ensure 'linespace' option is passed along to MacVim in case it was set
141 gui_mch_adjust_charheight();
143 gui_mch_init_has_finished = YES;
153 //NSLog(@"gui_mch_exit(rc=%d)", rc);
155 [[MMBackend sharedInstance] exit];
160 * Open the GUI window which was created by a call to gui_mch_init().
165 //NSLog(@"gui_mch_open()");
167 // This check is to avoid doing extra work when we're about to fork.
168 if (!gui_mch_init_has_finished)
171 return [[MMBackend sharedInstance] openGUIWindow];
175 // -- Updating --------------------------------------------------------------
179 * Catch up with any queued X events. This may put keyboard input into the
180 * input buffer, call resize call-backs, trigger timers etc. If there is
181 * nothing in the X event queue (& no timers pending), then we return
187 // This function is called extremely often. It is tempting to do nothing
188 // here to avoid reduced frame-rates but then it would not be possible to
189 // interrupt Vim by presssing Ctrl-C during lengthy operations (e.g. after
190 // entering "10gs" it would not be possible to bring Vim out of the 10 s
191 // sleep prematurely). As a compromise we check for Ctrl-C only once per
193 static CFAbsoluteTime lastTime = 0;
195 CFAbsoluteTime nowTime = CFAbsoluteTimeGetCurrent();
196 if (nowTime - lastTime > 1.0) {
197 [[MMBackend sharedInstance] update];
203 /* Flush any output to the screen */
207 // This function is called way too often to be useful as a hint for
208 // flushing. If we were to flush every time it was called the screen would
213 /* Force flush output to MacVim. Do not call this method unless absolutely
216 gui_macvim_force_flush(void)
218 [[MMBackend sharedInstance] flushQueue:YES];
223 * GUI input routine called by gui_wait_for_chars(). Waits for a character
225 * wtime == -1 Wait forever.
226 * wtime == 0 This should never happen.
227 * wtime > 0 Wait wtime milliseconds for a character.
228 * Returns OK if a character was found to be available within the given time,
232 gui_mch_wait_for_chars(int wtime)
234 // NOTE! In all likelihood Vim will take a nap when waitForInput: is
235 // called, so force a flush of the command queue here.
236 [[MMBackend sharedInstance] flushQueue:YES];
238 return [[MMBackend sharedInstance] waitForInput:wtime];
242 // -- Drawing ---------------------------------------------------------------
246 * Clear the whole text window.
249 gui_mch_clear_all(void)
251 [[MMBackend sharedInstance] clearAll];
256 * Clear a rectangular region of the screen from text pos (row1, col1) to
257 * (row2, col2) inclusive.
260 gui_mch_clear_block(int row1, int col1, int row2, int col2)
262 [[MMBackend sharedInstance] clearBlockFromRow:row1 column:col1
263 toRow:row2 column:col2];
268 * Delete the given number of lines from the given row, scrolling up any
269 * text further down within the scroll region.
272 gui_mch_delete_lines(int row, int num_lines)
274 [[MMBackend sharedInstance] deleteLinesFromRow:row count:num_lines
275 scrollBottom:gui.scroll_region_bot
276 left:gui.scroll_region_left
277 right:gui.scroll_region_right];
282 gui_mch_draw_string(int row, int col, char_u *s, int len, int flags)
285 char_u *conv_str = NULL;
286 if (output_conv.vc_type != CONV_NONE) {
287 conv_str = string_convert(&output_conv, s, &len);
293 [[MMBackend sharedInstance] drawString:(char*)s length:len row:row
294 column:col cells:len flags:flags];
304 gui_macvim_draw_string(int row, int col, char_u *s, int len, int flags)
311 MMBackend *backend = [MMBackend sharedInstance];
313 char_u *conv_str = NULL;
315 if (output_conv.vc_type != CONV_NONE) {
316 conv_str = string_convert(&output_conv, s, &len);
322 // Loop over each character and output text when it changes from normal to
323 // wide and vice versa.
324 for (i = 0; i < len; i += cl) {
325 c = utf_ptr2char(s + i);
326 cn = utf_char2cells(c);
327 cl = utf_ptr2len(s + i);
329 len = i; // len must be wrong (shouldn't happen)
331 if (!utf_iscomposing(c)) {
332 if ((cn > 1 && !wide) || (cn <= 1 && wide)) {
333 // Changed from normal to wide or vice versa.
334 [backend drawString:(char*)(s+start) length:i-start
335 row:row column:startcol
336 cells:endcol-startcol
337 flags:(wide ? flags|DRAW_WIDE : flags)];
348 // Output remaining characters.
349 [backend drawString:(char*)(s+start) length:len-start
350 row:row column:startcol cells:endcol-startcol
351 flags:(wide ? flags|DRAW_WIDE : flags)];
363 * Insert the given number of lines before the given row, scrolling down any
364 * following text within the scroll region.
367 gui_mch_insert_lines(int row, int num_lines)
369 [[MMBackend sharedInstance] insertLinesFromRow:row count:num_lines
370 scrollBottom:gui.scroll_region_bot
371 left:gui.scroll_region_left
372 right:gui.scroll_region_right];
377 * Set the current text foreground color.
380 gui_mch_set_fg_color(guicolor_T color)
382 [[MMBackend sharedInstance] setForegroundColor:color];
387 * Set the current text background color.
390 gui_mch_set_bg_color(guicolor_T color)
392 [[MMBackend sharedInstance] setBackgroundColor:color];
397 * Set the current text special color (used for underlines).
400 gui_mch_set_sp_color(guicolor_T color)
402 [[MMBackend sharedInstance] setSpecialColor:color];
407 * Set default colors.
412 MMBackend *backend = [MMBackend sharedInstance];
414 // The default colors are taken from system values
415 gui.def_norm_pixel = gui.norm_pixel =
416 [backend lookupColorWithKey:@"MacTextColor"];
417 gui.def_back_pixel = gui.back_pixel =
418 [backend lookupColorWithKey:@"MacTextBackgroundColor"];
423 * Called when the foreground or background color has been changed.
426 gui_mch_new_colors(void)
428 gui.def_back_pixel = gui.back_pixel;
429 gui.def_norm_pixel = gui.norm_pixel;
431 //NSLog(@"gui_mch_new_colors(back=%x, norm=%x)", gui.def_back_pixel,
432 // gui.def_norm_pixel);
434 [[MMBackend sharedInstance]
435 setDefaultColorsBackground:gui.def_back_pixel
436 foreground:gui.def_norm_pixel];
440 * Invert a rectangle from row r, column c, for nr rows and nc columns.
443 gui_mch_invert_rectangle(int r, int c, int nr, int nc, int invert)
445 [[MMBackend sharedInstance] drawInvertedRectAtRow:r column:c numRows:nr
446 numColumns:nc invert:invert];
451 // -- Tabline ---------------------------------------------------------------
455 * Set the current tab to "nr". First tab is 1.
458 gui_mch_set_curtab(int nr)
460 [[MMBackend sharedInstance] selectTab:nr];
465 * Return TRUE when tabline is displayed.
468 gui_mch_showing_tabline(void)
470 return [[MMBackend sharedInstance] tabBarVisible];
474 * Update the labels of the tabline.
477 gui_mch_update_tabline(void)
479 [[MMBackend sharedInstance] updateTabBar];
483 * Show or hide the tabline.
486 gui_mch_show_tabline(int showit)
488 [[MMBackend sharedInstance] showTabBar:showit];
492 // -- Clipboard -------------------------------------------------------------
496 clip_mch_lose_selection(VimClipboard *cbd)
502 clip_mch_own_selection(VimClipboard *cbd)
509 clip_mch_request_selection(VimClipboard *cbd)
511 NSPasteboard *pb = [NSPasteboard generalPasteboard];
512 NSArray *supportedTypes = [NSArray arrayWithObjects:VimPBoardType,
513 NSStringPboardType, nil];
514 NSString *bestType = [pb availableTypeFromArray:supportedTypes];
515 if (!bestType) return;
517 int motion_type = MCHAR;
518 NSString *string = nil;
520 if ([bestType isEqual:VimPBoardType]) {
521 // This type should consist of an array with two objects:
522 // 1. motion type (NSNumber)
523 // 2. text (NSString)
524 // If this is not the case we fall back on using NSStringPboardType.
525 id plist = [pb propertyListForType:VimPBoardType];
526 if ([plist isKindOfClass:[NSArray class]] && [plist count] == 2) {
527 id obj = [plist objectAtIndex:1];
528 if ([obj isKindOfClass:[NSString class]]) {
529 motion_type = [[plist objectAtIndex:0] intValue];
536 // Use NSStringPboardType. The motion type is set to line-wise if the
537 // string contains at least one EOL character, otherwise it is set to
538 // character-wise (block-wise is never used).
539 NSMutableString *mstring =
540 [[pb stringForType:NSStringPboardType] mutableCopy];
541 if (!mstring) return;
543 // Replace unrecognized end-of-line sequences with \x0a (line feed).
544 NSRange range = { 0, [mstring length] };
545 unsigned n = [mstring replaceOccurrencesOfString:@"\x0d\x0a"
546 withString:@"\x0a" options:0
549 n = [mstring replaceOccurrencesOfString:@"\x0d" withString:@"\x0a"
550 options:0 range:range];
553 // Scan for newline character to decide whether the string should be
554 // pasted line-wise or character-wise.
556 if (0 < n || NSNotFound != [mstring rangeOfString:@"\n"].location)
562 if (!(MCHAR == motion_type || MLINE == motion_type || MBLOCK == motion_type
563 || MAUTO == motion_type))
566 char_u *str = (char_u*)[string UTF8String];
567 int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
570 if (input_conv.vc_type != CONV_NONE)
571 str = string_convert(&input_conv, str, &len);
575 clip_yank_selection(motion_type, str, len, cbd);
578 if (input_conv.vc_type != CONV_NONE)
585 * Send the current selection to the clipboard.
588 clip_mch_set_selection(VimClipboard *cbd)
590 // If the '*' register isn't already filled in, fill it in now.
592 clip_get_selection(cbd);
595 // Get the text to put on the pasteboard.
596 long_u llen = 0; char_u *str = 0;
597 int motion_type = clip_convert_selection(&str, &llen, cbd);
601 // TODO: Avoid overflow.
604 if (output_conv.vc_type != CONV_NONE) {
605 char_u *conv_str = string_convert(&output_conv, str, &len);
614 NSString *string = [[NSString alloc]
615 initWithBytes:str length:len encoding:NSUTF8StringEncoding];
617 // See clip_mch_request_selection() for info on pasteboard types.
618 NSPasteboard *pb = [NSPasteboard generalPasteboard];
619 NSArray *supportedTypes = [NSArray arrayWithObjects:VimPBoardType,
620 NSStringPboardType, nil];
621 [pb declareTypes:supportedTypes owner:nil];
623 NSNumber *motion = [NSNumber numberWithInt:motion_type];
624 NSArray *plist = [NSArray arrayWithObjects:motion, string, nil];
625 [pb setPropertyList:plist forType:VimPBoardType];
627 [pb setString:string forType:NSStringPboardType];
636 // -- Menu ------------------------------------------------------------------
640 * A menu descriptor represents the "address" of a menu as an array of strings.
641 * E.g. the menu "File->Close" has descriptor { "File", "Close" }.
644 descriptor_for_menu(vimmenu_T *menu)
646 if (!menu) return nil;
648 NSMutableArray *desc = [NSMutableArray array];
650 NSString *name = [NSString stringWithVimString:menu->dname];
651 [desc insertObject:name atIndex:0];
659 menu_for_descriptor(NSArray *desc)
661 if (!(desc && [desc count] > 0)) return NULL;
663 vimmenu_T *menu = root_menu;
664 int i, count = [desc count];
666 for (i = 0; i < count; ++i) {
667 NSString *component = [desc objectAtIndex:i];
669 NSString *name = [NSString stringWithVimString:menu->dname];
670 if ([component isEqual:name]) {
672 return menu; // Matched all components, so return menu
673 menu = menu->children;
684 * Add a submenu to the menu bar, toolbar, or a popup menu.
687 gui_mch_add_menu(vimmenu_T *menu, int idx)
689 NSArray *desc = descriptor_for_menu(menu);
690 [[MMBackend sharedInstance] queueMessage:AddMenuMsgID properties:
691 [NSDictionary dictionaryWithObjectsAndKeys:
693 [NSNumber numberWithInt:idx], @"index",
698 // Taken from gui_gtk.c (slightly modified)
700 lookup_menu_iconfile(char_u *iconfile, char_u *dest)
702 expand_env(iconfile, dest, MAXPATHL);
704 if (mch_isFullName(dest))
705 return vim_fexists(dest);
707 static const char suffixes[][4] = {"png", "bmp"};
708 char_u buf[MAXPATHL];
711 for (i = 0; i < sizeof(suffixes)/sizeof(suffixes[0]); ++i)
712 if (gui_find_bitmap(dest, buf, (char *)suffixes[i]) == OK) {
722 * Add a menu item to a menu
725 gui_mch_add_menu_item(vimmenu_T *menu, int idx)
727 char_u *tip = menu->strings[MENU_INDEX_TIP]
728 ? menu->strings[MENU_INDEX_TIP] : menu->actext;
729 NSArray *desc = descriptor_for_menu(menu);
730 NSString *keyEquivalent = menu->mac_key
731 ? [NSString stringWithFormat:@"%C", specialKeyToNSKey(menu->mac_key)]
733 int modifierMask = vimModMaskToEventModifierFlags(menu->mac_mods);
736 if (menu_is_toolbar(menu->parent->name)) {
737 char_u fname[MAXPATHL];
739 // Try to use the icon=.. argument
740 if (menu->iconfile && lookup_menu_iconfile(menu->iconfile, fname))
743 // If not found and not builtin specified try using the menu name
744 if (!icon && !menu->icon_builtin
745 && lookup_menu_iconfile(menu->name, fname))
748 // Last resort, use display name (usually signals a builtin icon)
753 [[MMBackend sharedInstance] queueMessage:AddMenuItemMsgID properties:
754 [NSDictionary dictionaryWithObjectsAndKeys:
756 [NSNumber numberWithInt:idx], @"index",
757 [NSString stringWithVimString:tip], @"tip",
758 [NSString stringWithVimString:icon], @"icon",
759 keyEquivalent, @"keyEquivalent",
760 [NSNumber numberWithInt:modifierMask], @"modifierMask",
761 [NSString stringWithVimString:menu->mac_action], @"action",
762 [NSNumber numberWithBool:menu->mac_alternate], @"isAlternate",
768 * Destroy the machine specific menu widget.
771 gui_mch_destroy_menu(vimmenu_T *menu)
773 NSArray *desc = descriptor_for_menu(menu);
774 [[MMBackend sharedInstance] queueMessage:RemoveMenuItemMsgID properties:
775 [NSDictionary dictionaryWithObject:desc forKey:@"descriptor"]];
780 * Make a menu either grey or not grey.
783 gui_mch_menu_grey(vimmenu_T *menu, int grey)
785 /* Only update menu if the 'grey' state has changed to avoid having to pass
786 * lots of unnecessary data to MacVim. (Skipping this test makes MacVim
787 * pause noticably on mode changes. */
788 NSArray *desc = descriptor_for_menu(menu);
789 if (menu->was_grey == grey)
792 menu->was_grey = grey;
794 [[MMBackend sharedInstance] queueMessage:EnableMenuItemMsgID properties:
795 [NSDictionary dictionaryWithObjectsAndKeys:
797 [NSNumber numberWithInt:!grey], @"enable",
803 * Make menu item hidden or not hidden
806 gui_mch_menu_hidden(vimmenu_T *menu, int hidden)
808 // HACK! There is no (obvious) way to hide a menu item, so simply
809 // enable/disable it instead.
810 gui_mch_menu_grey(menu, hidden);
815 * This is called when user right clicks.
818 gui_mch_show_popupmenu(vimmenu_T *menu)
820 NSArray *desc = descriptor_for_menu(menu);
821 [[MMBackend sharedInstance] queueMessage:ShowPopupMenuMsgID properties:
822 [NSDictionary dictionaryWithObject:desc forKey:@"descriptor"]];
827 * This is called when a :popup command is executed.
830 gui_make_popup(char_u *path_name, int mouse_pos)
832 vimmenu_T *menu = gui_find_menu(path_name);
833 if (!(menu && menu->children)) return;
835 NSArray *desc = descriptor_for_menu(menu);
836 NSDictionary *p = (mouse_pos || NULL == curwin)
837 ? [NSDictionary dictionaryWithObject:desc forKey:@"descriptor"]
838 : [NSDictionary dictionaryWithObjectsAndKeys:
840 [NSNumber numberWithInt:curwin->w_wrow], @"row",
841 [NSNumber numberWithInt:curwin->w_wcol], @"column",
844 [[MMBackend sharedInstance] queueMessage:ShowPopupMenuMsgID properties:p];
849 * This is called after setting all the menus to grey/hidden or not.
852 gui_mch_draw_menubar(void)
854 // The (main) menu draws itself in Mac OS X.
859 gui_mch_enable_menu(int flag)
861 // The (main) menu is always enabled in Mac OS X.
867 gui_mch_set_menu_pos(int x, int y, int w, int h)
869 // The (main) menu cannot be moved in Mac OS X.
875 gui_mch_show_toolbar(int showit)
878 if (toolbar_flags & TOOLBAR_TEXT) flags |= ToolbarLabelFlag;
879 if (toolbar_flags & TOOLBAR_ICONS) flags |= ToolbarIconFlag;
880 if (tbis_flags & (TBIS_MEDIUM|TBIS_LARGE)) flags |= ToolbarSizeRegularFlag;
882 [[MMBackend sharedInstance] showToolbar:showit flags:flags];
888 // -- Fonts -----------------------------------------------------------------
892 * If a font is not going to be used, free its structure.
895 gui_mch_free_font(font)
898 if (font != NOFONT) {
899 //NSLog(@"gui_mch_free_font(font=0x%x)", font);
906 gui_mch_retain_font(GuiFont font)
908 return (GuiFont)[(id)font retain];
913 * Get a font structure for highlighting.
916 gui_mch_get_font(char_u *name, int giveErrorIfMissing)
918 //NSLog(@"gui_mch_get_font(name=%s, giveErrorIfMissing=%d)", name,
919 // giveErrorIfMissing);
921 GuiFont font = gui_macvim_font_with_name(name);
925 if (giveErrorIfMissing)
926 EMSG2(_(e_font), name);
932 #if defined(FEAT_EVAL) || defined(PROTO)
934 * Return the name of font "font" in allocated memory.
935 * TODO: use 'font' instead of 'name'?
938 gui_mch_get_fontname(GuiFont font, char_u *name)
940 return name ? vim_strsave(name) : NULL;
946 * Initialise vim to use the font with the given name. Return FAIL if the font
947 * could not be loaded, OK otherwise.
950 gui_mch_init_font(char_u *font_name, int fontset)
952 //NSLog(@"gui_mch_init_font(font_name=%s, fontset=%d)", font_name, fontset);
954 if (font_name && STRCMP(font_name, "*") == 0) {
955 // :set gfn=* shows the font panel.
956 do_cmdline_cmd((char_u*)":macaction orderFrontFontPanel:");
960 GuiFont font = gui_macvim_font_with_name(font_name);
964 gui_mch_free_font(gui.norm_font);
965 gui.norm_font = font;
967 // NOTE: MacVim keeps separate track of the normal and wide fonts.
968 // Unless the user changes 'guifontwide' manually, they are based on
969 // the same (normal) font. Also note that each time the normal font is
970 // set, the advancement may change so the wide font needs to be updated
971 // as well (so that it is always twice the width of the normal font).
972 [[MMBackend sharedInstance] setFont:font wide:NO];
973 [[MMBackend sharedInstance] setFont:(NOFONT != gui.wide_font ? gui.wide_font
982 * Set the current text font.
985 gui_mch_set_font(GuiFont font)
987 // Font selection is done inside MacVim...nothing here to do.
992 * Return GuiFont in allocated memory. The caller must free it using
993 * gui_mch_free_font().
996 gui_macvim_font_with_name(char_u *name)
999 return (GuiFont)[[NSString alloc] initWithFormat:@"%@:%d",
1000 MMDefaultFontName, MMDefaultFontSize];
1002 NSString *fontName = [NSString stringWithVimString:name];
1003 int size = MMDefaultFontSize;
1004 BOOL parseFailed = NO;
1006 NSArray *components = [fontName componentsSeparatedByString:@":"];
1007 if ([components count] == 2) {
1008 NSString *sizeString = [components lastObject];
1009 if ([sizeString length] > 0
1010 && [sizeString characterAtIndex:0] == 'h') {
1011 sizeString = [sizeString substringFromIndex:1];
1012 if ([sizeString length] > 0) {
1013 size = (int)round([sizeString floatValue]);
1014 fontName = [components objectAtIndex:0];
1019 } else if ([components count] > 2) {
1024 // Replace underscores with spaces.
1025 fontName = [[fontName componentsSeparatedByString:@"_"]
1026 componentsJoinedByString:@" "];
1029 if (!parseFailed && [fontName length] > 0) {
1030 if (size < MMMinFontSize) size = MMMinFontSize;
1031 if (size > MMMaxFontSize) size = MMMaxFontSize;
1033 // If the default font is requested we don't check if NSFont can load
1034 // it since the font most likely isn't loaded anyway (it may only be
1035 // available to the MacVim binary). If it is not the default font we
1036 // ask NSFont if it can load it.
1037 if ([fontName isEqualToString:MMDefaultFontName]
1038 || [NSFont fontWithName:fontName size:size])
1039 return [[NSString alloc] initWithFormat:@"%@:%d", fontName, size];
1045 // -- Scrollbars ------------------------------------------------------------
1049 gui_mch_create_scrollbar(
1051 int orient) /* SBAR_VERT or SBAR_HORIZ */
1053 [[MMBackend sharedInstance]
1054 createScrollbarWithIdentifier:sb->ident type:sb->type];
1059 gui_mch_destroy_scrollbar(scrollbar_T *sb)
1061 [[MMBackend sharedInstance]
1062 destroyScrollbarWithIdentifier:sb->ident];
1067 gui_mch_enable_scrollbar(
1071 [[MMBackend sharedInstance]
1072 showScrollbarWithIdentifier:sb->ident state:flag];
1077 gui_mch_set_scrollbar_pos(
1086 if (SBAR_BOTTOM == sb->type) {
1091 [[MMBackend sharedInstance]
1092 setScrollbarPosition:pos length:len identifier:sb->ident];
1097 gui_mch_set_scrollbar_thumb(
1103 [[MMBackend sharedInstance]
1104 setScrollbarThumbValue:val size:size max:max identifier:sb->ident];
1108 // -- Cursor ----------------------------------------------------------------
1112 * Draw a cursor without focus.
1115 gui_mch_draw_hollow_cursor(guicolor_T color)
1117 return [[MMBackend sharedInstance]
1118 drawCursorAtRow:gui.row column:gui.col shape:MMInsertionPointHollow
1119 fraction:100 color:color];
1124 * Draw part of a cursor, only w pixels wide, and h pixels high.
1127 gui_mch_draw_part_cursor(int w, int h, guicolor_T color)
1129 // HACK! 'w' and 'h' are always 1 since we do not tell Vim about the exact
1130 // font dimensions. Thus these parameters are useless. Instead we look at
1131 // the shape_table to determine the shape and size of the cursor (just like
1132 // gui_update_cursor() does).
1134 #ifdef FEAT_RIGHTLEFT
1135 // If 'rl' is set the insert mode cursor must be drawn on the right-hand
1136 // side of a text cell.
1137 int rl = curwin ? curwin->w_p_rl : FALSE;
1141 int idx = get_shape_idx(FALSE);
1142 int shape = MMInsertionPointBlock;
1143 switch (shape_table[idx].shape) {
1145 shape = MMInsertionPointHorizontal;
1148 shape = rl ? MMInsertionPointVerticalRight
1149 : MMInsertionPointVertical;
1153 return [[MMBackend sharedInstance]
1154 drawCursorAtRow:gui.row column:gui.col shape:shape
1155 fraction:shape_table[idx].percentage color:color];
1160 * Cursor blink functions.
1162 * This is a simple state machine:
1163 * BLINK_NONE not blinking at all
1164 * BLINK_OFF blinking, cursor is not shown
1165 * BLINK_ON blinking, cursor is shown
1168 gui_mch_set_blinking(long wait, long on, long off)
1170 [[MMBackend sharedInstance] setBlinkWait:wait on:on off:off];
1175 * Start the cursor blinking. If it was already blinking, this restarts the
1176 * waiting time and shows the cursor.
1179 gui_mch_start_blink(void)
1181 [[MMBackend sharedInstance] startBlink];
1186 * Stop the cursor blinking. Show the cursor if it wasn't shown.
1189 gui_mch_stop_blink(void)
1191 [[MMBackend sharedInstance] stopBlink];
1195 // -- Mouse -----------------------------------------------------------------
1199 * Get current mouse coordinates in text window.
1202 gui_mch_getmouse(int *x, int *y)
1204 //NSLog(@"gui_mch_getmouse()");
1209 gui_mch_setmouse(int x, int y)
1211 //NSLog(@"gui_mch_setmouse(x=%d, y=%d)", x, y);
1216 mch_set_mouse_shape(int shape)
1218 [[MMBackend sharedInstance] setMouseShape:shape];
1224 // -- Input Method ----------------------------------------------------------
1226 #if defined(USE_IM_CONTROL)
1229 im_set_position(int row, int col)
1231 // The pre-edit area is a popup window which is displayed by MMTextView.
1232 [[MMBackend sharedInstance] setPreEditRow:row column:col];
1237 im_set_active(int active)
1239 // Set roman or the system script if 'active' is TRUE or FALSE,
1241 SInt32 systemScript = GetScriptManagerVariable(smSysScript);
1243 if (!p_imdisable && smRoman != systemScript)
1244 KeyScript(active ? smKeySysScript : smKeyRoman);
1251 // IM is active whenever the current script is the system script and the
1252 // system script isn't roman. (Hence IM can only be active when using
1253 // non-roman scripts.)
1254 SInt32 currentScript = GetScriptManagerVariable(smKeyScript);
1255 SInt32 systemScript = GetScriptManagerVariable(smSysScript);
1257 return currentScript != smRoman && currentScript == systemScript;
1260 #endif // defined(USE_IM_CONTROL)
1265 // -- Find & Replace dialog -------------------------------------------------
1267 #ifdef FIND_REPLACE_DIALOG
1270 macvim_find_and_replace(char_u *arg, BOOL replace)
1272 // TODO: Specialized dialog for find without replace?
1273 int wholeWord = FALSE;
1274 int matchCase = !p_ic;
1275 char_u *text = get_find_dialog_text(arg, &wholeWord, &matchCase);
1278 if (wholeWord) flags |= FRD_WHOLE_WORD;
1279 if (matchCase) flags |= FRD_MATCH_CASE;
1281 NSDictionary *args = [NSDictionary dictionaryWithObjectsAndKeys:
1282 [NSString stringWithVimString:text], @"text",
1283 [NSNumber numberWithInt:flags], @"flags",
1286 [[MMBackend sharedInstance] queueMessage:ShowFindReplaceDialogMsgID
1291 gui_mch_find_dialog(exarg_T *eap)
1293 macvim_find_and_replace(eap->arg, NO);
1297 gui_mch_replace_dialog(exarg_T *eap)
1299 macvim_find_and_replace(eap->arg, YES);
1302 #endif // FIND_REPLACE_DIALOG
1307 // -- Unsorted --------------------------------------------------------------
1315 EMSG(_("E???: Command only available in GUI mode"));
1319 char_u *arg = eap->arg;
1321 arg = CONVERT_TO_UTF8(arg);
1324 NSDictionary *actionDict = [[MMBackend sharedInstance] actionDict];
1325 NSString *name = [NSString stringWithUTF8String:(char*)arg];
1326 if (actionDict && [actionDict objectForKey:name] != nil) {
1327 [[MMBackend sharedInstance] executeActionWithName:name];
1329 EMSG2(_("E???: Invalid action: %s"), eap->arg);
1333 arg = CONVERT_TO_UTF8(arg);
1339 * Adjust gui.char_height (after 'linespace' was changed).
1342 gui_mch_adjust_charheight(void)
1344 [[MMBackend sharedInstance] adjustLinespace:p_linespace];
1359 * Pop open a file browser and return the file selected, in allocated memory,
1360 * or NULL if Cancel is hit.
1361 * saving - TRUE if the file will be saved to, FALSE if it will be opened.
1362 * title - Title message for the file browser dialog.
1363 * dflt - Default name of file.
1364 * ext - Default extension to be added to files without extensions.
1365 * initdir - directory in which to open the browser (NULL = current dir)
1366 * filter - Filter for matched files to choose from.
1367 * Has a format like this:
1368 * "C Files (*.c)\0*.c\0"
1369 * "All Files\0*.*\0\0"
1370 * If these two strings were concatenated, then a choice of two file
1371 * filters will be selectable to the user. Then only matching files will
1372 * be shown in the browser. If NULL, the default allows all files.
1374 * *NOTE* - the filter string must be terminated with TWO nulls.
1385 //NSLog(@"gui_mch_browse(saving=%d, title=%s, dflt=%s, ext=%s, initdir=%s,"
1386 // " filter=%s", saving, title, dflt, ext, initdir, filter);
1388 // Ensure no data is on the output queue before presenting the dialog.
1389 gui_macvim_force_flush();
1391 NSMutableDictionary *attr = [NSMutableDictionary
1392 dictionaryWithObject:[NSNumber numberWithBool:saving]
1395 [attr setObject:[NSString stringWithVimString:initdir] forKey:@"dir"];
1397 char_u *s = (char_u*)[[MMBackend sharedInstance]
1398 browseForFileWithAttributes:attr];
1402 #endif /* FEAT_BROWSE */
1415 //NSLog(@"gui_mch_dialog(type=%d title=%s message=%s buttons=%s "
1416 // "dfltbutton=%d textfield=%s)", type, title, message, buttons,
1417 // dfltbutton, textfield);
1419 // Ensure no data is on the output queue before presenting the dialog.
1420 gui_macvim_force_flush();
1422 int style = NSInformationalAlertStyle;
1423 if (VIM_WARNING == type) style = NSWarningAlertStyle;
1424 else if (VIM_ERROR == type) style = NSCriticalAlertStyle;
1426 NSMutableDictionary *attr = [NSMutableDictionary
1427 dictionaryWithObject:[NSNumber numberWithInt:style]
1428 forKey:@"alertStyle"];
1431 // 'buttons' is a string of '\n'-separated button titles
1432 NSString *string = [NSString stringWithVimString:buttons];
1433 NSArray *array = [string componentsSeparatedByString:@"\n"];
1434 [attr setObject:array forKey:@"buttonTitles"];
1437 NSString *messageText = nil;
1439 messageText = [NSString stringWithVimString:title];
1442 NSString *informativeText = [NSString stringWithVimString:message];
1444 // HACK! If there is a '\n\n' or '\n' sequence in the message, then
1445 // make the part up to there into the title. We only do this
1446 // because Vim has lots of dialogs without a title and they look
1448 // TODO: Fix the actual dialog texts.
1449 NSRange eolRange = [informativeText rangeOfString:@"\n\n"];
1450 if (NSNotFound == eolRange.location)
1451 eolRange = [informativeText rangeOfString:@"\n"];
1452 if (NSNotFound != eolRange.location) {
1453 messageText = [informativeText substringToIndex:
1455 informativeText = [informativeText substringFromIndex:
1456 NSMaxRange(eolRange)];
1460 [attr setObject:informativeText forKey:@"informativeText"];
1464 [attr setObject:messageText forKey:@"messageText"];
1467 NSString *string = [NSString stringWithVimString:textfield];
1468 [attr setObject:string forKey:@"textFieldString"];
1471 return [[MMBackend sharedInstance] showDialogWithAttributes:attr
1472 textField:(char*)textfield];
1477 gui_mch_flash(int msec)
1483 * Return the Pixel value (color) for the given color name. This routine was
1484 * pretty much taken from example code in the Silicon Graphics OSF/Motif
1485 * Programmer's Guide.
1486 * Return INVALCOLOR when failed.
1489 gui_mch_get_color(char_u *name)
1492 name = CONVERT_TO_UTF8(name);
1495 NSString *key = [NSString stringWithUTF8String:(char*)name];
1496 guicolor_T col = [[MMBackend sharedInstance] lookupColorWithKey:key];
1499 CONVERT_TO_UTF8_FREE(name);
1507 * Return the RGB value of a pixel as long.
1510 gui_mch_get_rgb(guicolor_T pixel)
1512 // This is only implemented so that vim can guess the correct value for
1513 // 'background' (which otherwise defaults to 'dark'); it is not used for
1514 // anything else (as far as I know).
1515 // The implementation is simple since colors are stored in an int as
1522 * Get the screen dimensions.
1523 * Allow 10 pixels for horizontal borders, 40 for vertical borders.
1524 * Is there no way to find out how wide the borders really are?
1525 * TODO: Add live udate of those value on suspend/resume.
1528 gui_mch_get_screen_dimensions(int *screen_w, int *screen_h)
1530 //NSLog(@"gui_mch_get_screen_dimensions()");
1531 *screen_w = Columns;
1537 * Get the position of the top left corner of the window.
1540 gui_mch_get_winpos(int *x, int *y)
1548 * Return OK if the key with the termcap name "name" is supported.
1551 gui_mch_haskey(char_u *name)
1556 name = CONVERT_TO_UTF8(name);
1559 NSString *value = [NSString stringWithUTF8String:(char*)name];
1561 ok = [[MMBackend sharedInstance] hasSpecialKeyWithValue:value];
1564 CONVERT_TO_UTF8_FREE(name);
1572 * Iconify the GUI window.
1575 gui_mch_iconify(void)
1580 #if defined(FEAT_EVAL) || defined(PROTO)
1582 * Bring the Vim window to the foreground.
1585 gui_mch_set_foreground(void)
1587 [[MMBackend sharedInstance] activate];
1594 gui_mch_set_shellsize(
1603 //NSLog(@"gui_mch_set_shellsize(width=%d, height=%d, min_width=%d,"
1604 // " min_height=%d, base_width=%d, base_height=%d, direction=%d)",
1605 // width, height, min_width, min_height, base_width, base_height,
1607 [[MMBackend sharedInstance] setRows:height columns:width];
1612 gui_mch_set_text_area_pos(int x, int y, int w, int h)
1617 * Set the position of the top left corner of the window to the given
1621 gui_mch_set_winpos(int x, int y)
1628 * Set the window title and icon.
1629 * (The icon is not taken care of).
1632 gui_mch_settitle(char_u *title, char_u *icon)
1634 //NSLog(@"gui_mch_settitle(title=%s, icon=%s)", title, icon);
1637 title = CONVERT_TO_UTF8(title);
1640 MMBackend *backend = [MMBackend sharedInstance];
1641 [backend setWindowTitle:(char*)title];
1643 // TODO: Convert filename to UTF-8?
1645 [backend setDocumentFilename:(char*)curbuf->b_ffname];
1648 CONVERT_TO_UTF8_FREE(title);
1655 gui_mch_toggle_tearoffs(int enable)
1662 gui_mch_enter_fullscreen(int fuoptions_flags, guicolor_T bg)
1664 [[MMBackend sharedInstance] enterFullscreen:fuoptions_flags background:bg];
1669 gui_mch_leave_fullscreen()
1671 [[MMBackend sharedInstance] leaveFullscreen];
1676 gui_mch_fuopt_update()
1679 if (fuoptions_flags & FUOPT_BGCOLOR_HLGROUP) {
1680 syn_id2colors(fuoptions_bgcolor, &fg, &bg);
1682 bg = fuoptions_bgcolor;
1685 [[MMBackend sharedInstance] setFullscreenBackgroundColor:bg];
1690 gui_macvim_update_modified_flag()
1692 [[MMBackend sharedInstance] updateModifiedFlag];
1696 * Add search pattern 'pat' to the OS X find pasteboard. This allows other
1697 * apps access the last pattern searched for (hitting <D-g> in another app will
1698 * initiate a search for the same pattern).
1701 gui_macvim_add_to_find_pboard(char_u *pat)
1706 pat = CONVERT_TO_UTF8(pat);
1708 NSString *s = [NSString stringWithUTF8String:(char*)pat];
1710 CONVERT_TO_UTF8_FREE(pat);
1715 NSPasteboard *pb = [NSPasteboard pasteboardWithName:NSFindPboard];
1716 [pb declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil];
1717 [pb setString:s forType:NSStringPboardType];
1721 gui_macvim_set_antialias(int antialias)
1723 [[MMBackend sharedInstance] setAntialias:antialias];
1728 gui_macvim_wait_for_startup()
1730 MMBackend *backend = [MMBackend sharedInstance];
1731 if ([backend waitForAck])
1732 [backend waitForConnectionAcknowledgement];
1735 void gui_macvim_get_window_layout(int *count, int *layout)
1737 if (!(count && layout)) return;
1739 // NOTE: Only set 'layout' if the backend has requested a != 0 layout, else
1740 // any command line arguments (-p/-o) would be ignored.
1741 int window_layout = [[MMBackend sharedInstance] initialWindowLayout];
1742 if (window_layout > 0 && window_layout < 4) {
1743 // The window_layout numbers must match the WIN_* defines in main.c.
1745 *layout = window_layout;
1750 // -- Client/Server ---------------------------------------------------------
1752 #ifdef MAC_CLIENTSERVER
1755 // NOTE: Client/Server is only fully supported with a GUI. Theoretically it
1756 // would be possible to make the server code work with terminal Vim, but it
1757 // would require that a run-loop is set up and checked. This should not be
1758 // difficult to implement, simply call gui_mch_update() at opportune moments
1759 // and it will take care of the run-loop. Another (bigger) problem with
1760 // supporting servers in terminal mode is that the server listing code talks to
1761 // MacVim (the GUI) to figure out which servers are running.
1766 * Register connection with 'name'. The actual connection is named something
1767 * like 'org.vim.MacVim.VIM3', whereas the server is called 'VIM3'.
1770 serverRegisterName(char_u *name)
1773 name = CONVERT_TO_UTF8(name);
1776 NSString *svrName = [NSString stringWithUTF8String:(char*)name];
1777 [[MMBackend sharedInstance] registerServerWithName:svrName];
1780 CONVERT_TO_UTF8_FREE(name);
1786 * Send to an instance of Vim.
1787 * Returns 0 for OK, negative for an error.
1790 serverSendToVim(char_u *name, char_u *cmd, char_u **result,
1791 int *port, int asExpr, int silent)
1794 name = CONVERT_TO_UTF8(name);
1795 cmd = CONVERT_TO_UTF8(cmd);
1798 BOOL ok = [[MMBackend sharedInstance]
1799 sendToServer:[NSString stringWithUTF8String:(char*)name]
1800 string:[NSString stringWithUTF8String:(char*)cmd]
1807 CONVERT_TO_UTF8_FREE(name);
1808 CONVERT_TO_UTF8_FREE(cmd);
1816 * Ask MacVim for the names of all Vim servers.
1819 serverGetVimNames(void)
1821 char_u *names = NULL;
1822 NSArray *list = [[MMBackend sharedInstance] serverList];
1825 NSString *string = [list componentsJoinedByString:@"\n"];
1826 names = [string vimStringSave];
1834 * 'str' is a hex int representing the send port of the connection.
1837 serverStrToPort(char_u *str)
1841 sscanf((char *)str, "0x%x", &port);
1843 EMSG2(_("E573: Invalid server id used: %s"), str);
1850 * Check for replies from server with send port 'port'.
1851 * Return TRUE and a non-malloc'ed string if there is. Else return FALSE.
1854 serverPeekReply(int port, char_u **str)
1856 NSString *reply = [[MMBackend sharedInstance] peekForReplyOnPort:port];
1857 int len = [reply lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1859 if (str && len > 0) {
1860 *str = (char_u*)[reply UTF8String];
1863 if (input_conv.vc_type != CONV_NONE) {
1864 char_u *s = string_convert(&input_conv, *str, &len);
1867 // HACK! Since 's' needs to be freed we cannot simply set
1868 // '*str = s' or memory will leak. Instead, create a dummy
1869 // NSData and return its 'bytes' pointer, then autorelease the
1871 NSData *data = [NSData dataWithBytes:s length:len+1];
1872 *str = (char_u*)[data bytes];
1880 return reply != nil;
1885 * Wait for replies from server with send port 'port'.
1886 * Return 0 and the malloc'ed string when a reply is available.
1887 * Return -1 on error.
1890 serverReadReply(int port, char_u **str)
1892 NSString *reply = [[MMBackend sharedInstance] waitForReplyOnPort:port];
1894 *str = [reply vimStringSave];
1903 * Send a reply string (notification) to client with port given by "serverid".
1904 * Return -1 if the window is invalid.
1907 serverSendReply(char_u *serverid, char_u *reply)
1910 int port = serverStrToPort(serverid);
1911 if (port > 0 && reply) {
1913 reply = CONVERT_TO_UTF8(reply);
1915 BOOL ok = [[MMBackend sharedInstance]
1916 sendReply:[NSString stringWithUTF8String:(char*)reply]
1918 retval = ok ? 0 : -1;
1920 CONVERT_TO_UTF8_FREE(reply);
1927 #endif // MAC_CLIENTSERVER
1932 // -- ODB Editor Support ----------------------------------------------------
1934 #ifdef FEAT_ODB_EDITOR
1936 * The ODB Editor protocol works like this:
1937 * - An external program (the server) asks MacVim to open a file and associates
1938 * three things with this file: (1) a server id (a four character code that
1939 * identifies the server), (2) a path that can be used as window title for
1940 * the file (optional), (3) an arbitrary token (optional)
1941 * - When a file is saved or closed, MacVim should tell the server about which
1942 * file was modified and also pass back the token
1944 * All communication between MacVim and the server goes via Apple Events.
1948 odb_event(buf_T *buf, const AEEventID action)
1950 if (!(buf->b_odb_server_id && buf->b_ffname))
1953 NSAppleEventDescriptor *targetDesc = [NSAppleEventDescriptor
1954 descriptorWithDescriptorType:typeApplSignature
1955 bytes:&buf->b_odb_server_id
1956 length:sizeof(OSType)];
1958 // TODO: Convert b_ffname to UTF-8?
1959 NSString *path = [NSString stringWithUTF8String:(char*)buf->b_ffname];
1960 NSData *pathData = [[[NSURL fileURLWithPath:path] absoluteString]
1961 dataUsingEncoding:NSUTF8StringEncoding];
1962 NSAppleEventDescriptor *pathDesc = [NSAppleEventDescriptor
1963 descriptorWithDescriptorType:typeFileURL data:pathData];
1965 NSAppleEventDescriptor *event = [NSAppleEventDescriptor
1966 appleEventWithEventClass:kODBEditorSuite
1968 targetDescriptor:targetDesc
1969 returnID:kAutoGenerateReturnID
1970 transactionID:kAnyTransactionID];
1972 [event setParamDescriptor:pathDesc forKeyword:keyDirectObject];
1974 if (buf->b_odb_token)
1975 [event setParamDescriptor:buf->b_odb_token forKeyword:keySenderToken];
1977 return AESendMessage([event aeDesc], NULL, kAENoReply | kAENeverInteract,
1982 odb_buffer_close(buf_T *buf)
1986 err = odb_event(buf, kAEClosedFile);
1988 buf->b_odb_server_id = 0;
1990 if (buf->b_odb_token) {
1991 [(NSAppleEventDescriptor *)(buf->b_odb_token) release];
1992 buf->b_odb_token = NULL;
1995 if (buf->b_odb_fname) {
1996 vim_free(buf->b_odb_fname);
1997 buf->b_odb_fname = NULL;
2005 odb_post_buffer_write(buf_T *buf)
2007 return buf ? odb_event(buf, kAEModifiedFile) : noErr;
2014 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
2015 odb_buffer_close(buf);
2018 #endif // FEAT_ODB_EDITOR
2022 get_macaction_name(expand_T *xp, int idx)
2024 static char_u *str = NULL;
2025 NSDictionary *actionDict = [[MMBackend sharedInstance] actionDict];
2027 if (nil == actionDict || idx < 0 || idx >= [actionDict count])
2030 NSString *string = [[actionDict allKeys] objectAtIndex:idx];
2034 char_u *plainStr = (char_u*)[string UTF8String];
2041 if (input_conv.vc_type != CONV_NONE) {
2042 int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
2043 str = string_convert(&input_conv, plainStr, &len);
2053 is_valid_macaction(char_u *action)
2056 NSDictionary *actionDict = [[MMBackend sharedInstance] actionDict];
2059 action = CONVERT_TO_UTF8(action);
2061 NSString *string = [NSString stringWithUTF8String:(char*)action];
2062 isValid = (nil != [actionDict objectForKey:string]);
2064 CONVERT_TO_UTF8_FREE(action);
2071 static int specialKeyToNSKey(int key)
2073 if (!IS_SPECIAL(key))
2080 { K_UP, NSUpArrowFunctionKey },
2081 { K_DOWN, NSDownArrowFunctionKey },
2082 { K_LEFT, NSLeftArrowFunctionKey },
2083 { K_RIGHT, NSRightArrowFunctionKey },
2084 { K_F1, NSF1FunctionKey },
2085 { K_F2, NSF2FunctionKey },
2086 { K_F3, NSF3FunctionKey },
2087 { K_F4, NSF4FunctionKey },
2088 { K_F5, NSF5FunctionKey },
2089 { K_F6, NSF6FunctionKey },
2090 { K_F7, NSF7FunctionKey },
2091 { K_F8, NSF8FunctionKey },
2092 { K_F9, NSF9FunctionKey },
2093 { K_F10, NSF10FunctionKey },
2094 { K_F11, NSF11FunctionKey },
2095 { K_F12, NSF12FunctionKey },
2096 { K_F13, NSF13FunctionKey },
2097 { K_F14, NSF14FunctionKey },
2098 { K_F15, NSF15FunctionKey },
2099 { K_F16, NSF16FunctionKey },
2100 { K_F17, NSF17FunctionKey },
2101 { K_F18, NSF18FunctionKey },
2102 { K_F19, NSF19FunctionKey },
2103 { K_F20, NSF20FunctionKey },
2104 { K_F21, NSF21FunctionKey },
2105 { K_F22, NSF22FunctionKey },
2106 { K_F23, NSF23FunctionKey },
2107 { K_F24, NSF24FunctionKey },
2108 { K_F25, NSF25FunctionKey },
2109 { K_F26, NSF26FunctionKey },
2110 { K_F27, NSF27FunctionKey },
2111 { K_F28, NSF28FunctionKey },
2112 { K_F29, NSF29FunctionKey },
2113 { K_F30, NSF30FunctionKey },
2114 { K_F31, NSF31FunctionKey },
2115 { K_F32, NSF32FunctionKey },
2116 { K_F33, NSF33FunctionKey },
2117 { K_F34, NSF34FunctionKey },
2118 { K_F35, NSF35FunctionKey },
2119 { K_DEL, NSBackspaceCharacter },
2120 { K_BS, NSDeleteCharacter },
2121 { K_HOME, NSHomeFunctionKey },
2122 { K_END, NSEndFunctionKey },
2123 { K_PAGEUP, NSPageUpFunctionKey },
2124 { K_PAGEDOWN, NSPageDownFunctionKey }
2128 for (i = 0; i < sizeof(sp2ns)/sizeof(sp2ns[0]); ++i) {
2129 if (sp2ns[i].special == key)
2130 return sp2ns[i].nskey;
2136 static int vimModMaskToEventModifierFlags(int mods)
2140 if (mods & MOD_MASK_SHIFT)
2141 flags |= NSShiftKeyMask;
2142 if (mods & MOD_MASK_CTRL)
2143 flags |= NSControlKeyMask;
2144 if (mods & MOD_MASK_ALT)
2145 flags |= NSAlternateKeyMask;
2146 if (mods & MOD_MASK_CMD)
2147 flags |= NSCommandKeyMask;