Search code examples
intellij-ideaintellij-plugin

Plugin development: how to insert parameterized content into the editor similar to Live Templates?


I am developing a domain-specific custom language as an Intellij IDEA plugin.

I created an intention that allows the user to fix an error in the code.

I am able to make updates to the content in the editor, and then place the caret where I want the user to add some text. However, there are multiple places the user needs to add text at, and I would like to automatically have the caret placed in all of them, one after the other, similar to how it's done when using the Live Templates feature, when adding a Live Template with parameters in it.

When using Live Templates, it looks like this:

Notice the red box. The caret gets there automatically, and when I finish typing and click enter - it moves to the next parameter and the red box appears there.

Note that in the scenario I'm implementing the text is completely dynamic. If creating temporary ad-hoc Live Templates on the fly is possible then that might be a viable solution, but otherwise I need another way to control this mechanism.

Does anyone know how to pull it off?


Solution

  • It's possible to create live templates on the fly. The most convenient API for that is TemplateBuilder, see its javadoc. If you don't have PSI available, you can assemble a template manually by carefully constructing TemplateImpl object and then using TemplateManager#startTemplate. There are numerous examples for both cases in IntelliJ IDEA Community edition codebase.