PsiElement (@NotNull final PsiElement elementToMove, @NotNull final Document document, int lineEndOffset, boolean down) { PsiElement destination = PyUtil.findPrevAtOffset(elementToMove.getContainingFile(), lineEndOffset, PsiWhiteSpace.class); PsiElement sibling = down ? PsiTreeUtil.getNextSiblingOfType(elementToMove, PyStatement.class) : PsiTreeUtil.getPrevSiblingOfType(elementToMove, PyStatement.class); if (destination == null) { if (elementToMove instanceof PyClass) { destination = sibling; } else if (elementToMove instanceof PyFunction) { if (!(sibling instanceof PyClass)) destination = sibling; else destination = null; } else { return null; } } if (destination instanceof PsiComment) return destination; if (elementToMove instanceof PyClass) { destination = sibling; } else if (elementToMove instanceof PyFunction) { if (!(sibling instanceof PyClass)) destination = sibling; else destination = null; } else { destination = getCommentOrStatement(document, sibling == null ? destination : sibling); } return destination; }