PyFromImportStatement (@NotNull PyFromImportStatement fromImport) { final PyImportElement[] allNames = fromImport.getImportElements(); final PyImportElement firstName = allNames[0]; final PyElementGenerator generator = PyElementGenerator.getInstance(fromImport.getProject()); final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(fromImport.getProject()); if (fromImport.getLeftParen() == null) { // Surround with parentheses stripping obsolete continuation backslashes and added trailing comma if necessary final String beforeFirstName = fromImport.getText().substring(0, firstName.getStartOffsetInParent()); final StringBuilder newStatementText = new StringBuilder(beforeFirstName); newStatementText.append("("); boolean lastElementWasComment = false; int lastVisibleNameCommaOffset = -1; for (PsiElement cur = firstName; cur != null; cur = cur.getNextSibling()) { if (cur instanceof PsiWhiteSpace) { newStatementText.append(cur.getText().replace("\\", "")); } else { newStatementText.append(cur.getText()); } if (cur instanceof PyImportElement && cur.getTextLength() != 0) { lastVisibleNameCommaOffset = newStatementText.length(); } else if (lastVisibleNameCommaOffset != -1 && cur.getNode().getElementType() == PyTokenTypes.COMMA) { lastVisibleNameCommaOffset = -1; } lastElementWasComment = cur instanceof PsiComment; } final PyCodeStyleSettings pySettings = myHelper.getSettings().getRootSettings().getCustomSettings(PyCodeStyleSettings.class); if (lastVisibleNameCommaOffset != -1 && pySettings.FROM_IMPORT_TRAILING_COMMA_IF_MULTILINE) { newStatementText.insert(lastVisibleNameCommaOffset, ","); } if (lastElementWasComment) { newStatementText.append("\n"); } newStatementText.append(")"); final LanguageLevel level = LanguageLevel.forElement(fromImport); PyFromImportStatement newFromImport = generator.createFromText(level, PyFromImportStatement.class, newStatementText.toString()); newFromImport = (PyFromImportStatement)fromImport.replace(newFromImport); newFromImport = (PyFromImportStatement)codeStyleManager.reformat(newFromImport, true); myHelper.updateResultRange(fromImport.getTextLength(), newFromImport.getTextLength()); return newFromImport; } else { final int oldLength = fromImport.getTextLength(); // Add only trailing comma fromImport.addAfter(generator.createComma().getPsi(), allNames[allNames.length - 1]); // Adjust spaces around the comma if necessary codeStyleManager.reformat(fromImport, true); myHelper.updateResultRange(oldLength, fromImport.getTextLength()); return fromImport; } }