Sunday, December 07, 2008

Hooking into Eclipse command execution

When I was working on implementing the Clips plug-in I wanted to intercept the Cut and Copy actions and automatically create clips from the selection. To my delight I discovered the necessary mechanism to exactly do that. Basically I had to add the following listener:
// Add listener to monitor Cut and Copy commands
ICommandService commandService = (ICommandService) PlatformUI
if (commandService != null) {
commandService.addExecutionListener(new IExecutionListener() {

public void notHandled(String commandId,
NotHandledException exception) {

public void postExecuteFailure(String commandId,
ExecutionException exception) {

public void postExecuteSuccess(String commandId,
Object returnValue) {
// Is it a Cut or Copy command
if ("org.eclipse.ui.edit.copy".equals(commandId)
|| "org.eclipse.ui.edit.cut".equals(commandId)) {
Clipboard clipboard = new Clipboard(PlatformUI
Object contents = clipboard
if (contents instanceof String) {
// Now do something with text selection


public void preExecute(String commandId, ExecutionEvent event) {


Cool huh?


Anonymous said...

Where did you place this code. As in which class?

Sandip Chitale said...

In an implementation of org.eclipse.ui.IStartup registered using the extension point org.eclipse.ui.startup.