[java-completion] Complete statement: keep comments when fixing 'if' condition (IDEA-153023)

GitOrigin-RevId: f6bdbd611adb8105fa8ee6a6bb4621fc38800643
This commit is contained in:
Tagir Valeev
2022-04-20 13:08:08 +02:00
committed by intellij-monorepo-bot
parent 42b05fea59
commit c62e2b7740
4 changed files with 28 additions and 3 deletions

View File

@@ -5,9 +5,9 @@ import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.util.IncorrectOperationException;
@SuppressWarnings({"HardCodedStringLiteral"})
public class IfConditionFixer implements Fixer {
@Override
public void apply(Editor editor, JavaSmartEnterProcessor processor, PsiElement psiElement) throws IncorrectOperationException {
@@ -27,9 +27,20 @@ public class IfConditionFixer implements Fixer {
}
stopOffset = Math.min(stopOffset, ifStatement.getTextRange().getEndOffset());
doc.replaceString(ifStatement.getTextRange().getStartOffset(), stopOffset, "if ()");
PsiElement lastChild = ifStatement.getLastChild();
String innerComment = "";
String lastComment = "";
if (lParen != null && PsiUtilCore.getElementType(lastChild) == JavaTokenType.C_STYLE_COMMENT) {
innerComment = lastChild.getText();
}
else if (lastChild instanceof PsiComment) {
lastComment = lastChild.getText();
}
processor.registerUnresolvedError(ifStatement.getTextRange().getStartOffset() + "if (".length());
String prefix = "if (" + innerComment;
doc.replaceString(ifStatement.getTextRange().getStartOffset(), stopOffset, prefix + ")" + lastComment);
processor.registerUnresolvedError(ifStatement.getTextRange().getStartOffset() + prefix.length());
} else {
processor.registerUnresolvedError(lParen.getTextRange().getEndOffset());
}

View File

@@ -0,0 +1,6 @@
class A {
void foo() {
if(/**/<caret>
}
}

View File

@@ -0,0 +1,7 @@
class A {
void foo() {
if (<caret>/**/) {
}
}
}

View File

@@ -67,6 +67,7 @@ public class CompleteStatementTest extends EditorActionTestCase {
public void testForIncrementExpressionAndBody() { doTest(); }
public void testEmptyBeforeReturn() { doTest(); }
public void testIf() { doTest(); }
public void testIfWithComment() { doTest(); }
public void testIfWithoutParentheses() { doTest(); }
public void testBeforeStatement() { doTest(); }
public void testTry1() { doTest(); }