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>
22 // HACK! Used in gui.c to determine which string drawing code to use.
23 int use_gui_macvim_draw_string = 1;
26 // NOTE: The default font is bundled with the application.
27 static NSString *MMDefaultFontName = @"DejaVu Sans Mono";
28 static int MMDefaultFontSize = 12;
29 static int MMMinFontSize = 6;
30 static int MMMaxFontSize = 100;
33 static GuiFont gui_macvim_font_with_name(char_u *name);
34 static int specialKeyToNSKey(int key);
35 static int vimModMaskToEventModifierFlags(int mods);
37 NSArray *descriptor_for_menu(vimmenu_T *menu);
38 vimmenu_T *menu_for_descriptor(NSArray *desc);
42 // -- Initialization --------------------------------------------------------
47 NSBundle *bundle = [NSBundle mainBundle];
49 // Set environment variables $VIM and $VIMRUNTIME
50 NSString *path = [[bundle resourcePath]
51 stringByAppendingPathComponent:@"vim"];
52 vim_setenv((char_u*)"VIM", (char_u*)[path UTF8String]);
54 path = [path stringByAppendingPathComponent:@"runtime"];
55 vim_setenv((char_u*)"VIMRUNTIME", (char_u*)[path UTF8String]);
58 #if 0 // NOTE: setlocale(LC_ALL, "") seems to work after a restart so this is
59 // not necessary. The locale used depends on what "Region" is set
60 // inside the "Formats" tab of the "International" System Preferences
62 // Try to ensure that the locale is set to match that used by NSBundle to
63 // load localized resources. If there is a mismatch e.g. between the
64 // MacVim menu and other menus, then this code needs to change (nb. the
65 // MacVim menu is set up inside a nib file so the locale used for it is
66 // chosen by NSBundle and the other menus are set up by Vim so their locale
67 // matches whatever we set here).
68 NSLocale *loc = [NSLocale currentLocale];
70 NSString *s = [NSString stringWithFormat:@"%@_%@.UTF-8",
71 [loc objectForKey:NSLocaleLanguageCode],
72 [loc objectForKey:NSLocaleCountryCode]];
73 setlocale(LC_ALL, [s UTF8String]);
74 fprintf(stderr, "locale=%s\n", [s UTF8String]);
82 * Parse the GUI related command-line arguments. Any arguments used are
83 * deleted from argv, and *argc is decremented accordingly. This is called
84 * when vim is started, whether or not the GUI has been started.
85 * NOTE: This function will be called twice if the Vim process forks.
88 gui_mch_prepare(int *argc, char **argv)
91 for (i = 0; i < *argc; ++i) {
92 if (strncmp(argv[i], "--mmwaitforack", 14) == 0) {
93 [[MMBackend sharedInstance] setWaitForAck:YES];
96 mch_memmove(&argv[i], &argv[i+1], (*argc-i) * sizeof(char*));
101 #ifdef FEAT_NETBEANS_INTG
102 for (i = 0; i < *argc; ++i) {
103 if (strncmp(argv[i], "-nb", 3) == 0) {
105 netbeansArg = argv[i];
108 mch_memmove(&argv[i], &argv[i+1], (*argc-i) * sizeof(char*));
116 /* Called directly after forking (even if we didn't fork). */
118 gui_macvim_after_fork_init()
123 // Restore autosaved rows & columns
125 Boolean rowsValid, colsValid;
126 rows = CFPreferencesGetAppIntegerValue((CFStringRef)MMAutosaveRowsKey,
127 kCFPreferencesCurrentApplication,
129 cols = CFPreferencesGetAppIntegerValue((CFStringRef)MMAutosaveColumnsKey,
130 kCFPreferencesCurrentApplication,
132 if (rowsValid && colsValid
133 && (rows > 4 && rows < 1000 && cols > 29 && cols < 4000)) {
137 // Use the defaults (typically 80x24), if there are no autosaved rows &
140 gui.num_cols = Columns;
143 // Check which code path to take for string drawing.
146 val = CFPreferencesGetAppIntegerValue((CFStringRef)MMRendererKey,
147 kCFPreferencesCurrentApplication,
150 ASLogInfo(@"Use renderer=%d", val);
151 use_gui_macvim_draw_string = (val != MMRendererCoreText);
157 * Check if the GUI can be started. Called before gvimrc is sourced.
161 gui_mch_init_check(void)
168 * Initialise the GUI. Create all the windows, set up all the call-backs etc.
169 * Returns OK for success, FAIL when the GUI can't be started.
176 if (![[MMBackend sharedInstance] checkin]) {
177 // TODO: Kill the process if there is no terminal to fall back on,
178 // otherwise the process will run outputting to the console.
182 // Force 'termencoding' to utf-8 (changes to 'tenc' are disallowed in
183 // 'option.c', so that ':set termencoding=...' is impossible).
184 set_option_value((char_u *)"termencoding", 0L, (char_u *)"utf-8", 0);
186 // Set values so that pixels and characters are in one-to-one
187 // correspondence (assuming all characters have the same dimensions).
188 gui.scrollbar_width = gui.scrollbar_height = 0;
194 gui_mch_def_colors();
196 [[MMBackend sharedInstance]
197 setDefaultColorsBackground:gui.back_pixel foreground:gui.norm_pixel];
198 [[MMBackend sharedInstance] setBackgroundColor:gui.back_pixel];
199 [[MMBackend sharedInstance] setForegroundColor:gui.norm_pixel];
201 // NOTE: If this call is left out the cursor is opaque.
202 highlight_gui_started();
204 // Ensure 'linespace' option is passed along to MacVim in case it was set
206 gui_mch_adjust_charheight();
216 ASLogDebug(@"rc=%d", rc);
218 [[MMBackend sharedInstance] exit];
223 * Open the GUI window which was created by a call to gui_mch_init().
228 return [[MMBackend sharedInstance] openGUIWindow];
232 // -- Updating --------------------------------------------------------------
236 * Catch up with any queued X events. This may put keyboard input into the
237 * input buffer, call resize call-backs, trigger timers etc. If there is
238 * nothing in the X event queue (& no timers pending), then we return
244 // This function is called extremely often. It is tempting to do nothing
245 // here to avoid reduced frame-rates but then it would not be possible to
246 // interrupt Vim by presssing Ctrl-C during lengthy operations (e.g. after
247 // entering "10gs" it would not be possible to bring Vim out of the 10 s
248 // sleep prematurely). As a compromise we check for Ctrl-C only once per
249 // second. Note that Cmd-. sends SIGINT so it has higher success rate at
251 static CFAbsoluteTime lastTime = 0;
253 CFAbsoluteTime nowTime = CFAbsoluteTimeGetCurrent();
254 if (nowTime - lastTime > 1.0) {
255 [[MMBackend sharedInstance] update];
261 /* Flush any output to the screen */
265 // This function is called way too often to be useful as a hint for
266 // flushing. If we were to flush every time it was called the screen would
272 gui_macvim_flush(void)
274 // This function counts how many times it is called and only flushes the
275 // draw queue if called sufficiently often. The first few times it is
276 // called it will flush often, but the more it is called the less likely is
277 // it that anything will be flushed. (The counter resets itself if the
278 // function isn't called for a second.)
280 // NOTE: Should only be used in loops where it is impossible to know how
281 // often Vim needs to flush. It was written to handle output from external
282 // commands (see mch_call_shell() in os_unix.c).
284 static CFAbsoluteTime lastTime = 0;
285 static int delay = 1;
286 static int counter = 0;
287 static int scrolls = 0;
289 CFAbsoluteTime nowTime = CFAbsoluteTimeGetCurrent();
290 CFAbsoluteTime delta = nowTime - lastTime;
294 // We assume that each call corresponds roughly to one line of output.
295 // When one page has scrolled by we increase the delay before the next
297 if (++scrolls > gui.num_rows) {
304 if (++counter > delay) {
305 gui_macvim_force_flush();
313 /* Force flush output to MacVim. Do not call this method unless absolutely
316 gui_macvim_force_flush(void)
318 [[MMBackend sharedInstance] flushQueue:YES];
323 * GUI input routine called by gui_wait_for_chars(). Waits for a character
325 * wtime == -1 Wait forever.
326 * wtime == 0 This should never happen.
327 * wtime > 0 Wait wtime milliseconds for a character.
328 * Returns OK if a character was found to be available within the given time,
332 gui_mch_wait_for_chars(int wtime)
334 // NOTE! In all likelihood Vim will take a nap when waitForInput: is
335 // called, so force a flush of the command queue here.
336 [[MMBackend sharedInstance] flushQueue:YES];
338 return [[MMBackend sharedInstance] waitForInput:wtime];
342 // -- Drawing ---------------------------------------------------------------
346 * Clear the whole text window.
349 gui_mch_clear_all(void)
351 [[MMBackend sharedInstance] clearAll];
356 * Clear a rectangular region of the screen from text pos (row1, col1) to
357 * (row2, col2) inclusive.
360 gui_mch_clear_block(int row1, int col1, int row2, int col2)
362 [[MMBackend sharedInstance] clearBlockFromRow:row1 column:col1
363 toRow:row2 column:col2];
368 * Delete the given number of lines from the given row, scrolling up any
369 * text further down within the scroll region.
372 gui_mch_delete_lines(int row, int num_lines)
374 [[MMBackend sharedInstance] deleteLinesFromRow:row count:num_lines
375 scrollBottom:gui.scroll_region_bot
376 left:gui.scroll_region_left
377 right:gui.scroll_region_right];
382 gui_mch_draw_string(int row, int col, char_u *s, int len, int cells, int flags)
385 char_u *conv_str = NULL;
386 if (output_conv.vc_type != CONV_NONE) {
387 conv_str = string_convert(&output_conv, s, &len);
393 [[MMBackend sharedInstance] drawString:s
407 gui_macvim_draw_string(int row, int col, char_u *s, int len, int flags)
414 MMBackend *backend = [MMBackend sharedInstance];
416 char_u *conv_str = NULL;
418 if (output_conv.vc_type != CONV_NONE) {
419 conv_str = string_convert(&output_conv, s, &len);
425 // Loop over each character and output text when it changes from normal to
426 // wide and vice versa.
427 for (i = 0; i < len; i += cl) {
428 c = utf_ptr2char(s + i);
429 cn = utf_char2cells(c);
430 cl = utf_ptr2len(s + i);
432 len = i; // len must be wrong (shouldn't happen)
434 if (!utf_iscomposing(c)) {
435 if ((cn > 1 && !wide) || (cn <= 1 && wide)) {
436 // Changed from normal to wide or vice versa.
437 [backend drawString:(s+start) length:i-start
438 row:row column:startcol
439 cells:endcol-startcol
440 flags:(wide ? flags|DRAW_WIDE : flags)];
451 // Output remaining characters.
452 [backend drawString:(s+start) length:len-start
453 row:row column:startcol cells:endcol-startcol
454 flags:(wide ? flags|DRAW_WIDE : flags)];
466 * Insert the given number of lines before the given row, scrolling down any
467 * following text within the scroll region.
470 gui_mch_insert_lines(int row, int num_lines)
472 [[MMBackend sharedInstance] insertLinesFromRow:row count:num_lines
473 scrollBottom:gui.scroll_region_bot
474 left:gui.scroll_region_left
475 right:gui.scroll_region_right];
480 * Set the current text foreground color.
483 gui_mch_set_fg_color(guicolor_T color)
485 [[MMBackend sharedInstance] setForegroundColor:color];
490 * Set the current text background color.
493 gui_mch_set_bg_color(guicolor_T color)
495 [[MMBackend sharedInstance] setBackgroundColor:color];
500 * Set the current text special color (used for underlines).
503 gui_mch_set_sp_color(guicolor_T color)
505 [[MMBackend sharedInstance] setSpecialColor:color];
510 * Set default colors.
515 MMBackend *backend = [MMBackend sharedInstance];
517 // The default colors are taken from system values
518 gui.def_norm_pixel = gui.norm_pixel =
519 [backend lookupColorWithKey:@"MacTextColor"];
520 gui.def_back_pixel = gui.back_pixel =
521 [backend lookupColorWithKey:@"MacTextBackgroundColor"];
526 * Called when the foreground or background color has been changed.
529 gui_mch_new_colors(void)
531 gui.def_back_pixel = gui.back_pixel;
532 gui.def_norm_pixel = gui.norm_pixel;
534 ASLogDebug(@"back=%x norm=%x", gui.def_back_pixel, gui.def_norm_pixel);
536 [[MMBackend sharedInstance]
537 setDefaultColorsBackground:gui.def_back_pixel
538 foreground:gui.def_norm_pixel];
542 * Invert a rectangle from row r, column c, for nr rows and nc columns.
545 gui_mch_invert_rectangle(int r, int c, int nr, int nc, int invert)
547 [[MMBackend sharedInstance] drawInvertedRectAtRow:r column:c numRows:nr
548 numColumns:nc invert:invert];
553 // -- Tabline ---------------------------------------------------------------
557 * Set the current tab to "nr". First tab is 1.
560 gui_mch_set_curtab(int nr)
562 [[MMBackend sharedInstance] selectTab:nr];
567 * Return TRUE when tabline is displayed.
570 gui_mch_showing_tabline(void)
572 return [[MMBackend sharedInstance] tabBarVisible];
576 * Update the labels of the tabline.
579 gui_mch_update_tabline(void)
581 [[MMBackend sharedInstance] updateTabBar];
585 * Show or hide the tabline.
588 gui_mch_show_tabline(int showit)
590 [[MMBackend sharedInstance] showTabBar:showit];
594 // -- Clipboard -------------------------------------------------------------
598 clip_mch_lose_selection(VimClipboard *cbd)
604 clip_mch_own_selection(VimClipboard *cbd)
611 clip_mch_request_selection(VimClipboard *cbd)
613 NSPasteboard *pb = [NSPasteboard generalPasteboard];
614 NSArray *supportedTypes = [NSArray arrayWithObjects:VimPBoardType,
615 NSStringPboardType, nil];
616 NSString *bestType = [pb availableTypeFromArray:supportedTypes];
617 if (!bestType) return;
619 int motion_type = MCHAR;
620 NSString *string = nil;
622 if ([bestType isEqual:VimPBoardType]) {
623 // This type should consist of an array with two objects:
624 // 1. motion type (NSNumber)
625 // 2. text (NSString)
626 // If this is not the case we fall back on using NSStringPboardType.
627 id plist = [pb propertyListForType:VimPBoardType];
628 if ([plist isKindOfClass:[NSArray class]] && [plist count] == 2) {
629 id obj = [plist objectAtIndex:1];
630 if ([obj isKindOfClass:[NSString class]]) {
631 motion_type = [[plist objectAtIndex:0] intValue];
638 // Use NSStringPboardType. The motion type is set to line-wise if the
639 // string contains at least one EOL character, otherwise it is set to
640 // character-wise (block-wise is never used).
641 NSMutableString *mstring =
642 [[pb stringForType:NSStringPboardType] mutableCopy];
643 if (!mstring) return;
645 // Replace unrecognized end-of-line sequences with \x0a (line feed).
646 NSRange range = { 0, [mstring length] };
647 unsigned n = [mstring replaceOccurrencesOfString:@"\x0d\x0a"
648 withString:@"\x0a" options:0
651 n = [mstring replaceOccurrencesOfString:@"\x0d" withString:@"\x0a"
652 options:0 range:range];
655 // Scan for newline character to decide whether the string should be
656 // pasted line-wise or character-wise.
658 if (0 < n || NSNotFound != [mstring rangeOfString:@"\n"].location)
664 if (!(MCHAR == motion_type || MLINE == motion_type || MBLOCK == motion_type
665 || MAUTO == motion_type))
668 char_u *str = (char_u*)[string UTF8String];
669 int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
672 if (input_conv.vc_type != CONV_NONE)
673 str = string_convert(&input_conv, str, &len);
677 clip_yank_selection(motion_type, str, len, cbd);
680 if (input_conv.vc_type != CONV_NONE)
687 * Send the current selection to the clipboard.
690 clip_mch_set_selection(VimClipboard *cbd)
692 // If the '*' register isn't already filled in, fill it in now.
694 clip_get_selection(cbd);
697 // Get the text to put on the pasteboard.
698 long_u llen = 0; char_u *str = 0;
699 int motion_type = clip_convert_selection(&str, &llen, cbd);
703 // TODO: Avoid overflow.
706 if (output_conv.vc_type != CONV_NONE) {
707 char_u *conv_str = string_convert(&output_conv, str, &len);
716 NSString *string = [[NSString alloc]
717 initWithBytes:str length:len encoding:NSUTF8StringEncoding];
719 // See clip_mch_request_selection() for info on pasteboard types.
720 NSPasteboard *pb = [NSPasteboard generalPasteboard];
721 NSArray *supportedTypes = [NSArray arrayWithObjects:VimPBoardType,
722 NSStringPboardType, nil];
723 [pb declareTypes:supportedTypes owner:nil];
725 NSNumber *motion = [NSNumber numberWithInt:motion_type];
726 NSArray *plist = [NSArray arrayWithObjects:motion, string, nil];
727 [pb setPropertyList:plist forType:VimPBoardType];
729 [pb setString:string forType:NSStringPboardType];
738 // -- Menu ------------------------------------------------------------------
742 * A menu descriptor represents the "address" of a menu as an array of strings.
743 * E.g. the menu "File->Close" has descriptor { "File", "Close" }.
746 descriptor_for_menu(vimmenu_T *menu)
748 if (!menu) return nil;
750 NSMutableArray *desc = [NSMutableArray array];
752 NSString *name = [NSString stringWithVimString:menu->dname];
753 [desc insertObject:name atIndex:0];
761 menu_for_descriptor(NSArray *desc)
763 if (!(desc && [desc count] > 0)) return NULL;
765 vimmenu_T *menu = root_menu;
766 int i, count = [desc count];
768 for (i = 0; i < count; ++i) {
769 NSString *component = [desc objectAtIndex:i];
771 NSString *name = [NSString stringWithVimString:menu->dname];
772 if ([component isEqual:name]) {
774 return menu; // Matched all components, so return menu
775 menu = menu->children;
786 * Add a submenu to the menu bar, toolbar, or a popup menu.
789 gui_mch_add_menu(vimmenu_T *menu, int idx)
791 NSArray *desc = descriptor_for_menu(menu);
792 [[MMBackend sharedInstance] queueMessage:AddMenuMsgID properties:
793 [NSDictionary dictionaryWithObjectsAndKeys:
795 [NSNumber numberWithInt:idx], @"index",
800 // Taken from gui_gtk.c (slightly modified)
802 lookup_menu_iconfile(char_u *iconfile, char_u *dest)
804 expand_env(iconfile, dest, MAXPATHL);
806 if (mch_isFullName(dest))
807 return vim_fexists(dest);
809 static const char suffixes[][4] = {"png", "bmp"};
810 char_u buf[MAXPATHL];
813 for (i = 0; i < sizeof(suffixes)/sizeof(suffixes[0]); ++i)
814 if (gui_find_bitmap(dest, buf, (char *)suffixes[i]) == OK) {
824 * Add a menu item to a menu
827 gui_mch_add_menu_item(vimmenu_T *menu, int idx)
829 char_u *tip = menu->strings[MENU_INDEX_TIP]
830 ? menu->strings[MENU_INDEX_TIP] : menu->actext;
831 NSArray *desc = descriptor_for_menu(menu);
832 NSString *keyEquivalent = menu->mac_key
833 ? [NSString stringWithFormat:@"%C", specialKeyToNSKey(menu->mac_key)]
835 int modifierMask = vimModMaskToEventModifierFlags(menu->mac_mods);
838 if (menu_is_toolbar(menu->parent->name)) {
839 char_u fname[MAXPATHL];
841 // Try to use the icon=.. argument
842 if (menu->iconfile && lookup_menu_iconfile(menu->iconfile, fname))
845 // If not found and not builtin specified try using the menu name
846 if (!icon && !menu->icon_builtin
847 && lookup_menu_iconfile(menu->name, fname))
850 // Still no icon found, try using a builtin icon. (If this also fails,
851 // then a warning icon will be displayed).
853 icon = lookup_toolbar_item(menu->iconidx);
856 [[MMBackend sharedInstance] queueMessage:AddMenuItemMsgID properties:
857 [NSDictionary dictionaryWithObjectsAndKeys:
859 [NSNumber numberWithInt:idx], @"index",
860 [NSString stringWithVimString:tip], @"tip",
861 [NSString stringWithVimString:icon], @"icon",
862 keyEquivalent, @"keyEquivalent",
863 [NSNumber numberWithInt:modifierMask], @"modifierMask",
864 [NSString stringWithVimString:menu->mac_action], @"action",
865 [NSNumber numberWithBool:menu->mac_alternate], @"isAlternate",
871 * Destroy the machine specific menu widget.
874 gui_mch_destroy_menu(vimmenu_T *menu)
876 NSArray *desc = descriptor_for_menu(menu);
877 [[MMBackend sharedInstance] queueMessage:RemoveMenuItemMsgID properties:
878 [NSDictionary dictionaryWithObject:desc forKey:@"descriptor"]];
883 * Make a menu either grey or not grey.
886 gui_mch_menu_grey(vimmenu_T *menu, int grey)
888 /* Only update menu if the 'grey' state has changed to avoid having to pass
889 * lots of unnecessary data to MacVim. (Skipping this test makes MacVim
890 * pause noticably on mode changes. */
891 NSArray *desc = descriptor_for_menu(menu);
892 if (menu->was_grey == grey)
895 menu->was_grey = grey;
897 [[MMBackend sharedInstance] queueMessage:EnableMenuItemMsgID properties:
898 [NSDictionary dictionaryWithObjectsAndKeys:
900 [NSNumber numberWithInt:!grey], @"enable",
906 * Make menu item hidden or not hidden
909 gui_mch_menu_hidden(vimmenu_T *menu, int hidden)
911 // HACK! There is no (obvious) way to hide a menu item, so simply
912 // enable/disable it instead.
913 gui_mch_menu_grey(menu, hidden);
918 * This is called when user right clicks.
921 gui_mch_show_popupmenu(vimmenu_T *menu)
923 NSArray *desc = descriptor_for_menu(menu);
924 [[MMBackend sharedInstance] queueMessage:ShowPopupMenuMsgID properties:
925 [NSDictionary dictionaryWithObject:desc forKey:@"descriptor"]];
930 * This is called when a :popup command is executed.
933 gui_make_popup(char_u *path_name, int mouse_pos)
935 vimmenu_T *menu = gui_find_menu(path_name);
936 if (!(menu && menu->children)) return;
938 NSArray *desc = descriptor_for_menu(menu);
939 NSDictionary *p = (mouse_pos || NULL == curwin)
940 ? [NSDictionary dictionaryWithObject:desc forKey:@"descriptor"]
941 : [NSDictionary dictionaryWithObjectsAndKeys:
943 [NSNumber numberWithInt:curwin->w_wrow], @"row",
944 [NSNumber numberWithInt:curwin->w_wcol], @"column",
947 [[MMBackend sharedInstance] queueMessage:ShowPopupMenuMsgID properties:p];
952 * This is called after setting all the menus to grey/hidden or not.
955 gui_mch_draw_menubar(void)
957 // The (main) menu draws itself in Mac OS X.
962 gui_mch_enable_menu(int flag)
964 // The (main) menu is always enabled in Mac OS X.
970 gui_mch_set_menu_pos(int x, int y, int w, int h)
972 // The (main) menu cannot be moved in Mac OS X.
978 gui_mch_show_toolbar(int showit)
981 if (toolbar_flags & TOOLBAR_TEXT) flags |= ToolbarLabelFlag;
982 if (toolbar_flags & TOOLBAR_ICONS) flags |= ToolbarIconFlag;
983 if (tbis_flags & (TBIS_MEDIUM|TBIS_LARGE)) flags |= ToolbarSizeRegularFlag;
985 [[MMBackend sharedInstance] showToolbar:showit flags:flags];
991 // -- Fonts -----------------------------------------------------------------
995 * If a font is not going to be used, free its structure.
998 gui_mch_free_font(font)
1001 if (font != NOFONT) {
1002 ASLogDebug(@"font=0x%x", font);
1009 gui_mch_retain_font(GuiFont font)
1011 return (GuiFont)[(id)font retain];
1016 * Get a font structure for highlighting.
1019 gui_mch_get_font(char_u *name, int giveErrorIfMissing)
1021 ASLogDebug(@"name='%s' giveErrorIfMissing=%d", name, giveErrorIfMissing);
1023 GuiFont font = gui_macvim_font_with_name(name);
1027 if (giveErrorIfMissing)
1028 EMSG2(_(e_font), name);
1034 #if defined(FEAT_EVAL) || defined(PROTO)
1036 * Return the name of font "font" in allocated memory.
1037 * TODO: use 'font' instead of 'name'?
1040 gui_mch_get_fontname(GuiFont font, char_u *name)
1042 return name ? vim_strsave(name) : NULL;
1048 * Initialise vim to use the font with the given name. Return FAIL if the font
1049 * could not be loaded, OK otherwise.
1052 gui_mch_init_font(char_u *font_name, int fontset)
1054 ASLogDebug(@"font_name='%s' fontset=%d", font_name, fontset);
1056 if (font_name && STRCMP(font_name, "*") == 0) {
1057 // :set gfn=* shows the font panel.
1058 do_cmdline_cmd((char_u*)":macaction orderFrontFontPanel:");
1062 GuiFont font = gui_macvim_font_with_name(font_name);
1066 gui_mch_free_font(gui.norm_font);
1067 gui.norm_font = font;
1069 // NOTE: MacVim keeps separate track of the normal and wide fonts.
1070 // Unless the user changes 'guifontwide' manually, they are based on
1071 // the same (normal) font. Also note that each time the normal font is
1072 // set, the advancement may change so the wide font needs to be updated
1073 // as well (so that it is always twice the width of the normal font).
1074 [[MMBackend sharedInstance] setFont:font wide:NO];
1075 [[MMBackend sharedInstance] setFont:(NOFONT != gui.wide_font ? gui.wide_font
1084 * Set the current text font.
1087 gui_mch_set_font(GuiFont font)
1089 // Font selection is done inside MacVim...nothing here to do.
1094 * Return GuiFont in allocated memory. The caller must free it using
1095 * gui_mch_free_font().
1098 gui_macvim_font_with_name(char_u *name)
1101 return (GuiFont)[[NSString alloc] initWithFormat:@"%@:%d",
1102 MMDefaultFontName, MMDefaultFontSize];
1104 NSString *fontName = [NSString stringWithVimString:name];
1105 int size = MMDefaultFontSize;
1106 BOOL parseFailed = NO;
1108 NSArray *components = [fontName componentsSeparatedByString:@":"];
1109 if ([components count] == 2) {
1110 NSString *sizeString = [components lastObject];
1111 if ([sizeString length] > 0
1112 && [sizeString characterAtIndex:0] == 'h') {
1113 sizeString = [sizeString substringFromIndex:1];
1114 if ([sizeString length] > 0) {
1115 size = (int)round([sizeString floatValue]);
1116 fontName = [components objectAtIndex:0];
1121 } else if ([components count] > 2) {
1126 // Replace underscores with spaces.
1127 fontName = [[fontName componentsSeparatedByString:@"_"]
1128 componentsJoinedByString:@" "];
1131 if (!parseFailed && [fontName length] > 0) {
1132 if (size < MMMinFontSize) size = MMMinFontSize;
1133 if (size > MMMaxFontSize) size = MMMaxFontSize;
1135 // If the default font is requested we don't check if NSFont can load
1136 // it since the font most likely isn't loaded anyway (it may only be
1137 // available to the MacVim binary). If it is not the default font we
1138 // ask NSFont if it can load it.
1139 if ([fontName isEqualToString:MMDefaultFontName]
1140 || [NSFont fontWithName:fontName size:size])
1141 return [[NSString alloc] initWithFormat:@"%@:%d", fontName, size];
1147 // -- Scrollbars ------------------------------------------------------------
1149 // NOTE: Even though scrollbar identifiers are 'long' we tacitly assume that
1150 // they only use 32 bits (in particular when compiling for 64 bit). This is
1151 // justified since identifiers are generated from a 32 bit counter in
1152 // gui_create_scrollbar(). However if that code changes we may be in trouble
1153 // (if ever that many scrollbars are allocated...). The reason behind this is
1154 // that we pass scrollbar identifers over process boundaries so the width of
1155 // the variable needs to be fixed (and why fix at 64 bit when only 32 are
1159 gui_mch_create_scrollbar(
1161 int orient) /* SBAR_VERT or SBAR_HORIZ */
1163 [[MMBackend sharedInstance]
1164 createScrollbarWithIdentifier:(int32_t)sb->ident type:sb->type];
1169 gui_mch_destroy_scrollbar(scrollbar_T *sb)
1171 [[MMBackend sharedInstance]
1172 destroyScrollbarWithIdentifier:(int32_t)sb->ident];
1177 gui_mch_enable_scrollbar(
1181 [[MMBackend sharedInstance]
1182 showScrollbarWithIdentifier:(int32_t)sb->ident state:flag];
1187 gui_mch_set_scrollbar_pos(
1196 if (SBAR_BOTTOM == sb->type) {
1201 [[MMBackend sharedInstance]
1202 setScrollbarPosition:pos length:len identifier:(int32_t)sb->ident];
1207 gui_mch_set_scrollbar_thumb(
1213 [[MMBackend sharedInstance]
1214 setScrollbarThumbValue:val
1217 identifier:(int32_t)sb->ident];
1221 // -- Cursor ----------------------------------------------------------------
1225 * Draw a cursor without focus.
1228 gui_mch_draw_hollow_cursor(guicolor_T color)
1230 return [[MMBackend sharedInstance]
1231 drawCursorAtRow:gui.row column:gui.col shape:MMInsertionPointHollow
1232 fraction:100 color:color];
1237 * Draw part of a cursor, only w pixels wide, and h pixels high.
1240 gui_mch_draw_part_cursor(int w, int h, guicolor_T color)
1242 // HACK! 'w' and 'h' are always 1 since we do not tell Vim about the exact
1243 // font dimensions. Thus these parameters are useless. Instead we look at
1244 // the shape_table to determine the shape and size of the cursor (just like
1245 // gui_update_cursor() does).
1247 #ifdef FEAT_RIGHTLEFT
1248 // If 'rl' is set the insert mode cursor must be drawn on the right-hand
1249 // side of a text cell.
1250 int rl = curwin ? curwin->w_p_rl : FALSE;
1254 int idx = get_shape_idx(FALSE);
1255 int shape = MMInsertionPointBlock;
1256 switch (shape_table[idx].shape) {
1258 shape = MMInsertionPointHorizontal;
1261 shape = rl ? MMInsertionPointVerticalRight
1262 : MMInsertionPointVertical;
1266 return [[MMBackend sharedInstance]
1267 drawCursorAtRow:gui.row column:gui.col shape:shape
1268 fraction:shape_table[idx].percentage color:color];
1273 * Cursor blink functions.
1275 * This is a simple state machine:
1276 * BLINK_NONE not blinking at all
1277 * BLINK_OFF blinking, cursor is not shown
1278 * BLINK_ON blinking, cursor is shown
1281 gui_mch_set_blinking(long wait, long on, long off)
1283 [[MMBackend sharedInstance] setBlinkWait:wait on:on off:off];
1288 * Start the cursor blinking. If it was already blinking, this restarts the
1289 * waiting time and shows the cursor.
1292 gui_mch_start_blink(void)
1294 [[MMBackend sharedInstance] startBlink];
1299 * Stop the cursor blinking. Show the cursor if it wasn't shown.
1302 gui_mch_stop_blink(void)
1304 [[MMBackend sharedInstance] stopBlink];
1308 // -- Mouse -----------------------------------------------------------------
1312 * Get current mouse coordinates in text window.
1315 gui_mch_getmouse(int *x, int *y)
1317 ASLogInfo(@"Not implemented!");
1322 gui_mch_setmouse(int x, int y)
1324 ASLogInfo(@"Not implemented!");
1329 mch_set_mouse_shape(int shape)
1331 [[MMBackend sharedInstance] setMouseShape:shape];
1337 // -- Input Method ----------------------------------------------------------
1339 #if defined(USE_IM_CONTROL)
1342 im_set_position(int row, int col)
1344 // The pre-edit area is a popup window which is displayed by MMTextView.
1345 [[MMBackend sharedInstance] setPreEditRow:row column:col];
1350 im_set_control(int enable)
1352 // Tell frontend whether it should notify us when the input method changes
1353 // or not (called when 'imd' is toggled).
1354 int msgid = enable ? EnableImControlMsgID : DisableImControlMsgID;
1355 [[MMBackend sharedInstance] queueMessage:msgid properties:nil];
1360 im_set_active(int active)
1362 // Tell frontend to enable/disable IM (called e.g. when the mode changes).
1364 int msgid = active ? ActivateKeyScriptMsgID : DeactivateKeyScriptMsgID;
1365 [[MMBackend sharedInstance] setImState:active];
1366 [[MMBackend sharedInstance] queueMessage:msgid properties:nil];
1374 return [[MMBackend sharedInstance] imState];
1377 #endif // defined(USE_IM_CONTROL)
1382 // -- Find & Replace dialog -------------------------------------------------
1384 #ifdef FIND_REPLACE_DIALOG
1387 macvim_find_and_replace(char_u *arg, BOOL replace)
1389 // TODO: Specialized dialog for find without replace?
1390 int wholeWord = FALSE;
1391 int matchCase = !p_ic;
1392 char_u *text = get_find_dialog_text(arg, &wholeWord, &matchCase);
1395 if (wholeWord) flags |= FRD_WHOLE_WORD;
1396 if (matchCase) flags |= FRD_MATCH_CASE;
1398 NSDictionary *args = [NSDictionary dictionaryWithObjectsAndKeys:
1399 [NSString stringWithVimString:text], @"text",
1400 [NSNumber numberWithInt:flags], @"flags",
1403 [[MMBackend sharedInstance] queueMessage:ShowFindReplaceDialogMsgID
1408 gui_mch_find_dialog(exarg_T *eap)
1410 macvim_find_and_replace(eap->arg, NO);
1414 gui_mch_replace_dialog(exarg_T *eap)
1416 macvim_find_and_replace(eap->arg, YES);
1419 #endif // FIND_REPLACE_DIALOG
1424 // -- Unsorted --------------------------------------------------------------
1432 EMSG(_("E???: Command only available in GUI mode"));
1436 char_u *arg = eap->arg;
1438 arg = CONVERT_TO_UTF8(arg);
1441 NSDictionary *actionDict = [[MMBackend sharedInstance] actionDict];
1442 NSString *name = [NSString stringWithUTF8String:(char*)arg];
1443 if (actionDict && [actionDict objectForKey:name] != nil) {
1444 [[MMBackend sharedInstance] executeActionWithName:name];
1446 EMSG2(_("E???: Invalid action: %s"), eap->arg);
1450 arg = CONVERT_TO_UTF8(arg);
1456 * Adjust gui.char_height (after 'linespace' was changed).
1459 gui_mch_adjust_charheight(void)
1461 [[MMBackend sharedInstance] adjustLinespace:p_linespace];
1476 * Pop open a file browser and return the file selected, in allocated memory,
1477 * or NULL if Cancel is hit.
1478 * saving - TRUE if the file will be saved to, FALSE if it will be opened.
1479 * title - Title message for the file browser dialog.
1480 * dflt - Default name of file.
1481 * ext - Default extension to be added to files without extensions.
1482 * initdir - directory in which to open the browser (NULL = current dir)
1483 * filter - Filter for matched files to choose from.
1484 * Has a format like this:
1485 * "C Files (*.c)\0*.c\0"
1486 * "All Files\0*.*\0\0"
1487 * If these two strings were concatenated, then a choice of two file
1488 * filters will be selectable to the user. Then only matching files will
1489 * be shown in the browser. If NULL, the default allows all files.
1491 * *NOTE* - the filter string must be terminated with TWO nulls.
1502 ASLogDebug(@"saving=%d title='%s' dflt='%s' ext='%s' initdir='%s' "
1503 "filter='%s'", saving, title, dflt, ext, initdir, filter);
1505 // Ensure no data is on the output queue before presenting the dialog.
1506 gui_macvim_force_flush();
1508 NSMutableDictionary *attr = [NSMutableDictionary
1509 dictionaryWithObject:[NSNumber numberWithBool:saving]
1512 [attr setObject:[NSString stringWithVimString:initdir] forKey:@"dir"];
1514 char_u *s = (char_u*)[[MMBackend sharedInstance]
1515 browseForFileWithAttributes:attr];
1519 #endif /* FEAT_BROWSE */
1532 ASLogDebug(@"type=%d title='%s' message='%s' buttons='%s' dfltbutton=%d "
1533 "textfield='%s'", type, title, message, buttons, dfltbutton,
1536 // Ensure no data is on the output queue before presenting the dialog.
1537 gui_macvim_force_flush();
1539 int style = NSInformationalAlertStyle;
1540 if (VIM_WARNING == type) style = NSWarningAlertStyle;
1541 else if (VIM_ERROR == type) style = NSCriticalAlertStyle;
1543 NSMutableDictionary *attr = [NSMutableDictionary
1544 dictionaryWithObject:[NSNumber numberWithInt:style]
1545 forKey:@"alertStyle"];
1548 // 'buttons' is a string of '\n'-separated button titles
1549 NSString *string = [NSString stringWithVimString:buttons];
1550 NSArray *array = [string componentsSeparatedByString:@"\n"];
1551 [attr setObject:array forKey:@"buttonTitles"];
1554 NSString *messageText = nil;
1556 messageText = [NSString stringWithVimString:title];
1559 NSString *informativeText = [NSString stringWithVimString:message];
1561 // HACK! If there is a '\n\n' or '\n' sequence in the message, then
1562 // make the part up to there into the title. We only do this
1563 // because Vim has lots of dialogs without a title and they look
1565 // TODO: Fix the actual dialog texts.
1566 NSRange eolRange = [informativeText rangeOfString:@"\n\n"];
1567 if (NSNotFound == eolRange.location)
1568 eolRange = [informativeText rangeOfString:@"\n"];
1569 if (NSNotFound != eolRange.location) {
1570 messageText = [informativeText substringToIndex:
1572 informativeText = [informativeText substringFromIndex:
1573 NSMaxRange(eolRange)];
1577 [attr setObject:informativeText forKey:@"informativeText"];
1581 [attr setObject:messageText forKey:@"messageText"];
1584 NSString *string = [NSString stringWithVimString:textfield];
1585 [attr setObject:string forKey:@"textFieldString"];
1588 return [[MMBackend sharedInstance] showDialogWithAttributes:attr
1589 textField:(char*)textfield];
1594 gui_mch_flash(int msec)
1600 * Return the Pixel value (color) for the given color name. This routine was
1601 * pretty much taken from example code in the Silicon Graphics OSF/Motif
1602 * Programmer's Guide.
1603 * Return INVALCOLOR when failed.
1606 gui_mch_get_color(char_u *name)
1609 name = CONVERT_TO_UTF8(name);
1612 NSString *key = [NSString stringWithUTF8String:(char*)name];
1613 guicolor_T col = [[MMBackend sharedInstance] lookupColorWithKey:key];
1616 CONVERT_TO_UTF8_FREE(name);
1624 * Return the RGB value of a pixel as long.
1627 gui_mch_get_rgb(guicolor_T pixel)
1629 // This is only implemented so that vim can guess the correct value for
1630 // 'background' (which otherwise defaults to 'dark'); it is not used for
1631 // anything else (as far as I know).
1632 // The implementation is simple since colors are stored in an int as
1639 * Get the screen dimensions.
1640 * Allow 10 pixels for horizontal borders, 40 for vertical borders.
1641 * Is there no way to find out how wide the borders really are?
1642 * TODO: Add live udate of those value on suspend/resume.
1645 gui_mch_get_screen_dimensions(int *screen_w, int *screen_h)
1647 ASLogDebug(@"Columns=%d Rows=%d", Columns, Rows);
1648 *screen_w = Columns;
1654 * Get the position of the top left corner of the window.
1657 gui_mch_get_winpos(int *x, int *y)
1665 * Return OK if the key with the termcap name "name" is supported.
1668 gui_mch_haskey(char_u *name)
1670 return [[MMBackend sharedInstance] hasSpecialKeyWithValue:name];
1675 * Iconify the GUI window.
1678 gui_mch_iconify(void)
1683 #if defined(FEAT_EVAL) || defined(PROTO)
1685 * Bring the Vim window to the foreground.
1688 gui_mch_set_foreground(void)
1690 [[MMBackend sharedInstance] activate];
1697 gui_mch_set_shellsize(
1706 ASLogDebug(@"width=%d height=%d min_width=%d min_height=%d base_width=%d "
1707 "base_height=%d direction=%d", width, height, min_width,
1708 min_height, base_width, base_height, direction);
1709 [[MMBackend sharedInstance] setRows:height columns:width];
1714 gui_mch_set_text_area_pos(int x, int y, int w, int h)
1719 * Set the position of the top left corner of the window to the given
1723 gui_mch_set_winpos(int x, int y)
1730 * Set the window title and icon.
1731 * (The icon is not taken care of).
1734 gui_mch_settitle(char_u *title, char_u *icon)
1736 ASLogDebug(@"title='%s' icon='%s'", title, icon);
1739 title = CONVERT_TO_UTF8(title);
1742 MMBackend *backend = [MMBackend sharedInstance];
1743 [backend setWindowTitle:(char*)title];
1745 // TODO: Convert filename to UTF-8?
1747 [backend setDocumentFilename:(char*)curbuf->b_ffname];
1750 CONVERT_TO_UTF8_FREE(title);
1757 gui_mch_toggle_tearoffs(int enable)
1764 gui_mch_enter_fullscreen(int fuoptions_flags, guicolor_T bg)
1766 [[MMBackend sharedInstance] enterFullscreen:fuoptions_flags background:bg];
1771 gui_mch_leave_fullscreen()
1773 [[MMBackend sharedInstance] leaveFullscreen];
1778 gui_mch_fuopt_update()
1784 if (fuoptions_flags & FUOPT_BGCOLOR_HLGROUP) {
1785 syn_id2colors(fuoptions_bgcolor, &fg, &bg);
1787 bg = fuoptions_bgcolor;
1790 [[MMBackend sharedInstance] setFullscreenBackgroundColor:bg];
1795 gui_macvim_update_modified_flag()
1797 [[MMBackend sharedInstance] updateModifiedFlag];
1801 * Add search pattern 'pat' to the OS X find pasteboard. This allows other
1802 * apps access the last pattern searched for (hitting <D-g> in another app will
1803 * initiate a search for the same pattern).
1806 gui_macvim_add_to_find_pboard(char_u *pat)
1811 pat = CONVERT_TO_UTF8(pat);
1813 NSString *s = [NSString stringWithUTF8String:(char*)pat];
1815 CONVERT_TO_UTF8_FREE(pat);
1820 NSPasteboard *pb = [NSPasteboard pasteboardWithName:NSFindPboard];
1821 [pb declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil];
1822 [pb setString:s forType:NSStringPboardType];
1826 gui_macvim_set_antialias(int antialias)
1828 [[MMBackend sharedInstance] setAntialias:antialias];
1833 gui_macvim_wait_for_startup()
1835 MMBackend *backend = [MMBackend sharedInstance];
1836 if ([backend waitForAck])
1837 [backend waitForConnectionAcknowledgement];
1840 void gui_macvim_get_window_layout(int *count, int *layout)
1842 if (!(count && layout)) return;
1844 // NOTE: Only set 'layout' if the backend has requested a != 0 layout, else
1845 // any command line arguments (-p/-o) would be ignored.
1846 int window_layout = [[MMBackend sharedInstance] initialWindowLayout];
1847 if (window_layout > 0 && window_layout < 4) {
1848 // The window_layout numbers must match the WIN_* defines in main.c.
1850 *layout = window_layout;
1855 // -- Client/Server ---------------------------------------------------------
1857 #ifdef MAC_CLIENTSERVER
1860 // NOTE: Client/Server is only fully supported with a GUI. Theoretically it
1861 // would be possible to make the server code work with terminal Vim, but it
1862 // would require that a run-loop is set up and checked. This should not be
1863 // difficult to implement, simply call gui_mch_update() at opportune moments
1864 // and it will take care of the run-loop. Another (bigger) problem with
1865 // supporting servers in terminal mode is that the server listing code talks to
1866 // MacVim (the GUI) to figure out which servers are running.
1871 * Register connection with 'name'. The actual connection is named something
1872 * like 'org.vim.MacVim.VIM3', whereas the server is called 'VIM3'.
1875 serverRegisterName(char_u *name)
1878 name = CONVERT_TO_UTF8(name);
1881 NSString *svrName = [NSString stringWithUTF8String:(char*)name];
1882 [[MMBackend sharedInstance] registerServerWithName:svrName];
1885 CONVERT_TO_UTF8_FREE(name);
1891 * Send to an instance of Vim.
1892 * Returns 0 for OK, negative for an error.
1895 serverSendToVim(char_u *name, char_u *cmd, char_u **result,
1896 int *port, int asExpr, int silent)
1899 name = CONVERT_TO_UTF8(name);
1900 cmd = CONVERT_TO_UTF8(cmd);
1903 BOOL ok = [[MMBackend sharedInstance]
1904 sendToServer:[NSString stringWithUTF8String:(char*)name]
1905 string:[NSString stringWithUTF8String:(char*)cmd]
1912 CONVERT_TO_UTF8_FREE(name);
1913 CONVERT_TO_UTF8_FREE(cmd);
1921 * Ask MacVim for the names of all Vim servers.
1924 serverGetVimNames(void)
1926 char_u *names = NULL;
1927 NSArray *list = [[MMBackend sharedInstance] serverList];
1930 NSString *string = [list componentsJoinedByString:@"\n"];
1931 names = [string vimStringSave];
1939 * 'str' is a hex int representing the send port of the connection.
1942 serverStrToPort(char_u *str)
1946 sscanf((char *)str, "0x%x", &port);
1948 EMSG2(_("E573: Invalid server id used: %s"), str);
1955 * Check for replies from server with send port 'port'.
1956 * Return TRUE and a non-malloc'ed string if there is. Else return FALSE.
1959 serverPeekReply(int port, char_u **str)
1961 NSString *reply = [[MMBackend sharedInstance] peekForReplyOnPort:port];
1962 int len = [reply lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1964 if (str && len > 0) {
1965 *str = (char_u*)[reply UTF8String];
1968 if (input_conv.vc_type != CONV_NONE) {
1969 char_u *s = string_convert(&input_conv, *str, &len);
1972 // HACK! Since 's' needs to be freed we cannot simply set
1973 // '*str = s' or memory will leak. Instead, create a dummy
1974 // NSData and return its 'bytes' pointer, then autorelease the
1976 NSData *data = [NSData dataWithBytes:s length:len+1];
1977 *str = (char_u*)[data bytes];
1985 return reply != nil;
1990 * Wait for replies from server with send port 'port'.
1991 * Return 0 and the malloc'ed string when a reply is available.
1992 * Return -1 on error.
1995 serverReadReply(int port, char_u **str)
1997 NSString *reply = [[MMBackend sharedInstance] waitForReplyOnPort:port];
1999 *str = [reply vimStringSave];
2008 * Send a reply string (notification) to client with port given by "serverid".
2009 * Return -1 if the window is invalid.
2012 serverSendReply(char_u *serverid, char_u *reply)
2015 int port = serverStrToPort(serverid);
2016 if (port > 0 && reply) {
2018 reply = CONVERT_TO_UTF8(reply);
2020 BOOL ok = [[MMBackend sharedInstance]
2021 sendReply:[NSString stringWithUTF8String:(char*)reply]
2023 retval = ok ? 0 : -1;
2025 CONVERT_TO_UTF8_FREE(reply);
2032 #endif // MAC_CLIENTSERVER
2037 // -- ODB Editor Support ----------------------------------------------------
2039 #ifdef FEAT_ODB_EDITOR
2041 * The ODB Editor protocol works like this:
2042 * - An external program (the server) asks MacVim to open a file and associates
2043 * three things with this file: (1) a server id (a four character code that
2044 * identifies the server), (2) a path that can be used as window title for
2045 * the file (optional), (3) an arbitrary token (optional)
2046 * - When a file is saved or closed, MacVim should tell the server about which
2047 * file was modified and also pass back the token
2049 * All communication between MacVim and the server goes via Apple Events.
2053 odb_event(buf_T *buf, const AEEventID action)
2055 if (!(buf->b_odb_server_id && buf->b_ffname))
2058 NSAppleEventDescriptor *targetDesc = [NSAppleEventDescriptor
2059 descriptorWithDescriptorType:typeApplSignature
2060 bytes:&buf->b_odb_server_id
2061 length:sizeof(uint32_t)];
2063 // TODO: Convert b_ffname to UTF-8?
2064 NSString *path = [NSString stringWithUTF8String:(char*)buf->b_ffname];
2065 NSData *pathData = [[[NSURL fileURLWithPath:path] absoluteString]
2066 dataUsingEncoding:NSUTF8StringEncoding];
2067 NSAppleEventDescriptor *pathDesc = [NSAppleEventDescriptor
2068 descriptorWithDescriptorType:typeFileURL data:pathData];
2070 NSAppleEventDescriptor *event = [NSAppleEventDescriptor
2071 appleEventWithEventClass:kODBEditorSuite
2073 targetDescriptor:targetDesc
2074 returnID:kAutoGenerateReturnID
2075 transactionID:kAnyTransactionID];
2077 [event setParamDescriptor:pathDesc forKeyword:keyDirectObject];
2079 if (buf->b_odb_token)
2080 [event setParamDescriptor:buf->b_odb_token forKeyword:keySenderToken];
2082 return AESendMessage([event aeDesc], NULL, kAENoReply | kAENeverInteract,
2087 odb_buffer_close(buf_T *buf)
2089 int16_t err = noErr;
2091 err = odb_event(buf, kAEClosedFile);
2093 buf->b_odb_server_id = 0;
2095 if (buf->b_odb_token) {
2096 [(NSAppleEventDescriptor *)(buf->b_odb_token) release];
2097 buf->b_odb_token = NULL;
2100 if (buf->b_odb_fname) {
2101 vim_free(buf->b_odb_fname);
2102 buf->b_odb_fname = NULL;
2110 odb_post_buffer_write(buf_T *buf)
2112 return buf ? odb_event(buf, kAEModifiedFile) : noErr;
2119 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
2120 odb_buffer_close(buf);
2123 #endif // FEAT_ODB_EDITOR
2127 get_macaction_name(expand_T *xp, int idx)
2129 static char_u *str = NULL;
2130 NSDictionary *actionDict = [[MMBackend sharedInstance] actionDict];
2132 if (nil == actionDict || idx < 0 || idx >= [actionDict count])
2135 NSString *string = [[actionDict allKeys] objectAtIndex:idx];
2139 char_u *plainStr = (char_u*)[string UTF8String];
2146 if (input_conv.vc_type != CONV_NONE) {
2147 int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
2148 str = string_convert(&input_conv, plainStr, &len);
2158 is_valid_macaction(char_u *action)
2161 NSDictionary *actionDict = [[MMBackend sharedInstance] actionDict];
2164 action = CONVERT_TO_UTF8(action);
2166 NSString *string = [NSString stringWithUTF8String:(char*)action];
2167 isValid = (nil != [actionDict objectForKey:string]);
2169 CONVERT_TO_UTF8_FREE(action);
2176 static int specialKeyToNSKey(int key)
2178 if (!IS_SPECIAL(key))
2185 { K_UP, NSUpArrowFunctionKey },
2186 { K_DOWN, NSDownArrowFunctionKey },
2187 { K_LEFT, NSLeftArrowFunctionKey },
2188 { K_RIGHT, NSRightArrowFunctionKey },
2189 { K_F1, NSF1FunctionKey },
2190 { K_F2, NSF2FunctionKey },
2191 { K_F3, NSF3FunctionKey },
2192 { K_F4, NSF4FunctionKey },
2193 { K_F5, NSF5FunctionKey },
2194 { K_F6, NSF6FunctionKey },
2195 { K_F7, NSF7FunctionKey },
2196 { K_F8, NSF8FunctionKey },
2197 { K_F9, NSF9FunctionKey },
2198 { K_F10, NSF10FunctionKey },
2199 { K_F11, NSF11FunctionKey },
2200 { K_F12, NSF12FunctionKey },
2201 { K_F13, NSF13FunctionKey },
2202 { K_F14, NSF14FunctionKey },
2203 { K_F15, NSF15FunctionKey },
2204 { K_F16, NSF16FunctionKey },
2205 { K_F17, NSF17FunctionKey },
2206 { K_F18, NSF18FunctionKey },
2207 { K_F19, NSF19FunctionKey },
2208 { K_F20, NSF20FunctionKey },
2209 { K_F21, NSF21FunctionKey },
2210 { K_F22, NSF22FunctionKey },
2211 { K_F23, NSF23FunctionKey },
2212 { K_F24, NSF24FunctionKey },
2213 { K_F25, NSF25FunctionKey },
2214 { K_F26, NSF26FunctionKey },
2215 { K_F27, NSF27FunctionKey },
2216 { K_F28, NSF28FunctionKey },
2217 { K_F29, NSF29FunctionKey },
2218 { K_F30, NSF30FunctionKey },
2219 { K_F31, NSF31FunctionKey },
2220 { K_F32, NSF32FunctionKey },
2221 { K_F33, NSF33FunctionKey },
2222 { K_F34, NSF34FunctionKey },
2223 { K_F35, NSF35FunctionKey },
2224 { K_DEL, NSBackspaceCharacter },
2225 { K_BS, NSDeleteCharacter },
2226 { K_HOME, NSHomeFunctionKey },
2227 { K_END, NSEndFunctionKey },
2228 { K_PAGEUP, NSPageUpFunctionKey },
2229 { K_PAGEDOWN, NSPageDownFunctionKey }
2233 for (i = 0; i < sizeof(sp2ns)/sizeof(sp2ns[0]); ++i) {
2234 if (sp2ns[i].special == key)
2235 return sp2ns[i].nskey;
2241 static int vimModMaskToEventModifierFlags(int mods)
2245 if (mods & MOD_MASK_SHIFT)
2246 flags |= NSShiftKeyMask;
2247 if (mods & MOD_MASK_CTRL)
2248 flags |= NSControlKeyMask;
2249 if (mods & MOD_MASK_ALT)
2250 flags |= NSAlternateKeyMask;
2251 if (mods & MOD_MASK_CMD)
2252 flags |= NSCommandKeyMask;
2259 // -- NetBeans Support ------------------------------------------------------
2261 #ifdef FEAT_NETBEANS_INTG
2263 /* Set NetBeans socket to CFRunLoop */
2265 gui_macvim_set_netbeans_socket(int socket)
2267 [[MMBackend sharedInstance] setNetbeansSocket:socket];
2270 #endif // FEAT_NETBEANS_INTG