PsiElement (@NotNull final PsiElement declaration, final IntroduceOperation operation) { final PyExpression expression = operation.getInitializer(); final Project project = operation.getProject(); final SmartPsiElementPointer<PsiElement> result = WriteCommandAction.writeCommandAction(project, expression.getContainingFile()).compute(() -> { final PsiElement insertedDeclaration; try { final RefactoringEventData afterData = new RefactoringEventData(); afterData.addElement(declaration); project.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC) .refactoringStarted(getRefactoringId(), afterData); insertedDeclaration = addDeclaration(operation, declaration); PyExpression newExpression = createExpression(project, operation.getName(), declaration); if (operation.isReplaceAll()) { List<PsiElement> newOccurrences = new ArrayList<>(); for (PsiElement occurrence : operation.getOccurrences()) { final PsiElement replaced = replaceExpression(occurrence, newExpression, operation); if (replaced != null) { newOccurrences.add(replaced); } } operation.setOccurrences(newOccurrences); } else { final PsiElement replaced = replaceExpression(expression, newExpression, operation); operation.setOccurrences(Collections.singletonList(replaced)); } postRefactoring(operation.getElement()); } finally { final RefactoringEventData afterData = new RefactoringEventData(); afterData.addElement(declaration); project.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC) .refactoringDone(getRefactoringId(), afterData); } return ObjectUtils.doIfNotNull(insertedDeclaration, SmartPointerManager::createPointer); }); return ObjectUtils.doIfNotNull(result, SmartPsiElementPointer::getElement); }