Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I script an undo operation in an Eclipse plug-in?

I'm making a plug-in for Eclipse and I want to leverage the built-in Eclipse 'Undo' action (org.eclipse.core.commands.operations) whenever a user presses the undo button associated with the plug-in.

Ideally, it would just reproduce what happens when you press CTRL+Z, but I didn't get simulating keypresses working.

I've tried these code snippets:

Undo performed in a workbench:

IWorkbenchOperationSupport operationSupport = PlatformUI.getWorkbench().getOperationSupport();
IUndoContext context = operationSupport.getUndoContext();
IOperationHistory operationHistory = operationSupport.getOperationHistory();    
IStatus status = operationHistory.undo(context, null, null);

Undo performed in a workspace:

IWorkbenchOperationSupport operationSupport = PlatformUI.getWorkbench().getOperationSupport();
IUndoContext context= (IUndoContext)ResourcesPlugin.getWorkspace().getAdapter(IUndoContext.class);
IOperationHistory operationHistory = operationSupport.getOperationHistory();
IStatus status = operationHistory.undo(context, null, null);

What I am then looking for, analogously, is this, but it doesn't work:

Undo performed on editor/document:

IWorkbenchOperationSupport operationSupport = PlatformUI.getWorkbench().getOperationSupport();
IEditorPart currentEditor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
IUndoContext context = (IUndoContext) currentEditor.getAdapter(IUndoContext.class);
IOperationHistory operationHistory = operationSupport.getOperationHistory();
IStatus status = operationHistory.undo(context, null, null);
like image 251
Maarten Avatar asked Aug 03 '11 10:08

Maarten


1 Answers

If your editor has a viewer on it (e.g. TextViewer, SourceViewer, ProjectionViewer), then you can add an undo action that calls the undo operation on the viewer, e.g.

Action undoAction = new Action()
{
  @Override
  public void run()
  {
    getViewer().doOperation( ITextOperationTarget.UNDO );
  }
}; 
like image 145
Scott Ellis Avatar answered Nov 03 '22 14:11

Scott Ellis