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 * MMAppController is the delegate of NSApp and as such handles file open
14 * requests, application termination, etc. It sets up a named NSConnection on
15 * which it listens to incoming connections from Vim processes. It also
16 * coordinates all MMVimControllers.
18 * A new Vim process is started by calling launchVimProcessWithArguments:.
19 * When the Vim process is initialized it notifies the app controller by
20 * sending a connectBackend:pid: message. At this point a new MMVimController
21 * is allocated. Afterwards, the Vim process communicates directly with its
24 * A Vim process started from the command line connects directly by sending the
25 * connectBackend:pid: message (launchVimProcessWithArguments: is never called
29 #import "MMAppController.h"
30 #import "MMVimController.h"
31 #import "MMWindowController.h"
36 // Default timeout intervals on all connections.
37 static NSTimeInterval MMRequestTimeout = 5;
38 static NSTimeInterval MMReplyTimeout = 5;
41 #pragma options align=mac68k
44 short unused1; // 0 (not used)
45 short lineNum; // line to select (< 0 to specify range)
46 long startRange; // start of selection range (if line < 0)
47 long endRange; // end of selection range (if line < 0)
48 long unused2; // 0 (not used)
49 long theDate; // modification date/time
51 #pragma options align=reset
54 @interface MMAppController (MMServices)
55 - (void)openSelection:(NSPasteboard *)pboard userData:(NSString *)userData
56 error:(NSString **)error;
57 - (void)openFile:(NSPasteboard *)pboard userData:(NSString *)userData
58 error:(NSString **)error;
62 @interface MMAppController (Private)
63 - (MMVimController *)keyVimController;
64 - (MMVimController *)topmostVimController;
65 - (int)launchVimProcessWithArguments:(NSArray *)args;
66 - (NSArray *)filterFilesAndNotify:(NSArray *)files;
67 - (NSArray *)filterOpenFiles:(NSArray *)filenames remote:(OSType)theID
69 token:(NSAppleEventDescriptor *)token
70 selectionRange:(MMSelectionRange *)selRange;
71 - (void)handleXcodeModEvent:(NSAppleEventDescriptor *)event
72 replyEvent:(NSAppleEventDescriptor *)reply;
73 - (NSString *)inputStringFromSelectionRange:(MMSelectionRange *)selRange;
76 @interface NSMenu (MMExtras)
77 - (void)recurseSetAutoenablesItems:(BOOL)on;
80 @interface NSNumber (MMExtras)
86 @implementation MMAppController
90 NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
91 [NSNumber numberWithBool:NO], MMNoWindowKey,
92 [NSNumber numberWithInt:64], MMTabMinWidthKey,
93 [NSNumber numberWithInt:6*64], MMTabMaxWidthKey,
94 [NSNumber numberWithInt:132], MMTabOptimumWidthKey,
95 [NSNumber numberWithInt:2], MMTextInsetLeftKey,
96 [NSNumber numberWithInt:1], MMTextInsetRightKey,
97 [NSNumber numberWithInt:1], MMTextInsetTopKey,
98 [NSNumber numberWithInt:1], MMTextInsetBottomKey,
99 [NSNumber numberWithBool:NO], MMTerminateAfterLastWindowClosedKey,
100 @"MMTypesetter", MMTypesetterKey,
101 [NSNumber numberWithFloat:1], MMCellWidthMultiplierKey,
102 [NSNumber numberWithFloat:-1], MMBaselineOffsetKey,
103 [NSNumber numberWithBool:YES], MMTranslateCtrlClickKey,
104 [NSNumber numberWithBool:NO], MMOpenFilesInTabsKey,
105 [NSNumber numberWithBool:NO], MMNoFontSubstitutionKey,
106 [NSNumber numberWithBool:NO], MMLoginShellKey,
109 [[NSUserDefaults standardUserDefaults] registerDefaults:dict];
111 NSArray *types = [NSArray arrayWithObject:NSStringPboardType];
112 [NSApp registerServicesMenuSendTypes:types returnTypes:types];
117 if ((self = [super init])) {
118 fontContainerRef = loadFonts();
120 vimControllers = [NSMutableArray new];
121 pidArguments = [NSMutableDictionary new];
123 // NOTE! If the name of the connection changes here it must also be
124 // updated in MMBackend.m.
125 NSConnection *connection = [NSConnection defaultConnection];
126 NSString *name = [NSString stringWithFormat:@"%@-connection",
127 [[NSBundle mainBundle] bundleIdentifier]];
128 //NSLog(@"Registering connection with name '%@'", name);
129 if ([connection registerName:name]) {
130 [connection setRequestTimeout:MMRequestTimeout];
131 [connection setReplyTimeout:MMReplyTimeout];
132 [connection setRootObject:self];
134 // NOTE: When the user is resizing the window the AppKit puts the
135 // run loop in event tracking mode. Unless the connection listens
136 // to request in this mode, live resizing won't work.
137 [connection addRequestMode:NSEventTrackingRunLoopMode];
139 NSLog(@"WARNING: Failed to register connection with name '%@'",
149 //NSLog(@"MMAppController dealloc");
151 [pidArguments release];
152 [vimControllers release];
153 [openSelectionString release];
158 - (void)applicationWillFinishLaunching:(NSNotification *)notification
160 [[NSAppleEventManager sharedAppleEventManager]
162 andSelector:@selector(handleXcodeModEvent:replyEvent:)
167 - (void)applicationDidFinishLaunching:(NSNotification *)notification
169 [NSApp setServicesProvider:self];
172 - (BOOL)applicationShouldOpenUntitledFile:(NSApplication *)sender
174 // NOTE! This way it possible to start the app with the command-line
175 // argument '-nowindow yes' and no window will be opened by default.
176 untitledWindowOpening =
177 ![[NSUserDefaults standardUserDefaults] boolForKey:MMNoWindowKey];
178 return untitledWindowOpening;
181 - (BOOL)applicationOpenUntitledFile:(NSApplication *)sender
183 [self newWindow:self];
187 - (void)application:(NSApplication *)sender openFiles:(NSArray *)filenames
190 NSString *remotePath = nil;
191 NSAppleEventManager *aem;
192 NSAppleEventDescriptor *remoteToken = nil;
193 NSAppleEventDescriptor *odbdesc = nil;
194 NSAppleEventDescriptor *xcodedesc = nil;
195 MMSelectionRange *selRange = NULL;
197 aem = [NSAppleEventManager sharedAppleEventManager];
198 odbdesc = [aem currentAppleEvent];
199 if (![odbdesc paramDescriptorForKeyword:keyFileSender]) {
200 // The ODB paramaters may hide inside the 'keyAEPropData' descriptor.
201 odbdesc = [odbdesc paramDescriptorForKeyword:keyAEPropData];
202 if (![odbdesc paramDescriptorForKeyword:keyFileSender])
207 remoteID = [[odbdesc paramDescriptorForKeyword:keyFileSender]
209 remotePath = [[odbdesc paramDescriptorForKeyword:keyFileCustomPath]
211 remoteToken = [[odbdesc paramDescriptorForKeyword:keyFileSenderToken]
215 xcodedesc = [[aem currentAppleEvent]
216 paramDescriptorForKeyword:keyAEPosition];
218 selRange = (MMSelectionRange*)[[xcodedesc data] bytes];
220 filenames = [self filterOpenFiles:filenames remote:remoteID path:remotePath
221 token:remoteToken selectionRange:selRange];
222 if ([filenames count]) {
224 BOOL openInTabs = [[NSUserDefaults standardUserDefaults]
225 boolForKey:MMOpenFilesInTabsKey];
227 if (openInTabs && (vc = [self topmostVimController])) {
228 // Open files in tabs in the topmost window.
229 [vc dropFiles:filenames forceOpen:YES];
231 [vc odbEdit:filenames server:remoteID path:remotePath
234 [vc addVimInput:[self inputStringFromSelectionRange:selRange]];
236 // Open files in tabs in a new window.
237 NSMutableArray *args = [NSMutableArray arrayWithObject:@"-p"];
238 [args addObjectsFromArray:filenames];
239 int pid = [self launchVimProcessWithArguments:args];
241 // The Vim process starts asynchronously. Some arguments cannot be
242 // on the command line, so store them in a dictionary and pass them
243 // to the process once it has started.
245 // TODO: If the Vim process fails to start, or if it changes PID,
246 // then the memory allocated for these parameters will leak.
247 // Ensure that this cannot happen or somehow detect it.
248 NSMutableDictionary *argDict = nil;
250 // The remote token can be arbitrary data so it is cannot
251 // (without encoding it as text) be passed on the command line.
252 argDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:
253 filenames, @"filenames",
254 [NSNumber numberWithUnsignedInt:remoteID], @"remoteID",
257 [argDict setObject:remotePath forKey:@"remotePath"];
259 [argDict setObject:remoteToken forKey:@"remoteToken"];
264 argDict = [NSMutableDictionary
265 dictionaryWithObject:[xcodedesc data]
266 forKey:@"selectionRangeData"];
268 [argDict setObject:[xcodedesc data]
269 forKey:@"selectionRangeData"];
273 [pidArguments setObject:argDict
274 forKey:[NSNumber numberWithInt:pid]];
278 [NSApp replyToOpenOrPrint:NSApplicationDelegateReplySuccess];
279 // NSApplicationDelegateReplySuccess = 0,
280 // NSApplicationDelegateReplyCancel = 1,
281 // NSApplicationDelegateReplyFailure = 2
284 - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender
286 return [[NSUserDefaults standardUserDefaults]
287 boolForKey:MMTerminateAfterLastWindowClosedKey];
290 - (NSApplicationTerminateReply)applicationShouldTerminate:
291 (NSApplication *)sender
293 // TODO: Follow Apple's guidelines for 'Graceful Application Termination'
294 // (in particular, allow user to review changes and save).
295 int reply = NSTerminateNow;
296 BOOL modifiedBuffers = NO;
298 // Go through windows, checking for modified buffers. (Each Vim process
299 // tells MacVim when any buffer has been modified and MacVim sets the
300 // 'documentEdited' flag of the window correspondingly.)
301 NSEnumerator *e = [[NSApp windows] objectEnumerator];
303 while ((window = [e nextObject])) {
304 if ([window isDocumentEdited]) {
305 modifiedBuffers = YES;
310 if (modifiedBuffers) {
311 NSAlert *alert = [[NSAlert alloc] init];
312 [alert addButtonWithTitle:@"Quit"];
313 [alert addButtonWithTitle:@"Cancel"];
314 [alert setMessageText:@"Quit without saving?"];
315 [alert setInformativeText:@"There are modified buffers, "
316 "if you quit now all changes will be lost. Quit anyway?"];
317 [alert setAlertStyle:NSWarningAlertStyle];
319 if ([alert runModal] != NSAlertFirstButtonReturn)
320 reply = NSTerminateCancel;
325 // Tell all Vim processes to terminate now (otherwise they'll leave swap
327 if (NSTerminateNow == reply) {
328 e = [vimControllers objectEnumerator];
330 while ((vc = [e nextObject]))
331 [vc sendMessage:TerminateNowMsgID data:nil];
337 - (void)applicationWillTerminate:(NSNotification *)notification
339 [[NSAppleEventManager sharedAppleEventManager]
340 removeEventHandlerForEventClass:'KAHL'
343 // This will invalidate all connections (since they were spawned from the
344 // default connection).
345 [[NSConnection defaultConnection] invalidate];
347 // Send a SIGINT to all running Vim processes, so that they are sure to
348 // receive the connectionDidDie: notification (a process has to be checking
349 // the run-loop for this to happen).
350 unsigned i, count = [vimControllers count];
351 for (i = 0; i < count; ++i) {
352 MMVimController *controller = [vimControllers objectAtIndex:i];
353 int pid = [controller pid];
358 if (fontContainerRef) {
359 ATSFontDeactivate(fontContainerRef, NULL, kATSOptionFlagsDefault);
360 fontContainerRef = 0;
363 // TODO: Is this a correct way of releasing the MMAppController?
364 // (It doesn't seem like dealloc is ever called.)
365 [NSApp setDelegate:nil];
369 - (void)removeVimController:(id)controller
371 //NSLog(@"%s%@", _cmd, controller);
373 [[controller windowController] close];
375 [vimControllers removeObject:controller];
377 if (![vimControllers count]) {
378 // Turn on autoenabling of menus (because no Vim is open to handle it),
379 // but do not touch the MacVim menu. Note that the menus must be
380 // enabled first otherwise autoenabling does not work.
381 NSMenu *mainMenu = [NSApp mainMenu];
382 int i, count = [mainMenu numberOfItems];
383 for (i = 1; i < count; ++i) {
384 NSMenuItem *item = [mainMenu itemAtIndex:i];
385 [item setEnabled:YES];
386 [[item submenu] recurseSetAutoenablesItems:YES];
391 - (void)windowControllerWillOpen:(MMWindowController *)windowController
393 NSPoint topLeft = NSZeroPoint;
394 NSWindow *keyWin = [NSApp keyWindow];
395 NSWindow *win = [windowController window];
399 // If there is a key window, cascade from it, otherwise use the autosaved
400 // window position (if any).
402 NSRect frame = [keyWin frame];
403 topLeft = NSMakePoint(frame.origin.x, NSMaxY(frame));
405 NSString *topLeftString = [[NSUserDefaults standardUserDefaults]
406 stringForKey:MMTopLeftPointKey];
408 topLeft = NSPointFromString(topLeftString);
411 if (!NSEqualPoints(topLeft, NSZeroPoint)) {
413 topLeft = [win cascadeTopLeftFromPoint:topLeft];
415 [win setFrameTopLeftPoint:topLeft];
418 if (openSelectionString) {
419 // There is some text to paste into this window as a result of the
420 // services menu "Open selection ..." being used.
421 [[windowController vimController] dropString:openSelectionString];
422 [openSelectionString release];
423 openSelectionString = nil;
427 - (IBAction)newWindow:(id)sender
429 [self launchVimProcessWithArguments:nil];
432 - (IBAction)selectNextWindow:(id)sender
434 unsigned i, count = [vimControllers count];
437 NSWindow *keyWindow = [NSApp keyWindow];
438 for (i = 0; i < count; ++i) {
439 MMVimController *vc = [vimControllers objectAtIndex:i];
440 if ([[[vc windowController] window] isEqual:keyWindow])
447 MMVimController *vc = [vimControllers objectAtIndex:i];
448 [[vc windowController] showWindow:self];
452 - (IBAction)selectPreviousWindow:(id)sender
454 unsigned i, count = [vimControllers count];
457 NSWindow *keyWindow = [NSApp keyWindow];
458 for (i = 0; i < count; ++i) {
459 MMVimController *vc = [vimControllers objectAtIndex:i];
460 if ([[[vc windowController] window] isEqual:keyWindow])
470 MMVimController *vc = [vimControllers objectAtIndex:i];
471 [[vc windowController] showWindow:self];
475 - (IBAction)fontSizeUp:(id)sender
477 [[NSFontManager sharedFontManager] modifyFont:
478 [NSNumber numberWithInt:NSSizeUpFontAction]];
481 - (IBAction)fontSizeDown:(id)sender
483 [[NSFontManager sharedFontManager] modifyFont:
484 [NSNumber numberWithInt:NSSizeDownFontAction]];
487 - (byref id <MMFrontendProtocol>)
488 connectBackend:(byref in id <MMBackendProtocol>)backend
491 //NSLog(@"Connect backend (pid=%d)", pid);
493 [(NSDistantObject*)backend
494 setProtocolForProxy:@protocol(MMBackendProtocol)];
496 MMVimController *vc = [[[MMVimController alloc]
497 initWithBackend:backend pid:pid] autorelease];
499 if (![vimControllers count]) {
500 // The first window autosaves its position. (The autosaving features
501 // of Cocoa are not used because we need more control over what is
502 // autosaved and when it is restored.)
503 [[vc windowController] setWindowAutosaveKey:MMTopLeftPointKey];
506 [vimControllers addObject:vc];
508 // HACK! MacVim does not get activated if it is launched from the
509 // terminal, so we forcibly activate here unless it is an untitled window
510 // opening (i.e. MacVim was opened from the Finder). Untitled windows are
511 // treated differently, else MacVim would steal the focus if another app
512 // was activated while the untitled window was loading.
513 if (!untitledWindowOpening)
514 [NSApp activateIgnoringOtherApps:YES];
516 untitledWindowOpening = NO;
518 // Arguments to a new Vim process that cannot be passed on the command line
519 // are stored in a dictionary and passed to the Vim process here.
520 NSNumber *key = [NSNumber numberWithInt:pid];
521 NSDictionary *args = [pidArguments objectForKey:key];
523 if ([args objectForKey:@"remoteID"]) {
524 [vc odbEdit:[args objectForKey:@"filenames"]
525 server:[[args objectForKey:@"remoteID"] unsignedIntValue]
526 path:[args objectForKey:@"remotePath"]
527 token:[args objectForKey:@"remoteToken"]];
530 if ([args objectForKey:@"selectionRangeData"]) {
531 MMSelectionRange *selRange = (MMSelectionRange*)
532 [[args objectForKey:@"selectionRangeData"] bytes];
533 [vc addVimInput:[self inputStringFromSelectionRange:selRange]];
536 [pidArguments removeObjectForKey:key];
542 - (NSArray *)serverList
544 NSMutableArray *array = [NSMutableArray array];
546 unsigned i, count = [vimControllers count];
547 for (i = 0; i < count; ++i) {
548 MMVimController *controller = [vimControllers objectAtIndex:i];
549 if ([controller serverName])
550 [array addObject:[controller serverName]];
556 @end // MMAppController
561 @implementation MMAppController (MMServices)
563 - (void)openSelection:(NSPasteboard *)pboard userData:(NSString *)userData
564 error:(NSString **)error
566 if (![[pboard types] containsObject:NSStringPboardType]) {
567 NSLog(@"WARNING: Pasteboard contains no object of type "
568 "NSStringPboardType");
572 MMVimController *vc = [self topmostVimController];
574 // Open a new tab first, since dropString: does not do this.
575 [vc sendMessage:AddNewTabMsgID data:nil];
576 [vc dropString:[pboard stringForType:NSStringPboardType]];
578 // NOTE: There is no window to paste the selection into, so save the
579 // text, open a new window, and paste the text when the next window
580 // opens. (If this is called several times in a row, then all but the
581 // last call might be ignored.)
582 if (openSelectionString) [openSelectionString release];
583 openSelectionString = [[pboard stringForType:NSStringPboardType] copy];
585 [self newWindow:self];
589 - (void)openFile:(NSPasteboard *)pboard userData:(NSString *)userData
590 error:(NSString **)error
592 if (![[pboard types] containsObject:NSStringPboardType]) {
593 NSLog(@"WARNING: Pasteboard contains no object of type "
594 "NSStringPboardType");
598 // TODO: Parse multiple filenames and create array with names.
599 NSString *string = [pboard stringForType:NSStringPboardType];
600 string = [string stringByTrimmingCharactersInSet:
601 [NSCharacterSet whitespaceAndNewlineCharacterSet]];
602 string = [string stringByStandardizingPath];
604 NSArray *filenames = [self filterFilesAndNotify:
605 [NSArray arrayWithObject:string]];
606 if ([filenames count] > 0) {
607 MMVimController *vc = nil;
608 if (userData && [userData isEqual:@"Tab"])
609 vc = [self topmostVimController];
612 [vc dropFiles:filenames forceOpen:YES];
614 [self application:NSApp openFiles:filenames];
619 @end // MMAppController (MMServices)
624 @implementation MMAppController (Private)
626 - (MMVimController *)keyVimController
628 NSWindow *keyWindow = [NSApp keyWindow];
630 unsigned i, count = [vimControllers count];
631 for (i = 0; i < count; ++i) {
632 MMVimController *vc = [vimControllers objectAtIndex:i];
633 if ([[[vc windowController] window] isEqual:keyWindow])
641 - (MMVimController *)topmostVimController
643 NSArray *windows = [NSApp orderedWindows];
644 if ([windows count] > 0) {
645 NSWindow *window = [windows objectAtIndex:0];
646 unsigned i, count = [vimControllers count];
647 for (i = 0; i < count; ++i) {
648 MMVimController *vc = [vimControllers objectAtIndex:i];
649 if ([[[vc windowController] window] isEqual:window])
657 - (int)launchVimProcessWithArguments:(NSArray *)args
659 NSString *taskPath = nil;
660 NSArray *taskArgs = nil;
661 NSString *path = [[NSBundle mainBundle] pathForAuxiliaryExecutable:@"Vim"];
664 NSLog(@"ERROR: Vim executable could not be found inside app bundle!");
668 if ([[NSUserDefaults standardUserDefaults] boolForKey:MMLoginShellKey]) {
669 // Run process with a login shell
670 // $SHELL -l -c "exec Vim -g -f args"
671 // (-g for GUI, -f for foreground, i.e. don't fork)
673 NSMutableString *execArg = [NSMutableString
674 stringWithFormat:@"exec \"%@\" -g -f", path];
676 // Append all arguments while making sure that arguments containing
677 // spaces are enclosed in quotes.
678 NSCharacterSet *space = [NSCharacterSet whitespaceCharacterSet];
679 unsigned i, count = [args count];
681 for (i = 0; i < count; ++i) {
682 NSString *arg = [args objectAtIndex:i];
683 if (NSNotFound != [arg rangeOfCharacterFromSet:space].location)
684 [execArg appendFormat:@" \"%@\"", arg];
686 [execArg appendFormat:@" %@", arg];
690 // Launch the process with a login shell so that users environment
691 // settings get sourced. This does not always happen when MacVim is
693 taskArgs = [NSArray arrayWithObjects:@"-l", @"-c", execArg, nil];
694 taskPath = [[[NSProcessInfo processInfo] environment]
695 objectForKey:@"SHELL"];
697 taskPath = @"/bin/sh";
699 // Run process directly:
701 // (-g for GUI, -f for foreground, i.e. don't fork)
703 taskArgs = [NSArray arrayWithObjects:@"-g", @"-f", nil];
705 taskArgs = [taskArgs arrayByAddingObjectsFromArray:args];
708 NSTask *task =[NSTask launchedTaskWithLaunchPath:taskPath
710 //NSLog(@"launch %@ with args=%@ (pid=%d)", taskPath, taskArgs,
711 // [task processIdentifier]);
713 return [task processIdentifier];
716 - (NSArray *)filterFilesAndNotify:(NSArray *)filenames
718 // Go trough 'filenames' array and make sure each file exists. Present
719 // warning dialog if some file was missing.
721 NSString *firstMissingFile = nil;
722 NSMutableArray *files = [NSMutableArray array];
723 unsigned i, count = [filenames count];
725 for (i = 0; i < count; ++i) {
726 NSString *name = [filenames objectAtIndex:i];
727 if ([[NSFileManager defaultManager] fileExistsAtPath:name]) {
728 [files addObject:name];
729 } else if (!firstMissingFile) {
730 firstMissingFile = name;
734 if (firstMissingFile) {
735 NSAlert *alert = [[NSAlert alloc] init];
736 [alert addButtonWithTitle:@"OK"];
739 if ([files count] >= count-1) {
740 [alert setMessageText:@"File not found"];
741 text = [NSString stringWithFormat:@"Could not open file with "
742 "name %@.", firstMissingFile];
744 [alert setMessageText:@"Multiple files not found"];
745 text = [NSString stringWithFormat:@"Could not open file with "
746 "name %@, and %d other files.", firstMissingFile,
747 count-[files count]-1];
750 [alert setInformativeText:text];
751 [alert setAlertStyle:NSWarningAlertStyle];
756 [NSApp replyToOpenOrPrint:NSApplicationDelegateReplyFailure];
762 - (NSArray *)filterOpenFiles:(NSArray *)filenames remote:(OSType)theID
763 path:(NSString *)path
764 token:(NSAppleEventDescriptor *)token
765 selectionRange:(MMSelectionRange *)selRange
767 // Check if any of the files in the 'filenames' array are open in any Vim
768 // process. Remove the files that are open from the 'filenames' array and
769 // return it. If all files were filtered out, then raise the first file in
770 // the Vim process it is open. Files that are filtered are sent an odb
771 // open event in case theID is not zero.
773 MMVimController *raiseController = nil;
774 NSString *raiseFile = nil;
775 NSMutableArray *files = [filenames mutableCopy];
776 NSString *expr = [NSString stringWithFormat:
777 @"map([\"%@\"],\"bufloaded(v:val)\")",
778 [files componentsJoinedByString:@"\",\""]];
779 unsigned i, count = [vimControllers count];
781 for (i = 0; i < count && [files count]; ++i) {
782 MMVimController *controller = [vimControllers objectAtIndex:i];
783 id proxy = [controller backendProxy];
786 NSString *eval = [proxy evaluateExpression:expr];
787 NSIndexSet *idxSet = [NSIndexSet indexSetWithVimList:eval];
788 if ([idxSet count]) {
790 // Remember the file and which Vim that has it open so that
791 // we can raise it later on.
792 raiseController = controller;
793 raiseFile = [files objectAtIndex:[idxSet firstIndex]];
794 [[raiseFile retain] autorelease];
797 // Send an odb open event to the Vim process.
799 [controller odbEdit:[files objectsAtIndexes:idxSet]
800 server:theID path:path token:token];
802 // Remove all the files that were open in this Vim process and
803 // create a new expression to evaluate.
804 [files removeObjectsAtIndexes:idxSet];
805 expr = [NSString stringWithFormat:
806 @"map([\"%@\"],\"bufloaded(v:val)\")",
807 [files componentsJoinedByString:@"\",\""]];
810 @catch (NSException *e) {
815 if (![files count] && raiseFile) {
816 // Raise the window containing the first file that was already open,
817 // and make sure that the tab containing that file is selected. Only
818 // do this if there are no more files to open, otherwise sometimes the
819 // window with 'raiseFile' will be raised, other times it might be the
820 // window that will open with the files in the 'files' array.
821 raiseFile = [raiseFile stringByEscapingSpecialFilenameCharacters];
822 NSString *input = [NSString stringWithFormat:@"<C-\\><C-N>"
823 ":let oldswb=&swb|let &swb=\"useopen,usetab\"|"
824 "tab sb %@|let &swb=oldswb|unl oldswb|"
825 "cal foreground()|redr|f<CR>", raiseFile];
828 input = [input stringByAppendingString:
829 [self inputStringFromSelectionRange:selRange]];
831 [raiseController addVimInput:input];
837 - (void)handleXcodeModEvent:(NSAppleEventDescriptor *)event
838 replyEvent:(NSAppleEventDescriptor *)reply
841 // Xcode sends this event to query MacVim which open files have been
843 NSLog(@"reply:%@", reply);
844 NSLog(@"event:%@", event);
846 NSEnumerator *e = [vimControllers objectEnumerator];
848 while ((vc = [e nextObject])) {
849 DescType type = [reply descriptorType];
850 unsigned len = [[type data] length];
851 NSMutableData *data = [NSMutableData data];
853 [data appendBytes:&type length:sizeof(DescType)];
854 [data appendBytes:&len length:sizeof(unsigned)];
855 [data appendBytes:[reply data] length:len];
857 [vc sendMessage:XcodeModMsgID data:data];
862 - (NSString *)inputStringFromSelectionRange:(MMSelectionRange *)selRange
865 return [NSString string];
868 if (selRange->lineNum < 0) {
869 input = [NSString stringWithFormat:@"<C-\\><C-N>%dGV%dG",
870 selRange->endRange+1, selRange->startRange+1];
872 input = [NSString stringWithFormat:@"<C-\\><C-N>%dGz.",
873 selRange->lineNum+1];
879 @end // MMAppController (Private)
884 @implementation NSMenu (MMExtras)
886 - (void)recurseSetAutoenablesItems:(BOOL)on
888 [self setAutoenablesItems:on];
890 int i, count = [self numberOfItems];
891 for (i = 0; i < count; ++i) {
892 NSMenuItem *item = [self itemAtIndex:i];
893 [item setEnabled:YES];
894 NSMenu *submenu = [item submenu];
896 [submenu recurseSetAutoenablesItems:on];
901 @end // NSMenu (MMExtras)
906 @implementation NSNumber (MMExtras)
909 return [self intValue];
911 @end // NSNumber (MMExtras)