1// Copyright (C) 2021 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3
4#include "qtextcursor_p.h"
5#include "qtextdocument_p.h"
6#include "qtextblock_p.h"
7
8QT_BEGIN_NAMESPACE
9
10namespace Utils {
11
12class TextFrame;
13class TextTable;
14class TextTableCell;
15
16TextCursor::TextCursor(TextDocument *document) : m_document(document) { }
17
18bool TextCursor::movePosition(TextCursor::MoveOperation op, TextCursor::MoveMode mode, int n)
19{
20 Q_UNUSED(n);
21 switch (op) {
22 case NoMove:
23 return true;
24 case Start:
25 m_position = 0;
26 break;
27 case PreviousCharacter:
28 while (--n >= 0) {
29 if (m_position == 0)
30 return false;
31 --m_position;
32 }
33 break;
34 case End:
35 m_position = m_document->characterCount();
36 break;
37 case NextCharacter:
38 while (--n >= 0) {
39 if (m_position == m_document->characterCount())
40 return false;
41 ++m_position;
42 }
43 break;
44 }
45
46 if (mode == MoveAnchor)
47 m_anchor = m_position;
48
49 return false;
50}
51
52int TextCursor::position() const
53{
54 return m_position;
55}
56
57void TextCursor::setPosition(int pos, Utils::TextCursor::MoveMode mode)
58{
59 m_position = pos;
60 if (mode == MoveAnchor)
61 m_anchor = pos;
62}
63
64QString TextCursor::selectedText() const
65{
66 return m_document->toPlainText().mid(position: qMin(a: m_position, b: m_anchor), n: qAbs(t: m_position - m_anchor));
67}
68
69void TextCursor::clearSelection()
70{
71 m_anchor = m_position;
72}
73
74TextDocument *TextCursor::document() const
75{
76 return m_document;
77}
78
79void TextCursor::insertText(const QString &text)
80{
81 const QString orig = m_document->toPlainText();
82 const QString left = orig.left(n: qMin(a: m_position, b: m_anchor));
83 const QString right = orig.mid(position: qMax(a: m_position, b: m_anchor));
84 m_document->setPlainText(left + text + right);
85}
86
87TextBlock TextCursor::block() const
88{
89 TextBlock current = m_document->firstBlock();
90 while (current.isValid()) {
91 if (current.position() <= position()
92 && current.position() + current.length() > current.position())
93 break;
94 current = current.next();
95 }
96 return current;
97}
98
99int TextCursor::positionInBlock() const
100{
101 return m_position - block().position();
102}
103
104int TextCursor::blockNumber() const
105{
106 return block().blockNumber();
107}
108
109void TextCursor::removeSelectedText()
110{
111 insertText(text: QString());
112}
113
114int TextCursor::selectionEnd() const
115{
116 return qMax(a: m_position, b: m_anchor);
117}
118
119bool TextCursor::isNull() const
120{
121 return m_document == nullptr;
122}
123
124} // namespace Utils
125
126QT_END_NAMESPACE
127

source code of qtdeclarative/src/qmlls/qtextcursor.cpp