Control automatic insertation of brackets in various situations.

def _autoinsert_brackets(self, key):
        """Control automatic insertation of brackets in various situations."""
        char = self.BRACKETS_CHAR[key]
        pair = self.BRACKETS_PAIR[key]

        line_text = self.editor.get_text('sol', 'eol')
        line_to_cursor = self.editor.get_text('sol', 'cursor')
        cursor = self.editor.textCursor()
        trailing_text = self.editor.get_text('cursor', 'eol').strip()

        if self.editor.has_selected_text():
            text = self.editor.get_selected_text()
            self.editor.insert_text("{0}{1}{2}".format(pair[0], text, pair[1]))
            # Keep text selected, for inserting multiple brackets
            cursor.movePosition(QTextCursor.Left, QTextCursor.MoveAnchor, 1)
            cursor.movePosition(QTextCursor.Left, QTextCursor.KeepAnchor,
                                len(text))
            self.editor.setTextCursor(cursor)
        elif key in self.BRACKETS_LEFT:
            if (not trailing_text or
                    trailing_text[0] in self.BRACKETS_RIGHT.values() or
                    trailing_text[0] in [',', ':', ';']):
                # Automatic insertion of brackets
                self.editor.insert_text(pair)
                cursor.movePosition(QTextCursor.PreviousCharacter)
                self.editor.setTextCursor(cursor)
            else:
                self.editor.insert_text(char)
            if char in self.editor.signature_completion_characters:
                self.editor.request_signature()
        elif key in self.BRACKETS_RIGHT:
            if (self.editor.next_char() == char and
                    not self.editor.textCursor().atBlockEnd() and
                    not self.unmatched_brackets_in_line(
                        cursor.block().text(), char)):
                # Overwrite an existing brackets if all in line are matched
                cursor.movePosition(QTextCursor.NextCharacter,
                                    QTextCursor.KeepAnchor, 1)
                cursor.clearSelection()
                self.editor.setTextCursor(cursor)
            else:
                self.editor.insert_text(char)