Using a File/Code Template as a Live Template
Answered
Hello,
I'm currently using a File/Code Template to generate some code inside an existing file. Is there a way to trigger the live template behaviour programmatically (i.e. inside an Action) using this FIle Template for some properties that haven't been filled in? E.g. if i have the file template:
public void ${NAME} {
${BODY}
}
and I programmatically set NAME but not BODY, and I generate this inside of an existing file, is there a way to automatically point the cursor at BODY (and any other variables that weren't provided)?
Please sign in to leave a comment.
Hi Marcus,
Sorry, but it doesn't seem possible.
Hi Karol Lewandowski ,
I thought this functionality already exists in the platform. For example, there is a Code Template for generating a Java test method, and when generating it inside the editor, it places the cursor over the method name to be completed.
To give more context, I am trying to do that as well, but I'm inserting a Code/File Template (using getText) into a Plain Text PSI File (by creating a temporary psi element from the template text).
I looked into some of the implementations and it seemed like they were using TemplateBuilder. However, I could not get it to work by passing in the inserted PSI element, and I wasn't exactly sure why. Do you have any guidance on this?
Hi Marcus,
Thanks for pointing this out. I was looking for APIs connecting these two APIs and didn't think about this case. Please always refer to the existing features if possible, as we are not aware of every feature and use case. This will make providing support much easier.
Regarding answer, it seems that live templates are created programmatically:
https://github.com/JetBrains/intellij-community/blob/241/java/java-impl/src/com/intellij/testIntegration/TestIntegrationUtils.java#L227-L304
In short, a code template is retrieved by name, and its variables are replaced by live template placeholders.