PsiElement (@NotNull final PsiElement elementToMove, @NotNull final Editor editor, @Nullable PsiElement parent, boolean down) { PsiElement scope = PsiTreeUtil.getParentOfType(parent, PyStatementList.class, PyFile.class); final int offset = elementToMove.getTextOffset(); PsiElement sibling = elementToMove; while (scope != null && elementToMove instanceof PsiComment) { // stupid workaround for PY-6408. Related to PSI structure final PsiElement prevSibling = down ? PsiTreeUtil.getNextSiblingOfType(sibling, PyStatement.class) : PsiTreeUtil.getPrevSiblingOfType(sibling, PyStatement.class); if (prevSibling == null) break; if (editor.offsetToLogicalPosition(prevSibling.getTextOffset()).column == editor.offsetToLogicalPosition(offset).column) break; sibling = scope; scope = PsiTreeUtil.getParentOfType(scope, PyStatementList.class, PyFile.class); } return scope; }