IDEA-74544 Copy-Paste a string literal with '\n' character inserts actual line-feed instead of '\n'

StringLiteralCopyPasteProcessor handles string literals at the pasted text now
This commit is contained in:
Denis.Zhdanov
2011-10-04 14:28:34 +04:00
parent 9e9228da43
commit 4642c32042
2 changed files with 62 additions and 0 deletions
@@ -71,6 +71,9 @@ public class StringLiteralCopyPasteProcessor implements CopyPastePreProcessor {
if (rawText != null && rawText.rawText != null) return rawText.rawText; // Copied from the string literal. Copy as is.
return escapeCharCharacters(text);
}
else {
text = escapePastedLiteral(text);
}
return text;
}
@@ -119,4 +122,38 @@ public class StringLiteralCopyPasteProcessor implements CopyPastePreProcessor {
StringUtil.escapeStringCharacters(s.length(), s, "\'", buffer);
return buffer.toString();
}
/**
* There is a possible case that pasted string contains string literal. We need to escape problem symbols within it then
* (see IDEA-74544 for the problem example).
*
* @param s target string to paste
* @return string that should be actually pasted
*/
@SuppressWarnings("AssignmentToForLoopParameter")
public static String escapePastedLiteral(@NotNull String s) {
StringBuilder buffer = new StringBuilder();
int literalStart = -1;
int literalEnd = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case '\\': i++;break;
case '"':
if (literalStart < 0) {
literalStart = i + 1;
buffer.append(s, literalEnd, literalStart);
}
else {
literalEnd = i;
buffer.append(StringUtil.escapeStringCharacters(s.substring(literalStart, literalEnd)));
literalStart = -1;
}
}
}
if (literalEnd < s.length()) {
buffer.append(s.substring(Math.max(literalStart, literalEnd)));
}
return buffer.toString();
}
}
@@ -0,0 +1,25 @@
package com.intellij.codeInsight.editorActions;
import org.jetbrains.annotations.NotNull;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* @author Denis Zhdanov
* @since 10/4/11 1:28 PM
*/
public class StringLiteralCopyPasteProcessorTest {
@Test
public void escapePastedStringLiteral() {
doEscapePastedStringLiteralTest("identity", "identity");
doEscapePastedStringLiteralTest("\"complete \n literal\"", "\"complete \\n literal\"");
doEscapePastedStringLiteralTest("\"incomplete \n literal", "\"incomplete \n literal");
doEscapePastedStringLiteralTest("partial \"string \n literal\"", "partial \"string \\n literal\"");
}
private static void doEscapePastedStringLiteralTest(@NotNull String initial, @NotNull String expected) {
assertEquals(expected, StringLiteralCopyPasteProcessor.escapePastedLiteral(initial));
}
}