void (@NotNull PsiElement anchor) { final StringBuilder content = new StringBuilder(); for (List<PyImportStatementBase> imports : myGroups.values()) { if (content.length() > 0 && !imports.isEmpty()) { // one extra blank line between import groups according to PEP 8 content.append("\n"); } for (PyImportStatementBase statement : imports) { for (PsiComment comment : myNewImportToLineComments.get(statement)) { content.append(comment.getText()).append("\n"); } content.append(statement.getText()); final Collection<PsiComment> innerComments = myNewImportToInnerComments.get(statement); if (!innerComments.isEmpty()) { content.append(" # "); // Join several comments for the same import statement by ";" as isort does final String combinedComment = StringUtil.join(innerComments, comment -> comment.getText().substring(1).trim(), "; "); content.append(combinedComment).append("\n"); } else { content.append("\n"); } } } if (!myDanglingComments.isEmpty()) { content.append("\n"); for (PsiComment comment : myDanglingComments) { content.append(comment.getText()).append("\n"); } } final Project project = anchor.getProject(); final PyFile file = (PyFile)myGenerator.createDummyFile(myLangLevel, content.toString()); final PyFile reformattedFile = (PyFile)CodeStyleManager.getInstance(project).reformat(file); final List<PyImportStatementBase> newImportBlock = reformattedFile.getImportBlock(); assert newImportBlock != null; myFile.addRangeAfter(reformattedFile.getFirstChild(), reformattedFile.getLastChild(), anchor); }