[java-templates] Avoid braces when completing 'throw' in switch rule branch

GitOrigin-RevId: ef54453da96b8bf9f957cf40d9d6d162debab8ea
This commit is contained in:
Tagir Valeev
2022-09-18 07:48:32 +02:00
committed by intellij-monorepo-bot
parent 1fe5cc18af
commit d3fffdcc31
4 changed files with 47 additions and 15 deletions

View File

@@ -35,22 +35,29 @@ public class JavaTemplateSubstitutor implements TemplateSubstitutor {
public @Nullable TemplateImpl substituteTemplate(@NotNull TemplateSubstitutionContext substitutionContext,
@NotNull TemplateImpl template) {
PsiFile file = substitutionContext.getPsiFile();
if (file.getLanguage().isKindOf(JavaLanguage.INSTANCE) &&
EXPR_LAMBDA_BODY.accepts(file.findElementAt(substitutionContext.getOffset()))) {
String text = template.getString();
try {
PsiStatement statement = JavaPsiFacade.getElementFactory(substitutionContext.getProject()).createStatementFromText(text, null);
String resultText;
if (statement instanceof PsiExpressionStatement) {
resultText = ((PsiExpressionStatement)statement).getExpression().getText();
} else {
resultText = "{" + text + "}";
if (file.getLanguage().isKindOf(JavaLanguage.INSTANCE)) {
PsiElement element = file.findElementAt(substitutionContext.getOffset());
if (EXPR_LAMBDA_BODY.accepts(element)) {
boolean inSwitch = element != null && element.getPrevSibling() instanceof PsiSwitchLabeledRuleStatement;
String text = template.getString();
try {
PsiStatement statement = JavaPsiFacade.getElementFactory(substitutionContext.getProject()).createStatementFromText(text, null);
String resultText;
if (inSwitch && (statement instanceof PsiExpressionStatement || statement instanceof PsiThrowStatement)) {
resultText = text;
}
else if (statement instanceof PsiExpressionStatement) {
resultText = ((PsiExpressionStatement)statement).getExpression().getText();
}
else {
resultText = "{" + text + "}";
}
TemplateImpl copy = template.copy();
copy.setString(resultText);
return copy;
}
catch (IncorrectOperationException ignored) {
}
TemplateImpl copy = template.copy();
copy.setString(resultText);
return copy;
}
catch (IncorrectOperationException ignored) {
}
}
return null;

View File

@@ -0,0 +1,9 @@
import java.util.List;
class Foo {
void test() {
switch(1) {
default -> throw new <caret>
}
}
}

View File

@@ -0,0 +1,9 @@
import java.util.List;
class Foo {
void test() {
switch(1) {
default -> <caret>
}
}
}

View File

@@ -211,6 +211,13 @@ class Outer {
checkResult()
}
void testThrInSwitch() {
configure()
startTemplate("thr", "Java")
stripTrailingSpaces()
checkResult()
}
private void stripTrailingSpaces() {
DocumentImpl document = (DocumentImpl)getEditor().getDocument()
document.setStripTrailingSpacesEnabled(true)