'Add prefix to current line or selected line(s)'

def add_prefix(self, prefix):

    cursor = self.textCursor()
    if self.has_selected_text():
        (start_pos, end_pos) = (cursor.selectionStart(), cursor.selectionEnd())
        first_pos = min([start_pos, end_pos])
        first_cursor = self.textCursor()
        first_cursor.setPosition(first_pos)
        begins_at_block_start = first_cursor.atBlockStart()
        cursor.beginEditBlock()
        cursor.setPosition(end_pos)
        if cursor.atBlockStart():
            cursor.movePosition(QTextCursor.PreviousBlock)
            if (cursor.position() < start_pos):
                cursor.setPosition(start_pos)
        while (cursor.position() >= start_pos):
            cursor.movePosition(QTextCursor.StartOfBlock)
            cursor.insertText(prefix)
            if ((start_pos == 0) and (cursor.blockNumber() == 0)):
                break
            cursor.movePosition(QTextCursor.PreviousBlock)
            cursor.movePosition(QTextCursor.EndOfBlock)
        cursor.endEditBlock()
        if begins_at_block_start:
            cursor = self.textCursor()
            start_pos = cursor.selectionStart()
            end_pos = cursor.selectionEnd()
            if (start_pos < end_pos):
                start_pos -= len(prefix)
            else:
                end_pos -= len(prefix)
            cursor.setPosition(start_pos, QTextCursor.MoveAnchor)
            cursor.setPosition(end_pos, QTextCursor.KeepAnchor)
            self.setTextCursor(cursor)
    else:
        cursor.beginEditBlock()
        cursor.movePosition(QTextCursor.StartOfBlock)
        cursor.insertText(prefix)
        cursor.endEditBlock()
