IntelliJ plugin development. Insert a string in a file
Code:
public class JavaCodePredictionProvider extends CompletionProvider<CompletionParameters> {
@Override
protected void addCompletions(@NotNull CompletionParameters parameters,
@NotNull ProcessingContext context, @NotNull CompletionResultSet result) {
Editor editor = parameters.getEditor();
Project project = parameters.getEditor().getProject();
PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
prepare(editor, psiFile, project);
}
public void prepare(Editor editor, PsiFile psiFile, Project project) {
// ...code omitted...
String codeSuggestion = "This is the string that I would like to insert into the file";
suggest(project, editor, codeSuggestion, offset);
}
// this method displays the suggestion to the user
public void suggest(Project project, Editor editor, String codeSuggestion, int offset) {
// Get the document and project
final Document document = editor.getDocument();
// Construct the runnable to substitute the string at offset in the document
Runnable runnable = () -> document.insertString(offset, codeSuggestion);
// Make the document change in the context of a write action.
WriteCommandAction.runWriteCommandAction(project, runnable);
}
}
I am developing a plugin for IntelliJ.
This plugin should return a code suggestion. I don't want the suggestion to appear in the list among the predictions already provided by IntelliJ, however I would like my prediction to appear in a light grey color in the file and then the user can choose to accept it or not (through a shortcut).
In my suggest method I am trying to inject the codeSuggestion string into the file. However I am getting an error saying:
"Must not start write action from within read action in the other thread - deadlock is coming
java.lang.Throwable: Must not start write action from within read action in the other thread - deadlock is coming"
Are there other ways to insert a string in a file? Maybe by modifying the PSI?
Thank you
请先登录再写评论。
Could you please share full code of your current solution? Please be aware that not using default UI might be confusing for users who are accustomed ot use completion popup to choose possible insertion text(s).