diff --git a/json/src/com/intellij/json/codeinsight/JsonStandardComplianceInspection.java b/json/src/com/intellij/json/codeinsight/JsonStandardComplianceInspection.java index 20fa1e7b0610..b4f7ffc2374d 100644 --- a/json/src/com/intellij/json/codeinsight/JsonStandardComplianceInspection.java +++ b/json/src/com/intellij/json/codeinsight/JsonStandardComplianceInspection.java @@ -139,15 +139,42 @@ public class JsonStandardComplianceInspection extends LocalInspectionTool { @Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { final PsiElement element = descriptor.getPsiElement(); + final String rawText = element.getText(); if (element instanceof JsonLiteral || element instanceof JsonReferenceExpression) { - final String content = JsonPsiUtil.stripQuotes(element.getText()); + String content = JsonPsiUtil.stripQuotes(rawText); + if (element instanceof JsonStringLiteral && rawText.startsWith("'")) { + content = escapeSingleQuotedStringContent(content); + } // TODO: find out better way to replace element and skip reformatting step afterwards final ASTNode replacement = new JsonElementGenerator(project).createValue("\"" + content + "\"").getNode(); element.getParent().getNode().replaceChild(element.getNode(), replacement); } else if (element != null) { - LOG.error("Quick fix was applied to unexpected element", element.getText(), element.getParent().getText()); + LOG.error("Quick fix was applied to unexpected element", rawText, element.getParent().getText()); } } + + @NotNull + private static String escapeSingleQuotedStringContent(@NotNull String content) { + final StringBuilder result = new StringBuilder(); + boolean nextCharEscaped = false; + for (int i = 0; i < content.length(); i++) { + final char c = content.charAt(i); + if ((nextCharEscaped && c != '\'') || (!nextCharEscaped && c == '"')) { + result.append('\\'); + } + if (c != '\\' || nextCharEscaped) { + result.append(c); + nextCharEscaped = false; + } + else { + nextCharEscaped = true; + } + } + if (nextCharEscaped) { + result.append('\\'); + } + return result.toString(); + } } } diff --git a/json/tests/test/com/intellij/json/JsonQuickFixTest.java b/json/tests/test/com/intellij/json/JsonQuickFixTest.java index f66d189aba84..92d4cc4bb175 100644 --- a/json/tests/test/com/intellij/json/JsonQuickFixTest.java +++ b/json/tests/test/com/intellij/json/JsonQuickFixTest.java @@ -30,6 +30,7 @@ public class JsonQuickFixTest extends JsonTestCase { checkWrapInDoubleQuotes("'foo\\\"", "\"foo\\\"\""); checkWrapInDoubleQuotes("{\"foo\": bar}", "{\"foo\": \"bar\"}"); checkWrapInDoubleQuotes("{\"foo\": 'bar'}", "{\"foo\": \"bar\"}"); + checkWrapInDoubleQuotes("'foo\\n\\'\"\\\\\\\"bar", "\"foo\\n'\\\"\\\\\\\"bar\""); } private void checkWrapInDoubleQuotes(@NotNull String before, @NotNull String after) {