HOWTO: Use IContextActivation to setup keybindings for a ViewPart or EditorPart
Just a quick tip for setting up view-specific and editor-specific keybindings. I had a bit trouble figuring it out and it took a whole day of googling to figure it out. If you want to get view-specific or editor-specific keybindings working you should:
- Use the org.eclipse.ui.contexts extension point to define a new context. The context ID should be the same as your editor or viewpart ID though it doesn’t have to be. The parent ID can be most anything but
org.eclipse.ui.context.windowis a safe value.
- Use the org.eclipse.ui.bindings to define a new keybinding that is only active in your view or editor. The
contextIdmust be the same ID you defined in the first step. A good default for
org.eclipse.ui.defaultAcceleratorConfiguration. For more about the difference between contexts and schemes see FAQ How do I provide a keyboard shortcut for my action?. It’s a little confusing but, in simplest terms, a context defines when your keybinding is active and a scheme defines what the actual accelerator shortcut for the command will be used. You provide a default but the user can re-assign the accelerator shortcut if he changes schemes.
- Finally you must programatically activate the context when your view or editor is opened. How you do this is important. (This is the tricky part.) If you want the keybindings to be only active when your view is in focus you should use the “site-specific service locator” ie
IContextService contextService = (IContextService) getSite().getService(IContextService.class);. If you want your keybindings to always be active you should use the “workbench service locator” ie
IContextService contextService = (IContextService) PlatformUI.getWorkbench().getService(IContextService.class);. If you use the site-specific service locator the deactivation of your context will all be automagically handled for you.