Time for action – binding commands to keys

To hook up the command to a keystroke a binding is used. This allows a key (or series of keys) to be used to invoke the command, instead of only via the menu. Bindings are set up via an extension point org.eclipse.ui.bindings, and connect a sequence of keystrokes to a command ID.

  1. Open the plugin.xml in the clock.ui project.
  2. In the plugin.xml tab, add the following:
    <extension point="org.eclipse.ui.bindings">
      <key commandId="com.packtpub.e4.clock.ui.command.hello"
        sequence="M1+9"
        contextId="org.eclipse.ui.contexts.window"
        schemeId=
        "org.eclipse.ui.defaultAcceleratorConfiguration"/>
    </extension>
  3. Run the Eclipse instance, and press Cmd + 9 (for OS X) or Ctrl + 9 (for Windows/Linux). The same Hello dialog should be displayed, as if it was shown from the menu. The same keystroke should be displayed in the Help menu.

What just happened?

The M1 key is the primary meta key, which is Cmd on OS X and Ctrl on Windows/Linux. This is typically used for the main operations; for example M1 + C is copy and M1 + V is paste on all systems. The sequence notation M1 + 9 is used to indicate pressing both keys at the same time.

The command that gets invoked is referenced by its commandId. This may be defined in the same plug-in, but does not have to be; it is possible for one application to provide a set of commands and another plug-in to provide keystrokes that bind them.

It is also possible to set up a sequence of key presses; for example, M1 + 9 8 7 would require pressing Cmd + 9 or Ctrl + 9 followed by 8 and then 7 before the command is executed. This allows a set of keystrokes to be used to invoke a command; for example, it's possible to emulate an Emacs quit operation with the keybinding Ctrl + X Ctrl + C to the quit command.

Other modifier keys include M2 (Shift), M3 (Alt/Option), and M4 (Ctrl on OS X). It is possible to use CTRL, SHIFT, or ALT as long names, but the meta names are preferred, since M1 tends to be bound to different keys on different operating systems.

The non-modifier keys themselves can either be single characters (A to Z), numbers (0 to 9), or one of a set of longer name key-codes, such as F12, ARROW_UP, TAB, and PAGE_UP. Certain common variations are allowed; for example, ESC/ESCAPE, ENTER/RETURN, and so on.

Finally, bindings are associated with a scheme, which in the default case should be org.eclipse.ui.defaultAcceleratorConfiguration. Schemes exist to allow the user to switch in and out of keybindings and replace them with others, which is how tools like "vrapper" (a vi emulator) and the Emacs bindings that come with Eclipse by default can be used. (This can be changed via Window | Preferences | Keys menu in Eclipse.)

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset