'Control how to automatically insert quotes in various situations'

def autoinsert_quotes(self, key):

    char = {Qt.Key_QuoteDbl: '"', Qt.Key_Apostrophe: "'"}[key]
    line_text = self.get_text('sol', 'eol')
    line_to_cursor = self.get_text('sol', 'cursor')
    cursor = self.textCursor()
    last_three = self.get_text('sol', 'cursor')[(-3):]
    last_two = self.get_text('sol', 'cursor')[(-2):]
    trailing_text = self.get_text('cursor', 'eol').strip()
    if self.has_selected_text():
        text = ''.join([char, self.get_selected_text(), char])
        self.insert_text(text)
    elif self.__in_comment():
        self.insert_text(char)
    elif ((len(trailing_text) > 0) and (not (self.__unmatched_quotes_in_line(line_to_cursor) == char))):
        self.insert_text(char)
    elif (self.__unmatched_quotes_in_line(line_text) and (not (last_three == (3 * char)))):
        self.insert_text(char)
    elif (self.__next_char() == char):
        cursor.movePosition(QTextCursor.NextCharacter, QTextCursor.KeepAnchor, 1)
        cursor.clearSelection()
        self.setTextCursor(cursor)
    elif (last_three == (3 * char)):
        self.insert_text((3 * char))
        cursor = self.textCursor()
        cursor.movePosition(QTextCursor.PreviousCharacter, QTextCursor.KeepAnchor, 3)
        cursor.clearSelection()
        self.setTextCursor(cursor)
    elif (last_two == (2 * char)):
        self.insert_text(char)
    else:
        self.insert_text((2 * char))
        cursor = self.textCursor()
        cursor.movePosition(QTextCursor.PreviousCharacter)
        self.setTextCursor(cursor)
