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 MMVimController *vc = nil;
492 //NSLog(@"Connect backend (pid=%d)", pid);
495 [(NSDistantObject*)backend
496 setProtocolForProxy:@protocol(MMBackendProtocol)];
498 vc = [[[MMVimController alloc]
499 initWithBackend:backend pid:pid] autorelease];
501 if (![vimControllers count]) {
502 // The first window autosaves its position. (The autosaving
503 // features of Cocoa are not used because we need more control over
504 // what is autosaved and when it is restored.)
505 [[vc windowController] setWindowAutosaveKey:MMTopLeftPointKey];
508 [vimControllers addObject:vc];
510 // HACK! MacVim does not get activated if it is launched from the
511 // terminal, so we forcibly activate here unless it is an untitled
512 // window opening (i.e. MacVim was opened from the Finder). Untitled
513 // windows are treated differently, else MacVim would steal the focus
514 // if another app was activated while the untitled window was loading.
515 if (!untitledWindowOpening)
516 [NSApp activateIgnoringOtherApps:YES];
518 untitledWindowOpening = NO;
520 // Arguments to a new Vim process that cannot be passed on the command
521 // line are stored in a dictionary and passed to the Vim process here.
522 NSNumber *key = [NSNumber numberWithInt:pid];
523 NSDictionary *args = [pidArguments objectForKey:key];
525 if ([args objectForKey:@"remoteID"]) {
526 [vc odbEdit:[args objectForKey:@"filenames"]
527 server:[[args objectForKey:@"remoteID"] unsignedIntValue]
528 path:[args objectForKey:@"remotePath"]
529 token:[args objectForKey:@"remoteToken"]];
532 if ([args objectForKey:@"selectionRangeData"]) {
533 MMSelectionRange *selRange = (MMSelectionRange*)
534 [[args objectForKey:@"selectionRangeData"] bytes];
535 [vc addVimInput:[self inputStringFromSelectionRange:selRange]];
538 [pidArguments removeObjectForKey:key];
544 @catch (NSException *e) {
545 NSLog(@"Exception caught in %s: \"%@\"", _cmd, e);
548 [vimControllers removeObject:vc];
554 - (NSArray *)serverList
556 NSMutableArray *array = [NSMutableArray array];
558 unsigned i, count = [vimControllers count];
559 for (i = 0; i < count; ++i) {
560 MMVimController *controller = [vimControllers objectAtIndex:i];
561 if ([controller serverName])
562 [array addObject:[controller serverName]];
568 @end // MMAppController
573 @implementation MMAppController (MMServices)
575 - (void)openSelection:(NSPasteboard *)pboard userData:(NSString *)userData
576 error:(NSString **)error
578 if (![[pboard types] containsObject:NSStringPboardType]) {
579 NSLog(@"WARNING: Pasteboard contains no object of type "
580 "NSStringPboardType");
584 MMVimController *vc = [self topmostVimController];
586 // Open a new tab first, since dropString: does not do this.
587 [vc sendMessage:AddNewTabMsgID data:nil];
588 [vc dropString:[pboard stringForType:NSStringPboardType]];
590 // NOTE: There is no window to paste the selection into, so save the
591 // text, open a new window, and paste the text when the next window
592 // opens. (If this is called several times in a row, then all but the
593 // last call might be ignored.)
594 if (openSelectionString) [openSelectionString release];
595 openSelectionString = [[pboard stringForType:NSStringPboardType] copy];
597 [self newWindow:self];
601 - (void)openFile:(NSPasteboard *)pboard userData:(NSString *)userData
602 error:(NSString **)error
604 if (![[pboard types] containsObject:NSStringPboardType]) {
605 NSLog(@"WARNING: Pasteboard contains no object of type "
606 "NSStringPboardType");
610 // TODO: Parse multiple filenames and create array with names.
611 NSString *string = [pboard stringForType:NSStringPboardType];
612 string = [string stringByTrimmingCharactersInSet:
613 [NSCharacterSet whitespaceAndNewlineCharacterSet]];
614 string = [string stringByStandardizingPath];
616 NSArray *filenames = [self filterFilesAndNotify:
617 [NSArray arrayWithObject:string]];
618 if ([filenames count] > 0) {
619 MMVimController *vc = nil;
620 if (userData && [userData isEqual:@"Tab"])
621 vc = [self topmostVimController];
624 [vc dropFiles:filenames forceOpen:YES];
626 [self application:NSApp openFiles:filenames];
631 @end // MMAppController (MMServices)
636 @implementation MMAppController (Private)
638 - (MMVimController *)keyVimController
640 NSWindow *keyWindow = [NSApp keyWindow];
642 unsigned i, count = [vimControllers count];
643 for (i = 0; i < count; ++i) {
644 MMVimController *vc = [vimControllers objectAtIndex:i];
645 if ([[[vc windowController] window] isEqual:keyWindow])
653 - (MMVimController *)topmostVimController
655 NSArray *windows = [NSApp orderedWindows];
656 if ([windows count] > 0) {
657 NSWindow *window = [windows objectAtIndex:0];
658 unsigned i, count = [vimControllers count];
659 for (i = 0; i < count; ++i) {
660 MMVimController *vc = [vimControllers objectAtIndex:i];
661 if ([[[vc windowController] window] isEqual:window])
669 - (int)launchVimProcessWithArguments:(NSArray *)args
671 NSString *taskPath = nil;
672 NSArray *taskArgs = nil;
673 NSString *path = [[NSBundle mainBundle] pathForAuxiliaryExecutable:@"Vim"];
676 NSLog(@"ERROR: Vim executable could not be found inside app bundle!");
680 if ([[NSUserDefaults standardUserDefaults] boolForKey:MMLoginShellKey]) {
681 // Run process with a login shell
682 // $SHELL -l -c "exec Vim -g -f args"
683 // (-g for GUI, -f for foreground, i.e. don't fork)
685 NSMutableString *execArg = [NSMutableString
686 stringWithFormat:@"exec \"%@\" -g -f", path];
688 // Append all arguments while making sure that arguments containing
689 // spaces are enclosed in quotes.
690 NSCharacterSet *space = [NSCharacterSet whitespaceCharacterSet];
691 unsigned i, count = [args count];
693 for (i = 0; i < count; ++i) {
694 NSString *arg = [args objectAtIndex:i];
695 if (NSNotFound != [arg rangeOfCharacterFromSet:space].location)
696 [execArg appendFormat:@" \"%@\"", arg];
698 [execArg appendFormat:@" %@", arg];
702 // Launch the process with a login shell so that users environment
703 // settings get sourced. This does not always happen when MacVim is
705 taskArgs = [NSArray arrayWithObjects:@"-l", @"-c", execArg, nil];
706 taskPath = [[[NSProcessInfo processInfo] environment]
707 objectForKey:@"SHELL"];
709 taskPath = @"/bin/sh";
711 // Run process directly:
713 // (-g for GUI, -f for foreground, i.e. don't fork)
715 taskArgs = [NSArray arrayWithObjects:@"-g", @"-f", nil];
717 taskArgs = [taskArgs arrayByAddingObjectsFromArray:args];
720 NSTask *task =[NSTask launchedTaskWithLaunchPath:taskPath
722 //NSLog(@"launch %@ with args=%@ (pid=%d)", taskPath, taskArgs,
723 // [task processIdentifier]);
725 return [task processIdentifier];
728 - (NSArray *)filterFilesAndNotify:(NSArray *)filenames
730 // Go trough 'filenames' array and make sure each file exists. Present
731 // warning dialog if some file was missing.
733 NSString *firstMissingFile = nil;
734 NSMutableArray *files = [NSMutableArray array];
735 unsigned i, count = [filenames count];
737 for (i = 0; i < count; ++i) {
738 NSString *name = [filenames objectAtIndex:i];
739 if ([[NSFileManager defaultManager] fileExistsAtPath:name]) {
740 [files addObject:name];
741 } else if (!firstMissingFile) {
742 firstMissingFile = name;
746 if (firstMissingFile) {
747 NSAlert *alert = [[NSAlert alloc] init];
748 [alert addButtonWithTitle:@"OK"];
751 if ([files count] >= count-1) {
752 [alert setMessageText:@"File not found"];
753 text = [NSString stringWithFormat:@"Could not open file with "
754 "name %@.", firstMissingFile];
756 [alert setMessageText:@"Multiple files not found"];
757 text = [NSString stringWithFormat:@"Could not open file with "
758 "name %@, and %d other files.", firstMissingFile,
759 count-[files count]-1];
762 [alert setInformativeText:text];
763 [alert setAlertStyle:NSWarningAlertStyle];
768 [NSApp replyToOpenOrPrint:NSApplicationDelegateReplyFailure];
774 - (NSArray *)filterOpenFiles:(NSArray *)filenames remote:(OSType)theID
775 path:(NSString *)path
776 token:(NSAppleEventDescriptor *)token
777 selectionRange:(MMSelectionRange *)selRange
779 // Check if any of the files in the 'filenames' array are open in any Vim
780 // process. Remove the files that are open from the 'filenames' array and
781 // return it. If all files were filtered out, then raise the first file in
782 // the Vim process it is open. Files that are filtered are sent an odb
783 // open event in case theID is not zero.
785 MMVimController *raiseController = nil;
786 NSString *raiseFile = nil;
787 NSMutableArray *files = [filenames mutableCopy];
788 NSString *expr = [NSString stringWithFormat:
789 @"map([\"%@\"],\"bufloaded(v:val)\")",
790 [files componentsJoinedByString:@"\",\""]];
791 unsigned i, count = [vimControllers count];
793 for (i = 0; i < count && [files count]; ++i) {
794 MMVimController *controller = [vimControllers objectAtIndex:i];
795 id proxy = [controller backendProxy];
798 NSString *eval = [proxy evaluateExpression:expr];
799 NSIndexSet *idxSet = [NSIndexSet indexSetWithVimList:eval];
800 if ([idxSet count]) {
802 // Remember the file and which Vim that has it open so that
803 // we can raise it later on.
804 raiseController = controller;
805 raiseFile = [files objectAtIndex:[idxSet firstIndex]];
806 [[raiseFile retain] autorelease];
809 // Send an odb open event to the Vim process.
811 [controller odbEdit:[files objectsAtIndexes:idxSet]
812 server:theID path:path token:token];
814 // Remove all the files that were open in this Vim process and
815 // create a new expression to evaluate.
816 [files removeObjectsAtIndexes:idxSet];
817 expr = [NSString stringWithFormat:
818 @"map([\"%@\"],\"bufloaded(v:val)\")",
819 [files componentsJoinedByString:@"\",\""]];
822 @catch (NSException *e) {
827 if (![files count] && raiseFile) {
828 // Raise the window containing the first file that was already open,
829 // and make sure that the tab containing that file is selected. Only
830 // do this if there are no more files to open, otherwise sometimes the
831 // window with 'raiseFile' will be raised, other times it might be the
832 // window that will open with the files in the 'files' array.
833 raiseFile = [raiseFile stringByEscapingSpecialFilenameCharacters];
834 NSString *input = [NSString stringWithFormat:@"<C-\\><C-N>"
835 ":let oldswb=&swb|let &swb=\"useopen,usetab\"|"
836 "tab sb %@|let &swb=oldswb|unl oldswb|"
837 "cal foreground()|redr|f<CR>", raiseFile];
840 input = [input stringByAppendingString:
841 [self inputStringFromSelectionRange:selRange]];
843 [raiseController addVimInput:input];
849 - (void)handleXcodeModEvent:(NSAppleEventDescriptor *)event
850 replyEvent:(NSAppleEventDescriptor *)reply
853 // Xcode sends this event to query MacVim which open files have been
855 NSLog(@"reply:%@", reply);
856 NSLog(@"event:%@", event);
858 NSEnumerator *e = [vimControllers objectEnumerator];
860 while ((vc = [e nextObject])) {
861 DescType type = [reply descriptorType];
862 unsigned len = [[type data] length];
863 NSMutableData *data = [NSMutableData data];
865 [data appendBytes:&type length:sizeof(DescType)];
866 [data appendBytes:&len length:sizeof(unsigned)];
867 [data appendBytes:[reply data] length:len];
869 [vc sendMessage:XcodeModMsgID data:data];
874 - (NSString *)inputStringFromSelectionRange:(MMSelectionRange *)selRange
877 return [NSString string];
880 if (selRange->lineNum < 0) {
881 input = [NSString stringWithFormat:@"<C-\\><C-N>%dGV%dG",
882 selRange->endRange+1, selRange->startRange+1];
884 input = [NSString stringWithFormat:@"<C-\\><C-N>%dGz.",
885 selRange->lineNum+1];
891 @end // MMAppController (Private)
896 @implementation NSMenu (MMExtras)
898 - (void)recurseSetAutoenablesItems:(BOOL)on
900 [self setAutoenablesItems:on];
902 int i, count = [self numberOfItems];
903 for (i = 0; i < count; ++i) {
904 NSMenuItem *item = [self itemAtIndex:i];
905 [item setEnabled:YES];
906 NSMenu *submenu = [item submenu];
908 [submenu recurseSetAutoenablesItems:on];
913 @end // NSMenu (MMExtras)
918 @implementation NSNumber (MMExtras)
921 return [self intValue];
923 @end // NSNumber (MMExtras)