PsiElement (@NotNull PyStringLiteralExpression oldExpression, @NotNull TextRange textRange, @NotNull String prefix, @NotNull String suffix, @NotNull PyArgumentList newStyleFormatValue, @NotNull String newText, @NotNull List<SubstitutionChunk> substitutions) { final PyElementGenerator generator = PyElementGenerator.getInstance(oldExpression.getProject()); final LanguageLevel languageLevel = LanguageLevel.forElement(oldExpression); final PyExpression[] arguments = newStyleFormatValue.getArguments(); boolean hasKeywords = false; int maxPosition = -1; for (SubstitutionChunk substitution : substitutions) { if (substitution.getMappingKey() != null) { hasKeywords = true; } final Integer position = substitution.getManualPosition(); if (position != null && position > maxPosition) { maxPosition = position; } } if (hasKeywords) { // 'foo{x}'.format(x='bar') -> '{s}oo{x}'.format(x='bar', s=s) final String newLiteralText = prefix + "{" + newText + "}" + suffix; final PyStringLiteralExpression newLiteralExpression = generator.createStringLiteralAlreadyEscaped(newLiteralText); oldExpression.replace(newLiteralExpression); final PyKeywordArgument kwarg = generator.createKeywordArgument(languageLevel, newText, newText); newStyleFormatValue.addArgument(kwarg); return kwarg.getValueExpression(); } else if (maxPosition >= 0) { // 'foo{0}'.format('bar') -> '{1}oo{0}'.format('bar', s) final String newLiteralText = prefix + "{" + (maxPosition + 1) + "}" + suffix; final PyStringLiteralExpression newLiteralExpression = generator.createStringLiteralAlreadyEscaped(newLiteralText); oldExpression.replace(newLiteralExpression); final PyExpression arg = generator.createExpressionFromText(languageLevel, newText); newStyleFormatValue.addArgument(arg); return arg; } else { // 'foo{}'.format('bar') -> '{}oo{}'.format(s, 'bar') final String newLiteralText = prefix + "{}" + suffix; final PyStringLiteralExpression newLiteralExpression = generator.createStringLiteralAlreadyEscaped(newLiteralText); oldExpression.replace(newLiteralExpression); final int i = getPositionInRanges(substitutionsToRanges(substitutions), textRange); final PyExpression arg = generator.createExpressionFromText(languageLevel, newText); if (i == 0) { newStyleFormatValue.addArgumentFirst(arg); } else if (i < arguments.length) { newStyleFormatValue.addArgumentAfter(arg, arguments[i - 1]); } else { newStyleFormatValue.addArgument(arg); } return arg; } }