How to use TemplateBuilder for "Introduce Variable"


I'm working on an "introduce variable" refactoring. What I have in mind is to use the template framework. From a selected text, I could search for the next "Module" where a variable can be introduced. So what I want is to turn this

after pressing Ctrl+Alt+V into an editable live template that looks like this

This shouldn't be hard, but I'm stumbling upon how to set up the placeholders for the template. My idea is to walk the tree upwards from the selection until I have to whole "Module" element. How can I use the text of the "Module" element and turn it into an appropriate template? Are there any good examples out there since documentation is not really existent. 


Hi Patrick,

It looks like to me that you "mimic" surround with runnable, where rename is started after variable is introduced. That is done with help of VariableInplaceRenamer, started on the extracted variable, see the code here: com.intellij.codeInsight.generation.surroundWith.JavaWithRunnableSurrounder#surroundStatements.

Actually the normal extract refactorings are implemented as inheritors of com.intellij.refactoring.introduce.inplace.AbstractInplaceIntroducer. It provides you with occurrences support and some preview. Though if you don't need both, then the previous one is easier and is enough. 



Permanently deleted user

Hey Anna,

Thank you for your answer. I think I grasped now what happens when invoking "introduce variable" in Java. The extent of the expression that is introduced is selected in


with a call to IntroduceTargetChooser.showChooser. After that is selected, you can choose which expressions are replaced with AbstractInplaceIntroducer which additionally gives the opportunity to rename the variable. I will postpone the implementation of this as there is a lot of Idea code I have to go through and understand. When I have more time, I'll come back to this.


Please sign in to leave a comment.