void () { assert myImportElement != null : "isAvailable() must have returned true, but myImportElement is null"; sure(myImportElement.getImportReferenceExpression()); final Project project = myImportElement.getProject(); final PyElementGenerator generator = PyElementGenerator.getInstance(project); final LanguageLevel languageLevel = LanguageLevel.forElement(myImportElement); // usages of imported name are qualifiers; what they refer to? try { // remember names and make them drop qualifiers final Set<String> usedNames = new HashSet<>(); for (PsiReference ref : myReferences) { final PsiElement elt = ref.getElement(); final PsiElement parentElt = elt.getParent(); // TODO: find ident node more properly final String nameUsed = sure(sure(parentElt).getLastChild()).getText(); usedNames.add(nameUsed); if (!FileModificationService.getInstance().preparePsiElementForWrite(elt)) { return; } assert parentElt instanceof PyReferenceExpression: parentElt.getClass(); final PyElement newReference = generator.createExpressionFromText(languageLevel, nameUsed); parentElt.replace(newReference); } // create a separate import stmt for the module final PsiElement importer = myImportElement.getParent(); final PyStatement importStatement; final PyImportElement[] importElements; if (importer instanceof PyImportStatement) { importStatement = (PyImportStatement)importer; importElements = ((PyImportStatement)importStatement).getImportElements(); } else if (importer instanceof PyFromImportStatement) { importStatement = (PyFromImportStatement)importer; importElements = ((PyFromImportStatement)importStatement).getImportElements(); } else { throw new IncorrectOperationException("Not an import at all"); } final PyFromImportStatement newImportStatement = generator.createFromImportStatement(languageLevel, getDots() + myModuleName, StringUtil.join(usedNames, ", "), null); final PsiElement parent = importStatement.getParent(); sure(parent); sure(parent.isValid()); if (importElements.length == 1) { if (myHasModuleReference) { parent.addAfter(newImportStatement, importStatement); // add 'import from': we need the module imported as is } else { // replace entire existing import sure(parent.getNode()).replaceChild(sure(importStatement.getNode()), sure(newImportStatement.getNode())); // import_statement.replace(from_import_stmt); } } else { if (!myHasModuleReference) { // cut the module out of import, add a from-import. for (PyImportElement pie : importElements) { if (pie == myImportElement) { pie.delete(); break; } } } parent.addAfter(newImportStatement, importStatement); } } catch (IncorrectOperationException ignored) { PythonUiService.getInstance().showBalloonWarning(project, PyPsiBundle.message("QFIX.action.failed")); } }