Tip and Tricks for Eclipse Plugin Developers


This is a short list of tips and tricks that I've encountered while working with the Eclipse PDE. This is sample code that shows how to do things that I had to look into the eclipse source code to find.

If you have any tips or tricks you'd like to see, please email Tom Schneider, schneidh at users.sourceforge.net.

How do I add copy and paste to a view?
In your view class's createPartControl method insert the following code:

Action cutAction = new Action() {
  public void run() {
    // cut action code here
  }
};
Action copyAction = new Action() {
  public void run() {
    // copy action code here
  }
};
Action pasteAction = new Action() {
  public void run() {
    // paste action code here
  }
};

IActionBars bars = this.getViewSite().getActionBars();
bars.setGlobalActionHandler(IWorkbenchActionConstants.CUT, cutAction);
bars.setGlobalActionHandler(IWorkbenchActionConstants.COPY, copyAction);
bars.setGlobalActionHandler(IWorkbenchActionConstants.PASTE, pasteAction);

This also works for any of the built-in Workbench global handlers.

How do I add a checked view menu item?
In your view class's createPartControl method insert the following code:

final Action toggleMenuAction = new Action() {
  public void run() {
    boolean selected = toggleMenuAction.getSelected();
    // toggle code here
    // (called on either a selection or a deselection)
  }
};
toggleMenuAction.setText("checkable action");
toggleMenuAction.setChecked(false);
IActionBars actionBars = getViewSite().getActionBars();
actionBars.getMenuManager().add(toggleMenuAction);
How do I set the default font and background color for a custom editor?
In your subclassed editor class add the following overridden method:
public void createPartControl(Composite arg0) {
  super.createPartControl(arg0);
  StyledText widget = getSourceViewer().getTextWidget();
  FontData font = // font data init here
  widget.setFont(new Font(Display.getCurrent(), font));
  Color background = // color init here
  widget.setBackground(background);
}
How do I autoscroll a StyledText widget?
// where widget is your StyledText object
protected void revealEndOfDocument() {
  StyledTextContent doc= widget.getContent();
  int docLength= doc.getCharCount();
  if (docLength > 0) {
    widget.setCaretOffset(docLength);
    widget.showSelection();
  }
}