'setPlainText(str) while retaining scrollbar positions'

def setPlainText(self, text):

    mode = self.model.mode
    highlight = ((mode != self.model.mode_none) and (mode != self.model.mode_untracked))
    self.highlighter.set_enabled(highlight)
    scrollbar = self.verticalScrollBar()
    if scrollbar:
        scrollvalue = scrollbar.value()
    else:
        scrollvalue = None
    if (text is None):
        return
    (offset, selection_text) = self.offset_and_selection()
    old_text = self.toPlainText()
    DiffTextEdit.setPlainText(self, text)
    if (selection_text and (selection_text in text)):
        idx = text.index(selection_text)
        cursor = self.textCursor()
        cursor.setPosition(idx)
        cursor.setPosition((idx + len(selection_text)), QtGui.QTextCursor.KeepAnchor)
        self.setTextCursor(cursor)
    elif (text == old_text):
        cursor = self.textCursor()
        cursor.setPosition(offset)
        self.setTextCursor(cursor)
    else:
        position = max(0, min(offset, (len(text) - 1)))
        cursor = self.textCursor()
        cursor.setPosition(position)
        cursor.movePosition(QtGui.QTextCursor.StartOfLine)
        self.setTextCursor(cursor)
    if (scrollbar and (scrollvalue is not None)):
        scrollbar.setValue(scrollvalue)
