Reformat Scratch File in Custom Editor
Hi,
I'm using an editor instance in a JFrame. Which took me a while to implement, but now it's working.
ScratchpadManager scratchpadManager = ScratchpadManager.getInstance(project);
VirtualFile scratchFile = scratchpadManager.createScratchFile(psiFile.getLanguage());
EditorFactory editorFactory = EditorFactory.getInstance();
Document document = editorFactory.createDocument(selectedText);
Editor editor = editorFactory.createEditor(document, project, scratchFile, false);The variable psiFile comes from the application editor. My questions is, how can I get the PSI File of scratchFile?
Or is there any method than CodeStyleManager.reformat() to reformat the code without getting the PSI File?
请先登录再写评论。
ScratchpadManager is not intended, and also completely unnecessary for this kind of use. Instead, use PsiFileFactory.createFileFromText() to create a PSI file from text and then PsiDocumentManager.getInstance(project).getDocument(file) to get the corresponding document. You can then call CodeStyleManager.reformat() on your PSI file.
Thanks for your answer.
Now I got the following code:
Try to use another factory method
and set eventSystemEnabled to true
Now I have
Now I have found a solution that fits my need. I am using an EditorTextField now.
final PsiFile psiFileFromText = PsiFileFactory.getInstance(project).createFileFromText("newSnippet." + fileExtension, psiFile.getLanguage(), selectedText, true, false);
Document newDocument = PsiDocumentManager.getInstance(project).getDocument(psiFileFromText);
assert newDocument != null;
editorTextField = new EditorTextField(newDocument, project, psiFile.getFileType(), false, false);
editorTextField.setBackground(EditorColors.GUTTER_BACKGROUND.getDefaultColor());
editorTextField.setPlaceholder("Please insert your code snippet here");
JComponent component = editorTextField.getComponent();
component.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
component.setVisible(true);
scrollPaneCode.setViewportView(component);
ApplicationManager.getApplication().invokeLater(
new Runnable() {
@Override
public void run() {
new WriteCommandAction(project) {
@Override
protected void run(@NotNull Result result) throws Throwable {
CodeStyleManager.getInstance(project).reformat(psiFileFromText, false);
}
}.execute();
}
}
);