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 language or XML etc..). So I guess, I need to get the AST for the selection. Currently I am able to get the selection as simple text. Is there any way out for such problem? Thanks already!!
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With