Java: correctly escape for text block (IDEA-331523)

in Replace concatenation with formatted output" intention"

GitOrigin-RevId: b3e57b2cc62bbbcdca3fe357d8a6896837ca3f73
This commit is contained in:
Bas Leijdekkers
2023-09-04 16:06:54 +02:00
committed by intellij-monorepo-bot
parent 2286383bda
commit 9cfda82b22
3 changed files with 6 additions and 5 deletions

View File

@@ -43,14 +43,15 @@ public class ConcatenationToMessageFormatAction extends PsiUpdateModCommandActio
PsiPolyadicExpression concatenation = getEnclosingLiteralConcatenation(element);
if (concatenation == null) return;
List<PsiExpression> args = new ArrayList<>();
final String formatString = PsiConcatenationUtil.buildUnescapedFormatString(concatenation, false, args);
final String formatString =
StringUtil.escapeStringCharacters(PsiConcatenationUtil.buildUnescapedFormatString(concatenation, false, args));
Project project = context.project();
final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
PsiMethodCallExpression call = (PsiMethodCallExpression)
factory.createExpressionFromText("java.text.MessageFormat.format()", concatenation);
PsiExpressionList argumentList = call.getArgumentList();
boolean textBlocks = ContainerUtil.exists(concatenation.getOperands(),
boolean textBlocks = ContainerUtil.exists(concatenation.getOperands(),
operand -> operand instanceof PsiLiteralExpression literal && literal.isTextBlock());
final String expressionText;
if (textBlocks) {
@@ -59,7 +60,7 @@ public class ConcatenationToMessageFormatAction extends PsiUpdateModCommandActio
.collect(Collectors.joining("\n", "\"\"\"\n", "\"\"\""));
}
else {
expressionText = "\"" + StringUtil.escapeStringCharacters(formatString) + "\"";
expressionText = "\"" + formatString + "\"";
}
PsiExpression formatArgument = factory.createExpressionFromText(expressionText, null);
argumentList.add(formatArgument);

View File

@@ -5,7 +5,7 @@ class C {
String s = java.text.MessageFormat.format("""
the text\s
block
line2
\\line2
{0}{1} "to" be""", a, b);
}
}

View File

@@ -3,7 +3,7 @@ class C {
void x(int a, int b) {
String s = """
the text \n block
line2
\\line2
""" +
a + b + <caret>//keep me
" \"to\" be";