qt富文本文档解读

界面接口:

void QTextEdit::setTextColor(const QColor &c)
{
    QTextCharFormat fmt;
    fmt.setForeground(QBrush(c));
    mergeCurrentCharFormat(fmt);
}

 1.设置形式:

    inline void setForeground(const QBrush &brush)
    { setProperty(ForegroundBrush, brush); }

2.

/*!
    Sets the property specified by the \a propertyId to the given \a value.
    \sa Property
*/
void QTextFormat::setProperty(int propertyId, const QVariant &value)
{
    if (!d)
        d = new QTextFormatPrivate;
    if (!value.isValid())
        clearProperty(propertyId);
    else
        d->insertProperty(propertyId, value);
}

3.

    inline void insertProperty(qint32 key, const QVariant &value)
    {
        hashDirty = true;
        if ((key >= QTextFormat::FirstFontProperty && key <= QTextFormat::LastFontProperty)
                || key == QTextFormat::FontLetterSpacingType) {
            fontDirty = true;
        }
        for (int i = 0; i < props.count(); ++i)
            if (props.at(i).key == key) {
                props[i].value = value;
                return;
            }
        props.append(Property(key, value));
    }

 props是d模式下的public数据结构:

QVector<Property> props;

调用基础接口d接口刷新数据:

1.

void QTextEdit::mergeCurrentCharFormat(const QTextCharFormat &modifier)
{
    Q_D(QTextEdit);
    d->control->mergeCurrentCharFormat(modifier);
}

2.调用d接口:

void QWidgetTextControl::mergeCurrentCharFormat(const QTextCharFormat &modifier)
{
    Q_D(QWidgetTextControl);
    d->cursor.mergeCharFormat(modifier); // [] 样式合入
    d->updateCurrentCharFormat();        // [] 更新
}

3.调用子类d接口,合入

这段代码的目的是设置文档中某些文本的字符格式,并且可能还会确保不会破坏文档中其他对象的索引

void QTextCursor::setCharFormat(const QTextCharFormat &format)
{
    if (!d || !d->priv)
        return;
    if (d->position == d->anchor) {
        d->currentCharFormat = d->priv->formatCollection()->indexForFormat(format);
        return;
    }
    d->setCharFormat(format, QTextDocumentPrivate::SetFormatAndPreserveObjectIndices);
}

4.查找到位置,将数据改变:

void QTextCursorPrivate::setCharFormat(const QTextCharFormat &_format, QTextDocumentPrivate::FormatChangeMode changeMode)
{
    Q_ASSERT(position != anchor);
    QTextCharFormat format = _format;
    format.clearProperty(QTextFormat::ObjectIndex);
    QTextTable *table = complexSelectionTable();
    if (table) {
        priv->beginEditBlock();
        int row_start, col_start, num_rows, num_cols;
        selectedTableCells(&row_start, &num_rows, &col_start, &num_cols);
        Q_ASSERT(row_start != -1);
        for (int r = row_start; r < row_start + num_rows; ++r) {
            for (int c = col_start; c < col_start + num_cols; ++c) {
                QTextTableCell cell = table->cellAt(r, c);
                int rspan = cell.rowSpan();
                int cspan = cell.columnSpan();
                if (rspan != 1) {
                    int cr = cell.row();
                    if (cr != r)
                        continue;
                }
                if (cspan != 1) {
                    int cc = cell.column();
                    if (cc != c)
                        continue;
                }
                int pos1 = cell.firstPosition();
                int pos2 = cell.lastPosition();
                priv->setCharFormat(pos1, pos2-pos1, format, changeMode);  //[]
            }
        }
        priv->endEditBlock();
    } else {
        int pos1 = position;
        int pos2 = adjusted_anchor;
        if (pos1 > pos2) {
            pos1 = adjusted_anchor;
            pos2 = position;
        }
        priv->setCharFormat(pos1, pos2-pos1, format, changeMode);
    }
}

加一个cell方便理解

QTextTableCell QTextTable::cellAt(int row, int col) const
{
    Q_D(const QTextTable);
    if (d->dirty)
        d->update();
    if (row < 0 || row >= d->nRows || col < 0 || col >= d->nCols)
        return QTextTableCell();
    return QTextTableCell(this, d->grid[row*d->nCols + col]);
}

 

接口:

void QTextEdit::setTextColor(const QColor &c)

头文件

/****************************************************************************
**
** Copyright (C) 2019 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtWidgets module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#ifndef QTEXTEDIT_H
#define QTEXTEDIT_H

#include <QtWidgets/qtwidgetsglobal.h>
#include <QtWidgets/qabstractscrollarea.h>
#include <QtGui/qtextdocument.h>
#include <QtGui/qtextoption.h>
#include <QtGui/qtextcursor.h>
#include <QtGui/qtextformat.h>

QT_REQUIRE_CONFIG(textedit);

QT_BEGIN_NAMESPACE

class QStyleSheet;
class QTextDocument;
class QMenu;
class QTextEditPrivate;
class QMimeData;
class QPagedPaintDevice;
class QRegularExpression;

class Q_WIDGETS_EXPORT QTextEdit : public QAbstractScrollArea
{
    Q_OBJECT
    Q_DECLARE_PRIVATE(QTextEdit)
    Q_PROPERTY(AutoFormatting autoFormatting READ autoFormatting WRITE setAutoFormatting)
    Q_PROPERTY(bool tabChangesFocus READ tabChangesFocus WRITE setTabChangesFocus)
    Q_PROPERTY(QString documentTitle READ documentTitle WRITE setDocumentTitle)
    Q_PROPERTY(bool undoRedoEnabled READ isUndoRedoEnabled WRITE setUndoRedoEnabled)
    Q_PROPERTY(LineWrapMode lineWrapMode READ lineWrapMode WRITE setLineWrapMode)
    QDOC_PROPERTY(QTextOption::WrapMode wordWrapMode READ wordWrapMode WRITE setWordWrapMode)
    Q_PROPERTY(int lineWrapColumnOrWidth READ lineWrapColumnOrWidth WRITE setLineWrapColumnOrWidth)
    Q_PROPERTY(bool readOnly READ isReadOnly WRITE setReadOnly)
#if QT_CONFIG(textmarkdownreader) && QT_CONFIG(textmarkdownwriter)
    Q_PROPERTY(QString markdown READ toMarkdown WRITE setMarkdown NOTIFY textChanged)
#endif
#ifndef QT_NO_TEXTHTMLPARSER
    Q_PROPERTY(QString html READ toHtml WRITE setHtml NOTIFY textChanged USER true)
#endif
    Q_PROPERTY(QString plainText READ toPlainText WRITE setPlainText DESIGNABLE false)
    Q_PROPERTY(bool overwriteMode READ overwriteMode WRITE setOverwriteMode)
#if QT_DEPRECATED_SINCE(5, 10)
    Q_PROPERTY(int tabStopWidth READ tabStopWidth WRITE setTabStopWidth)
#endif
    Q_PROPERTY(qreal tabStopDistance READ tabStopDistance WRITE setTabStopDistance)
    Q_PROPERTY(bool acceptRichText READ acceptRichText WRITE setAcceptRichText)
    Q_PROPERTY(int cursorWidth READ cursorWidth WRITE setCursorWidth)
    Q_PROPERTY(Qt::TextInteractionFlags textInteractionFlags READ textInteractionFlags WRITE setTextInteractionFlags)
    Q_PROPERTY(QTextDocument *document READ document WRITE setDocument DESIGNABLE false)
    Q_PROPERTY(QString placeholderText READ placeholderText WRITE setPlaceholderText)
public:
    enum LineWrapMode {
        NoWrap,
        WidgetWidth,
        FixedPixelWidth,
        FixedColumnWidth
    };
    Q_ENUM(LineWrapMode)

    enum AutoFormattingFlag {
        AutoNone = 0,
        AutoBulletList = 0x00000001,
        AutoAll = 0xffffffff
    };

    Q_DECLARE_FLAGS(AutoFormatting, AutoFormattingFlag)
    Q_FLAG(AutoFormatting)

    explicit QTextEdit(QWidget *parent = nullptr);
    explicit QTextEdit(const QString &text, QWidget *parent = nullptr);
    virtual ~QTextEdit();

    void setDocument(QTextDocument *document);
    QTextDocument *document() const;

    void setPlaceholderText(const QString &placeholderText);
    QString placeholderText() const;

    void setTextCursor(const QTextCursor &cursor);
    QTextCursor textCursor() const;

    bool isReadOnly() const;
    void setReadOnly(bool ro);

    void setTextInteractionFlags(Qt::TextInteractionFlags flags);
    Qt::TextInteractionFlags textInteractionFlags() const;

    qreal fontPointSize() const;
    QString fontFamily() const;
    int fontWeight() const;
    bool fontUnderline() const;
    bool fontItalic() const;
    QColor textColor() const;
    QColor textBackgroundColor() const;
    QFont currentFont() const;
    Qt::Alignment alignment() const;

    void mergeCurrentCharFormat(const QTextCharFormat &modifier);

    void setCurrentCharFormat(const QTextCharFormat &format);
    QTextCharFormat currentCharFormat() const;

    AutoFormatting autoFormatting() const;
    void setAutoFormatting(AutoFormatting features);

    bool tabChangesFocus() const;
    void setTabChangesFocus(bool b);

    inline void setDocumentTitle(const QString &title)
    { document()->setMetaInformation(QTextDocument::DocumentTitle, title); }
    inline QString documentTitle() const
    { return document()->metaInformation(QTextDocument::DocumentTitle); }

    inline bool isUndoRedoEnabled() const
    { return document()->isUndoRedoEnabled(); }
    inline void setUndoRedoEnabled(bool enable)
    { document()->setUndoRedoEnabled(enable); }

    LineWrapMode lineWrapMode() const;
    void setLineWrapMode(LineWrapMode mode);

    int lineWrapColumnOrWidth() const;
    void setLineWrapColumnOrWidth(int w);

    QTextOption::WrapMode wordWrapMode() const;
    void setWordWrapMode(QTextOption::WrapMode policy);

    bool find(const QString &exp, QTextDocument::FindFlags options = QTextDocument::FindFlags());
#ifndef QT_NO_REGEXP
    bool find(const QRegExp &exp, QTextDocument::FindFlags options = QTextDocument::FindFlags());
#endif
#if QT_CONFIG(regularexpression)
    bool find(const QRegularExpression &exp, QTextDocument::FindFlags options = QTextDocument::FindFlags());
#endif

    QString toPlainText() const;
#ifndef QT_NO_TEXTHTMLPARSER
    QString toHtml() const;
#endif
#if QT_CONFIG(textmarkdownwriter)
    QString toMarkdown(QTextDocument::MarkdownFeatures features = QTextDocument::MarkdownDialectGitHub) const;
#endif

    void ensureCursorVisible();

    Q_INVOKABLE virtual QVariant loadResource(int type, const QUrl &name);
#ifndef QT_NO_CONTEXTMENU
    QMenu *createStandardContextMenu();
    QMenu *createStandardContextMenu(const QPoint &position);
#endif

    QTextCursor cursorForPosition(const QPoint &pos) const;
    QRect cursorRect(const QTextCursor &cursor) const;
    QRect cursorRect() const;

    QString anchorAt(const QPoint& pos) const;

    bool overwriteMode() const;
    void setOverwriteMode(bool overwrite);

#if QT_DEPRECATED_SINCE(5, 10)
    QT_DEPRECATED int tabStopWidth() const;
    QT_DEPRECATED void setTabStopWidth(int width);
#endif

    qreal tabStopDistance() const;
    void setTabStopDistance(qreal distance);

    int cursorWidth() const;
    void setCursorWidth(int width);

    bool acceptRichText() const;
    void setAcceptRichText(bool accept);

    struct ExtraSelection
    {
        QTextCursor cursor;
        QTextCharFormat format;
    };
    void setExtraSelections(const QList<ExtraSelection> &selections);
    QList<ExtraSelection> extraSelections() const;

    void moveCursor(QTextCursor::MoveOperation operation, QTextCursor::MoveMode mode = QTextCursor::MoveAnchor);

    bool canPaste() const;

    void print(QPagedPaintDevice *printer) const;

    QVariant inputMethodQuery(Qt::InputMethodQuery property) const override;
    Q_INVOKABLE QVariant inputMethodQuery(Qt::InputMethodQuery query, QVariant argument) const;

public Q_SLOTS:
    void setFontPointSize(qreal s);
    void setFontFamily(const QString &fontFamily);
    void setFontWeight(int w);
    void setFontUnderline(bool b);
    void setFontItalic(bool b);
    void setTextColor(const QColor &c);
    void setTextBackgroundColor(const QColor &c);
    void setCurrentFont(const QFont &f);
    void setAlignment(Qt::Alignment a);

    void setPlainText(const QString &text);
#ifndef QT_NO_TEXTHTMLPARSER
    void setHtml(const QString &text);
#endif
#if QT_CONFIG(textmarkdownreader)
    void setMarkdown(const QString &markdown);
#endif
    void setText(const QString &text);

#ifndef QT_NO_CLIPBOARD
    void cut();
    void copy();
    void paste();
#endif

    void undo();
    void redo();

    void clear();
    void selectAll();

    void insertPlainText(const QString &text);
#ifndef QT_NO_TEXTHTMLPARSER
    void insertHtml(const QString &text);
#endif // QT_NO_TEXTHTMLPARSER

    void append(const QString &text);

    void scrollToAnchor(const QString &name);

    void zoomIn(int range = 1);
    void zoomOut(int range = 1);

Q_SIGNALS:
    void textChanged();
    void undoAvailable(bool b);
    void redoAvailable(bool b);
    void currentCharFormatChanged(const QTextCharFormat &format);
    void copyAvailable(bool b);
    void selectionChanged();
    void cursorPositionChanged();

protected:
    virtual bool event(QEvent *e) override;
    virtual void timerEvent(QTimerEvent *e) override;
    virtual void keyPressEvent(QKeyEvent *e) override;
    virtual void keyReleaseEvent(QKeyEvent *e) override;
    virtual void resizeEvent(QResizeEvent *e) override;
    virtual void paintEvent(QPaintEvent *e) override;
    virtual void mousePressEvent(QMouseEvent *e) override;
    virtual void mouseMoveEvent(QMouseEvent *e) override;
    virtual void mouseReleaseEvent(QMouseEvent *e) override;
    virtual void mouseDoubleClickEvent(QMouseEvent *e) override;
    virtual bool focusNextPrevChild(bool next) override;
#ifndef QT_NO_CONTEXTMENU
    virtual void contextMenuEvent(QContextMenuEvent *e) override;
#endif
#if QT_CONFIG(draganddrop)
    virtual void dragEnterEvent(QDragEnterEvent *e) override;
    virtual void dragLeaveEvent(QDragLeaveEvent *e) override;
    virtual void dragMoveEvent(QDragMoveEvent *e) override;
    virtual void dropEvent(QDropEvent *e) override;
#endif
    virtual void focusInEvent(QFocusEvent *e) override;
    virtual void focusOutEvent(QFocusEvent *e) override;
    virtual void showEvent(QShowEvent *) override;
    virtual void changeEvent(QEvent *e) override;
#if QT_CONFIG(wheelevent)
    virtual void wheelEvent(QWheelEvent *e) override;
#endif

    virtual QMimeData *createMimeDataFromSelection() const;
    virtual bool canInsertFromMimeData(const QMimeData *source) const;
    virtual void insertFromMimeData(const QMimeData *source);

    virtual void inputMethodEvent(QInputMethodEvent *) override;

    QTextEdit(QTextEditPrivate &dd, QWidget *parent);

    virtual void scrollContentsBy(int dx, int dy) override;
    virtual void doSetTextCursor(const QTextCursor &cursor);

    void zoomInF(float range);

private:
    Q_DISABLE_COPY(QTextEdit)
    Q_PRIVATE_SLOT(d_func(), void _q_repaintContents(const QRectF &r))
    Q_PRIVATE_SLOT(d_func(), void _q_currentCharFormatChanged(const QTextCharFormat &))
    Q_PRIVATE_SLOT(d_func(), void _q_adjustScrollbars())
    Q_PRIVATE_SLOT(d_func(), void _q_ensureVisible(const QRectF &))
    Q_PRIVATE_SLOT(d_func(), void _q_cursorPositionChanged())
#if QT_CONFIG(cursor)
    Q_PRIVATE_SLOT(d_func(), void _q_hoveredBlockWithMarkerChanged(const QTextBlock &))
#endif
    friend class QTextEditControl;
    friend class QTextDocument;
    friend class QWidgetTextControl;
};

Q_DECLARE_OPERATORS_FOR_FLAGS(QTextEdit::AutoFormatting)

QT_END_NAMESPACE

#endif // QTEXTEDIT_H

cpp文件;

/****************************************************************************
**
** Copyright (C) 2019 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtWidgets module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qtextedit_p.h"
#if QT_CONFIG(lineedit)
#include "qlineedit.h"
#endif
#if QT_CONFIG(textbrowser)
#include "qtextbrowser.h"
#endif

#include <qfont.h>
#include <qpainter.h>
#include <qevent.h>
#include <qdebug.h>
#if QT_CONFIG(draganddrop)
#include <qdrag.h>
#endif
#include <qclipboard.h>
#if QT_CONFIG(menu)
#include <qmenu.h>
#endif
#include <qstyle.h>
#include <qtimer.h>
#ifndef QT_NO_ACCESSIBILITY
#include <qaccessible.h>
#endif
#include "private/qtextdocumentlayout_p.h"
#include "qtextdocument.h"
#include "private/qtextdocument_p.h"
#include "qtextlist.h"
#include "private/qwidgettextcontrol_p.h"

#include <qtextformat.h>
#include <qdatetime.h>
#include <qapplication.h>
#include <private/qapplication_p.h>
#include <limits.h>
#include <qtexttable.h>
#include <qvariant.h>

QT_BEGIN_NAMESPACE

static inline bool shouldEnableInputMethod(QTextEdit *textedit)
{
    return !textedit->isReadOnly();
}

class QTextEditControl : public QWidgetTextControl
{
public:
    inline QTextEditControl(QObject *parent) : QWidgetTextControl(parent) {}

    virtual QMimeData *createMimeDataFromSelection() const override {
        QTextEdit *ed = qobject_cast<QTextEdit *>(parent());
        if (!ed)
            return QWidgetTextControl::createMimeDataFromSelection();
        return ed->createMimeDataFromSelection();
    }
    virtual bool canInsertFromMimeData(const QMimeData *source) const override {
        QTextEdit *ed = qobject_cast<QTextEdit *>(parent());
        if (!ed)
            return QWidgetTextControl::canInsertFromMimeData(source);
        return ed->canInsertFromMimeData(source);
    }
    virtual void insertFromMimeData(const QMimeData *source) override {
        QTextEdit *ed = qobject_cast<QTextEdit *>(parent());
        if (!ed)
            QWidgetTextControl::insertFromMimeData(source);
        else
            ed->insertFromMimeData(source);
    }
    QVariant loadResource(int type, const QUrl &name) override {
        auto *ed = qobject_cast<QTextEdit *>(parent());
        if (!ed)
            return QWidgetTextControl::loadResource(type, name);

        QUrl resolvedName = ed->d_func()->resolveUrl(name);
        return ed->loadResource(type, resolvedName);
    }
};

QTextEditPrivate::QTextEditPrivate()
    : control(nullptr),
      autoFormatting(QTextEdit::AutoNone), tabChangesFocus(false),
      lineWrap(QTextEdit::WidgetWidth), lineWrapColumnOrWidth(0),
      wordWrap(QTextOption::WrapAtWordBoundaryOrAnywhere), clickCausedFocus(0),
      textFormat(Qt::AutoText)
{
    ignoreAutomaticScrollbarAdjustment = false;
    preferRichText = false;
    showCursorOnInitialShow = true;
    inDrag = false;
}

void QTextEditPrivate::createAutoBulletList()
{
    QTextCursor cursor = control->textCursor();
    cursor.beginEditBlock();

    QTextBlockFormat blockFmt = cursor.blockFormat();

    QTextListFormat listFmt;
    listFmt.setStyle(QTextListFormat::ListDisc);
    listFmt.setIndent(blockFmt.indent() + 1);

    blockFmt.setIndent(0);
    cursor.setBlockFormat(blockFmt);

    cursor.createList(listFmt);

    cursor.endEditBlock();
    control->setTextCursor(cursor);
}

void QTextEditPrivate::init(const QString &html)
{
    Q_Q(QTextEdit);
    control = new QTextEditControl(q);
    control->setPalette(q->palette());

    QObject::connect(control, SIGNAL(microFocusChanged()), q, SLOT(updateMicroFocus()));
    QObject::connect(control, SIGNAL(documentSizeChanged(QSizeF)), q, SLOT(_q_adjustScrollbars()));
    QObject::connect(control, SIGNAL(updateRequest(QRectF)), q, SLOT(_q_repaintContents(QRectF)));
    QObject::connect(control, SIGNAL(visibilityRequest(QRectF)), q, SLOT(_q_ensureVisible(QRectF)));
    QObject::connect(control, SIGNAL(currentCharFormatChanged(QTextCharFormat)),
                     q, SLOT(_q_currentCharFormatChanged(QTextCharFormat)));

    QObject::connect(control, SIGNAL(textChanged()), q, SIGNAL(textChanged()));
    QObject::connect(control, SIGNAL(undoAvailable(bool)), q, SIGNAL(undoAvailable(bool)));
    QObject::connect(control, SIGNAL(redoAvailable(bool)), q, SIGNAL(redoAvailable(bool)));
    QObject::connect(control, SIGNAL(copyAvailable(bool)), q, SIGNAL(copyAvailable(bool)));
    QObject::connect(control, SIGNAL(selectionChanged()), q, SIGNAL(selectionChanged()));
    QObject::connect(control, SIGNAL(cursorPositionChanged()), q, SLOT(_q_cursorPositionChanged()));
#if QT_CONFIG(cursor)
    QObject::connect(control, SIGNAL(blockMarkerHovered(QTextBlock)), q, SLOT(_q_hoveredBlockWithMarkerChanged(QTextBlock)));
#endif

    QObject::connect(control, SIGNAL(textChanged()), q, SLOT(updateMicroFocus()));

    QTextDocument *doc = control->document();
    // set a null page size initially to avoid any relayouting until the textedit
    // is shown. relayoutDocument() will take care of setting the page size to the
    // viewport dimensions later.
    doc->setPageSize(QSize(0, 0));
    doc->documentLayout()->setPaintDevice(viewport);
    doc->setDefaultFont(q->font());
    doc->setUndoRedoEnabled(false); // flush undo buffer.
    doc->setUndoRedoEnabled(true);

    if (!html.isEmpty())
        control->setHtml(html);

    hbar->setSingleStep(20);
    vbar->setSingleStep(20);

    viewport->setBackgroundRole(QPalette::Base);
    q->setMouseTracking(true);
    q->setAcceptDrops(true);
    q->setFocusPolicy(Qt::StrongFocus);
    q->setAttribute(Qt::WA_KeyCompression);
    q->setAttribute(Qt::WA_InputMethodEnabled);
    q->setInputMethodHints(Qt::ImhMultiLine);
#ifndef QT_NO_CURSOR
    viewport->setCursor(Qt::IBeamCursor);
#endif
}

void QTextEditPrivate::_q_repaintContents(const QRectF &contentsRect)
{
    if (!contentsRect.isValid()) {
        viewport->update();
        return;
    }
    const int xOffset = horizontalOffset();
    const int yOffset = verticalOffset();
    const QRectF visibleRect(xOffset, yOffset, viewport->width(), viewport->height());

    QRect r = contentsRect.intersected(visibleRect).toAlignedRect();
    if (r.isEmpty())
        return;

    r.translate(-xOffset, -yOffset);
    viewport->update(r);
}

void QTextEditPrivate::_q_cursorPositionChanged()
{
    Q_Q(QTextEdit);
    emit q->cursorPositionChanged();
#ifndef QT_NO_ACCESSIBILITY
    QAccessibleTextCursorEvent event(q, q->textCursor().position());
    QAccessible::updateAccessibility(&event);
#endif
}

#if QT_CONFIG(cursor)
void QTextEditPrivate::_q_hoveredBlockWithMarkerChanged(const QTextBlock &block)
{
    Q_Q(QTextEdit);
    Qt::CursorShape cursor = cursorToRestoreAfterHover;
    if (block.isValid() && !q->isReadOnly()) {
        QTextBlockFormat::MarkerType marker = block.blockFormat().marker();
        if (marker != QTextBlockFormat::MarkerType::NoMarker) {
            if (viewport->cursor().shape() != Qt::PointingHandCursor)
                cursorToRestoreAfterHover = viewport->cursor().shape();
            cursor = Qt::PointingHandCursor;
        }
    }
    viewport->setCursor(cursor);
}
#endif

void QTextEditPrivate::pageUpDown(QTextCursor::MoveOperation op, QTextCursor::MoveMode moveMode)
{
    QTextCursor cursor = control->textCursor();
    bool moved = false;
    qreal lastY = control->cursorRect(cursor).top();
    qreal distance = 0;
    // move using movePosition to keep the cursor's x
    do {
        qreal y = control->cursorRect(cursor).top();
        distance += qAbs(y - lastY);
        lastY = y;
        moved = cursor.movePosition(op, moveMode);
    } while (moved && distance < viewport->height());

    if (moved) {
        if (op == QTextCursor::Up) {
            cursor.movePosition(QTextCursor::Down, moveMode);
            vbar->triggerAction(QAbstractSlider::SliderPageStepSub);
        } else {
            cursor.movePosition(QTextCursor::Up, moveMode);
            vbar->triggerAction(QAbstractSlider::SliderPageStepAdd);
        }
    }
    control->setTextCursor(cursor);
}

#if QT_CONFIG(scrollbar)
static QSize documentSize(QWidgetTextControl *control)
{
    QTextDocument *doc = control->document();
    QAbstractTextDocumentLayout *layout = doc->documentLayout();

    QSize docSize;

    if (QTextDocumentLayout *tlayout = qobject_cast<QTextDocumentLayout *>(layout)) {
        docSize = tlayout->dynamicDocumentSize().toSize();
        int percentageDone = tlayout->layoutStatus();
        // extrapolate height
        if (percentageDone > 0)
            docSize.setHeight(docSize.height() * 100 / percentageDone);
    } else {
        docSize = layout->documentSize().toSize();
    }

    return docSize;
}

void QTextEditPrivate::_q_adjustScrollbars()
{
    if (ignoreAutomaticScrollbarAdjustment)
        return;
    ignoreAutomaticScrollbarAdjustment = true; // avoid recursion, #106108

    QSize viewportSize = viewport->size();
    QSize docSize = documentSize(control);

    // due to the recursion guard we have to repeat this step a few times,
    // as adding/removing a scroll bar will cause the document or viewport
    // size to change
    // ideally we should loop until the viewport size and doc size stabilize,
    // but in corner cases they might fluctuate, so we need to limit the
    // number of iterations
    for (int i = 0; i < 4; ++i) {
        hbar->setRange(0, docSize.width() - viewportSize.width());
        hbar->setPageStep(viewportSize.width());

        vbar->setRange(0, docSize.height() - viewportSize.height());
        vbar->setPageStep(viewportSize.height());

        // if we are in left-to-right mode widening the document due to
        // lazy layouting does not require a repaint. If in right-to-left
        // the scroll bar has the value zero and it visually has the maximum
        // value (it is visually at the right), then widening the document
        // keeps it at value zero but visually adjusts it to the new maximum
        // on the right, hence we need an update.
        if (q_func()->isRightToLeft())
            viewport->update();

        _q_showOrHideScrollBars();

        const QSize oldViewportSize = viewportSize;
        const QSize oldDocSize = docSize;

        // make sure the document is layouted if the viewport width changes
        viewportSize = viewport->size();
        if (viewportSize.width() != oldViewportSize.width())
            relayoutDocument();

        docSize = documentSize(control);
        if (viewportSize == oldViewportSize && docSize == oldDocSize)
            break;
    }
    ignoreAutomaticScrollbarAdjustment = false;
}
#endif

// rect is in content coordinates
void QTextEditPrivate::_q_ensureVisible(const QRectF &_rect)
{
    const QRect rect = _rect.toRect();
    if ((vbar->isVisible() && vbar->maximum() < rect.bottom())
        || (hbar->isVisible() && hbar->maximum() < rect.right()))
        _q_adjustScrollbars();
    const int visibleWidth = viewport->width();
    const int visibleHeight = viewport->height();
    const bool rtl = q_func()->isRightToLeft();

    if (rect.x() < horizontalOffset()) {
        if (rtl)
            hbar->setValue(hbar->maximum() - rect.x());
        else
            hbar->setValue(rect.x());
    } else if (rect.x() + rect.width() > horizontalOffset() + visibleWidth) {
        if (rtl)
            hbar->setValue(hbar->maximum() - (rect.x() + rect.width() - visibleWidth));
        else
            hbar->setValue(rect.x() + rect.width() - visibleWidth);
    }

    if (rect.y() < verticalOffset())
        vbar->setValue(rect.y());
    else if (rect.y() + rect.height() > verticalOffset() + visibleHeight)
        vbar->setValue(rect.y() + rect.height() - visibleHeight);
}

/*!
    \class QTextEdit
    \brief The QTextEdit class provides a widget that is used to edit and display
    both plain and rich text.

    \ingroup richtext-processing
    \inmodule QtWidgets

    \tableofcontents

    \section1 Introduction and Concepts

    QTextEdit is an advanced WYSIWYG viewer/editor supporting rich
    text formatting using HTML-style tags, or Markdown format. It is optimized
    to handle large documents and to respond quickly to user input.

    QTextEdit works on paragraphs and characters. A paragraph is a
    formatted string which is word-wrapped to fit into the width of
    the widget. By default when reading plain text, one newline
    signifies a paragraph. A document consists of zero or more
    paragraphs. The words in the paragraph are aligned in accordance
    with the paragraph's alignment. Paragraphs are separated by hard
    line breaks. Each character within a paragraph has its own
    attributes, for example, font and color.

    QTextEdit can display images, lists and tables. If the text is
    too large to view within the text edit's viewport, scroll bars will
    appear. The text edit can load both plain text and rich text files.
    Rich text can be described using a subset of HTML 4 markup; refer to the
    \l {Supported HTML Subset} page for more information.

    If you just need to display a small piece of rich text use QLabel.

    The rich text support in Qt is designed to provide a fast, portable and
    efficient way to add reasonable online help facilities to
    applications, and to provide a basis for rich text editors. If
    you find the HTML support insufficient for your needs you may consider
    the use of Qt WebKit, which provides a full-featured web browser
    widget.

    The shape of the mouse cursor on a QTextEdit is Qt::IBeamCursor by default.
    It can be changed through the viewport()'s cursor property.

    \section1 Using QTextEdit as a Display Widget

    QTextEdit can display a large HTML subset, including tables and
    images.

    The text can be set or replaced using \l setHtml() which deletes any
    existing text and replaces it with the text passed in the
    setHtml() call. If you call setHtml() with legacy HTML, and then
    call toHtml(), the text that is returned may have different markup,
    but will render the same. The entire text can be deleted with clear().

    Text can also be set or replaced using \l setMarkdown(), and the same
    caveats apply: if you then call \l toMarkdown(), the text that is returned
    may be different, but the meaning is preserved as much as possible.
    Markdown with some embedded HTML can be parsed, with the same limitations
    that \l setHtml() has; but \l toMarkdown() only writes "pure" Markdown,
    without any embedded HTML.

    Text itself can be inserted using the QTextCursor class or using the
    convenience functions insertHtml(), insertPlainText(), append() or
    paste(). QTextCursor is also able to insert complex objects like tables
    or lists into the document, and it deals with creating selections
    and applying changes to selected text.

    By default the text edit wraps words at whitespace to fit within
    the text edit widget. The setLineWrapMode() function is used to
    specify the kind of line wrap you want, or \l NoWrap if you don't
    want any wrapping. Call setLineWrapMode() to set a fixed pixel width
    \l FixedPixelWidth, or character column (e.g. 80 column) \l
    FixedColumnWidth with the pixels or columns specified with
    setLineWrapColumnOrWidth(). If you use word wrap to the widget's width
    \l WidgetWidth, you can specify whether to break on whitespace or
    anywhere with setWordWrapMode().

    The find() function can be used to find and select a given string
    within the text.

    If you want to limit the total number of paragraphs in a QTextEdit,
    as for example it is often useful in a log viewer, then you can use
    QTextDocument's maximumBlockCount property for that.

    \section2 Read-only Key Bindings

    When QTextEdit is used read-only the key bindings are limited to
    navigation, and text may only be selected with the mouse:
    \table
    \header \li Keypresses \li Action
    \row \li Up        \li Moves one line up.
    \row \li Down        \li Moves one line down.
    \row \li Left        \li Moves one character to the left.
    \row \li Right        \li Moves one character to the right.
    \row \li PageUp        \li Moves one (viewport) page up.
    \row \li PageDown        \li Moves one (viewport) page down.
    \row \li Home        \li Moves to the beginning of the text.
    \row \li End                \li Moves to the end of the text.
    \row \li Alt+Wheel
         \li Scrolls the page horizontally (the Wheel is the mouse wheel).
    \row \li Ctrl+Wheel        \li Zooms the text.
    \row \li Ctrl+A            \li Selects all text.
    \endtable

    The text edit may be able to provide some meta-information. For
    example, the documentTitle() function will return the text from
    within HTML \c{<title>} tags.

    \note Zooming into HTML documents only works if the font-size is not set to a fixed size.

    \section1 Using QTextEdit as an Editor

    All the information about using QTextEdit as a display widget also
    applies here.

    The current char format's attributes are set with setFontItalic(),
    setFontWeight(), setFontUnderline(), setFontFamily(),
    setFontPointSize(), setTextColor() and setCurrentFont(). The current
    paragraph's alignment is set with setAlignment().

    Selection of text is handled by the QTextCursor class, which provides
    functionality for creating selections, retrieving the text contents or
    deleting selections. You can retrieve the object that corresponds with
    the user-visible cursor using the textCursor() method. If you want to set
    a selection in QTextEdit just create one on a QTextCursor object and
    then make that cursor the visible cursor using setTextCursor(). The selection
    can be copied to the clipboard with copy(), or cut to the clipboard with
    cut(). The entire text can be selected using selectAll().

    When the cursor is moved and the underlying formatting attributes change,
    the currentCharFormatChanged() signal is emitted to reflect the new attributes
    at the new cursor position.

    The textChanged() signal is emitted whenever the text changes (as a result
    of setText() or through the editor itself).

    QTextEdit holds a QTextDocument object which can be retrieved using the
    document() method. You can also set your own document object using setDocument().

    QTextDocument provides an \l {QTextDocument::isModified()}{isModified()}
    function which will return true if the text has been modified since it was
    either loaded or since the last call to setModified with false as argument.
    In addition it provides methods for undo and redo.

    \section2 Drag and Drop

    QTextEdit also supports custom drag and drop behavior. By default,
    QTextEdit will insert plain text, HTML and rich text when the user drops
    data of these MIME types onto a document. Reimplement
    canInsertFromMimeData() and insertFromMimeData() to add support for
    additional MIME types.

    For example, to allow the user to drag and drop an image onto a QTextEdit,
    you could the implement these functions in the following way:

    \snippet textdocument-imagedrop/textedit.cpp 0

    We add support for image MIME types by returning true. For all other
    MIME types, we use the default implementation.

    \snippet textdocument-imagedrop/textedit.cpp 1

    We unpack the image from the QVariant held by the MIME source and insert
    it into the document as a resource.

    \section2 Editing Key Bindings

    The list of key bindings which are implemented for editing:
    \table
    \header \li Keypresses \li Action
    \row \li Backspace \li Deletes the character to the left of the cursor.
    \row \li Delete \li Deletes the character to the right of the cursor.
    \row \li Ctrl+C \li Copy the selected text to the clipboard.
    \row \li Ctrl+Insert \li Copy the selected text to the clipboard.
    \row \li Ctrl+K \li Deletes to the end of the line.
    \row \li Ctrl+V \li Pastes the clipboard text into text edit.
    \row \li Shift+Insert \li Pastes the clipboard text into text edit.
    \row \li Ctrl+X \li Deletes the selected text and copies it to the clipboard.
    \row \li Shift+Delete \li Deletes the selected text and copies it to the clipboard.
    \row \li Ctrl+Z \li Undoes the last operation.
    \row \li Ctrl+Y \li Redoes the last operation.
    \row \li Left \li Moves the cursor one character to the left.
    \row \li Ctrl+Left \li Moves the cursor one word to the left.
    \row \li Right \li Moves the cursor one character to the right.
    \row \li Ctrl+Right \li Moves the cursor one word to the right.
    \row \li Up \li Moves the cursor one line up.
    \row \li Down \li Moves the cursor one line down.
    \row \li PageUp \li Moves the cursor one page up.
    \row \li PageDown \li Moves the cursor one page down.
    \row \li Home \li Moves the cursor to the beginning of the line.
    \row \li Ctrl+Home \li Moves the cursor to the beginning of the text.
    \row \li End \li Moves the cursor to the end of the line.
    \row \li Ctrl+End \li Moves the cursor to the end of the text.
    \row \li Alt+Wheel \li Scrolls the page horizontally (the Wheel is the mouse wheel).
    \endtable

    To select (mark) text hold down the Shift key whilst pressing one
    of the movement keystrokes, for example, \e{Shift+Right}
    will select the character to the right, and \e{Shift+Ctrl+Right} will select the word to the right, etc.

    \sa QTextDocument, QTextCursor, {Application Example},
        {Syntax Highlighter Example}, {Rich Text Processing}
*/

/*!
    \property QTextEdit::plainText
    \since 4.3

    This property gets and sets the text editor's contents as plain
    text. Previous contents are removed and undo/redo history is reset
    when the property is set. currentCharFormat() is also reset, unless
    textCursor() is already at the beginning of the document.

    If the text edit has another content type, it will not be replaced
    by plain text if you call toPlainText(). The only exception to this
    is the non-break space, \e{nbsp;}, that will be converted into
    standard space.

    By default, for an editor with no contents, this property contains
    an empty string.

    \sa html
*/

/*!
    \property QTextEdit::undoRedoEnabled
    \brief whether undo and redo are enabled

    Users are only able to undo or redo actions if this property is
    true, and if there is an action that can be undone (or redone).
*/

/*!
    \enum QTextEdit::LineWrapMode

    \value NoWrap
    \value WidgetWidth
    \value FixedPixelWidth
    \value FixedColumnWidth
*/

/*!
    \enum QTextEdit::AutoFormattingFlag

    \value AutoNone Don't do any automatic formatting.
    \value AutoBulletList Automatically create bullet lists (e.g. when
    the user enters an asterisk ('*') in the left most column, or
    presses Enter in an existing list item.
    \value AutoAll Apply all automatic formatting. Currently only
    automatic bullet lists are supported.
*/


/*!
    Constructs an empty QTextEdit with parent \a
    parent.
*/
QTextEdit::QTextEdit(QWidget *parent)
    : QAbstractScrollArea(*new QTextEditPrivate, parent)
{
    Q_D(QTextEdit);
    d->init();
}

/*!
    \internal
*/
QTextEdit::QTextEdit(QTextEditPrivate &dd, QWidget *parent)
    : QAbstractScrollArea(dd, parent)
{
    Q_D(QTextEdit);
    d->init();
}

/*!
    Constructs a QTextEdit with parent \a parent. The text edit will display
    the text \a text. The text is interpreted as html.
*/
QTextEdit::QTextEdit(const QString &text, QWidget *parent)
    : QAbstractScrollArea(*new QTextEditPrivate, parent)
{
    Q_D(QTextEdit);
    d->init(text);
}



/*!
    Destructor.
*/
QTextEdit::~QTextEdit()
{
}

/*!
    Returns the point size of the font of the current format.

    \sa setFontFamily(), setCurrentFont(), setFontPointSize()
*/
qreal QTextEdit::fontPointSize() const
{
    Q_D(const QTextEdit);
    return d->control->textCursor().charFormat().fontPointSize();
}

/*!
    Returns the font family of the current format.

    \sa setFontFamily(), setCurrentFont(), setFontPointSize()
*/
QString QTextEdit::fontFamily() const
{
    Q_D(const QTextEdit);
    return d->control->textCursor().charFormat().fontFamily();
}

/*!
    Returns the font weight of the current format.

    \sa setFontWeight(), setCurrentFont(), setFontPointSize(), QFont::Weight
*/
int QTextEdit::fontWeight() const
{
    Q_D(const QTextEdit);
    return d->control->textCursor().charFormat().fontWeight();
}

/*!
    Returns \c true if the font of the current format is underlined; otherwise returns
    false.

    \sa setFontUnderline()
*/
bool QTextEdit::fontUnderline() const
{
    Q_D(const QTextEdit);
    return d->control->textCursor().charFormat().fontUnderline();
}

/*!
    Returns \c true if the font of the current format is italic; otherwise returns
    false.

    \sa setFontItalic()
*/
bool QTextEdit::fontItalic() const
{
    Q_D(const QTextEdit);
    return d->control->textCursor().charFormat().fontItalic();
}

/*!
    Returns the text color of the current format.

    \sa setTextColor()
*/
QColor QTextEdit::textColor() const
{
    Q_D(const QTextEdit);
    return d->control->textCursor().charFormat().foreground().color();
}

/*!
    \since 4.4

    Returns the text background color of the current format.

    \sa setTextBackgroundColor()
*/
QColor QTextEdit::textBackgroundColor() const
{
    Q_D(const QTextEdit);
    return d->control->textCursor().charFormat().background().color();
}

/*!
    Returns the font of the current format.

    \sa setCurrentFont(), setFontFamily(), setFontPointSize()
*/
QFont QTextEdit::currentFont() const
{
    Q_D(const QTextEdit);
    return d->control->textCursor().charFormat().font();
}

/*!
    Sets the alignment of the current paragraph to \a a. Valid
    alignments are Qt::AlignLeft, Qt::AlignRight,
    Qt::AlignJustify and Qt::AlignCenter (which centers
    horizontally).
*/
void QTextEdit::setAlignment(Qt::Alignment a)
{
    Q_D(QTextEdit);
    QTextBlockFormat fmt;
    fmt.setAlignment(a);
    QTextCursor cursor = d->control->textCursor();
    cursor.mergeBlockFormat(fmt);
    d->control->setTextCursor(cursor);
    d->relayoutDocument();
}

/*!
    Returns the alignment of the current paragraph.

    \sa setAlignment()
*/
Qt::Alignment QTextEdit::alignment() const
{
    Q_D(const QTextEdit);
    return d->control->textCursor().blockFormat().alignment();
}

/*!
    \property QTextEdit::document
    \brief the underlying document of the text editor.

    \note The editor \e{does not take ownership of the document} unless it
    is the document's parent object. The parent object of the provided document
    remains the owner of the object. If the previously assigned document is a
    child of the editor then it will be deleted.
*/
void QTextEdit::setDocument(QTextDocument *document)
{
    Q_D(QTextEdit);
    d->control->setDocument(document);
    d->updateDefaultTextOption();
    d->relayoutDocument();
}

QTextDocument *QTextEdit::document() const
{
    Q_D(const QTextEdit);
    return d->control->document();
}

/*!
    \since 5.2

    \property QTextEdit::placeholderText
    \brief the editor placeholder text

    Setting this property makes the editor display a grayed-out
    placeholder text as long as the document() is empty.

    By default, this property contains an empty string.

    \sa document()
*/
QString QTextEdit::placeholderText() const
{
    Q_D(const QTextEdit);
    return d->placeholderText;
}

void QTextEdit::setPlaceholderText(const QString &placeholderText)
{
    Q_D(QTextEdit);
    if (d->placeholderText != placeholderText) {
        d->placeholderText = placeholderText;
        if (d->control->document()->isEmpty())
            d->viewport->update();
    }
}

/*!
    Sets the visible \a cursor.
*/
void QTextEdit::setTextCursor(const QTextCursor &cursor)
{
    doSetTextCursor(cursor);
}

/*!
    \internal

     This provides a hook for subclasses to intercept cursor changes.
*/

void QTextEdit::doSetTextCursor(const QTextCursor &cursor)
{
    Q_D(QTextEdit);
    d->control->setTextCursor(cursor);
}

/*!
    Returns a copy of the QTextCursor that represents the currently visible cursor.
    Note that changes on the returned cursor do not affect QTextEdit's cursor; use
    setTextCursor() to update the visible cursor.
 */
QTextCursor QTextEdit::textCursor() const
{
    Q_D(const QTextEdit);
    return d->control->textCursor();
}

/*!
    Sets the font family of the current format to \a fontFamily.

    \sa fontFamily(), setCurrentFont()
*/
void QTextEdit::setFontFamily(const QString &fontFamily)
{
    QTextCharFormat fmt;
    fmt.setFontFamily(fontFamily);
    mergeCurrentCharFormat(fmt);
}

/*!
    Sets the point size of the current format to \a s.

    Note that if \a s is zero or negative, the behavior of this
    function is not defined.

    \sa fontPointSize(), setCurrentFont(), setFontFamily()
*/
void QTextEdit::setFontPointSize(qreal s)
{
    QTextCharFormat fmt;
    fmt.setFontPointSize(s);
    mergeCurrentCharFormat(fmt);
}

/*!
    \fn void QTextEdit::setFontWeight(int weight)

    Sets the font weight of the current format to the given \a weight,
    where the value used is in the range defined by the QFont::Weight
    enum.

    \sa fontWeight(), setCurrentFont(), setFontFamily()
*/
void QTextEdit::setFontWeight(int w)
{
    QTextCharFormat fmt;
    fmt.setFontWeight(w);
    mergeCurrentCharFormat(fmt);
}

/*!
    If \a underline is true, sets the current format to underline;
    otherwise sets the current format to non-underline.

    \sa fontUnderline()
*/
void QTextEdit::setFontUnderline(bool underline)
{
    QTextCharFormat fmt;
    fmt.setFontUnderline(underline);
    mergeCurrentCharFormat(fmt);
}

/*!
    If \a italic is true, sets the current format to italic;
    otherwise sets the current format to non-italic.

    \sa fontItalic()
*/
void QTextEdit::setFontItalic(bool italic)
{
    QTextCharFormat fmt;
    fmt.setFontItalic(italic);
    mergeCurrentCharFormat(fmt);
}

/*!
    Sets the text color of the current format to \a c.

    \sa textColor()
*/
void QTextEdit::setTextColor(const QColor &c)
{
    QTextCharFormat fmt;
    fmt.setForeground(QBrush(c));
    mergeCurrentCharFormat(fmt);
}

/*!
    \since 4.4

    Sets the text background color of the current format to \a c.

    \sa textBackgroundColor()
*/
void QTextEdit::setTextBackgroundColor(const QColor &c)
{
    QTextCharFormat fmt;
    fmt.setBackground(QBrush(c));
    mergeCurrentCharFormat(fmt);
}

/*!
    Sets the font of the current format to \a f.

    \sa currentFont(), setFontPointSize(), setFontFamily()
*/
void QTextEdit::setCurrentFont(const QFont &f)
{
    QTextCharFormat fmt;
    fmt.setFont(f);
    mergeCurrentCharFormat(fmt);
}

/*!
    \since 4.2

    Undoes the last operation.

    If there is no operation to undo, i.e. there is no undo step in
    the undo/redo history, nothing happens.

    \sa redo()
*/
void QTextEdit::undo()
{
    Q_D(QTextEdit);
    d->control->undo();
}

void QTextEdit::redo()
{
    Q_D(QTextEdit);
    d->control->redo();
}

/*!
    \fn void QTextEdit::redo()
    \since 4.2

    Redoes the last operation.

    If there is no operation to redo, i.e. there is no redo step in
    the undo/redo history, nothing happens.

    \sa undo()
*/

#ifndef QT_NO_CLIPBOARD
/*!
    Copies the selected text to the clipboard and deletes it from
    the text edit.

    If there is no selected text nothing happens.

    \sa copy(), paste()
*/

void QTextEdit::cut()
{
    Q_D(QTextEdit);
    d->control->cut();
}

/*!
    Copies any selected text to the clipboard.

    \sa copyAvailable()
*/

void QTextEdit::copy()
{
    Q_D(QTextEdit);
    d->control->copy();
}

/*!
    Pastes the text from the clipboard into the text edit at the
    current cursor position.

    If there is no text in the clipboard nothing happens.

    To change the behavior of this function, i.e. to modify what
    QTextEdit can paste and how it is being pasted, reimplement the
    virtual canInsertFromMimeData() and insertFromMimeData()
    functions.

    \sa cut(), copy()
*/

void QTextEdit::paste()
{
    Q_D(QTextEdit);
    d->control->paste();
}
#endif

/*!
    Deletes all the text in the text edit.

    Notes:
    \list
    \li The undo/redo history is also cleared.
    \li currentCharFormat() is reset, unless textCursor()
    is already at the beginning of the document.
    \endlist

    \sa cut(), setPlainText(), setHtml()
*/
void QTextEdit::clear()
{
    Q_D(QTextEdit);
    // clears and sets empty content
    d->control->clear();
}


/*!
    Selects all text.

    \sa copy(), cut(), textCursor()
 */
void QTextEdit::selectAll()
{
    Q_D(QTextEdit);
    d->control->selectAll();
}

/*! \internal
*/
bool QTextEdit::event(QEvent *e)
{
    Q_D(QTextEdit);
#ifndef QT_NO_CONTEXTMENU
    if (e->type() == QEvent::ContextMenu
        && static_cast<QContextMenuEvent *>(e)->reason() == QContextMenuEvent::Keyboard) {
        Q_D(QTextEdit);
        ensureCursorVisible();
        const QPoint cursorPos = cursorRect().center();
        QContextMenuEvent ce(QContextMenuEvent::Keyboard, cursorPos, d->viewport->mapToGlobal(cursorPos));
        ce.setAccepted(e->isAccepted());
        const bool result = QAbstractScrollArea::event(&ce);
        e->setAccepted(ce.isAccepted());
        return result;
    } else if (e->type() == QEvent::ShortcutOverride
               || e->type() == QEvent::ToolTip) {
        d->sendControlEvent(e);
    }
#else
    Q_UNUSED(d)
#endif // QT_NO_CONTEXTMENU
#ifdef QT_KEYPAD_NAVIGATION
    if (e->type() == QEvent::EnterEditFocus || e->type() == QEvent::LeaveEditFocus) {
        if (QApplicationPrivate::keypadNavigationEnabled())
            d->sendControlEvent(e);
    }
#endif
    return QAbstractScrollArea::event(e);
}

/*! \internal
*/

void QTextEdit::timerEvent(QTimerEvent *e)
{
    Q_D(QTextEdit);
    if (e->timerId() == d->autoScrollTimer.timerId()) {
        QRect visible = d->viewport->rect();
        QPoint pos;
        if (d->inDrag) {
            pos = d->autoScrollDragPos;
            visible.adjust(qMin(visible.width()/3,20), qMin(visible.height()/3,20),
                           -qMin(visible.width()/3,20), -qMin(visible.height()/3,20));
        } else {
            const QPoint globalPos = QCursor::pos();
            pos = d->viewport->mapFromGlobal(globalPos);
            QMouseEvent ev(QEvent::MouseMove, pos, mapTo(topLevelWidget(), pos), globalPos, Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);
            mouseMoveEvent(&ev);
        }
        int deltaY = qMax(pos.y() - visible.top(), visible.bottom() - pos.y()) - visible.height();
        int deltaX = qMax(pos.x() - visible.left(), visible.right() - pos.x()) - visible.width();
        int delta = qMax(deltaX, deltaY);
        if (delta >= 0) {
            if (delta < 7)
                delta = 7;
            int timeout = 4900 / (delta * delta);
            d->autoScrollTimer.start(timeout, this);

            if (deltaY > 0)
                d->vbar->triggerAction(pos.y() < visible.center().y() ?
                                       QAbstractSlider::SliderSingleStepSub
                                       : QAbstractSlider::SliderSingleStepAdd);
            if (deltaX > 0)
                d->hbar->triggerAction(pos.x() < visible.center().x() ?
                                       QAbstractSlider::SliderSingleStepSub
                                       : QAbstractSlider::SliderSingleStepAdd);
        }
    }
#ifdef QT_KEYPAD_NAVIGATION
    else if (e->timerId() == d->deleteAllTimer.timerId()) {
        d->deleteAllTimer.stop();
        clear();
    }
#endif
}

/*!
    Changes the text of the text edit to the string \a text.
    Any previous text is removed.

    Notes:
    \list
    \li \a text is interpreted as plain text.
    \li The undo/redo history is also cleared.
    \li currentCharFormat() is reset, unless textCursor()
    is already at the beginning of the document.
    \endlist

    \sa toPlainText()
*/

void QTextEdit::setPlainText(const QString &text)
{
    Q_D(QTextEdit);
    d->control->setPlainText(text);
    d->preferRichText = false;
}

/*!
    QString QTextEdit::toPlainText() const

    Returns the text of the text edit as plain text.

    \sa QTextEdit::setPlainText()
 */
QString QTextEdit::toPlainText() const
{
    Q_D(const QTextEdit);
    return d->control->toPlainText();
}

/*!
    \property QTextEdit::html

    This property provides an HTML interface to the text of the text edit.

    toHtml() returns the text of the text edit as html.

    setHtml() changes the text of the text edit.  Any previous text is
    removed and the undo/redo history is cleared. The input text is
    interpreted as rich text in html format. currentCharFormat() is also
    reset, unless textCursor() is already at the beginning of the document.

    \note It is the responsibility of the caller to make sure that the
    text is correctly decoded when a QString containing HTML is created
    and passed to setHtml().

    By default, for a newly-created, empty document, this property contains
    text to describe an HTML 4.0 document with no body text.

    \sa {Supported HTML Subset}, plainText
*/

#ifndef QT_NO_TEXTHTMLPARSER
void QTextEdit::setHtml(const QString &text)
{
    Q_D(QTextEdit);
    d->control->setHtml(text);
    d->preferRichText = true;
}

QString QTextEdit::toHtml() const
{
    Q_D(const QTextEdit);
    return d->control->toHtml();
}
#endif

#if QT_CONFIG(textmarkdownreader) && QT_CONFIG(textmarkdownwriter)
/*!
    \property QTextEdit::markdown

    This property provides a Markdown interface to the text of the text edit.

    \c toMarkdown() returns the text of the text edit as "pure" Markdown,
    without any embedded HTML formatting. Some features that QTextDocument
    supports (such as the use of specific colors and named fonts) cannot be
    expressed in "pure" Markdown, and they will be omitted.

    \c setMarkdown() changes the text of the text edit.  Any previous text is
    removed and the undo/redo history is cleared. The input text is
    interpreted as rich text in Markdown format.

    Parsing of HTML included in the \a markdown string is handled in the same
    way as in \l setHtml; however, Markdown formatting inside HTML blocks is
    not supported.

    Some features of the parser can be enabled or disabled via the \a features
    argument:

    \value MarkdownNoHTML
           Any HTML tags in the Markdown text will be discarded
    \value MarkdownDialectCommonMark
           The parser supports only the features standardized by CommonMark
    \value MarkdownDialectGitHub
           The parser supports the GitHub dialect

    The default is \c MarkdownDialectGitHub.

    \sa plainText, html, QTextDocument::toMarkdown(), QTextDocument::setMarkdown()
    \since 5.14
*/
#endif

#if QT_CONFIG(textmarkdownreader)
void QTextEdit::setMarkdown(const QString &markdown)
{
    Q_D(const QTextEdit);
    d->control->setMarkdown(markdown);
}
#endif

#if QT_CONFIG(textmarkdownwriter)
QString QTextEdit::toMarkdown(QTextDocument::MarkdownFeatures features) const
{
    Q_D(const QTextEdit);
    return d->control->toMarkdown(features);
}
#endif

/*! \reimp
*/
void QTextEdit::keyPressEvent(QKeyEvent *e)
{
    Q_D(QTextEdit);

#ifdef QT_KEYPAD_NAVIGATION
    switch (e->key()) {
        case Qt::Key_Select:
            if (QApplicationPrivate::keypadNavigationEnabled()) {
                // code assumes linksaccessible + editable isn't meaningful
                if (d->control->textInteractionFlags() & Qt::TextEditable) {
                    setEditFocus(!hasEditFocus());
                } else {
                    if (!hasEditFocus())
                        setEditFocus(true);
                    else {
                        QTextCursor cursor = d->control->textCursor();
                        QTextCharFormat charFmt = cursor.charFormat();
                        if (!(d->control->textInteractionFlags() & Qt::LinksAccessibleByKeyboard)
                            || !cursor.hasSelection() || charFmt.anchorHref().isEmpty()) {
                            e->accept();
                            return;
                        }
                    }
                }
            }
            break;
        case Qt::Key_Back:
        case Qt::Key_No:
            if (!QApplicationPrivate::keypadNavigationEnabled()
                    || (QApplicationPrivate::keypadNavigationEnabled() && !hasEditFocus())) {
                e->ignore();
                return;
            }
            break;
        default:
            if (QApplicationPrivate::keypadNavigationEnabled()) {
                if (!hasEditFocus() && !(e->modifiers() & Qt::ControlModifier)) {
                    if (e->text()[0].isPrint())
                        setEditFocus(true);
                    else {
                        e->ignore();
                        return;
                    }
                }
            }
            break;
    }
#endif
#ifndef QT_NO_SHORTCUT

    Qt::TextInteractionFlags tif = d->control->textInteractionFlags();

    if (tif & Qt::TextSelectableByKeyboard){
        if (e == QKeySequence::SelectPreviousPage) {
            e->accept();
            d->pageUpDown(QTextCursor::Up, QTextCursor::KeepAnchor);
            return;
        } else if (e ==QKeySequence::SelectNextPage) {
            e->accept();
            d->pageUpDown(QTextCursor::Down, QTextCursor::KeepAnchor);
            return;
        }
    }
    if (tif & (Qt::TextSelectableByKeyboard | Qt::TextEditable)) {
        if (e == QKeySequence::MoveToPreviousPage) {
            e->accept();
            d->pageUpDown(QTextCursor::Up, QTextCursor::MoveAnchor);
            return;
        } else if (e == QKeySequence::MoveToNextPage) {
            e->accept();
            d->pageUpDown(QTextCursor::Down, QTextCursor::MoveAnchor);
            return;
        }
    }

    if (!(tif & Qt::TextEditable)) {
        switch (e->key()) {
            case Qt::Key_Space:
                e->accept();
                if (e->modifiers() & Qt::ShiftModifier)
                    d->vbar->triggerAction(QAbstractSlider::SliderPageStepSub);
                else
                    d->vbar->triggerAction(QAbstractSlider::SliderPageStepAdd);
                break;
            default:
                d->sendControlEvent(e);
                if (!e->isAccepted() && e->modifiers() == Qt::NoModifier) {
                    if (e->key() == Qt::Key_Home) {
                        d->vbar->triggerAction(QAbstractSlider::SliderToMinimum);
                        e->accept();
                    } else if (e->key() == Qt::Key_End) {
                        d->vbar->triggerAction(QAbstractSlider::SliderToMaximum);
                        e->accept();
                    }
                }
                if (!e->isAccepted()) {
                    QAbstractScrollArea::keyPressEvent(e);
                }
        }
        return;
    }
#endif // QT_NO_SHORTCUT

    {
        QTextCursor cursor = d->control->textCursor();
        const QString text = e->text();
        if (cursor.atBlockStart()
            && (d->autoFormatting & AutoBulletList)
            && (text.length() == 1)
            && (text.at(0) == QLatin1Char('-') || text.at(0) == QLatin1Char('*'))
            && (!cursor.currentList())) {

            d->createAutoBulletList();
            e->accept();
            return;
        }
    }

    d->sendControlEvent(e);
#ifdef QT_KEYPAD_NAVIGATION
    if (!e->isAccepted()) {
        switch (e->key()) {
            case Qt::Key_Up:
            case Qt::Key_Down:
                if (QApplicationPrivate::keypadNavigationEnabled()) {
                    // Cursor position didn't change, so we want to leave
                    // these keys to change focus.
                    e->ignore();
                    return;
                }
                break;
            case Qt::Key_Back:
                if (!e->isAutoRepeat()) {
                    if (QApplicationPrivate::keypadNavigationEnabled()) {
                        if (document()->isEmpty() || !(d->control->textInteractionFlags() & Qt::TextEditable)) {
                            setEditFocus(false);
                            e->accept();
                        } else if (!d->deleteAllTimer.isActive()) {
                            e->accept();
                            d->deleteAllTimer.start(750, this);
                        }
                    } else {
                        e->ignore();
                        return;
                    }
                }
                break;
            default: break;
        }
    }
#endif
}

/*! \reimp
*/
void QTextEdit::keyReleaseEvent(QKeyEvent *e)
{
#ifdef QT_KEYPAD_NAVIGATION
    Q_D(QTextEdit);
    if (QApplicationPrivate::keypadNavigationEnabled()) {
        if (!e->isAutoRepeat() && e->key() == Qt::Key_Back
            && d->deleteAllTimer.isActive()) {
            d->deleteAllTimer.stop();
            QTextCursor cursor = d->control->textCursor();
            QTextBlockFormat blockFmt = cursor.blockFormat();

            QTextList *list = cursor.currentList();
            if (list && cursor.atBlockStart()) {
                list->remove(cursor.block());
            } else if (cursor.atBlockStart() && blockFmt.indent() > 0) {
                blockFmt.setIndent(blockFmt.indent() - 1);
                cursor.setBlockFormat(blockFmt);
            } else {
                cursor.deletePreviousChar();
            }
            setTextCursor(cursor);
            e->accept();
            return;
        }
    }
#endif
    e->ignore();
}

/*!
    Loads the resource specified by the given \a type and \a name.

    This function is an extension of QTextDocument::loadResource().

    \sa QTextDocument::loadResource()
*/
QVariant QTextEdit::loadResource(int type, const QUrl &name)
{
    Q_UNUSED(type);
    Q_UNUSED(name);
    return QVariant();
}

/*! \reimp
*/
void QTextEdit::resizeEvent(QResizeEvent *e)
{
    Q_D(QTextEdit);

    if (d->lineWrap == NoWrap) {
        QTextDocument *doc = d->control->document();
        QVariant alignmentProperty = doc->documentLayout()->property("contentHasAlignment");

        if (!doc->pageSize().isNull()
            && alignmentProperty.userType() == QMetaType::Bool
            && !alignmentProperty.toBool()) {

            d->_q_adjustScrollbars();
            return;
        }
    }

    if (d->lineWrap != FixedPixelWidth
        && e->oldSize().width() != e->size().width())
        d->relayoutDocument();
    else
        d->_q_adjustScrollbars();
}

void QTextEditPrivate::relayoutDocument()
{
    QTextDocument *doc = control->document();
    QAbstractTextDocumentLayout *layout = doc->documentLayout();

    if (QTextDocumentLayout *tlayout = qobject_cast<QTextDocumentLayout *>(layout)) {
        if (lineWrap == QTextEdit::FixedColumnWidth)
            tlayout->setFixedColumnWidth(lineWrapColumnOrWidth);
        else
            tlayout->setFixedColumnWidth(-1);
    }

    QTextDocumentLayout *tlayout = qobject_cast<QTextDocumentLayout *>(layout);
    QSize lastUsedSize;
    if (tlayout)
        lastUsedSize = tlayout->dynamicDocumentSize().toSize();
    else
        lastUsedSize = layout->documentSize().toSize();

    // ignore calls to _q_adjustScrollbars caused by an emission of the
    // usedSizeChanged() signal in the layout, as we're calling it
    // later on our own anyway (or deliberately not) .
    const bool oldIgnoreScrollbarAdjustment = ignoreAutomaticScrollbarAdjustment;
    ignoreAutomaticScrollbarAdjustment = true;

    int width = viewport->width();
    if (lineWrap == QTextEdit::FixedPixelWidth)
        width = lineWrapColumnOrWidth;
    else if (lineWrap == QTextEdit::NoWrap) {
        QVariant alignmentProperty = doc->documentLayout()->property("contentHasAlignment");
        if (alignmentProperty.userType() == QMetaType::Bool && !alignmentProperty.toBool()) {

            width = 0;
        }
    }

    doc->setPageSize(QSize(width, -1));
    if (tlayout)
        tlayout->ensureLayouted(verticalOffset() + viewport->height());

    ignoreAutomaticScrollbarAdjustment = oldIgnoreScrollbarAdjustment;

    QSize usedSize;
    if (tlayout)
        usedSize = tlayout->dynamicDocumentSize().toSize();
    else
        usedSize = layout->documentSize().toSize();

    // this is an obscure situation in the layout that can happen:
    // if a character at the end of a line is the tallest one and therefore
    // influencing the total height of the line and the line right below it
    // is always taller though, then it can happen that if due to line breaking
    // that tall character wraps into the lower line the document not only shrinks
    // horizontally (causing the character to wrap in the first place) but also
    // vertically, because the original line is now smaller and the one below kept
    // its size. So a layout with less width _can_ take up less vertical space, too.
    // If the wider case causes a vertical scroll bar to appear and the narrower one
    // (narrower because the vertical scroll bar takes up horizontal space)) to disappear
    // again then we have an endless loop, as _q_adjustScrollBars sets new ranges on the
    // scroll bars, the QAbstractScrollArea will find out about it and try to show/hide
    // the scroll bars again. That's why we try to detect this case here and break out.
    //
    // (if you change this please also check the layoutingLoop() testcase in
    // QTextEdit's autotests)
    if (lastUsedSize.isValid()
        && !vbar->isHidden()
        && viewport->width() < lastUsedSize.width()
        && usedSize.height() < lastUsedSize.height()
        && usedSize.height() <= viewport->height())
        return;

    _q_adjustScrollbars();
}

void QTextEditPrivate::paint(QPainter *p, QPaintEvent *e)
{
    const int xOffset = horizontalOffset();
    const int yOffset = verticalOffset();

    QRect r = e->rect();
    p->translate(-xOffset, -yOffset);
    r.translate(xOffset, yOffset);

    QTextDocument *doc = control->document();
    QTextDocumentLayout *layout = qobject_cast<QTextDocumentLayout *>(doc->documentLayout());

    // the layout might need to expand the root frame to
    // the viewport if NoWrap is set
    if (layout)
        layout->setViewport(viewport->rect());

    control->drawContents(p, r, q_func());

    if (layout)
        layout->setViewport(QRect());

    if (!placeholderText.isEmpty() && doc->isEmpty() && !control->isPreediting()) {
        const QColor col = control->palette().placeholderText().color();
        p->setPen(col);
        const int margin = int(doc->documentMargin());
        p->drawText(viewport->rect().adjusted(margin, margin, -margin, -margin), Qt::AlignTop | Qt::TextWordWrap, placeholderText);
    }
}

/*! \fn void QTextEdit::paintEvent(QPaintEvent *event)

This event handler can be reimplemented in a subclass to receive paint events passed in \a event.
It is usually unnecessary to reimplement this function in a subclass of QTextEdit.

\warning The underlying text document must not be modified from within a reimplementation
of this function.
*/
void QTextEdit::paintEvent(QPaintEvent *e)
{
    Q_D(QTextEdit);
    QPainter p(d->viewport);
    d->paint(&p, e);
}

void QTextEditPrivate::_q_currentCharFormatChanged(const QTextCharFormat &fmt)
{
    Q_Q(QTextEdit);
    emit q->currentCharFormatChanged(fmt);
}

void QTextEditPrivate::updateDefaultTextOption()
{
    QTextDocument *doc = control->document();

    QTextOption opt = doc->defaultTextOption();
    QTextOption::WrapMode oldWrapMode = opt.wrapMode();

    if (lineWrap == QTextEdit::NoWrap)
        opt.setWrapMode(QTextOption::NoWrap);
    else
        opt.setWrapMode(wordWrap);

    if (opt.wrapMode() != oldWrapMode)
        doc->setDefaultTextOption(opt);
}

/*! \reimp
*/
void QTextEdit::mousePressEvent(QMouseEvent *e)
{
    Q_D(QTextEdit);
#ifdef QT_KEYPAD_NAVIGATION
    if (QApplicationPrivate::keypadNavigationEnabled() && !hasEditFocus())
        setEditFocus(true);
#endif
    d->sendControlEvent(e);
}

/*! \reimp
*/
void QTextEdit::mouseMoveEvent(QMouseEvent *e)
{
    Q_D(QTextEdit);
    d->inDrag = false; // paranoia
    const QPoint pos = e->pos();
    d->sendControlEvent(e);
    if (!(e->buttons() & Qt::LeftButton))
        return;
    if (e->source() == Qt::MouseEventNotSynthesized) {
        const QRect visible = d->viewport->rect();
        if (visible.contains(pos))
            d->autoScrollTimer.stop();
        else if (!d->autoScrollTimer.isActive())
            d->autoScrollTimer.start(100, this);
    }
}

/*! \reimp
*/
void QTextEdit::mouseReleaseEvent(QMouseEvent *e)
{
    Q_D(QTextEdit);
    d->sendControlEvent(e);
    if (e->source() == Qt::MouseEventNotSynthesized && d->autoScrollTimer.isActive()) {
        d->autoScrollTimer.stop();
        ensureCursorVisible();
    }
    if (!isReadOnly() && rect().contains(e->pos()))
        d->handleSoftwareInputPanel(e->button(), d->clickCausedFocus);
    d->clickCausedFocus = 0;
}

/*! \reimp
*/
void QTextEdit::mouseDoubleClickEvent(QMouseEvent *e)
{
    Q_D(QTextEdit);
    d->sendControlEvent(e);
}

/*! \reimp
*/
bool QTextEdit::focusNextPrevChild(bool next)
{
    Q_D(const QTextEdit);
    if (!d->tabChangesFocus && d->control->textInteractionFlags() & Qt::TextEditable)
        return false;
    return QAbstractScrollArea::focusNextPrevChild(next);
}

#ifndef QT_NO_CONTEXTMENU
/*!
  \fn void QTextEdit::contextMenuEvent(QContextMenuEvent *event)

  Shows the standard context menu created with createStandardContextMenu().

  If you do not want the text edit to have a context menu, you can set
  its \l contextMenuPolicy to Qt::NoContextMenu. If you want to
  customize the context menu, reimplement this function. If you want
  to extend the standard context menu, reimplement this function, call
  createStandardContextMenu() and extend the menu returned.

  Information about the event is passed in the \a event object.

  \snippet code/src_gui_widgets_qtextedit.cpp 0
*/
void QTextEdit::contextMenuEvent(QContextMenuEvent *e)
{
    Q_D(QTextEdit);
    d->sendControlEvent(e);
}
#endif // QT_NO_CONTEXTMENU

#if QT_CONFIG(draganddrop)
/*! \reimp
*/
void QTextEdit::dragEnterEvent(QDragEnterEvent *e)
{
    Q_D(QTextEdit);
    d->inDrag = true;
    d->sendControlEvent(e);
}

/*! \reimp
*/
void QTextEdit::dragLeaveEvent(QDragLeaveEvent *e)
{
    Q_D(QTextEdit);
    d->inDrag = false;
    d->autoScrollTimer.stop();
    d->sendControlEvent(e);
}

/*! \reimp
*/
void QTextEdit::dragMoveEvent(QDragMoveEvent *e)
{
    Q_D(QTextEdit);
    d->autoScrollDragPos = e->pos();
    if (!d->autoScrollTimer.isActive())
        d->autoScrollTimer.start(100, this);
    d->sendControlEvent(e);
}

/*! \reimp
*/
void QTextEdit::dropEvent(QDropEvent *e)
{
    Q_D(QTextEdit);
    d->inDrag = false;
    d->autoScrollTimer.stop();
    d->sendControlEvent(e);
}

#endif // QT_CONFIG(draganddrop)

/*! \reimp
 */
void QTextEdit::inputMethodEvent(QInputMethodEvent *e)
{
    Q_D(QTextEdit);
#ifdef QT_KEYPAD_NAVIGATION
    if (d->control->textInteractionFlags() & Qt::TextEditable
        && QApplicationPrivate::keypadNavigationEnabled()
        && !hasEditFocus())
        setEditFocus(true);
#endif
    d->sendControlEvent(e);
    ensureCursorVisible();
}

/*!\reimp
*/
void QTextEdit::scrollContentsBy(int dx, int dy)
{
    Q_D(QTextEdit);
    if (isRightToLeft())
        dx = -dx;
    d->viewport->scroll(dx, dy);
    QGuiApplication::inputMethod()->update(Qt::ImCursorRectangle | Qt::ImAnchorRectangle);
}

/*!\reimp
*/
QVariant QTextEdit::inputMethodQuery(Qt::InputMethodQuery property) const
{
    return inputMethodQuery(property, QVariant());
}

/*!\internal
 */
QVariant QTextEdit::inputMethodQuery(Qt::InputMethodQuery query, QVariant argument) const
{
    Q_D(const QTextEdit);
    switch (query) {
        case Qt::ImHints:
        case Qt::ImInputItemClipRectangle:
        return QWidget::inputMethodQuery(query);
    default:
        break;
    }

    const QPointF offset(-d->horizontalOffset(), -d->verticalOffset());
    switch (argument.userType()) {
    case QMetaType::QRectF:
        argument = argument.toRectF().translated(-offset);
        break;
    case QMetaType::QPointF:
        argument = argument.toPointF() - offset;
        break;
    case QMetaType::QRect:
        argument = argument.toRect().translated(-offset.toPoint());
        break;
    case QMetaType::QPoint:
        argument = argument.toPoint() - offset;
        break;
    default:
        break;
    }

    const QVariant v = d->control->inputMethodQuery(query, argument);
    switch (v.userType()) {
    case QMetaType::QRectF:
        return v.toRectF().translated(offset);
    case QMetaType::QPointF:
        return v.toPointF() + offset;
    case QMetaType::QRect:
        return v.toRect().translated(offset.toPoint());
    case QMetaType::QPoint:
        return v.toPoint() + offset.toPoint();
    default:
        break;
    }
    return v;
}

/*! \reimp
*/
void QTextEdit::focusInEvent(QFocusEvent *e)
{
    Q_D(QTextEdit);
    if (e->reason() == Qt::MouseFocusReason) {
        d->clickCausedFocus = 1;
    }
    QAbstractScrollArea::focusInEvent(e);
    d->sendControlEvent(e);
}

/*! \reimp
*/
void QTextEdit::focusOutEvent(QFocusEvent *e)
{
    Q_D(QTextEdit);
    QAbstractScrollArea::focusOutEvent(e);
    d->sendControlEvent(e);
}

/*! \reimp
*/
void QTextEdit::showEvent(QShowEvent *)
{
    Q_D(QTextEdit);
    if (!d->anchorToScrollToWhenVisible.isEmpty()) {
        scrollToAnchor(d->anchorToScrollToWhenVisible);
        d->anchorToScrollToWhenVisible.clear();
        d->showCursorOnInitialShow = false;
    } else if (d->showCursorOnInitialShow) {
        d->showCursorOnInitialShow = false;
        ensureCursorVisible();
    }
}

/*! \reimp
*/
void QTextEdit::changeEvent(QEvent *e)
{
    Q_D(QTextEdit);
    QAbstractScrollArea::changeEvent(e);
    if (e->type() == QEvent::ApplicationFontChange
        || e->type() == QEvent::FontChange) {
        d->control->document()->setDefaultFont(font());
    }  else if(e->type() == QEvent::ActivationChange) {
        if (!isActiveWindow())
            d->autoScrollTimer.stop();
    } else if (e->type() == QEvent::EnabledChange) {
        e->setAccepted(isEnabled());
        d->control->setPalette(palette());
        d->sendControlEvent(e);
    } else if (e->type() == QEvent::PaletteChange) {
        d->control->setPalette(palette());
    } else if (e->type() == QEvent::LayoutDirectionChange) {
        d->sendControlEvent(e);
    }
}

/*! \reimp
*/
#if QT_CONFIG(wheelevent)
void QTextEdit::wheelEvent(QWheelEvent *e)
{
    Q_D(QTextEdit);
    if (!(d->control->textInteractionFlags() & Qt::TextEditable)) {
        if (e->modifiers() & Qt::ControlModifier) {
            float delta = e->angleDelta().y() / 120.f;
            zoomInF(delta);
            return;
        }
    }
    QAbstractScrollArea::wheelEvent(e);
    updateMicroFocus();
}
#endif

#ifndef QT_NO_CONTEXTMENU
/*!  This function creates the standard context menu which is shown
  when the user clicks on the text edit with the right mouse
  button. It is called from the default contextMenuEvent() handler.
  The popup menu's ownership is transferred to the caller.

  We recommend that you use the createStandardContextMenu(QPoint) version instead
  which will enable the actions that are sensitive to where the user clicked.
*/

QMenu *QTextEdit::createStandardContextMenu()
{
    Q_D(QTextEdit);
    return d->control->createStandardContextMenu(QPointF(), this);
}

/*!
  \since 4.4
  This function creates the standard context menu which is shown
  when the user clicks on the text edit with the right mouse
  button. It is called from the default contextMenuEvent() handler
  and it takes the \a position in document coordinates where the mouse click was.
  This can enable actions that are sensitive to the position where the user clicked.
  The popup menu's ownership is transferred to the caller.
*/

QMenu *QTextEdit::createStandardContextMenu(const QPoint &position)
{
    Q_D(QTextEdit);
    return d->control->createStandardContextMenu(position, this);
}
#endif // QT_NO_CONTEXTMENU

/*!
  returns a QTextCursor at position \a pos (in viewport coordinates).
*/
QTextCursor QTextEdit::cursorForPosition(const QPoint &pos) const
{
    Q_D(const QTextEdit);
    return d->control->cursorForPosition(d->mapToContents(pos));
}

/*!
  returns a rectangle (in viewport coordinates) that includes the
  \a cursor.
 */
QRect QTextEdit::cursorRect(const QTextCursor &cursor) const
{
    Q_D(const QTextEdit);
    if (cursor.isNull())
        return QRect();

    QRect r = d->control->cursorRect(cursor).toRect();
    r.translate(-d->horizontalOffset(),-d->verticalOffset());
    return r;
}

/*!
  returns a rectangle (in viewport coordinates) that includes the
  cursor of the text edit.
 */
QRect QTextEdit::cursorRect() const
{
    Q_D(const QTextEdit);
    QRect r = d->control->cursorRect().toRect();
    r.translate(-d->horizontalOffset(),-d->verticalOffset());
    return r;
}


/*!
    Returns the reference of the anchor at position \a pos, or an
    empty string if no anchor exists at that point.
*/
QString QTextEdit::anchorAt(const QPoint& pos) const
{
    Q_D(const QTextEdit);
    return d->control->anchorAt(d->mapToContents(pos));
}

/*!
   \property QTextEdit::overwriteMode
   \since 4.1
   \brief whether text entered by the user will overwrite existing text

   As with many text editors, the text editor widget can be configured
   to insert or overwrite existing text with new text entered by the user.

   If this property is \c true, existing text is overwritten, character-for-character
   by new text; otherwise, text is inserted at the cursor position, displacing
   existing text.

   By default, this property is \c false (new text does not overwrite existing text).
*/

bool QTextEdit::overwriteMode() const
{
    Q_D(const QTextEdit);
    return d->control->overwriteMode();
}

void QTextEdit::setOverwriteMode(bool overwrite)
{
    Q_D(QTextEdit);
    d->control->setOverwriteMode(overwrite);
}

#if QT_DEPRECATED_SINCE(5, 10)
/*!
    \property QTextEdit::tabStopWidth
    \brief the tab stop width in pixels
    \since 4.1
    \deprecated in Qt 5.10. Use tabStopDistance instead.

    By default, this property contains a value of 80 pixels.
*/

int QTextEdit::tabStopWidth() const
{
    return qRound(tabStopDistance());
}

void QTextEdit::setTabStopWidth(int width)
{
    setTabStopDistance(width);
}
#endif

/*!
    \property QTextEdit::tabStopDistance
    \brief the tab stop distance in pixels
    \since 5.10

    By default, this property contains a value of 80 pixels.
*/

qreal QTextEdit::tabStopDistance() const
{
    Q_D(const QTextEdit);
    return d->control->document()->defaultTextOption().tabStopDistance();
}

void QTextEdit::setTabStopDistance(qreal distance)
{
    Q_D(QTextEdit);
    QTextOption opt = d->control->document()->defaultTextOption();
    if (opt.tabStopDistance() == distance || distance < 0)
        return;
    opt.setTabStopDistance(distance);
    d->control->document()->setDefaultTextOption(opt);
}

/*!
    \since 4.2
    \property QTextEdit::cursorWidth

    This property specifies the width of the cursor in pixels. The default value is 1.
*/
int QTextEdit::cursorWidth() const
{
    Q_D(const QTextEdit);
    return d->control->cursorWidth();
}

void QTextEdit::setCursorWidth(int width)
{
    Q_D(QTextEdit);
    d->control->setCursorWidth(width);
}

/*!
    \property QTextEdit::acceptRichText
    \brief whether the text edit accepts rich text insertions by the user
    \since 4.1

    When this propery is set to false text edit will accept only
    plain text input from the user. For example through clipboard or drag and drop.

    This property's default is true.
*/

bool QTextEdit::acceptRichText() const
{
    Q_D(const QTextEdit);
    return d->control->acceptRichText();
}

void QTextEdit::setAcceptRichText(bool accept)
{
    Q_D(QTextEdit);
    d->control->setAcceptRichText(accept);
}

/*!
    \class QTextEdit::ExtraSelection
    \since 4.2
    \inmodule QtWidgets

    \brief The QTextEdit::ExtraSelection structure provides a way of specifying a
           character format for a given selection in a document.
*/

/*!
    \variable QTextEdit::ExtraSelection::cursor
    A cursor that contains a selection in a QTextDocument
*/

/*!
    \variable QTextEdit::ExtraSelection::format
    A format that is used to specify a foreground or background brush/color
    for the selection.
*/

/*!
    \since 4.2
    This function allows temporarily marking certain regions in the document
    with a given color, specified as \a selections. This can be useful for
    example in a programming editor to mark a whole line of text with a given
    background color to indicate the existence of a breakpoint.

    \sa QTextEdit::ExtraSelection, extraSelections()
*/
void QTextEdit::setExtraSelections(const QList<ExtraSelection> &selections)
{
    Q_D(QTextEdit);
    d->control->setExtraSelections(selections);
}

/*!
    \since 4.2
    Returns previously set extra selections.

    \sa setExtraSelections()
*/
QList<QTextEdit::ExtraSelection> QTextEdit::extraSelections() const
{
    Q_D(const QTextEdit);
    return d->control->extraSelections();
}

/*!
    This function returns a new MIME data object to represent the contents
    of the text edit's current selection. It is called when the selection needs
    to be encapsulated into a new QMimeData object; for example, when a drag
    and drop operation is started, or when data is copied to the clipboard.

    If you reimplement this function, note that the ownership of the returned
    QMimeData object is passed to the caller. The selection can be retrieved
    by using the textCursor() function.
*/
QMimeData *QTextEdit::createMimeDataFromSelection() const
{
    Q_D(const QTextEdit);
    return d->control->QWidgetTextControl::createMimeDataFromSelection();
}

/*!
    This function returns \c true if the contents of the MIME data object, specified
    by \a source, can be decoded and inserted into the document. It is called
    for example when during a drag operation the mouse enters this widget and it
    is necessary to determine whether it is possible to accept the drag and drop
    operation.

    Reimplement this function to enable drag and drop support for additional MIME types.
 */
bool QTextEdit::canInsertFromMimeData(const QMimeData *source) const
{
    Q_D(const QTextEdit);
    return d->control->QWidgetTextControl::canInsertFromMimeData(source);
}

/*!
    This function inserts the contents of the MIME data object, specified
    by \a source, into the text edit at the current cursor position. It is
    called whenever text is inserted as the result of a clipboard paste
    operation, or when the text edit accepts data from a drag and drop
    operation.

    Reimplement this function to enable drag and drop support for additional MIME types.
 */
void QTextEdit::insertFromMimeData(const QMimeData *source)
{
    Q_D(QTextEdit);
    d->control->QWidgetTextControl::insertFromMimeData(source);
}

/*!
    \property QTextEdit::readOnly
    \brief whether the text edit is read-only

    In a read-only text edit the user can only navigate through the
    text and select text; modifying the text is not possible.

    This property's default is false.
*/

bool QTextEdit::isReadOnly() const
{
    Q_D(const QTextEdit);
    return !(d->control->textInteractionFlags() & Qt::TextEditable);
}

void QTextEdit::setReadOnly(bool ro)
{
    Q_D(QTextEdit);
    Qt::TextInteractionFlags flags = Qt::NoTextInteraction;
    if (ro) {
        flags = Qt::TextSelectableByMouse;
#if QT_CONFIG(textbrowser)
        if (qobject_cast<QTextBrowser *>(this))
            flags |= Qt::TextBrowserInteraction;
#endif
    } else {
        flags = Qt::TextEditorInteraction;
    }
    d->control->setTextInteractionFlags(flags);
    setAttribute(Qt::WA_InputMethodEnabled, shouldEnableInputMethod(this));
    QEvent event(QEvent::ReadOnlyChange);
    QCoreApplication::sendEvent(this, &event);
}

/*!
    \property QTextEdit::textInteractionFlags
    \since 4.2

    Specifies how the widget should interact with user input.

    The default value depends on whether the QTextEdit is read-only
    or editable, and whether it is a QTextBrowser or not.
*/

void QTextEdit::setTextInteractionFlags(Qt::TextInteractionFlags flags)
{
    Q_D(QTextEdit);
    d->control->setTextInteractionFlags(flags);
}

Qt::TextInteractionFlags QTextEdit::textInteractionFlags() const
{
    Q_D(const QTextEdit);
    return d->control->textInteractionFlags();
}

/*!
    Merges the properties specified in \a modifier into the current character
    format by calling QTextCursor::mergeCharFormat on the editor's cursor.
    If the editor has a selection then the properties of \a modifier are
    directly applied to the selection.

    \sa QTextCursor::mergeCharFormat()
 */
void QTextEdit::mergeCurrentCharFormat(const QTextCharFormat &modifier)
{
    Q_D(QTextEdit);
    d->control->mergeCurrentCharFormat(modifier);
}

/*!
    Sets the char format that is be used when inserting new text to \a
    format by calling QTextCursor::setCharFormat() on the editor's
    cursor.  If the editor has a selection then the char format is
    directly applied to the selection.
 */
void QTextEdit::setCurrentCharFormat(const QTextCharFormat &format)
{
    Q_D(QTextEdit);
    d->control->setCurrentCharFormat(format);
}

/*!
    Returns the char format that is used when inserting new text.
 */
QTextCharFormat QTextEdit::currentCharFormat() const
{
    Q_D(const QTextEdit);
    return d->control->currentCharFormat();
}

/*!
    \property QTextEdit::autoFormatting
    \brief the enabled set of auto formatting features

    The value can be any combination of the values in the
    AutoFormattingFlag enum.  The default is AutoNone. Choose
    AutoAll to enable all automatic formatting.

    Currently, the only automatic formatting feature provided is
    AutoBulletList; future versions of Qt may offer more.
*/

QTextEdit::AutoFormatting QTextEdit::autoFormatting() const
{
    Q_D(const QTextEdit);
    return d->autoFormatting;
}

void QTextEdit::setAutoFormatting(AutoFormatting features)
{
    Q_D(QTextEdit);
    d->autoFormatting = features;
}

/*!
    Convenience slot that inserts \a text at the current
    cursor position.

    It is equivalent to

    \snippet code/src_gui_widgets_qtextedit.cpp 1
 */
void QTextEdit::insertPlainText(const QString &text)
{
    Q_D(QTextEdit);
    d->control->insertPlainText(text);
}

/*!
    Convenience slot that inserts \a text which is assumed to be of
    html formatting at the current cursor position.

    It is equivalent to:

    \snippet code/src_gui_widgets_qtextedit.cpp 2

    \note When using this function with a style sheet, the style sheet will
    only apply to the current block in the document. In order to apply a style
    sheet throughout a document, use QTextDocument::setDefaultStyleSheet()
    instead.
 */
#ifndef QT_NO_TEXTHTMLPARSER
void QTextEdit::insertHtml(const QString &text)
{
    Q_D(QTextEdit);
    d->control->insertHtml(text);
}
#endif // QT_NO_TEXTHTMLPARSER

/*!
    Scrolls the text edit so that the anchor with the given \a name is
    visible; does nothing if the \a name is empty, or is already
    visible, or isn't found.
*/
void QTextEdit::scrollToAnchor(const QString &name)
{
    Q_D(QTextEdit);
    if (name.isEmpty())
        return;

    if (!isVisible()) {
        d->anchorToScrollToWhenVisible = name;
        return;
    }

    QPointF p = d->control->anchorPosition(name);
    const int newPosition = qRound(p.y());
    if ( d->vbar->maximum() < newPosition )
        d->_q_adjustScrollbars();
    d->vbar->setValue(newPosition);
}

/*!
    Zooms in on the text by making the base font size \a range
    points larger and recalculating all font sizes to be the new size.
    This does not change the size of any images.

    \sa zoomOut()
*/
void QTextEdit::zoomIn(int range)
{
    zoomInF(range);
}

/*!
    Zooms out on the text by making the base font size \a range points
    smaller and recalculating all font sizes to be the new size. This
    does not change the size of any images.

    \sa zoomIn()
*/
void QTextEdit::zoomOut(int range)
{
    zoomInF(-range);
}

/*!
    \internal
*/
void QTextEdit::zoomInF(float range)
{
    if (range == 0.f)
        return;
    QFont f = font();
    const float newSize = f.pointSizeF() + range;
    if (newSize <= 0)
        return;
    f.setPointSizeF(newSize);
    setFont(f);
}

/*!
    \since 4.2
    Moves the cursor by performing the given \a operation.

    If \a mode is QTextCursor::KeepAnchor, the cursor selects the text it moves over.
    This is the same effect that the user achieves when they hold down the Shift key
    and move the cursor with the cursor keys.

    \sa QTextCursor::movePosition()
*/
void QTextEdit::moveCursor(QTextCursor::MoveOperation operation, QTextCursor::MoveMode mode)
{
    Q_D(QTextEdit);
    d->control->moveCursor(operation, mode);
}

/*!
    \since 4.2
    Returns whether text can be pasted from the clipboard into the textedit.
*/
bool QTextEdit::canPaste() const
{
    Q_D(const QTextEdit);
    return d->control->canPaste();
}

/*!
    \since 4.3
    Convenience function to print the text edit's document to the given \a printer. This
    is equivalent to calling the print method on the document directly except that this
    function also supports QPrinter::Selection as print range.

    \sa QTextDocument::print()
*/
#ifndef QT_NO_PRINTER
void QTextEdit::print(QPagedPaintDevice *printer) const
{
    Q_D(const QTextEdit);
    d->control->print(printer);
}
#endif

/*! \property QTextEdit::tabChangesFocus
  \brief whether \uicontrol Tab changes focus or is accepted as input

  In some occasions text edits should not allow the user to input
  tabulators or change indentation using the \uicontrol Tab key, as this breaks
  the focus chain. The default is false.

*/

bool QTextEdit::tabChangesFocus() const
{
    Q_D(const QTextEdit);
    return d->tabChangesFocus;
}

void QTextEdit::setTabChangesFocus(bool b)
{
    Q_D(QTextEdit);
    d->tabChangesFocus = b;
}

/*!
    \property QTextEdit::documentTitle
    \brief the title of the document parsed from the text.

    By default, for a newly-created, empty document, this property contains
    an empty string.
*/

/*!
    \property QTextEdit::lineWrapMode
    \brief the line wrap mode

    The default mode is WidgetWidth which causes words to be
    wrapped at the right edge of the text edit. Wrapping occurs at
    whitespace, keeping whole words intact. If you want wrapping to
    occur within words use setWordWrapMode(). If you set a wrap mode of
    FixedPixelWidth or FixedColumnWidth you should also call
    setLineWrapColumnOrWidth() with the width you want.

    \sa lineWrapColumnOrWidth
*/

QTextEdit::LineWrapMode QTextEdit::lineWrapMode() const
{
    Q_D(const QTextEdit);
    return d->lineWrap;
}

void QTextEdit::setLineWrapMode(LineWrapMode wrap)
{
    Q_D(QTextEdit);
    if (d->lineWrap == wrap)
        return;
    d->lineWrap = wrap;
    d->updateDefaultTextOption();
    d->relayoutDocument();
}

/*!
    \property QTextEdit::lineWrapColumnOrWidth
    \brief the position (in pixels or columns depending on the wrap mode) where text will be wrapped

    If the wrap mode is FixedPixelWidth, the value is the number of
    pixels from the left edge of the text edit at which text should be
    wrapped. If the wrap mode is FixedColumnWidth, the value is the
    column number (in character columns) from the left edge of the
    text edit at which text should be wrapped.

    By default, this property contains a value of 0.

    \sa lineWrapMode
*/

int QTextEdit::lineWrapColumnOrWidth() const
{
    Q_D(const QTextEdit);
    return d->lineWrapColumnOrWidth;
}

void QTextEdit::setLineWrapColumnOrWidth(int w)
{
    Q_D(QTextEdit);
    d->lineWrapColumnOrWidth = w;
    d->relayoutDocument();
}

/*!
    \property QTextEdit::wordWrapMode
    \brief the mode QTextEdit will use when wrapping text by words

    By default, this property is set to QTextOption::WrapAtWordBoundaryOrAnywhere.

    \sa QTextOption::WrapMode
*/

QTextOption::WrapMode QTextEdit::wordWrapMode() const
{
    Q_D(const QTextEdit);
    return d->wordWrap;
}

void QTextEdit::setWordWrapMode(QTextOption::WrapMode mode)
{
    Q_D(QTextEdit);
    if (mode == d->wordWrap)
        return;
    d->wordWrap = mode;
    d->updateDefaultTextOption();
}

/*!
    Finds the next occurrence of the string, \a exp, using the given
    \a options. Returns \c true if \a exp was found and changes the
    cursor to select the match; otherwise returns \c false.
*/
bool QTextEdit::find(const QString &exp, QTextDocument::FindFlags options)
{
    Q_D(QTextEdit);
    return d->control->find(exp, options);
}

/*!
    \fn bool QTextEdit::find(const QRegExp &exp, QTextDocument::FindFlags options)

    \since 5.3
    \overload

    Finds the next occurrence, matching the regular expression, \a exp, using the given
    \a options. The QTextDocument::FindCaseSensitively option is ignored for this overload,
    use QRegExp::caseSensitivity instead.

    Returns \c true if a match was found and changes the cursor to select the match;
    otherwise returns \c false.
*/
#ifndef QT_NO_REGEXP
bool QTextEdit::find(const QRegExp &exp, QTextDocument::FindFlags options)
{
    Q_D(QTextEdit);
    return d->control->find(exp, options);
}
#endif

/*!
    \fn bool QTextEdit::find(const QRegularExpression &exp, QTextDocument::FindFlags options)

    \since 5.13
    \overload

    Finds the next occurrence, matching the regular expression, \a exp, using the given
    \a options. The QTextDocument::FindCaseSensitively option is ignored for this overload,
    use QRegularExpression::CaseInsensitiveOption instead.

    Returns \c true if a match was found and changes the cursor to select the match;
    otherwise returns \c false.
*/
#if QT_CONFIG(regularexpression)
bool QTextEdit::find(const QRegularExpression &exp, QTextDocument::FindFlags options)
{
    Q_D(QTextEdit);
    return d->control->find(exp, options);
}
#endif

/*!
    \fn void QTextEdit::copyAvailable(bool yes)

    This signal is emitted when text is selected or de-selected in the
    text edit.

    When text is selected this signal will be emitted with \a yes set
    to true. If no text has been selected or if the selected text is
    de-selected this signal is emitted with \a yes set to false.

    If \a yes is true then copy() can be used to copy the selection to
    the clipboard. If \a yes is false then copy() does nothing.

    \sa selectionChanged()
*/

/*!
    \fn void QTextEdit::currentCharFormatChanged(const QTextCharFormat &f)

    This signal is emitted if the current character format has changed, for
    example caused by a change of the cursor position.

    The new format is \a f.

    \sa setCurrentCharFormat()
*/

/*!
    \fn void QTextEdit::selectionChanged()

    This signal is emitted whenever the selection changes.

    \sa copyAvailable()
*/

/*!
    \fn void QTextEdit::cursorPositionChanged()

    This signal is emitted whenever the position of the
    cursor changed.
*/

/*!
    \since 4.2

    Sets the text edit's \a text. The text can be plain text or HTML
    and the text edit will try to guess the right format.

    Use setHtml() or setPlainText() directly to avoid text edit's guessing.

    \sa toPlainText(), toHtml()
*/
void QTextEdit::setText(const QString &text)
{
    Q_D(QTextEdit);
    Qt::TextFormat format = d->textFormat;
    if (d->textFormat == Qt::AutoText)
        format = Qt::mightBeRichText(text) ? Qt::RichText : Qt::PlainText;
#ifndef QT_NO_TEXTHTMLPARSER
    if (format == Qt::RichText)
        setHtml(text);
    else
#else
    Q_UNUSED(format);
#endif
        setPlainText(text);
}


/*!
    Appends a new paragraph with \a text to the end of the text edit.

    \note The new paragraph appended will have the same character format and
    block format as the current paragraph, determined by the position of the cursor.

    \sa currentCharFormat(), QTextCursor::blockFormat()
*/

void QTextEdit::append(const QString &text)
{
    Q_D(QTextEdit);
    const bool atBottom = isReadOnly() ?  d->verticalOffset() >= d->vbar->maximum() :
            d->control->textCursor().atEnd();
    d->control->append(text);
    if (atBottom)
        d->vbar->setValue(d->vbar->maximum());
}

/*!
    Ensures that the cursor is visible by scrolling the text edit if
    necessary.
*/
void QTextEdit::ensureCursorVisible()
{
    Q_D(QTextEdit);
    d->control->ensureCursorVisible();
}

/*!
    \fn void QTextEdit::textChanged()

    This signal is emitted whenever the document's content changes; for
    example, when text is inserted or deleted, or when formatting is applied.
*/

/*!
    \fn void QTextEdit::undoAvailable(bool available)

    This signal is emitted whenever undo operations become available
    (\a available is true) or unavailable (\a available is false).
*/

/*!
    \fn void QTextEdit::redoAvailable(bool available)

    This signal is emitted whenever redo operations become available
    (\a available is true) or unavailable (\a available is false).
*/

QT_END_NAMESPACE

#include "moc_qtextedit.cpp"

 数据处理类:

/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qtextcursor.h"
#include "qtextcursor_p.h"
#include "qglobal.h"
#include "qtextdocumentfragment.h"
#include "qtextdocumentfragment_p.h"
#include "qtextlist.h"
#include "qtexttable.h"
#include "qtexttable_p.h"
#include "qtextengine_p.h"
#include "qabstracttextdocumentlayout.h"

#include <qtextlayout.h>
#include <qdebug.h>

QT_BEGIN_NAMESPACE

enum {
    AdjustPrev = 0x1,
    AdjustUp = 0x3,
    AdjustNext = 0x4,
    AdjustDown = 0x12
};

QTextCursorPrivate::QTextCursorPrivate(QTextDocumentPrivate *p)
    : priv(p), x(0), position(0), anchor(0), adjusted_anchor(0),
      currentCharFormat(-1), visualNavigation(false), keepPositionOnInsert(false),
      changed(false)
{
    priv->addCursor(this);
}

QTextCursorPrivate::QTextCursorPrivate(const QTextCursorPrivate &rhs)
    : QSharedData(rhs)
{
    position = rhs.position;
    anchor = rhs.anchor;
    adjusted_anchor = rhs.adjusted_anchor;
    priv = rhs.priv;
    x = rhs.x;
    currentCharFormat = rhs.currentCharFormat;
    visualNavigation = rhs.visualNavigation;
    keepPositionOnInsert = rhs.keepPositionOnInsert;
    changed = rhs.changed;
    if (priv != nullptr)
        priv->addCursor(this);
}

QTextCursorPrivate::~QTextCursorPrivate()
{
    if (priv)
        priv->removeCursor(this);
}

QTextCursorPrivate::AdjustResult QTextCursorPrivate::adjustPosition(int positionOfChange, int charsAddedOrRemoved, QTextUndoCommand::Operation op)
{
    QTextCursorPrivate::AdjustResult result = QTextCursorPrivate::CursorMoved;
    // not(!) <= , so that inserting text adjusts the cursor correctly
    if (position < positionOfChange
        || (position == positionOfChange
            && (op == QTextUndoCommand::KeepCursor
                || keepPositionOnInsert)
            )
         ) {
        result = CursorUnchanged;
    } else {
        if (charsAddedOrRemoved < 0 && position < positionOfChange - charsAddedOrRemoved)
            position = positionOfChange;
        else
            position += charsAddedOrRemoved;

        currentCharFormat = -1;
    }

    if (anchor >= positionOfChange
        && (anchor != positionOfChange || op != QTextUndoCommand::KeepCursor)) {
        if (charsAddedOrRemoved < 0 && anchor < positionOfChange - charsAddedOrRemoved)
            anchor = positionOfChange;
        else
            anchor += charsAddedOrRemoved;
    }

    if (adjusted_anchor >= positionOfChange
        && (adjusted_anchor != positionOfChange || op != QTextUndoCommand::KeepCursor)) {
        if (charsAddedOrRemoved < 0 && adjusted_anchor < positionOfChange - charsAddedOrRemoved)
            adjusted_anchor = positionOfChange;
        else
            adjusted_anchor += charsAddedOrRemoved;
    }

    return result;
}

void QTextCursorPrivate::setX()
{
    if (priv->isInEditBlock() || priv->inContentsChange) {
        x = -1; // mark dirty
        return;
    }

    QTextBlock block = this->block();
    const QTextLayout *layout = blockLayout(block);
    int pos = position - block.position();

    QTextLine line = layout->lineForTextPosition(pos);
    if (line.isValid())
        x = line.cursorToX(pos);
    else
        x = -1; // delayed init.  Makes movePosition() call setX later on again.
}

void QTextCursorPrivate::remove()
{
    if (anchor == position)
        return;
    currentCharFormat = -1;
    int pos1 = position;
    int pos2 = adjusted_anchor;
    QTextUndoCommand::Operation op = QTextUndoCommand::KeepCursor;
    if (pos1 > pos2) {
        pos1 = adjusted_anchor;
        pos2 = position;
        op = QTextUndoCommand::MoveCursor;
    }

    // deleting inside table? -> delete only content
    QTextTable *table = complexSelectionTable();
    if (table) {
        priv->beginEditBlock();
        int startRow, startCol, numRows, numCols;
        selectedTableCells(&startRow, &numRows, &startCol, &numCols);
        clearCells(table, startRow, startCol, numRows, numCols, op);
        adjusted_anchor = anchor = position;
        priv->endEditBlock();
    } else {
        priv->remove(pos1, pos2-pos1, op);
        adjusted_anchor = anchor = position;
    }

}

void QTextCursorPrivate::clearCells(QTextTable *table, int startRow, int startCol, int numRows, int numCols, QTextUndoCommand::Operation op)
{
    priv->beginEditBlock();

    for (int row = startRow; row < startRow + numRows; ++row)
        for (int col = startCol; col < startCol + numCols; ++col) {
            QTextTableCell cell = table->cellAt(row, col);
            const int startPos = cell.firstPosition();
            const int endPos = cell.lastPosition();
            Q_ASSERT(startPos <= endPos);
            priv->remove(startPos, endPos - startPos, op);
        }

    priv->endEditBlock();
}

bool QTextCursorPrivate::canDelete(int pos) const
{
    QTextDocumentPrivate::FragmentIterator fit = priv->find(pos);
    QTextCharFormat fmt = priv->formatCollection()->charFormat((*fit)->format);
    return (fmt.objectIndex() == -1 || fmt.objectType() == QTextFormat::ImageObject);
}

void QTextCursorPrivate::insertBlock(const QTextBlockFormat &format, const QTextCharFormat &charFormat)
{
    QTextFormatCollection *formats = priv->formatCollection();
    int idx = formats->indexForFormat(format);
    Q_ASSERT(formats->format(idx).isBlockFormat());

    priv->insertBlock(position, idx, formats->indexForFormat(charFormat));
    currentCharFormat = -1;
}

void QTextCursorPrivate::adjustCursor(QTextCursor::MoveOperation m)
{
    adjusted_anchor = anchor;
    if (position == anchor)
        return;

    QTextFrame *f_position = priv->frameAt(position);
    QTextFrame *f_anchor = priv->frameAt(adjusted_anchor);

    if (f_position != f_anchor) {
        // find common parent frame
        QList<QTextFrame *> positionChain;
        QList<QTextFrame *> anchorChain;
        QTextFrame *f = f_position;
        while (f) {
            positionChain.prepend(f);
            f = f->parentFrame();
        }
        f = f_anchor;
        while (f) {
            anchorChain.prepend(f);
            f = f->parentFrame();
        }
        Q_ASSERT(positionChain.at(0) == anchorChain.at(0));
        int i = 1;
        int l = qMin(positionChain.size(), anchorChain.size());
        for (; i < l; ++i) {
            if (positionChain.at(i) != anchorChain.at(i))
                break;
        }

        if (m <= QTextCursor::WordLeft) {
            if (i < positionChain.size())
                position = positionChain.at(i)->firstPosition() - 1;
        } else {
            if (i < positionChain.size())
                position = positionChain.at(i)->lastPosition() + 1;
        }
        if (position < adjusted_anchor) {
            if (i < anchorChain.size())
                adjusted_anchor = anchorChain.at(i)->lastPosition() + 1;
        } else {
            if (i < anchorChain.size())
                adjusted_anchor = anchorChain.at(i)->firstPosition() - 1;
        }

        f_position = positionChain.at(i-1);
    }

    // same frame, either need to adjust to cell boundaries or return
    QTextTable *table = qobject_cast<QTextTable *>(f_position);
    if (!table)
        return;

    QTextTableCell c_position = table->cellAt(position);
    QTextTableCell c_anchor = table->cellAt(adjusted_anchor);
    if (c_position != c_anchor) {
        position = c_position.firstPosition();
        if (position < adjusted_anchor)
            adjusted_anchor = c_anchor.lastPosition();
        else
            adjusted_anchor = c_anchor.firstPosition();
    }
    currentCharFormat = -1;
}

void QTextCursorPrivate::aboutToRemoveCell(int from, int to)
{
    Q_ASSERT(from <= to);
    if (position == anchor)
        return;

    QTextTable *t = qobject_cast<QTextTable *>(priv->frameAt(position));
    if (!t)
        return;
    QTextTableCell removedCellFrom = t->cellAt(from);
    QTextTableCell removedCellEnd = t->cellAt(to);
    if (! removedCellFrom.isValid() || !removedCellEnd.isValid())
        return;

    int curFrom = position;
    int curTo = adjusted_anchor;
    if (curTo < curFrom)
        qSwap(curFrom, curTo);

    QTextTableCell cellStart = t->cellAt(curFrom);
    QTextTableCell cellEnd = t->cellAt(curTo);

    if (cellStart.row() >= removedCellFrom.row() && cellEnd.row() <= removedCellEnd.row()
            && cellStart.column() >= removedCellFrom.column()
              && cellEnd.column() <= removedCellEnd.column()) { // selection is completely removed
        // find a new position, as close as possible to where we were.
        QTextTableCell cell;
        if (removedCellFrom.row() == 0 && removedCellEnd.row() == t->rows()-1) // removed n columns
            cell = t->cellAt(cellStart.row(), removedCellEnd.column()+1);
        else if (removedCellFrom.column() == 0 && removedCellEnd.column() == t->columns()-1) // removed n rows
            cell = t->cellAt(removedCellEnd.row() + 1, cellStart.column());

        int newPosition;
        if (cell.isValid())
            newPosition = cell.firstPosition();
        else
            newPosition = t->lastPosition()+1;

        setPosition(newPosition);
        anchor = newPosition;
        adjusted_anchor = newPosition;
        x = 0;
    }
    else if (cellStart.row() >= removedCellFrom.row() && cellStart.row() <= removedCellEnd.row()
        && cellEnd.row() > removedCellEnd.row()) {
        int newPosition = t->cellAt(removedCellEnd.row() + 1, cellStart.column()).firstPosition();
        if (position < anchor)
            position = newPosition;
        else
            anchor = adjusted_anchor = newPosition;
    }
    else if (cellStart.column() >= removedCellFrom.column() && cellStart.column() <= removedCellEnd.column()
        && cellEnd.column() > removedCellEnd.column()) {
        int newPosition = t->cellAt(cellStart.row(), removedCellEnd.column()+1).firstPosition();
        if (position < anchor)
            position = newPosition;
        else
            anchor = adjusted_anchor = newPosition;
    }
}

bool QTextCursorPrivate::movePosition(QTextCursor::MoveOperation op, QTextCursor::MoveMode mode)
{
    currentCharFormat = -1;
    bool adjustX = true;
    QTextBlock blockIt = block();
    bool visualMovement = priv->defaultCursorMoveStyle == Qt::VisualMoveStyle;

    if (!blockIt.isValid())
        return false;

    if (blockIt.textDirection() == Qt::RightToLeft) {
        if (op == QTextCursor::WordLeft)
            op = QTextCursor::NextWord;
        else if (op == QTextCursor::WordRight)
            op = QTextCursor::PreviousWord;

        if (!visualMovement) {
            if (op == QTextCursor::Left)
                op = QTextCursor::NextCharacter;
            else if (op == QTextCursor::Right)
                op = QTextCursor::PreviousCharacter;
        }
    }

    const QTextLayout *layout = blockLayout(blockIt);
    int relativePos = position - blockIt.position();
    QTextLine line;
    if (!priv->isInEditBlock())
        line = layout->lineForTextPosition(relativePos);

    Q_ASSERT(priv->frameAt(position) == priv->frameAt(adjusted_anchor));

    int newPosition = position;

    if (mode == QTextCursor::KeepAnchor && complexSelectionTable() != nullptr) {
        if ((op >= QTextCursor::EndOfLine && op <= QTextCursor::NextWord)
                || (op >= QTextCursor::Right && op <= QTextCursor::WordRight)) {
            QTextTable *t = qobject_cast<QTextTable *>(priv->frameAt(position));
            Q_ASSERT(t); // as we have already made sure we have a complex selection
            QTextTableCell cell_pos = t->cellAt(position);
            if (cell_pos.column() + cell_pos.columnSpan() != t->columns())
                op = QTextCursor::NextCell;
        }
    }

    if (x == -1 && !priv->isInEditBlock() && (op == QTextCursor::Up || op == QTextCursor::Down))
        setX();

    switch(op) {
    case QTextCursor::NoMove:
        return true;

    case QTextCursor::Start:
        newPosition = 0;
        break;
    case QTextCursor::StartOfLine: {
        newPosition = blockIt.position();
        if (line.isValid())
            newPosition += line.textStart();

        break;
    }
    case QTextCursor::StartOfBlock: {
        newPosition = blockIt.position();
        break;
    }
    case QTextCursor::PreviousBlock: {
        if (blockIt == priv->blocksBegin())
            return false;
        blockIt = blockIt.previous();

        newPosition = blockIt.position();
        break;
    }
    case QTextCursor::PreviousCharacter:
        if (mode == QTextCursor::MoveAnchor && position != adjusted_anchor)
            newPosition = qMin(position, adjusted_anchor);
        else
            newPosition = priv->previousCursorPosition(position, QTextLayout::SkipCharacters);
        break;
    case QTextCursor::Left:
        if (mode == QTextCursor::MoveAnchor && position != adjusted_anchor)
            newPosition = visualMovement ? qMax(position, adjusted_anchor)
                                         : qMin(position, adjusted_anchor);
        else
            newPosition = visualMovement ? priv->leftCursorPosition(position)
                                         : priv->previousCursorPosition(position, QTextLayout::SkipCharacters);
        break;
    case QTextCursor::StartOfWord: {
        if (relativePos == 0)
            break;

        // skip if already at word start
        QTextEngine *engine = layout->engine();
        const QCharAttributes *attributes = engine->attributes();
        if ((relativePos == blockIt.length() - 1)
            && (attributes[relativePos - 1].whiteSpace || engine->atWordSeparator(relativePos - 1)))
            return false;

        if (relativePos < blockIt.length()-1)
            ++position;

        Q_FALLTHROUGH();
    }
    case QTextCursor::PreviousWord:
    case QTextCursor::WordLeft:
        newPosition = priv->previousCursorPosition(position, QTextLayout::SkipWords);
        break;
    case QTextCursor::Up: {
        int i = line.lineNumber() - 1;
        if (i == -1) {
            if (blockIt == priv->blocksBegin())
                return false;
            int blockPosition = blockIt.position();
            QTextTable *table = qobject_cast<QTextTable *>(priv->frameAt(blockPosition));
            if (table) {
                QTextTableCell cell = table->cellAt(blockPosition);
                if (cell.firstPosition() == blockPosition) {
                    int row = cell.row() - 1;
                    if (row >= 0) {
                        blockPosition = table->cellAt(row, cell.column()).lastPosition();
                    } else {
                        // move to line above the table
                        blockPosition = table->firstPosition() - 1;
                    }
                    blockIt = priv->blocksFind(blockPosition);
                } else {
                    blockIt = blockIt.previous();
                }
            } else {
                blockIt = blockIt.previous();
            }
            layout = blockLayout(blockIt);
            i = layout->lineCount()-1;
        }
        if (layout->lineCount()) {
            QTextLine line = layout->lineAt(i);
            newPosition = line.xToCursor(x) + blockIt.position();
        } else {
            newPosition = blockIt.position();
        }
        adjustX = false;
        break;
    }

    case QTextCursor::End:
        newPosition = priv->length() - 1;
        break;
    case QTextCursor::EndOfLine: {
        if (!line.isValid() || line.textLength() == 0) {
            if (blockIt.length() >= 1)
                // position right before the block separator
                newPosition = blockIt.position() + blockIt.length() - 1;
            break;
        }
        newPosition = blockIt.position() + line.textStart() + line.textLength();
        if (newPosition >= priv->length())
            newPosition = priv->length() - 1;
        if (line.lineNumber() < layout->lineCount() - 1) {
            const QString text = blockIt.text();
            // ###### this relies on spaces being the cause for linebreaks.
            // this doesn't work with japanese
            if (text.at(line.textStart() + line.textLength() - 1).isSpace())
                --newPosition;
        }
        break;
    }
    case QTextCursor::EndOfWord: {
        QTextEngine *engine = layout->engine();
        const QCharAttributes *attributes = engine->attributes();
        const int len = blockIt.length() - 1;
        if (relativePos >= len)
            return false;
        if (engine->atWordSeparator(relativePos)) {
            ++relativePos;
            while (relativePos < len && engine->atWordSeparator(relativePos))
                ++relativePos;
        } else {
            while (relativePos < len && !attributes[relativePos].whiteSpace && !engine->atWordSeparator(relativePos))
                ++relativePos;
        }
        newPosition = blockIt.position() + relativePos;
        break;
    }
    case QTextCursor::EndOfBlock:
        if (blockIt.length() >= 1)
            // position right before the block separator
            newPosition = blockIt.position() + blockIt.length() - 1;
        break;
    case QTextCursor::NextBlock: {
        blockIt = blockIt.next();
        if (!blockIt.isValid())
            return false;

        newPosition = blockIt.position();
        break;
    }
    case QTextCursor::NextCharacter:
        if (mode == QTextCursor::MoveAnchor && position != adjusted_anchor)
            newPosition = qMax(position, adjusted_anchor);
        else
            newPosition = priv->nextCursorPosition(position, QTextLayout::SkipCharacters);
        break;
    case QTextCursor::Right:
        if (mode == QTextCursor::MoveAnchor && position != adjusted_anchor)
            newPosition = visualMovement ? qMin(position, adjusted_anchor)
                                         : qMax(position, adjusted_anchor);
        else
            newPosition = visualMovement ? priv->rightCursorPosition(position)
                                         : priv->nextCursorPosition(position, QTextLayout::SkipCharacters);
        break;
    case QTextCursor::NextWord:
    case QTextCursor::WordRight:
        newPosition = priv->nextCursorPosition(position, QTextLayout::SkipWords);
        break;

    case QTextCursor::Down: {
        int i = line.lineNumber() + 1;

        if (i >= layout->lineCount()) {
            int blockPosition = blockIt.position() + blockIt.length() - 1;
            QTextTable *table = qobject_cast<QTextTable *>(priv->frameAt(blockPosition));
            if (table) {
                QTextTableCell cell = table->cellAt(blockPosition);
                if (cell.lastPosition() == blockPosition) {
                    int row = cell.row() + cell.rowSpan();
                    if (row < table->rows()) {
                        blockPosition = table->cellAt(row, cell.column()).firstPosition();
                    } else {
                        // move to line below the table
                        blockPosition = table->lastPosition() + 1;
                    }
                    blockIt = priv->blocksFind(blockPosition);
                } else {
                    blockIt = blockIt.next();
                }
            } else {
                blockIt = blockIt.next();
            }

            if (blockIt == priv->blocksEnd())
                return false;
            layout = blockLayout(blockIt);
            i = 0;
        }
        if (layout->lineCount()) {
            QTextLine line = layout->lineAt(i);
            newPosition = line.xToCursor(x) + blockIt.position();
        } else {
            newPosition = blockIt.position();
        }
        adjustX = false;
        break;
    }
    case QTextCursor::NextCell:
    case QTextCursor::PreviousCell:
    case QTextCursor::NextRow:
    case QTextCursor::PreviousRow: {
        QTextTable *table = qobject_cast<QTextTable *>(priv->frameAt(position));
        if (!table)
            return false;

        QTextTableCell cell = table->cellAt(position);
        Q_ASSERT(cell.isValid());
        int column = cell.column();
        int row = cell.row();
        const int currentRow = row;
        if (op == QTextCursor::NextCell || op == QTextCursor::NextRow) {
            do {
                column += cell.columnSpan();
                if (column >= table->columns()) {
                    column = 0;
                    ++row;
                }
                cell = table->cellAt(row, column);
                // note we also continue while we have not reached a cell thats not merged with one above us
            } while (cell.isValid()
                    && ((op == QTextCursor::NextRow && currentRow == cell.row())
                        || cell.row() < row));
        }
        else if (op == QTextCursor::PreviousCell || op == QTextCursor::PreviousRow) {
            do {
                --column;
                if (column < 0) {
                    column = table->columns()-1;
                    --row;
                }
                cell = table->cellAt(row, column);
                // note we also continue while we have not reached a cell thats not merged with one above us
            } while (cell.isValid()
                    && ((op == QTextCursor::PreviousRow && currentRow == cell.row())
                        || cell.row() < row));
        }
        if (cell.isValid())
            newPosition = cell.firstPosition();
        break;
    }
    }

    if (mode == QTextCursor::KeepAnchor) {
        QTextTable *table = qobject_cast<QTextTable *>(priv->frameAt(position));
        if (table && ((op >= QTextCursor::PreviousBlock && op <= QTextCursor::WordLeft)
                      || (op >= QTextCursor::NextBlock && op <= QTextCursor::WordRight))) {
            int oldColumn = table->cellAt(position).column();

            const QTextTableCell otherCell = table->cellAt(newPosition);
            if (!otherCell.isValid())
                return false;

            int newColumn = otherCell.column();
            if ((oldColumn > newColumn && op >= QTextCursor::End)
                || (oldColumn < newColumn && op <= QTextCursor::WordLeft))
                return false;
        }
    }

    const bool moved = setPosition(newPosition);

    if (mode == QTextCursor::MoveAnchor) {
        anchor = position;
        adjusted_anchor = position;
    } else {
        adjustCursor(op);
    }

    if (adjustX)
        setX();

    return moved;
}

QTextTable *QTextCursorPrivate::complexSelectionTable() const
{
    if (position == anchor)
        return nullptr;

    QTextTable *t = qobject_cast<QTextTable *>(priv->frameAt(position));
    if (t) {
        QTextTableCell cell_pos = t->cellAt(position);
        QTextTableCell cell_anchor = t->cellAt(adjusted_anchor);

        Q_ASSERT(cell_anchor.isValid());

        if (cell_pos == cell_anchor)
            t = nullptr;
    }
    return t;
}

void QTextCursorPrivate::selectedTableCells(int *firstRow, int *numRows, int *firstColumn, int *numColumns) const
{
    *firstRow = -1;
    *firstColumn = -1;
    *numRows = -1;
    *numColumns = -1;

    if (position == anchor)
        return;

    QTextTable *t = qobject_cast<QTextTable *>(priv->frameAt(position));
    if (!t)
        return;

    QTextTableCell cell_pos = t->cellAt(position);
    QTextTableCell cell_anchor = t->cellAt(adjusted_anchor);

    Q_ASSERT(cell_anchor.isValid());

    if (cell_pos == cell_anchor)
        return;

    *firstRow = qMin(cell_pos.row(), cell_anchor.row());
    *firstColumn = qMin(cell_pos.column(), cell_anchor.column());
    *numRows = qMax(cell_pos.row() + cell_pos.rowSpan(), cell_anchor.row() + cell_anchor.rowSpan()) - *firstRow;
    *numColumns = qMax(cell_pos.column() + cell_pos.columnSpan(), cell_anchor.column() + cell_anchor.columnSpan()) - *firstColumn;
}

static void setBlockCharFormatHelper(QTextDocumentPrivate *priv, int pos1, int pos2,
                               const QTextCharFormat &format, QTextDocumentPrivate::FormatChangeMode changeMode)
{
    QTextBlock it = priv->blocksFind(pos1);
    QTextBlock end = priv->blocksFind(pos2);
    if (end.isValid())
        end = end.next();

    for (; it != end; it = it.next()) {
        priv->setCharFormat(it.position() - 1, 1, format, changeMode);
    }
}

void QTextCursorPrivate::setBlockCharFormat(const QTextCharFormat &_format,
    QTextDocumentPrivate::FormatChangeMode changeMode)
{
    priv->beginEditBlock();

    QTextCharFormat format = _format;
    format.clearProperty(QTextFormat::ObjectIndex);

    QTextTable *table = complexSelectionTable();
    if (table) {
        int row_start, col_start, num_rows, num_cols;
        selectedTableCells(&row_start, &num_rows, &col_start, &num_cols);

        Q_ASSERT(row_start != -1);
        for (int r = row_start; r < row_start + num_rows; ++r) {
            for (int c = col_start; c < col_start + num_cols; ++c) {
                QTextTableCell cell = table->cellAt(r, c);
                int rspan = cell.rowSpan();
                int cspan = cell.columnSpan();
                if (rspan != 1) {
                    int cr = cell.row();
                    if (cr != r)
                        continue;
                }
                if (cspan != 1) {
                    int cc = cell.column();
                    if (cc != c)
                        continue;
                }

                int pos1 = cell.firstPosition();
                int pos2 = cell.lastPosition();
                setBlockCharFormatHelper(priv, pos1, pos2, format, changeMode);
            }
        }
    } else {
        int pos1 = position;
        int pos2 = adjusted_anchor;
        if (pos1 > pos2) {
            pos1 = adjusted_anchor;
            pos2 = position;
        }

        setBlockCharFormatHelper(priv, pos1, pos2, format, changeMode);
    }
    priv->endEditBlock();
}


void QTextCursorPrivate::setBlockFormat(const QTextBlockFormat &format, QTextDocumentPrivate::FormatChangeMode changeMode)
{
    QTextTable *table = complexSelectionTable();
    if (table) {
        priv->beginEditBlock();
        int row_start, col_start, num_rows, num_cols;
        selectedTableCells(&row_start, &num_rows, &col_start, &num_cols);

        Q_ASSERT(row_start != -1);
        for (int r = row_start; r < row_start + num_rows; ++r) {
            for (int c = col_start; c < col_start + num_cols; ++c) {
                QTextTableCell cell = table->cellAt(r, c);
                int rspan = cell.rowSpan();
                int cspan = cell.columnSpan();
                if (rspan != 1) {
                    int cr = cell.row();
                    if (cr != r)
                        continue;
                }
                if (cspan != 1) {
                    int cc = cell.column();
                    if (cc != c)
                        continue;
                }

                int pos1 = cell.firstPosition();
                int pos2 = cell.lastPosition();
                priv->setBlockFormat(priv->blocksFind(pos1), priv->blocksFind(pos2), format, changeMode);
            }
        }
        priv->endEditBlock();
    } else {
        int pos1 = position;
        int pos2 = adjusted_anchor;
        if (pos1 > pos2) {
            pos1 = adjusted_anchor;
            pos2 = position;
        }

        priv->setBlockFormat(priv->blocksFind(pos1), priv->blocksFind(pos2), format, changeMode);
    }
}

void QTextCursorPrivate::setCharFormat(const QTextCharFormat &_format, QTextDocumentPrivate::FormatChangeMode changeMode)
{
    Q_ASSERT(position != anchor);

    QTextCharFormat format = _format;
    format.clearProperty(QTextFormat::ObjectIndex);

    QTextTable *table = complexSelectionTable();
    if (table) {
        priv->beginEditBlock();
        int row_start, col_start, num_rows, num_cols;
        selectedTableCells(&row_start, &num_rows, &col_start, &num_cols);

        Q_ASSERT(row_start != -1);
        for (int r = row_start; r < row_start + num_rows; ++r) {
            for (int c = col_start; c < col_start + num_cols; ++c) {
                QTextTableCell cell = table->cellAt(r, c);
                int rspan = cell.rowSpan();
                int cspan = cell.columnSpan();
                if (rspan != 1) {
                    int cr = cell.row();
                    if (cr != r)
                        continue;
                }
                if (cspan != 1) {
                    int cc = cell.column();
                    if (cc != c)
                        continue;
                }

                int pos1 = cell.firstPosition();
                int pos2 = cell.lastPosition();
                priv->setCharFormat(pos1, pos2-pos1, format, changeMode);
            }
        }
        priv->endEditBlock();
    } else {
        int pos1 = position;
        int pos2 = adjusted_anchor;
        if (pos1 > pos2) {
            pos1 = adjusted_anchor;
            pos2 = position;
        }

        priv->setCharFormat(pos1, pos2-pos1, format, changeMode);
    }
}


QTextLayout *QTextCursorPrivate::blockLayout(QTextBlock &block) const{
    QTextLayout *tl = block.layout();
    if (!tl->lineCount() && priv->layout())
        priv->layout()->blockBoundingRect(block);
    return tl;
}

/*!
    \class QTextCursor
    \reentrant
    \inmodule QtGui

    \brief The QTextCursor class offers an API to access and modify QTextDocuments.

    \ingroup richtext-processing
    \ingroup shared

    Text cursors are objects that are used to access and modify the
    contents and underlying structure of text documents via a
    programming interface that mimics the behavior of a cursor in a
    text editor. QTextCursor contains information about both the
    cursor's position within a QTextDocument and any selection that it
    has made.

    QTextCursor is modeled on the way a text cursor behaves in a text
    editor, providing a programmatic means of performing standard
    actions through the user interface. A document can be thought of
    as a single string of characters. The cursor's current position()
    then is always either \e between two consecutive characters in the
    string, or else \e before the very first character or \e after the
    very last character in the string.  Documents can also contain
    tables, lists, images, and other objects in addition to text but,
    from the developer's point of view, the document can be treated as
    one long string.  Some portions of that string can be considered
    to lie within particular blocks (e.g. paragraphs), or within a
    table's cell, or a list's item, or other structural elements. When
    we refer to "current character" we mean the character immediately
    \e before the cursor position() in the document. Similarly, the
    "current block" is the block that contains the cursor position().

    A QTextCursor also has an anchor() position. The text that is
    between the anchor() and the position() is the selection. If
    anchor() == position() there is no selection.

    The cursor position can be changed programmatically using
    setPosition() and movePosition(); the latter can also be used to
    select text. For selections see selectionStart(), selectionEnd(),
    hasSelection(), clearSelection(), and removeSelectedText().

    If the position() is at the start of a block, atBlockStart()
    returns \c true; and if it is at the end of a block, atBlockEnd() returns
    true. The format of the current character is returned by
    charFormat(), and the format of the current block is returned by
    blockFormat().

    Formatting can be applied to the current text document using the
    setCharFormat(), mergeCharFormat(), setBlockFormat() and
    mergeBlockFormat() functions. The 'set' functions will replace the
    cursor's current character or block format, while the 'merge'
    functions add the given format properties to the cursor's current
    format. If the cursor has a selection, the given format is applied
    to the current selection. Note that when only a part of a block is
    selected, the block format is applied to the entire block. The text
    at the current character position can be turned into a list using
    createList().

    Deletions can be achieved using deleteChar(),
    deletePreviousChar(), and removeSelectedText().

    Text strings can be inserted into the document with the insertText()
    function, blocks (representing new paragraphs) can be inserted with
    insertBlock().

    Existing fragments of text can be inserted with insertFragment() but,
    if you want to insert pieces of text in various formats, it is usually
    still easier to use insertText() and supply a character format.

    Various types of higher-level structure can also be inserted into the
    document with the cursor:

    \list
    \li Lists are ordered sequences of block elements that are decorated with
       bullet points or symbols. These are inserted in a specified format
       with insertList().
    \li Tables are inserted with the insertTable() function, and can be
       given an optional format. These contain an array of cells that can
       be traversed using the cursor.
    \li Inline images are inserted with insertImage(). The image to be
       used can be specified in an image format, or by name.
    \li Frames are inserted by calling insertFrame() with a specified format.
    \endlist

    Actions can be grouped (i.e. treated as a single action for
    undo/redo) using beginEditBlock() and endEditBlock().

    Cursor movements are limited to valid cursor positions. In Latin
    writing this is between any two consecutive characters in the
    text, before the first character, or after the last character. In
    some other writing systems cursor movements are limited to
    "clusters" (e.g. a syllable in Devanagari, or a base letter plus
    diacritics).  Functions such as movePosition() and deleteChar()
    limit cursor movement to these valid positions.

    \sa {Rich Text Processing}

*/

/*!
    \enum QTextCursor::MoveOperation

    \value NoMove Keep the cursor where it is

    \value Start Move to the start of the document.
    \value StartOfLine Move to the start of the current line.
    \value StartOfBlock Move to the start of the current block.
    \value StartOfWord Move to the start of the current word.
    \value PreviousBlock Move to the start of the previous block.
    \value PreviousCharacter Move to the previous character.
    \value PreviousWord Move to the beginning of the previous word.
    \value Up Move up one line.
    \value Left Move left one character.
    \value WordLeft Move left one word.

    \value End Move to the end of the document.
    \value EndOfLine Move to the end of the current line.
    \value EndOfWord Move to the end of the current word.
    \value EndOfBlock Move to the end of the current block.
    \value NextBlock Move to the beginning of the next block.
    \value NextCharacter Move to the next character.
    \value NextWord Move to the next word.
    \value Down Move down one line.
    \value Right Move right one character.
    \value WordRight Move right one word.

    \value NextCell  Move to the beginning of the next table cell inside the
           current table. If the current cell is the last cell in the row, the
           cursor will move to the first cell in the next row.
    \value PreviousCell  Move to the beginning of the previous table cell
           inside the current table. If the current cell is the first cell in
           the row, the cursor will move to the last cell in the previous row.
    \value NextRow  Move to the first new cell of the next row in the current
           table.
    \value PreviousRow  Move to the last cell of the previous row in the
           current table.

    \sa movePosition()
*/

/*!
    \enum QTextCursor::MoveMode

    \value MoveAnchor Moves the anchor to the same position as the cursor itself.
    \value KeepAnchor Keeps the anchor where it is.

    If the anchor() is kept where it is and the position() is moved,
    the text in between will be selected.
*/

/*!
    \enum QTextCursor::SelectionType

    This enum describes the types of selection that can be applied with the
    select() function.

    \value Document         Selects the entire document.
    \value BlockUnderCursor Selects the block of text under the cursor.
    \value LineUnderCursor  Selects the line of text under the cursor.
    \value WordUnderCursor  Selects the word under the cursor. If the cursor
           is not positioned within a string of selectable characters, no
           text is selected.
*/

/*!
    Constructs a null cursor.
 */
QTextCursor::QTextCursor()
    : d(nullptr)
{
}

/*!
    Constructs a cursor pointing to the beginning of the \a document.
 */
QTextCursor::QTextCursor(QTextDocument *document)
    : d(new QTextCursorPrivate(document->docHandle()))
{
}

/*!
    Constructs a cursor pointing to the beginning of the \a frame.
*/
QTextCursor::QTextCursor(QTextFrame *frame)
    : d(new QTextCursorPrivate(frame->document()->docHandle()))
{
    d->adjusted_anchor = d->anchor = d->position = frame->firstPosition();
}


/*!
    Constructs a cursor pointing to the beginning of the \a block.
*/
QTextCursor::QTextCursor(const QTextBlock &block)
    : d(new QTextCursorPrivate(block.docHandle()))
{
    d->adjusted_anchor = d->anchor = d->position = block.position();
}


/*!
  \internal
 */
QTextCursor::QTextCursor(QTextDocumentPrivate *p, int pos)
    : d(new QTextCursorPrivate(p))
{
    d->adjusted_anchor = d->anchor = d->position = pos;

    d->setX();
}

/*!
    \internal
*/
QTextCursor::QTextCursor(QTextCursorPrivate *d)
{
    Q_ASSERT(d);
    this->d = d;
}

/*!
    Constructs a new cursor that is a copy of \a cursor.
 */
QTextCursor::QTextCursor(const QTextCursor &cursor)
{
    d = cursor.d;
}

/*!
    Makes a copy of \a cursor and assigns it to this QTextCursor. Note
    that QTextCursor is an \l{Implicitly Shared Classes}{implicitly
    shared} class.

 */
QTextCursor &QTextCursor::operator=(const QTextCursor &cursor)
{
    d = cursor.d;
    return *this;
}

/*!
    \fn void QTextCursor::swap(QTextCursor &other)
    \since 5.0

    Swaps this text cursor instance with \a other. This function is
    very fast and never fails.
*/

/*!
    Destroys the QTextCursor.
 */
QTextCursor::~QTextCursor()
{
}

/*!
    Returns \c true if the cursor is null; otherwise returns \c false. A null
    cursor is created by the default constructor.
 */
bool QTextCursor::isNull() const
{
    return !d || !d->priv;
}

/*!
    Moves the cursor to the absolute position in the document specified by
    \a pos using a \c MoveMode specified by \a m. The cursor is positioned
    between characters.

    \note The "characters" in this case refer to the string of QChar
    objects, i.e. 16-bit Unicode characters, and \a pos is considered
    an index into this string. This does not necessarily correspond to
    individual graphemes in the writing system, as a single grapheme may
    be represented by multiple Unicode characters, such as in the case
    of surrogate pairs, linguistic ligatures or diacritics. For a more
    generic approach to navigating the document, use movePosition(),
    which will respect the actual grapheme boundaries in the text.

    \sa position(), movePosition(), anchor()
*/
void QTextCursor::setPosition(int pos, MoveMode m)
{
    if (!d || !d->priv)
        return;

    if (pos < 0 || pos >= d->priv->length()) {
        qWarning("QTextCursor::setPosition: Position '%d' out of range", pos);
        return;
    }

    d->setPosition(pos);
    if (m == MoveAnchor) {
        d->anchor = pos;
        d->adjusted_anchor = pos;
    } else { // keep anchor
        QTextCursor::MoveOperation op;
        if (pos < d->anchor)
            op = QTextCursor::Left;
        else
            op = QTextCursor::Right;
        d->adjustCursor(op);
    }
    d->setX();
}

/*!
    Returns the absolute position of the cursor within the document.
    The cursor is positioned between characters.

    \note The "characters" in this case refer to the string of QChar
    objects, i.e. 16-bit Unicode characters, and the position is considered
    an index into this string. This does not necessarily correspond to
    individual graphemes in the writing system, as a single grapheme may
    be represented by multiple Unicode characters, such as in the case
    of surrogate pairs, linguistic ligatures or diacritics.

    \sa setPosition(), movePosition(), anchor(), positionInBlock()
*/
int QTextCursor::position() const
{
    if (!d || !d->priv)
        return -1;
    return d->position;
}

/*!
    \since 4.7
    Returns the relative position of the cursor within the block.
    The cursor is positioned between characters.

    This is equivalent to \c{ position() - block().position()}.

    \note The "characters" in this case refer to the string of QChar
    objects, i.e. 16-bit Unicode characters, and the position is considered
    an index into this string. This does not necessarily correspond to
    individual graphemes in the writing system, as a single grapheme may
    be represented by multiple Unicode characters, such as in the case
    of surrogate pairs, linguistic ligatures or diacritics.

    \sa position()
*/
int QTextCursor::positionInBlock() const
{
    if (!d || !d->priv)
        return 0;
    return d->position - d->block().position();
}

/*!
    Returns the anchor position; this is the same as position() unless
    there is a selection in which case position() marks one end of the
    selection and anchor() marks the other end. Just like the cursor
    position, the anchor position is between characters.

    \sa position(), setPosition(), movePosition(), selectionStart(), selectionEnd()
*/
int QTextCursor::anchor() const
{
    if (!d || !d->priv)
        return -1;
    return d->anchor;
}

/*!
    \fn bool QTextCursor::movePosition(MoveOperation operation, MoveMode mode, int n)

    Moves the cursor by performing the given \a operation \a n times, using the specified
    \a mode, and returns \c true if all operations were completed successfully; otherwise
    returns \c false.

    For example, if this function is repeatedly used to seek to the end of the next
    word, it will eventually fail when the end of the document is reached.

    By default, the move operation is performed once (\a n = 1).

    If \a mode is \c KeepAnchor, the cursor selects the text it moves
    over. This is the same effect that the user achieves when they
    hold down the Shift key and move the cursor with the cursor keys.

    \sa setVisualNavigation()
*/
bool QTextCursor::movePosition(MoveOperation op, MoveMode mode, int n)
{
    if (!d || !d->priv)
        return false;
    switch (op) {
    case Start:
    case StartOfLine:
    case End:
    case EndOfLine:
        n = 1;
        break;
    default: break;
    }

    int previousPosition = d->position;
    for (; n > 0; --n) {
        if (!d->movePosition(op, mode))
            return false;
    }

    if (d->visualNavigation && !d->block().isVisible()) {
        QTextBlock b = d->block();
        if (previousPosition < d->position) {
            while (!b.next().isVisible())
                b = b.next();
            d->setPosition(b.position() + b.length() - 1);
        } else {
            while (!b.previous().isVisible())
                b = b.previous();
            d->setPosition(b.position());
        }
        if (mode == QTextCursor::MoveAnchor)
            d->anchor = d->position;
        while (d->movePosition(op, mode)
               && !d->block().isVisible())
            ;

    }
    return true;
}

/*!
  \since 4.4

  Returns \c true if the cursor does visual navigation; otherwise
  returns \c false.

  Visual navigation means skipping over hidden text paragraphs. The
  default is false.

  \sa setVisualNavigation(), movePosition()
 */
bool QTextCursor::visualNavigation() const
{
    return d ? d->visualNavigation : false;
}

/*!
  \since 4.4

  Sets visual navigation to \a b.

  Visual navigation means skipping over hidden text paragraphs. The
  default is false.

  \sa visualNavigation(), movePosition()
 */
void QTextCursor::setVisualNavigation(bool b)
{
    if (d)
        d->visualNavigation = b;
}


/*!
  \since 4.7

  Sets the visual x position for vertical cursor movements to \a x.

  The vertical movement x position is cleared automatically when the cursor moves horizontally, and kept
  unchanged when the cursor moves vertically. The mechanism allows the cursor to move up and down on a
  visually straight line with proportional fonts, and to gently "jump" over short lines.

  A value of -1 indicates no predefined x position. It will then be set automatically the next time the
  cursor moves up or down.

  \sa verticalMovementX()
  */
void QTextCursor::setVerticalMovementX(int x)
{
    if (d)
        d->x = x;
}

/*! \since 4.7

  Returns the visual x position for vertical cursor movements.

  A value of -1 indicates no predefined x position. It will then be set automatically the next time the
  cursor moves up or down.

  \sa setVerticalMovementX()
  */
int QTextCursor::verticalMovementX() const
{
    return d ? d->x : -1;
}

/*!
  \since 4.7

  Returns whether the cursor should keep its current position when text gets inserted at the position of the
  cursor.

  The default is false;

  \sa setKeepPositionOnInsert()
 */
bool QTextCursor::keepPositionOnInsert() const
{
    return d ? d->keepPositionOnInsert : false;
}

/*!
  \since 4.7

  Defines whether the cursor should keep its current position when text gets inserted at the current position of the
  cursor.

  If \a b is true, the cursor keeps its current position when text gets inserted at the positing of the cursor.
  If \a b is false, the cursor moves along with the inserted text.

  The default is false.

  Note that a cursor always moves when text is inserted before the current position of the cursor, and it
  always keeps its position when text is inserted after the current position of the cursor.

  \sa keepPositionOnInsert()
 */
void QTextCursor::setKeepPositionOnInsert(bool b)
{
    if (d)
        d->keepPositionOnInsert = b;
}



/*!
    Inserts \a text at the current position, using the current
    character format.

    If there is a selection, the selection is deleted and replaced by
    \a text, for example:
    \snippet code/src_gui_text_qtextcursor.cpp 0
    This clears any existing selection, selects the word at the cursor
    (i.e. from position() forward), and replaces the selection with
    the phrase "Hello World".

    Any ASCII linefeed characters (\\n) in the inserted text are transformed
    into unicode block separators, corresponding to insertBlock() calls.

    \sa charFormat(), hasSelection()
*/
void QTextCursor::insertText(const QString &text)
{
    QTextCharFormat fmt = charFormat();
    fmt.clearProperty(QTextFormat::ObjectType);
    insertText(text, fmt);
}

/*!
    \fn void QTextCursor::insertText(const QString &text, const QTextCharFormat &format)
    \overload

    Inserts \a text at the current position with the given \a format.
*/
void QTextCursor::insertText(const QString &text, const QTextCharFormat &_format)
{
    if (!d || !d->priv)
        return;

    Q_ASSERT(_format.isValid());

    QTextCharFormat format = _format;
    format.clearProperty(QTextFormat::ObjectIndex);

    bool hasEditBlock = false;

    if (d->anchor != d->position) {
        hasEditBlock = true;
        d->priv->beginEditBlock();
        d->remove();
    }

    if (!text.isEmpty()) {
        QTextFormatCollection *formats = d->priv->formatCollection();
        int formatIdx = formats->indexForFormat(format);
        Q_ASSERT(formats->format(formatIdx).isCharFormat());

        QTextBlockFormat blockFmt = blockFormat();


        int textStart = d->priv->text.length();
        int blockStart = 0;
        d->priv->text += text;
        int textEnd = d->priv->text.length();

        for (int i = 0; i < text.length(); ++i) {
            QChar ch = text.at(i);

            const int blockEnd = i;

            if (ch == QLatin1Char('\r')
                && (i + 1) < text.length()
                && text.at(i + 1) == QLatin1Char('\n')) {
                ++i;
                ch = text.at(i);
            }

            if (ch == QLatin1Char('\n')
                || ch == QChar::ParagraphSeparator
                || ch == QTextBeginningOfFrame
                || ch == QTextEndOfFrame
                || ch == QLatin1Char('\r')) {

                if (!hasEditBlock) {
                    hasEditBlock = true;
                    d->priv->beginEditBlock();
                }

                if (blockEnd > blockStart)
                    d->priv->insert(d->position, textStart + blockStart, blockEnd - blockStart, formatIdx);

                d->insertBlock(blockFmt, format);
                blockStart = i + 1;
            }
        }
        if (textStart + blockStart < textEnd)
            d->priv->insert(d->position, textStart + blockStart, textEnd - textStart - blockStart, formatIdx);
    }
    if (hasEditBlock)
        d->priv->endEditBlock();
    d->setX();
}

/*!
    If there is no selected text, deletes the character \e at the
    current cursor position; otherwise deletes the selected text.

    \sa deletePreviousChar(), hasSelection(), clearSelection()
*/
void QTextCursor::deleteChar()
{
    if (!d || !d->priv)
        return;

    if (d->position != d->anchor) {
        removeSelectedText();
        return;
    }

    if (!d->canDelete(d->position))
        return;
    d->adjusted_anchor = d->anchor =
                         d->priv->nextCursorPosition(d->anchor, QTextLayout::SkipCharacters);
    d->remove();
    d->setX();
}

/*!
    If there is no selected text, deletes the character \e before the
    current cursor position; otherwise deletes the selected text.

    \sa deleteChar(), hasSelection(), clearSelection()
*/
void QTextCursor::deletePreviousChar()
{
    if (!d || !d->priv)
        return;

    if (d->position != d->anchor) {
        removeSelectedText();
        return;
    }

    if (d->anchor < 1 || !d->canDelete(d->anchor-1))
        return;
    d->anchor--;

    QTextDocumentPrivate::FragmentIterator fragIt = d->priv->find(d->anchor);
    const QTextFragmentData * const frag = fragIt.value();
    int fpos = fragIt.position();
    QChar uc = d->priv->buffer().at(d->anchor - fpos + frag->stringPosition);
    if (d->anchor > fpos && uc.isLowSurrogate()) {
        // second half of a surrogate, check if we have the first half as well,
        // if yes delete both at once
        uc = d->priv->buffer().at(d->anchor - 1 - fpos + frag->stringPosition);
        if (uc.isHighSurrogate())
            --d->anchor;
    }

    d->adjusted_anchor = d->anchor;
    d->remove();
    d->setX();
}

/*!
    Selects text in the document according to the given \a selection.
*/
void QTextCursor::select(SelectionType selection)
{
    if (!d || !d->priv)
        return;

    clearSelection();

    const QTextBlock block = d->block();

    switch (selection) {
        case LineUnderCursor:
            movePosition(StartOfLine);
            movePosition(EndOfLine, KeepAnchor);
            break;
        case WordUnderCursor:
            movePosition(StartOfWord);
            movePosition(EndOfWord, KeepAnchor);
            break;
        case BlockUnderCursor:
            if (block.length() == 1) // no content
                break;
            movePosition(StartOfBlock);
            // also select the paragraph separator
            if (movePosition(PreviousBlock)) {
                movePosition(EndOfBlock);
                movePosition(NextBlock, KeepAnchor);
            }
            movePosition(EndOfBlock, KeepAnchor);
            break;
        case Document:
            movePosition(Start);
            movePosition(End, KeepAnchor);
            break;
    }
}

/*!
    Returns \c true if the cursor contains a selection; otherwise returns \c false.
*/
bool QTextCursor::hasSelection() const
{
    return !!d && d->position != d->anchor;
}


/*!
    Returns \c true if the cursor contains a selection that is not simply a
    range from selectionStart() to selectionEnd(); otherwise returns \c false.

    Complex selections are ones that span at least two cells in a table;
    their extent is specified by selectedTableCells().
*/
bool QTextCursor::hasComplexSelection() const
{
    if (!d)
        return false;

    return d->complexSelectionTable() != nullptr;
}

/*!
    If the selection spans over table cells, \a firstRow is populated
    with the number of the first row in the selection, \a firstColumn
    with the number of the first column in the selection, and \a
    numRows and \a numColumns with the number of rows and columns in
    the selection. If the selection does not span any table cells the
    results are harmless but undefined.
*/
void QTextCursor::selectedTableCells(int *firstRow, int *numRows, int *firstColumn, int *numColumns) const
{
    *firstRow = -1;
    *firstColumn = -1;
    *numRows = -1;
    *numColumns = -1;

    if (!d || d->position == d->anchor)
        return;

    d->selectedTableCells(firstRow, numRows, firstColumn, numColumns);
}


/*!
    Clears the current selection by setting the anchor to the cursor position.

    Note that it does \b{not} delete the text of the selection.

    \sa removeSelectedText(), hasSelection()
*/
void QTextCursor::clearSelection()
{
    if (!d)
        return;
    d->adjusted_anchor = d->anchor = d->position;
    d->currentCharFormat = -1;
}

/*!
    If there is a selection, its content is deleted; otherwise does
    nothing.

    \sa hasSelection()
*/
void QTextCursor::removeSelectedText()
{
    if (!d || !d->priv || d->position == d->anchor)
        return;

    d->priv->beginEditBlock();
    d->remove();
    d->priv->endEditBlock();
    d->setX();
}

/*!
    Returns the start of the selection or position() if the
    cursor doesn't have a selection.

    \sa selectionEnd(), position(), anchor()
*/
int QTextCursor::selectionStart() const
{
    if (!d || !d->priv)
        return -1;
    return qMin(d->position, d->adjusted_anchor);
}

/*!
    Returns the end of the selection or position() if the cursor
    doesn't have a selection.

    \sa selectionStart(), position(), anchor()
*/
int QTextCursor::selectionEnd() const
{
    if (!d || !d->priv)
        return -1;
    return qMax(d->position, d->adjusted_anchor);
}

static void getText(QString &text, QTextDocumentPrivate *priv, const QString &docText, int pos, int end)
{
    while (pos < end) {
        QTextDocumentPrivate::FragmentIterator fragIt = priv->find(pos);
        const QTextFragmentData * const frag = fragIt.value();

        const int offsetInFragment = qMax(0, pos - fragIt.position());
        const int len = qMin(int(frag->size_array[0] - offsetInFragment), end - pos);

        text += QString(docText.constData() + frag->stringPosition + offsetInFragment, len);
        pos += len;
    }
}

/*!
    Returns the current selection's text (which may be empty). This
    only returns the text, with no rich text formatting information.
    If you want a document fragment (i.e. formatted rich text) use
    selection() instead.

    \note If the selection obtained from an editor spans a line break,
    the text will contain a Unicode U+2029 paragraph separator character
    instead of a newline \c{\n} character. Use QString::replace() to
    replace these characters with newlines.
*/
QString QTextCursor::selectedText() const
{
    if (!d || !d->priv || d->position == d->anchor)
        return QString();

    const QString docText = d->priv->buffer();
    QString text;

    QTextTable *table = d->complexSelectionTable();
    if (table) {
        int row_start, col_start, num_rows, num_cols;
        selectedTableCells(&row_start, &num_rows, &col_start, &num_cols);

        Q_ASSERT(row_start != -1);
        for (int r = row_start; r < row_start + num_rows; ++r) {
            for (int c = col_start; c < col_start + num_cols; ++c) {
                QTextTableCell cell = table->cellAt(r, c);
                int rspan = cell.rowSpan();
                int cspan = cell.columnSpan();
                if (rspan != 1) {
                    int cr = cell.row();
                    if (cr != r)
                        continue;
                }
                if (cspan != 1) {
                    int cc = cell.column();
                    if (cc != c)
                        continue;
                }

                getText(text, d->priv, docText, cell.firstPosition(), cell.lastPosition());
            }
        }
    } else {
        getText(text, d->priv, docText, selectionStart(), selectionEnd());
    }

    return text;
}

/*!
    Returns the current selection (which may be empty) with all its
    formatting information. If you just want the selected text (i.e.
    plain text) use selectedText() instead.

    \note Unlike QTextDocumentFragment::toPlainText(),
    selectedText() may include special unicode characters such as
    QChar::ParagraphSeparator.

    \sa QTextDocumentFragment::toPlainText()
*/
QTextDocumentFragment QTextCursor::selection() const
{
    return QTextDocumentFragment(*this);
}

/*!
    Returns the block that contains the cursor.
*/
QTextBlock QTextCursor::block() const
{
    if (!d || !d->priv)
        return QTextBlock();
    return d->block();
}

/*!
    Returns the block format of the block the cursor is in.

    \sa setBlockFormat(), charFormat()
 */
QTextBlockFormat QTextCursor::blockFormat() const
{
    if (!d || !d->priv)
        return QTextBlockFormat();

    return d->block().blockFormat();
}

/*!
    Sets the block format of the current block (or all blocks that
    are contained in the selection) to \a format.

    \sa blockFormat(), mergeBlockFormat()
*/
void QTextCursor::setBlockFormat(const QTextBlockFormat &format)
{
    if (!d || !d->priv)
        return;

    d->setBlockFormat(format, QTextDocumentPrivate::SetFormat);
}

/*!
    Modifies the block format of the current block (or all blocks that
    are contained in the selection) with the block format specified by
    \a modifier.

    \sa setBlockFormat(), blockFormat()
*/
void QTextCursor::mergeBlockFormat(const QTextBlockFormat &modifier)
{
    if (!d || !d->priv)
        return;

    d->setBlockFormat(modifier, QTextDocumentPrivate::MergeFormat);
}

/*!
    Returns the block character format of the block the cursor is in.

    The block char format is the format used when inserting text at the
    beginning of an empty block.

    \sa setBlockCharFormat()
 */
QTextCharFormat QTextCursor::blockCharFormat() const
{
    if (!d || !d->priv)
        return QTextCharFormat();

    return d->block().charFormat();
}

/*!
    Sets the block char format of the current block (or all blocks that
    are contained in the selection) to \a format.

    \sa blockCharFormat()
*/
void QTextCursor::setBlockCharFormat(const QTextCharFormat &format)
{
    if (!d || !d->priv)
        return;

    d->setBlockCharFormat(format, QTextDocumentPrivate::SetFormatAndPreserveObjectIndices);
}

/*!
    Modifies the block char format of the current block (or all blocks that
    are contained in the selection) with the block format specified by
    \a modifier.

    \sa setBlockCharFormat()
*/
void QTextCursor::mergeBlockCharFormat(const QTextCharFormat &modifier)
{
    if (!d || !d->priv)
        return;

    d->setBlockCharFormat(modifier, QTextDocumentPrivate::MergeFormat);
}

/*!
    Returns the format of the character immediately before the cursor
    position(). If the cursor is positioned at the beginning of a text
    block that is not empty then the format of the character
    immediately after the cursor is returned.

    \sa insertText(), blockFormat()
 */
QTextCharFormat QTextCursor::charFormat() const
{
    if (!d || !d->priv)
        return QTextCharFormat();

    int idx = d->currentCharFormat;
    if (idx == -1) {
        QTextBlock block = d->block();

        int pos;
        if (d->position == block.position()
            && block.length() > 1)
            pos = d->position;
        else
            pos = d->position - 1;

        if (pos == -1) {
            idx = d->priv->blockCharFormatIndex(d->priv->blockMap().firstNode());
        } else {
            Q_ASSERT(pos >= 0 && pos < d->priv->length());

            QTextDocumentPrivate::FragmentIterator it = d->priv->find(pos);
            Q_ASSERT(!it.atEnd());
            idx = it.value()->format;
        }
    }

    QTextCharFormat cfmt = d->priv->formatCollection()->charFormat(idx);
    cfmt.clearProperty(QTextFormat::ObjectIndex);

    Q_ASSERT(cfmt.isValid());
    return cfmt;
}

/*!
    Sets the cursor's current character format to the given \a
    format. If the cursor has a selection, the given \a format is
    applied to the current selection.

    \sa hasSelection(), mergeCharFormat()
*/
void QTextCursor::setCharFormat(const QTextCharFormat &format)
{
    if (!d || !d->priv)
        return;
    if (d->position == d->anchor) {
        d->currentCharFormat = d->priv->formatCollection()->indexForFormat(format);
        return;
    }
    d->setCharFormat(format, QTextDocumentPrivate::SetFormatAndPreserveObjectIndices);
}

/*!
    Merges the cursor's current character format with the properties
    described by format \a modifier. If the cursor has a selection,
    this function applies all the properties set in \a modifier to all
    the character formats that are part of the selection.

    \sa hasSelection(), setCharFormat()
*/
void QTextCursor::mergeCharFormat(const QTextCharFormat &modifier)
{
    if (!d || !d->priv)
        return;
    if (d->position == d->anchor) {
        QTextCharFormat format = charFormat();
        format.merge(modifier);
        d->currentCharFormat = d->priv->formatCollection()->indexForFormat(format);
        return;
    }

    d->setCharFormat(modifier, QTextDocumentPrivate::MergeFormat);
}

/*!
    Returns \c true if the cursor is at the start of a block; otherwise
    returns \c false.

    \sa atBlockEnd(), atStart()
*/
bool QTextCursor::atBlockStart() const
{
    if (!d || !d->priv)
        return false;

    return d->position == d->block().position();
}

/*!
    Returns \c true if the cursor is at the end of a block; otherwise
    returns \c false.

    \sa atBlockStart(), atEnd()
*/
bool QTextCursor::atBlockEnd() const
{
    if (!d || !d->priv)
        return false;

    return d->position == d->block().position() + d->block().length() - 1;
}

/*!
    Returns \c true if the cursor is at the start of the document;
    otherwise returns \c false.

    \sa atBlockStart(), atEnd()
*/
bool QTextCursor::atStart() const
{
    if (!d || !d->priv)
        return false;

    return d->position == 0;
}

/*!
    \since 4.6

    Returns \c true if the cursor is at the end of the document;
    otherwise returns \c false.

    \sa atStart(), atBlockEnd()
*/
bool QTextCursor::atEnd() const
{
    if (!d || !d->priv)
        return false;

    return d->position == d->priv->length() - 1;
}

/*!
    Inserts a new empty block at the cursor position() with the
    current blockFormat() and charFormat().

    \sa setBlockFormat()
*/
void QTextCursor::insertBlock()
{
    insertBlock(blockFormat());
}

/*!
    \overload

    Inserts a new empty block at the cursor position() with block
    format \a format and the current charFormat() as block char format.

    \sa setBlockFormat()
*/
void QTextCursor::insertBlock(const QTextBlockFormat &format)
{
    QTextCharFormat charFmt = charFormat();
    charFmt.clearProperty(QTextFormat::ObjectType);
    insertBlock(format, charFmt);
}

/*!
    \fn void QTextCursor::insertBlock(const QTextBlockFormat &format, const QTextCharFormat &charFormat)
    \overload

    Inserts a new empty block at the cursor position() with block
    format \a format and \a charFormat as block char format.

    \sa setBlockFormat()
*/
void QTextCursor::insertBlock(const QTextBlockFormat &format, const QTextCharFormat &_charFormat)
{
    if (!d || !d->priv)
        return;

    QTextCharFormat charFormat = _charFormat;
    charFormat.clearProperty(QTextFormat::ObjectIndex);

    d->priv->beginEditBlock();
    d->remove();
    d->insertBlock(format, charFormat);
    d->priv->endEditBlock();
    d->setX();
}

/*!
    Inserts a new block at the current position and makes it the first
    list item of a newly created list with the given \a format. Returns
    the created list.

    \sa currentList(), createList(), insertBlock()
 */
QTextList *QTextCursor::insertList(const QTextListFormat &format)
{
    insertBlock();
    return createList(format);
}

/*!
    \overload

    Inserts a new block at the current position and makes it the first
    list item of a newly created list with the given \a style. Returns
    the created list.

    \sa currentList(), createList(), insertBlock()
 */
QTextList *QTextCursor::insertList(QTextListFormat::Style style)
{
    insertBlock();
    return createList(style);
}

/*!
    Creates and returns a new list with the given \a format, and makes the
    current paragraph the cursor is in the first list item.

    \sa insertList(), currentList()
 */
QTextList *QTextCursor::createList(const QTextListFormat &format)
{
    if (!d || !d->priv)
        return nullptr;

    QTextList *list = static_cast<QTextList *>(d->priv->createObject(format));
    QTextBlockFormat modifier;
    modifier.setObjectIndex(list->objectIndex());
    mergeBlockFormat(modifier);
    return list;
}

/*!
    \overload

    Creates and returns a new list with the given \a style, making the
    cursor's current paragraph the first list item.

    The style to be used is defined by the QTextListFormat::Style enum.

    \sa insertList(), currentList()
 */
QTextList *QTextCursor::createList(QTextListFormat::Style style)
{
    QTextListFormat fmt;
    fmt.setStyle(style);
    return createList(fmt);
}

/*!
    Returns the current list if the cursor position() is inside a
    block that is part of a list; otherwise returns \nullptr.

    \sa insertList(), createList()
 */
QTextList *QTextCursor::currentList() const
{
    if (!d || !d->priv)
        return nullptr;

    QTextBlockFormat b = blockFormat();
    QTextObject *o = d->priv->objectForFormat(b);
    return qobject_cast<QTextList *>(o);
}

/*!
    \fn QTextTable *QTextCursor::insertTable(int rows, int columns)

    \overload

    Creates a new table with the given number of \a rows and \a columns,
    inserts it at the current cursor position() in the document, and returns
    the table object. The cursor is moved to the beginning of the first cell.

    There must be at least one row and one column in the table.

    \sa currentTable()
 */
QTextTable *QTextCursor::insertTable(int rows, int cols)
{
    return insertTable(rows, cols, QTextTableFormat());
}

/*!
    \fn QTextTable *QTextCursor::insertTable(int rows, int columns, const QTextTableFormat &format)

    Creates a new table with the given number of \a rows and \a columns
    in the specified \a format, inserts it at the current cursor position()
    in the document, and returns the table object. The cursor is moved to
    the beginning of the first cell.

    There must be at least one row and one column in the table.

    \sa currentTable()
*/
QTextTable *QTextCursor::insertTable(int rows, int cols, const QTextTableFormat &format)
{
    if(!d || !d->priv || rows == 0 || cols == 0)
        return nullptr;

    int pos = d->position;
    QTextTable *t = QTextTablePrivate::createTable(d->priv, d->position, rows, cols, format);
    d->setPosition(pos+1);
    // ##### what should we do if we have a selection?
    d->anchor = d->position;
    d->adjusted_anchor = d->anchor;
    return t;
}

/*!
    Returns a pointer to the current table if the cursor position()
    is inside a block that is part of a table; otherwise returns \nullptr.

    \sa insertTable()
*/
QTextTable *QTextCursor::currentTable() const
{
    if(!d || !d->priv)
        return nullptr;

    QTextFrame *frame = d->priv->frameAt(d->position);
    while (frame) {
        QTextTable *table = qobject_cast<QTextTable *>(frame);
        if (table)
            return table;
        frame = frame->parentFrame();
    }
    return nullptr;
}

/*!
    Inserts a frame with the given \a format at the current cursor position(),
    moves the cursor position() inside the frame, and returns the frame.

    If the cursor holds a selection, the whole selection is moved inside the
    frame.

    \sa hasSelection()
*/
QTextFrame *QTextCursor::insertFrame(const QTextFrameFormat &format)
{
    if (!d || !d->priv)
        return nullptr;

    return d->priv->insertFrame(selectionStart(), selectionEnd(), format);
}

/*!
    Returns a pointer to the current frame. Returns \nullptr if the cursor is invalid.

    \sa insertFrame()
*/
QTextFrame *QTextCursor::currentFrame() const
{
    if(!d || !d->priv)
        return nullptr;

    return d->priv->frameAt(d->position);
}


/*!
    Inserts the text \a fragment at the current position().
*/
void QTextCursor::insertFragment(const QTextDocumentFragment &fragment)
{
    if (!d || !d->priv || fragment.isEmpty())
        return;

    d->priv->beginEditBlock();
    d->remove();
    fragment.d->insert(*this);
    d->priv->endEditBlock();
    d->setX();

    if (fragment.d && fragment.d->doc)
        d->priv->mergeCachedResources(fragment.d->doc->docHandle());
}

/*!
    \since 4.2
    Inserts the text \a html at the current position(). The text is interpreted as
    HTML.

    \note When using this function with a style sheet, the style sheet will
    only apply to the current block in the document. In order to apply a style
    sheet throughout a document, use QTextDocument::setDefaultStyleSheet()
    instead.
*/

#ifndef QT_NO_TEXTHTMLPARSER

void QTextCursor::insertHtml(const QString &html)
{
    if (!d || !d->priv)
        return;
    QTextDocumentFragment fragment = QTextDocumentFragment::fromHtml(html, d->priv->document());
    insertFragment(fragment);
}

#endif // QT_NO_TEXTHTMLPARSER

/*!
    \overload
    \since 4.2

    Inserts the image defined by the given \a format at the cursor's current position
    with the specified \a alignment.

    \sa position()
*/
void QTextCursor::insertImage(const QTextImageFormat &format, QTextFrameFormat::Position alignment)
{
    if (!d || !d->priv)
        return;

    QTextFrameFormat ffmt;
    ffmt.setPosition(alignment);
    QTextObject *obj = d->priv->createObject(ffmt);

    QTextImageFormat fmt = format;
    fmt.setObjectIndex(obj->objectIndex());

    d->priv->beginEditBlock();
    d->remove();
    const int idx = d->priv->formatCollection()->indexForFormat(fmt);
    d->priv->insert(d->position, QString(QChar(QChar::ObjectReplacementCharacter)), idx);
    d->priv->endEditBlock();
}

/*!
    Inserts the image defined by \a format at the current position().
*/
void QTextCursor::insertImage(const QTextImageFormat &format)
{
    insertText(QString(QChar::ObjectReplacementCharacter), format);
}

/*!
    \overload

    Convenience method for inserting the image with the given \a name at the
    current position().

    \snippet code/src_gui_text_qtextcursor.cpp 1
*/
void QTextCursor::insertImage(const QString &name)
{
    QTextImageFormat format;
    format.setName(name);
    insertImage(format);
}

/*!
    \since 4.5
    \overload

    Convenience function for inserting the given \a image with an optional
    \a name at the current position().
*/
void QTextCursor::insertImage(const QImage &image, const QString &name)
{
    if (image.isNull()) {
        qWarning("QTextCursor::insertImage: attempt to add an invalid image");
        return;
    }
    QString imageName = name;
    if (name.isEmpty())
        imageName = QString::number(image.cacheKey());
    d->priv->document()->addResource(QTextDocument::ImageResource, QUrl(imageName), image);
    QTextImageFormat format;
    format.setName(imageName);
    insertImage(format);
}

/*!
    \fn bool QTextCursor::operator!=(const QTextCursor &other) const

    Returns \c true if the \a other cursor is at a different position in
    the document as this cursor; otherwise returns \c false.
*/
bool QTextCursor::operator!=(const QTextCursor &rhs) const
{
    return !operator==(rhs);
}

/*!
    \fn bool QTextCursor::operator<(const QTextCursor &other) const

    Returns \c true if the \a other cursor is positioned later in the
    document than this cursor; otherwise returns \c false.
*/
bool QTextCursor::operator<(const QTextCursor &rhs) const
{
    if (!d)
        return !!rhs.d;

    if (!rhs.d)
        return false;

    Q_ASSERT_X(d->priv == rhs.d->priv, "QTextCursor::operator<", "cannot compare cursors attached to different documents");

    return d->position < rhs.d->position;
}

/*!
    \fn bool QTextCursor::operator<=(const QTextCursor &other) const

    Returns \c true if the \a other cursor is positioned later or at the
    same position in the document as this cursor; otherwise returns
    false.
*/
bool QTextCursor::operator<=(const QTextCursor &rhs) const
{
    if (!d)
        return true;

    if (!rhs.d)
        return false;

    Q_ASSERT_X(d->priv == rhs.d->priv, "QTextCursor::operator<=", "cannot compare cursors attached to different documents");

    return d->position <= rhs.d->position;
}

/*!
    \fn bool QTextCursor::operator==(const QTextCursor &other) const

    Returns \c true if the \a other cursor is at the same position in the
    document as this cursor; otherwise returns \c false.
*/
bool QTextCursor::operator==(const QTextCursor &rhs) const
{
    if (!d)
        return !rhs.d;

    if (!rhs.d)
        return false;

    return d->position == rhs.d->position && d->priv == rhs.d->priv;
}

/*!
    \fn bool QTextCursor::operator>=(const QTextCursor &other) const

    Returns \c true if the \a other cursor is positioned earlier or at the
    same position in the document as this cursor; otherwise returns
    false.
*/
bool QTextCursor::operator>=(const QTextCursor &rhs) const
{
    if (!d)
        return false;

    if (!rhs.d)
        return true;

    Q_ASSERT_X(d->priv == rhs.d->priv, "QTextCursor::operator>=", "cannot compare cursors attached to different documents");

    return d->position >= rhs.d->position;
}

/*!
    \fn bool QTextCursor::operator>(const QTextCursor &other) const

    Returns \c true if the \a other cursor is positioned earlier in the
    document than this cursor; otherwise returns \c false.
*/
bool QTextCursor::operator>(const QTextCursor &rhs) const
{
    if (!d)
        return false;

    if (!rhs.d)
        return true;

    Q_ASSERT_X(d->priv == rhs.d->priv, "QTextCursor::operator>", "cannot compare cursors attached to different documents");

    return d->position > rhs.d->position;
}

/*!
    Indicates the start of a block of editing operations on the
    document that should appear as a single operation from an
    undo/redo point of view.

    For example:

    \snippet code/src_gui_text_qtextcursor.cpp 2

    The call to undo() will cause both insertions to be undone,
    causing both "World" and "Hello" to be removed.

    It is possible to nest calls to beginEditBlock and endEditBlock. The
    top-most pair will determine the scope of the undo/redo operation.

    \sa endEditBlock()
 */
void QTextCursor::beginEditBlock()
{
    if (!d || !d->priv)
        return;

    if (d->priv->editBlock == 0) // we are the initial edit block, store current cursor position for undo
        d->priv->editBlockCursorPosition = d->position;

    d->priv->beginEditBlock();
}

/*!
    Like beginEditBlock() indicates the start of a block of editing operations
    that should appear as a single operation for undo/redo. However unlike
    beginEditBlock() it does not start a new block but reverses the previous call to
    endEditBlock() and therefore makes following operations part of the previous edit block created.

    For example:

    \snippet code/src_gui_text_qtextcursor.cpp 3

    The call to undo() will cause all three insertions to be undone.

    \sa beginEditBlock(), endEditBlock()
 */
void QTextCursor::joinPreviousEditBlock()
{
    if (!d || !d->priv)
        return;

    d->priv->joinPreviousEditBlock();
}

/*!
    Indicates the end of a block of editing operations on the document
    that should appear as a single operation from an undo/redo point
    of view.

    \sa beginEditBlock()
 */

void QTextCursor::endEditBlock()
{
    if (!d || !d->priv)
        return;

    d->priv->endEditBlock();
}

/*!
    Returns \c true if this cursor and \a other are copies of each other, i.e.
    one of them was created as a copy of the other and neither has moved since.
    This is much stricter than equality.

    \sa operator=(), operator==()
*/
bool QTextCursor::isCopyOf(const QTextCursor &other) const
{
    return d == other.d;
}

/*!
    \since 4.2
    Returns the number of the block the cursor is in, or 0 if the cursor is invalid.

    Note that this function only makes sense in documents without complex objects such
    as tables or frames.
*/
int QTextCursor::blockNumber() const
{
    if (!d || !d->priv)
        return 0;

    return d->block().blockNumber();
}


/*!
    \since 4.2
    Returns the position of the cursor within its containing line.

    Note that this is the column number relative to a wrapped line,
    not relative to the block (i.e. the paragraph).

    You probably want to call positionInBlock() instead.

    \sa positionInBlock()
*/
int QTextCursor::columnNumber() const
{
    if (!d || !d->priv)
        return 0;

    QTextBlock block = d->block();
    if (!block.isValid())
        return 0;

    const QTextLayout *layout = d->blockLayout(block);

    const int relativePos = d->position - block.position();

    if (layout->lineCount() == 0)
        return relativePos;

    QTextLine line = layout->lineForTextPosition(relativePos);
    if (!line.isValid())
        return 0;
    return relativePos - line.textStart();
}

/*!
    \since 4.5
    Returns the document this cursor is associated with.
*/
QTextDocument *QTextCursor::document() const
{
    if (d->priv)
        return d->priv->document();
    return nullptr; // document went away
}

QT_END_NAMESPACE

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值