'Remove prefix from current line or selected line(s)'

def remove_prefix(self, prefix):

    cursor = self.textCursor()
    if self.has_selected_text():
        (start_pos, end_pos) = sorted([cursor.selectionStart(), cursor.selectionEnd()])
        cursor.setPosition(start_pos)
        if (not cursor.atBlockStart()):
            cursor.movePosition(QTextCursor.StartOfBlock)
            start_pos = cursor.position()
        cursor.beginEditBlock()
        cursor.setPosition(end_pos)
        if cursor.atBlockStart():
            cursor.movePosition(QTextCursor.PreviousBlock)
            if (cursor.position() < start_pos):
                cursor.setPosition(start_pos)
        cursor.movePosition(QTextCursor.StartOfBlock)
        old_pos = None
        while (cursor.position() >= start_pos):
            new_pos = cursor.position()
            if (old_pos == new_pos):
                break
            else:
                old_pos = new_pos
            line_text = to_text_string(cursor.block().text())
            if ((prefix.strip() and line_text.lstrip().startswith(prefix)) or line_text.startswith(prefix)):
                cursor.movePosition(QTextCursor.Right, QTextCursor.MoveAnchor, line_text.find(prefix))
                cursor.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor, len(prefix))
                cursor.removeSelectedText()
            cursor.movePosition(QTextCursor.PreviousBlock)
        cursor.endEditBlock()
    else:
        cursor.movePosition(QTextCursor.StartOfBlock)
        line_text = to_text_string(cursor.block().text())
        if ((prefix.strip() and line_text.lstrip().startswith(prefix)) or line_text.startswith(prefix)):
            cursor.movePosition(QTextCursor.Right, QTextCursor.MoveAnchor, line_text.find(prefix))
            cursor.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor, len(prefix))
            cursor.removeSelectedText()
