void (List<UsageInfo> usages, Map<PsiElement, PsiElement> oldToNewMap) { final Set<PsiFile> updatedFiles = new HashSet<>(); for (UsageInfo usage : usages) { final PsiElement usageElement = usage.getElement(); if (usageElement != null && usage instanceof PyUsageInfo) { final PsiNamedElement movedElement = ((PyUsageInfo)usage).myFile; final PsiFile usageFile = usageElement.getContainingFile(); final PyImportStatementBase importStmt = PsiTreeUtil.getParentOfType(usageElement, PyImportStatementBase.class); // TODO: Retarget qualified expressions in docstrings if (importStmt != null) { if (getOriginalLocation(usageFile) != null) { // Leave relative imports as they are after #updateRelativeImportsInModule final TypeEvalContext typeEvalContext = TypeEvalContext.userInitiated(usageFile.getProject(), usageFile); final PyResolveContext resolveContext = PyResolveContext.implicitContext(typeEvalContext); if (ContainerUtil.getFirstItem(PyUtil.multiResolveTopPriority(usageElement, resolveContext)) == movedElement) { continue; } } updatedFiles.add(usageFile); final boolean usageInsideImportElement = PsiTreeUtil.getParentOfType(usageElement, PyImportElement.class) != null; if (usageInsideImportElement) { // Handles imported element in "from import" statement (from some.package import module) // or simple unqualified import of the module (import module). if (PyClassRefactoringUtil.updateUnqualifiedImportOfElement(importStmt, movedElement)) { continue; } } final QualifiedName newElementName = QualifiedNameFinder.findCanonicalImportPath(movedElement, usageElement); if (importStmt instanceof PyFromImportStatement) { if (!usageInsideImportElement) { replaceRelativeImportSourceWithQualifiedExpression((PyFromImportStatement)importStmt, newElementName); } } else { replaceWithQualifiedExpression(usageElement, newElementName); } } else if (usageElement instanceof PyReferenceExpression) { updatedFiles.add(usageFile); if (((PyReferenceExpression)usageElement).isQualified()) { final QualifiedName newQualifiedName = QualifiedNameFinder.findCanonicalImportPath(movedElement, usageElement); replaceWithQualifiedExpression(usageElement, newQualifiedName); } else { final QualifiedName newName = QualifiedName.fromComponents(PyPsiRefactoringUtil.getOriginalName(movedElement)); replaceWithQualifiedExpression(usageElement, newName); } } } } if (!updatedFiles.isEmpty()) { final PyImportOptimizer optimizer = PyImportOptimizer.onlyRemoveUnused(); for (PsiFile file : updatedFiles) { final boolean injectedFragment = InjectedLanguageManager.getInstance(file.getProject()).isInjectedFragment(file); if (!injectedFragment) { optimizer.processFile(file).run(); } } } }