For my plugin I’m trying to access the selected code in a CompilationUnitEditor. Therefore I added a contribution to the context menu and use following code:
public class ContextMenuHandler implements IEditorActionDelegate {
private IEditorPart editorPart;
@Override
public void setActiveEditor(IAction action, IEditorPart editorPart) {
this.editorPart = editorPart;
}
@Override
public void run(IAction action) {
JavaUI.getEditorInputJavaElement(editorPart.getEditorInput());
}
@Override
public void selectionChanged(IAction action, ISelection selection) {
if (selection instanceof TextSelection) {
TextSelection text = (TextSelection) selection;
System.out.println("Text: " + text.getText());
} else {
System.out.println(selection);
}
}
}
Now the problem is that the method selectionChanged(…) is only called when i really select something so that I could copy/paste it. But I want to access the Code elements that are highlighted like this (here I would like to get the “IEditorPart”)

Unfortunately, I have no idea what I should look for.
Using the inputs from the other answers, I ended up with the following solution: