PyFunction (@NotNull PsiElement anchor, @NotNull final PyFunction generatedMethod) { final Pair<PsiElement, TextRange> data = anchor.getUserData(PyReplaceExpressionUtil.SELECTION_BREAKS_AST_NODE); if (data != null) { anchor = data.first; } final PsiNamedElement parent = PsiTreeUtil.getParentOfType(anchor, PyFile.class, PyClass.class, PyFunction.class); final PsiElement result; // The only safe case to insert extracted function *after* the original scope owner is when it's function. if (parent instanceof PyFunction) { result = parent.getParent().addAfter(generatedMethod, parent); } else { final PsiElement target = parent instanceof PyClass ? ((PyClass)parent).getStatementList() : parent; final PsiElement insertionAnchor = PyPsiUtils.getParentRightBefore(anchor, target); assert insertionAnchor != null; final List<PsiComment> comments = PyPsiUtils.getPrecedingComments(insertionAnchor); result = insertionAnchor.getParent().addBefore(generatedMethod, !comments.isEmpty() ? comments.get(0) : insertionAnchor); } // to ensure correct reformatting, mark the entire method as generated result.accept(new PsiRecursiveElementVisitor() { @Override public void visitElement(@NotNull PsiElement element) { super.visitElement(element); CodeEditUtil.setNodeGenerated(element.getNode(), true); } }); return (PyFunction)result; }