Skip to content

Instantly share code, notes, and snippets.

@keith
Last active December 10, 2015 20:28
Show Gist options
  • Select an option

  • Save keith/4488045 to your computer and use it in GitHub Desktop.

Select an option

Save keith/4488045 to your computer and use it in GitHub Desktop.
http://smileykeith.com/2013/01/08/nstableview-vim-keys/ Override keyDown to use vim keys in something. Like an NSTableView. Only goodVimKeysSandbox.mm works perfectly in the OS X sandbox.
if ([theEvent keyCode] == 38) { // j
unichar down = NSDownArrowFunctionKey;
NSString *downString = [NSString stringWithCharacters:&down length:1];
NSEvent *newEvent =[NSEvent keyEventWithType:NSKeyDown
location:theEvent.locationInWindow
modifierFlags:theEvent.modifierFlags
timestamp:theEvent.timestamp
windowNumber:theEvent.windowNumber
context:nil
characters:downString
charactersIgnoringModifiers:downString
isARepeat:theEvent.isARepeat
keyCode:down];
[super keyDown:newEvent];
} else if ([theEvent keyCode] == 40) { // k
unichar up = NSUpArrowFunctionKey;
NSString *upString = [NSString stringWithCharacters:&up length:1];
NSEvent *newEvent =[NSEvent keyEventWithType:NSKeyDown
location:theEvent.locationInWindow
modifierFlags:theEvent.modifierFlags
timestamp:theEvent.timestamp
windowNumber:theEvent.windowNumber
context:nil
characters:upString
charactersIgnoringModifiers:upString
isARepeat:theEvent.isARepeat
keyCode:up];
[super keyDown:newEvent];
} else {
[super keyDown:theEvent];
}
if ([theEvent keyCode] == 38) { // The letter 'j'
CGEventRef e = CGEventCreateKeyboardEvent(NULL, (CGKeyCode)125, true);
CGEventPost(kCGSessionEventTap, e);
CFRelease(e);
} else if ([theEvent keyCode] == 40) { // The letter 'k'
CGEventRef e = CGEventCreateKeyboardEvent(NULL, (CGKeyCode)126, true);
CGEventPost(kCGSessionEventTap, e);
CFRelease(e);
}
NSUInteger flags = [theEvent modifierFlags] & NSDeviceIndependentModifierFlagsMask;
NSNumber *shiftPressed = @(flags & NSShiftKeyMask);
if ([theEvent keyCode] == 38) { // j
NSUInteger index = [[self selectedRowIndexes] lastIndex] + 1;
if ([shiftPressed boolValue]) {
[self selectRowIndexes:[NSIndexSet indexSetWithIndex:index] byExtendingSelection:YES];
} else {
[self selectRowIndexes:[NSIndexSet indexSetWithIndex:index] byExtendingSelection:NO];
}
} else if ([theEvent keyCode] == 40) { // k
NSUInteger index = [[self selectedRowIndexes] lastIndex] - 1;
if ([shiftPressed boolValue]) {
[self selectRowIndexes:[NSIndexSet indexSetWithIndex:index] byExtendingSelection:YES];
} else {
[self selectRowIndexes:[NSIndexSet indexSetWithIndex:index] byExtendingSelection:NO];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment