I'm creating an editor using 'SourceViewer'. Given below is the code snippet from my '@PostConstruct' method.

// viewer is my SourceViewer instance   
viewer = new SourceViewer(parent,verticalRuler, styles);

     IUndoManager undoManager = new TextViewerUndoManager(25);
     undoManager.connect(viewer);
     viewer.setUndoManager(undoManager);

Even though a default 'TextViewerUndoManager' associated with 'SourceViewer'. Ctrl+Z and Ctrl+Y is not working.

Another alternative that I tried is to override the 'IUndoManager getUndoManager(ISourceViewer sourceViewer)' of 'SourceViewerConfiguration' subclass and return a 'TextViewerUndoManager'. This approach also doesn't give the desired result.

Kindly let me know what I'm missing in the above approaches.

有帮助吗?

解决方案

It is normally the SourceViewerConfiguration that provides the Undo manager, the SourceViewer expects this and will set up the manager from that. The defaults already set up TextViewerUndoManager.

In an e4 application you do not get any default key bindings, commands or handlers so you will have to set up all these to make use of the undo manager.

In your application model declare Commands for undo and redo.

Declare key bindings for Ctrl+Z and Ctrl+Y specifying your commands. You might want to put the key bindings in a Binding Table that is specific to text editors.

Declare Handlers for the undo and redo commands, the code for undo might look like:

public class UndoHandler
{
  @Inject
  private Adapter _adapter; 

  @Execute
  public void execute(@Named(IServiceConstants.ACTIVE_PART) final MPart part)
  {
    final ITextOperationTarget opTarget = _adapter.adapt(part.getObject(), ITextOperationTarget.class);

    opTarget.doOperation(ITextOperationTarget.UNDO);
  }  

  @CanExecute
  public boolean canExecute(@Named(IServiceConstants.ACTIVE_PART) final MPart part)
  {
    final ITextOperationTarget opTarget = _adapter.adapt(part.getObject(), ITextOperationTarget.class);
    if (opTarget == null)
      return false;

    return opTarget.canDoOperation(ITextOperationTarget.UNDO);
  }
}

Redo would be similar but using ITextOperationTarget.REDO.

其他提示

The order of doing/registering things is important. Be sure to connect the undo manager AFTER setting the document to the SourceViewer instance because on connect() the document will be retrieved from the viewer by the undo manager and if it doesn't find a document it will not register anything and undoable() will always return false.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top