I am developing a plugin in Intellij idea. I am stuck at inserting a piece of code after a statement.
For eg:
mHelper.launchPurchaseflow(str,str,str);
I need to find the element launchPurchaseflow
and add a piece of code after that statement.I used PsiElement
and string matcher to get to the corresponding string.
Now my PsiElement = mhelper.launchPurchaseFlow
.
If I use
psiClass.addAfter(newElement, PsiElement.getContext());
It is only trying to add after the closing paranthesis.So its pop out my new element as Incorrect Statement.
For eg:
Its adding at position
mHelper.launchPurchaseflow(str,str,str)//newElement;
But I need to add at
mHelper.launchPurchaseflow(str,str,str); // new Element.
It's hard to give you a correct answer since you're not showing us how you are inserting the new text, but let's say you have a variable PsiElement myElement
that contains the expression mHelper.launchPurchaseflow(str,str,str)
(without the semicolon).
If you call getParent()
on that element, you will likely have access to the statement representing the method call:
// Should represent "mHelper.launchPurchaseflow(str,str,str);" with the semicolon
PsiElement parent = myElement.getParent();
If you add your code after this node, it should produce a valid statement.
Alternatively, if getParent()
does not return a PsiStatement
and you want to be certain to have the full statement, you can do this:
PsiElement statement = PsiTreeUtil.getParentOfType(myElement, PsiStatement.class);