Generating a method call in code with PSI


I am working on a plug-in, that should add code to existing code.

How can it be achieved that a method call is added to a Psielement, for example:
Adding the text ".myMethodCall()" to the PsiElement "MyClass", so it becomes : "Myclass.myMethodCall()" ?

I tried adding it as a PsiExpression with addAfter, but that puts it in a new line and deletes the dot-operator.

Ideally, i would like to do this for Groovy-Code, so i will use the Groovy equivalent like for instance GrExpression.

Comment actions Permalink

Please see org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory

Comment actions Permalink

Thanks Yann,


i found a clue in there. Now i must find out what anchor to add this after, currently trying the element at caret (LeafPsiElement), which represents the name of the class the method is supposed to be called in. This still has no dot-operator like this.

PsiElement elementAtCaret = file.findElementAt(editor.getCaretModel().getOffset());
GrMethodCallExpression methodCall = (GrMethodCallExpression) groovyFactory.createExpressionFromText(methodCallText, null);
Runnable r = () -> elementAtCaret.getParent().addAfter(methodCall, elementAtCaret);

It seems like it is required to also include the calling class into the MethodCallExpression, like "MyClass.myCall()". Like that i get the right output, but it makes it difficult, if what i want to chain the method call to is a complex expression by itself, like I was assuming the MethodCallExpression just consists of the actual calling-part(name of the method plus args) that i can hook to whatever was there (under caret)


Please sign in to leave a comment.