Issue
I am wrting an Eclipse plugin that rewrites java files (possibly multiple files) based on the content of a selected java file (right click -> custom menu item).
Everything works as intended but the rewriting of the files doesn't manage the content formating so after using the plugin I have to manually format each affected java files with the Eclipse format action.
I am able to programmatically call the Eclipse format action on the selected java file but i'd like to also format all other files.
Here's what I have right now (the part that should change is within the for loop):
@Override
public Object execute(ExecutionEvent event) throws ExecutionException
{
var workbench = PlatformUI.getWorkbench();
var activeWorkbenchWindow = workbench.getActiveWorkbenchWindow();
var selection = activeWorkbenchWindow.getActivePage().getSelection();
List<String> generatedClasses = null;
if ((selection instanceof IStructuredSelection structuredSelection)
&& (structuredSelection.getFirstElement() instanceof ICompilationUnit compilationUnit))
{
try
{
var projectClassLoader = getProjectClassLoader(compilationUnit.getJavaProject());
generatedClasses = bindingGenerator.generateBindings(compilationUnit, projectClassLoader);
}
catch (ClassNotFoundException | NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException | IOException
| IllegalClassFormatException | JavaModelException e)
{
// TODO pop an error message dialog?
return null;
}
for (String generatedClass : generatedClasses)
try
{
// I can find the IType of each affected java file here if it should help?
var type = compilationUnit.getJavaProject().findType(generatedClass);
// This is where the formating should be made. The code below currently format the selected file only.
var commandId = IJavaEditorActionDefinitionIds.FORMAT;
var handlerService = workbench.getService(IHandlerService.class);
try
{
handlerService.executeCommand(commandId, null);
}
catch (Exception e1)
{
e1.printStackTrace();
}
}
catch (JavaModelException e)
{
e.printStackTrace();
}
}
MessageDialog.openInformation(activeWorkbenchWindow.getShell(), "Generated bindings on files:", String.join(", ", generatedClasses));
return null;
}
Solution
Thanks to @greg-449 for pointing me out to ToolFactory.createCodeFormatter.
I just need to create a formatter with the project's options like this:
ToolFactory.createCodeFormatter(compilationUnit.getJavaProject().getOptions(true));
and then use the formatter on the file's sources.
Answered By - Fred
Answer Checked By - Timothy Miller (JavaFixing Admin)