PyStringLiteralExpression (@Nullable PsiFile destination, @NotNull String unescaped, final boolean preferUTF8) { boolean useDouble = !unescaped.contains("\""); boolean useMulti = unescaped.matches(".*(\r|\n).*"); String quotes; if (useMulti) { quotes = useDouble ? "\"\"\"" : "'''"; } else { quotes = useDouble ? "\"" : "'"; } StringBuilder buf = new StringBuilder(unescaped.length() * 2); buf.append(quotes); VirtualFile vfile = destination == null ? null : destination.getVirtualFile(); Charset charset; if (vfile == null) { charset = (preferUTF8 ? StandardCharsets.UTF_8 : StandardCharsets.US_ASCII); } else { charset = vfile.getCharset(); } CharsetEncoder encoder = charset.newEncoder(); Formatter formatter = new Formatter(buf); boolean unicode = false; for (int i = 0; i < unescaped.length(); i++) { int c = unescaped.codePointAt(i); if (c == '"' && useDouble) { buf.append("\\\""); } else if (c == '\'' && !useDouble) { buf.append("\\'"); } else if ((c == '\r' || c == '\n') && !useMulti) { buf.append(c == '\r' ? "\\r" : "\\n"); } else if (!encoder.canEncode(new String(Character.toChars(c)))) { if (c <= 0xff) { formatter.format("\\x%02x", c); } else if (c < 0xffff) { unicode = true; formatter.format("\\u%04x", c); } else { unicode = true; formatter.format("\\U%08x", c); } } else { buf.appendCodePoint(c); } } buf.append(quotes); if (unicode) buf.insert(0, "u"); return createStringLiteralAlreadyEscaped(buf.toString()); }