How to construct a block comment from text (Java)?

I am developing a plugin in which I want to rewrite the body of a method. For example, I want to do something like this:

Before rewriting:

int f(){
int x = 2;
return x;
}

After rewriting:

int f(){
int y = 3;
return y;
/*int x = 2;
return x;*/
}

As you can see, I want to (1) modify the method body (2) create a comment out of the old method body text and (3) add it in the rewritten method. I constructed the comment as follows:

PsiCommentImpl oldBodyComment = new PsiCommentImpl(JavaTokenType.C_STYLE_COMMENT, oldBodyText);

but when I try to do (3):

newMethodBody.add(oldBodyComment); //I am running this as a Runnable using runWriteCommandAction

it gives me the following error:

com.intellij.psi.PsiInvalidElementAccessException: Element: class com.intellij.psi.impl.source.tree.PsiCommentImpl because: parent is null;

What am I doing wrong? In general, what is the correct way to construct comments from some text in an IntelliJ IDEA plugin?

Any help is much appreciated.

0
3 comments
Official comment

Please try this:

JavaPsiFacade.getElementFactory(project).createCommentFromText(oldBodyText, null)
Avatar
Permanently deleted user

Yes this works! Thank you.

However, the catch here is that the text passed to createCommentFromText should already be a well defined comment in text form, as shown below

// This is a well defined comment text     (1)
This is NOT a well defined comment text (2)

This function returns a PsiComment for (1) but throws an "incorrect comment" exception for (2).

It would be nice to have a function that simply takes text, and builds the comment (especially when the text itself may have embedded comments).

0

I believe there's no such ready-made function, especially given there are many styles of comments in many different languages. So it appears you should make a well-formed comment itself. As for embedded comments, there's some logic on handling them in CommentByBlockCommentHandler, but I don't think it's extractable or even well-readable :(

0

Please sign in to leave a comment.