private PsiElement performReplace(
      @NotNull final PsiElement declaration, final IntroduceOperation operation) {
    final PyExpression expression = operation.getInitializer();
    final Project project = operation.getProject();
    return new WriteCommandAction<PsiElement>(project, expression.getContainingFile()) {
      protected void run(final Result<PsiElement> result) throws Throwable {
        result.setResult(addDeclaration(operation, declaration));

        PyExpression newExpression = createExpression(project, operation.getName(), declaration);

        if (operation.isReplaceAll()) {
          List<PsiElement> newOccurrences = new ArrayList<PsiElement>();
          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());
      }
    }.execute().getResultObject();
  }
 @Nullable
 public PsiElement addDeclaration(IntroduceOperation operation, PsiElement declaration) {
   final PsiElement expression = operation.getInitializer();
   final Pair<PsiElement, TextRange> data =
       expression.getUserData(PyReplaceExpressionUtil.SELECTION_BREAKS_AST_NODE);
   if (data == null) {
     return addDeclaration(expression, declaration, operation);
   } else {
     return addDeclaration(data.first, declaration, operation);
   }
 }
 public PyAssignmentStatement createDeclaration(IntroduceOperation operation) {
   final Project project = operation.getProject();
   final PyExpression initializer = operation.getInitializer();
   InitializerTextBuilder builder = new InitializerTextBuilder();
   initializer.accept(builder);
   String assignmentText = operation.getName() + " = " + builder.result();
   PsiElement anchor =
       operation.isReplaceAll()
           ? findAnchor(operation.getOccurrences())
           : PsiTreeUtil.getParentOfType(initializer, PyStatement.class);
   return createDeclaration(project, assignmentText, anchor);
 }