def _keep_cursor_in_buffer(self):
        """ Ensures that the cursor is inside the editing region. Returns
            whether the cursor was moved.
        """
        cursor = self._control.textCursor()
        endpos = cursor.selectionEnd()

        if endpos < self._prompt_pos:
            cursor.setPosition(endpos)
            line = cursor.blockNumber()
            prompt_line = self._get_prompt_cursor().blockNumber()
            if line == prompt_line:
                # Cursor is on prompt line, move to start of buffer
                cursor.setPosition(self._prompt_pos)
            else:
                # Cursor is not in buffer, move to the end
                cursor.movePosition(QtGui.QTextCursor.End)
            self._control.setTextCursor(cursor)
            return True

        startpos = cursor.selectionStart()

        new_endpos = self._move_position_in_buffer(endpos)
        new_startpos = self._move_position_in_buffer(startpos)
        if new_endpos == endpos and new_startpos == startpos:
            return False

        cursor.setPosition(new_startpos)
        cursor.setPosition(new_endpos, QtGui.QTextCursor.KeepAnchor)
        self._control.setTextCursor(cursor)
        return True
 Ensures that the cursor is inside the editing region. Returns
            whether the cursor was moved.
        
angrmanagement/vendor/qtconsole/console_widget.py