How to format a code fragment outside a file?
Or how to format a string in memory?
This is what I've done.
public static String format(Project project, Language language, String text) {
PsiFile psiFile = PsiFileFactoryImpl.getInstance(project).createFileFromText("virtual", language, text);
DocumentImpl document = (DocumentImpl) FileDocumentManager.getInstance().getDocument(psiFile.getVirtualFile());
document.myAssertThreading = false; // A dirty work around. Use reflections.
CodeStyleManager.getInstance(project).reformat(psiFile);
return psiFile.getText();
}
This code is not perfect, since it has a dirty work around and would produces a lot of exceptions. Is there any elegant method?
Please sign in to leave a comment.
I finally figured it out:
public static String format(final Project project, Language language, String text) {
final PsiFile psiFile = PsiFileFactoryImpl.getInstance(project).createFileFromText("virtual", language, text);
WriteCommandAction.Simple<String> command = new WriteCommandAction.Simple<String>(project, psiFile) {
@Override
protected void run() throws Throwable {
CodeStyleManager.getInstance(project).reformat(psiFile, false);
}
};
command.execute();
return psiFile.getText();
}