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

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