I need to get the AST for the current selection in the java editor fo eclipse. Basically I want to convert the selected java code in to some other form(maybe some other lang
Use the method org.eclipse.jdt.internal.ui.javaeditor.EditorUtility.getActiveEditorJavaInput()
. That returns the Java element edited in the current active editor. The return type is org.eclipse.jdt.core.IJavaElement
, but if it's a Java file that's being edited, the run time type will be org.eclipse.jdt.core.ICompilationUnit
.
To get the AST, i.e., the org.eclipse.jdt.core.dom.CompilationUnit
, you can use the following code:
public static CompilationUnit getCompilationUnit(ICompilationUnit icu,
IProgressMonitor monitor) {
final ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setSource(icu);
parser.setResolveBindings(true);
final CompilationUnit ret = (CompilationUnit) parser.createAST(monitor);
return ret;
}
Keep in mind that this is for Java >= 5. For earlier versions you'll need to switch the argument to ASTParser.newParser()
.
I realize that this question was answered but I wanted to shed light on the EditorUtility class, which is quite useful here.
IIRC, each node in the Eclipse AST contains an offset. All you need to do is to compute the offsets for the part of the code you are interested in then walk the AST to select the nodes within those offsets.
The following Code provides you the AST Node of the current selected Code from the CompilationUnitEditor.
ITextEditor editor = (ITextEditor) HandlerUtil.getActiveEditor(event);
ITextSelection sel = (ITextSelection) editor.getSelectionProvider().getSelection();
ITypeRoot typeRoot = JavaUI.getEditorInputTypeRoot(editor.getEditorInput());
ICompilationUnit icu = (ICompilationUnit) typeRoot.getAdapter(ICompilationUnit.class);
CompilationUnit cu = parse(icu);
NodeFinder finder = new NodeFinder(cu, sel.getOffset(), sel.getLength());
ASTNode node = finder.getCoveringNode();
The JavaUI is the entry point to the JDT UI plugin.
There are a number of handy tools for JDT plugin developers, especially the AST View which does pretty much what you are looking for. So, all you need to do is grab the code for AST View and check how it is done.
The plugin can be installed from the following update site: http://www.eclipse.org/jdt/ui/update-site
Use the plugin spy (read more about it in this article) to start digging into the view classes.
You are traveling into less trivial (and often undocumented) areas of JDT, developing your code digging skills will greatly improve your performance.