Search code examples
javaintellij-ideacode-completionintellij-plugin

How to use Code Completion on IntelliJ Plugin?


I am working on a plugin on IntelliJ. I have a problem like this:

It's known to us that if we are typing a key word, IntelliJ will using its Code Completion to give our tips like the picture shows.

enter image description here

Now I have a JTextField in my plugin on IntelliJ which need such function like this: when I fill some words to the JTextField, it will provide Code Completion tips like the picture shows. Does IntelliJ has some open api to do that? I do lots of work to investigate how to do that. but nothing gained.


Solution

  • For JTextField, IntelliJ IDEA has no such API. IDEA's completion requires IDEA's Editor to work. You can create one using EditorFactory (and don't forget to release it from the same EditorFactory after it's not needed). If your editor is one-line, you might consider using EditorTextField instead which makes things easier. Both have getComponent() methods that return usual Swing components that can be embedded into your GUI.

    Then you can either show/hide/handle the popup manually using LookupManager methods, or rely on the generic IDE completion machinery which will do many things automatically. But the latter requires you to associate the editor's document with a PsiFile (probably a plain text one, see PsiFileFactory.createFileFromText) and creating a CompletionContributor that would provide suggestion variants depending on the position in your file.