Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qtextcursor.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 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.h"
6#include "qglobal.h"
9#include "qtextlist.h"
10#include "qtexttable.h"
11#include "qtexttable_p.h"
12#include "qtextengine_p.h"
15
16#include <qtextlayout.h>
17#include <qdebug.h>
18#include <qnumeric.h>
19
21
22enum {
24 AdjustUp = 0x3,
27};
28
29QTextCursorPrivate::QTextCursorPrivate(QTextDocumentPrivate *p)
30 : priv(p), x(0), position(0), anchor(0), adjusted_anchor(0),
31 currentCharFormat(-1), visualNavigation(false), keepPositionOnInsert(false),
32 changed(false)
33{
34 priv->addCursor(this);
35}
36
37QTextCursorPrivate::QTextCursorPrivate(const QTextCursorPrivate &rhs)
38 : QSharedData(rhs)
39{
40 position = rhs.position;
41 anchor = rhs.anchor;
42 adjusted_anchor = rhs.adjusted_anchor;
43 priv = rhs.priv;
44 x = rhs.x;
45 currentCharFormat = rhs.currentCharFormat;
46 visualNavigation = rhs.visualNavigation;
47 keepPositionOnInsert = rhs.keepPositionOnInsert;
48 changed = rhs.changed;
49 if (priv != nullptr)
50 priv->addCursor(this);
51}
52
53QTextCursorPrivate::~QTextCursorPrivate()
54{
55 if (priv)
56 priv->removeCursor(this);
57}
58
59QTextCursorPrivate::AdjustResult QTextCursorPrivate::adjustPosition(int positionOfChange, int charsAddedOrRemoved, QTextUndoCommand::Operation op)
60{
61 QTextCursorPrivate::AdjustResult result = QTextCursorPrivate::CursorMoved;
62 // not(!) <= , so that inserting text adjusts the cursor correctly
63 if (position < positionOfChange
64 || (position == positionOfChange
65 && (op == QTextUndoCommand::KeepCursor
66 || keepPositionOnInsert)
67 )
68 ) {
69 result = CursorUnchanged;
70 } else {
71 if (charsAddedOrRemoved < 0 && position < positionOfChange - charsAddedOrRemoved)
72 position = positionOfChange;
73 else
74 position += charsAddedOrRemoved;
75
76 currentCharFormat = -1;
77 }
78
79 if (anchor >= positionOfChange
80 && (anchor != positionOfChange || op != QTextUndoCommand::KeepCursor)) {
81 if (charsAddedOrRemoved < 0 && anchor < positionOfChange - charsAddedOrRemoved)
82 anchor = positionOfChange;
83 else
84 anchor += charsAddedOrRemoved;
85 }
86
87 if (adjusted_anchor >= positionOfChange
88 && (adjusted_anchor != positionOfChange || op != QTextUndoCommand::KeepCursor)) {
89 if (charsAddedOrRemoved < 0 && adjusted_anchor < positionOfChange - charsAddedOrRemoved)
90 adjusted_anchor = positionOfChange;
91 else
92 adjusted_anchor += charsAddedOrRemoved;
93 }
94
95 return result;
96}
97
98void QTextCursorPrivate::setX()
99{
100 if (priv->isInEditBlock() || priv->inContentsChange) {
101 x = -1; // mark dirty
102 return;
103 }
104
105 QTextBlock block = this->block();
106 const QTextLayout *layout = blockLayout(block);
107 int pos = position - block.position();
108
109 QTextLine line = layout->lineForTextPosition(pos);
110 if (line.isValid())
111 x = line.cursorToX(pos);
112 else
113 x = -1; // delayed init. Makes movePosition() call setX later on again.
114}
115
116void QTextCursorPrivate::remove()
117{
118 if (anchor == position)
119 return;
120 currentCharFormat = -1;
121 int pos1 = position;
122 int pos2 = adjusted_anchor;
123 QTextUndoCommand::Operation op = QTextUndoCommand::KeepCursor;
124 if (pos1 > pos2) {
125 pos1 = adjusted_anchor;
126 pos2 = position;
127 op = QTextUndoCommand::MoveCursor;
128 }
129
130 // deleting inside table? -> delete only content
131 QTextTable *table = complexSelectionTable();
132 if (table) {
133 priv->beginEditBlock();
134 int startRow, startCol, numRows, numCols;
135 selectedTableCells(&startRow, &numRows, &startCol, &numCols);
136 clearCells(table, startRow, startCol, numRows, numCols, op);
137 adjusted_anchor = anchor = position;
138 priv->endEditBlock();
139 } else {
140 priv->remove(pos1, pos2-pos1, op);
141 adjusted_anchor = anchor = position;
142 }
143
144}
145
146void QTextCursorPrivate::clearCells(QTextTable *table, int startRow, int startCol, int numRows, int numCols, QTextUndoCommand::Operation op)
147{
148 priv->beginEditBlock();
149
150 for (int row = startRow; row < startRow + numRows; ++row)
151 for (int col = startCol; col < startCol + numCols; ++col) {
152 QTextTableCell cell = table->cellAt(row, col);
153 const int startPos = cell.firstPosition();
154 const int endPos = cell.lastPosition();
155 Q_ASSERT(startPos <= endPos);
156 priv->remove(startPos, endPos - startPos, op);
157 }
158
159 priv->endEditBlock();
160}
161
162bool QTextCursorPrivate::canDelete(int pos) const
163{
164 QTextDocumentPrivate::FragmentIterator fit = priv->find(pos);
165 QTextCharFormat fmt = priv->formatCollection()->charFormat((*fit)->format);
166 return (fmt.objectIndex() == -1 || fmt.objectType() == QTextFormat::ImageObject);
167}
168
169void QTextCursorPrivate::insertBlock(const QTextBlockFormat &format, const QTextCharFormat &charFormat)
170{
171 QTextFormatCollection *formats = priv->formatCollection();
172 int idx = formats->indexForFormat(format);
173 Q_ASSERT(formats->format(idx).isBlockFormat());
174
175 priv->insertBlock(position, idx, formats->indexForFormat(charFormat));
176 currentCharFormat = -1;
177}
178
179void QTextCursorPrivate::adjustCursor(QTextCursor::MoveOperation m)
180{
181 adjusted_anchor = anchor;
182 if (position == anchor)
183 return;
184
185 QTextFrame *f_position = priv->frameAt(position);
186 QTextFrame *f_anchor = priv->frameAt(adjusted_anchor);
187
188 if (f_position != f_anchor) {
189 // find common parent frame
190 QList<QTextFrame *> positionChain;
191 QList<QTextFrame *> anchorChain;
192 QTextFrame *f = f_position;
193 while (f) {
194 positionChain.prepend(f);
195 f = f->parentFrame();
196 }
197 f = f_anchor;
198 while (f) {
199 anchorChain.prepend(f);
200 f = f->parentFrame();
201 }
202 Q_ASSERT(positionChain.at(0) == anchorChain.at(0));
203 int i = 1;
204 int l = qMin(positionChain.size(), anchorChain.size());
205 for (; i < l; ++i) {
206 if (positionChain.at(i) != anchorChain.at(i))
207 break;
208 }
209
210 if (m <= QTextCursor::WordLeft) {
211 if (i < positionChain.size())
212 position = positionChain.at(i)->firstPosition() - 1;
213 } else {
214 if (i < positionChain.size())
215 position = positionChain.at(i)->lastPosition() + 1;
216 }
217 if (position < adjusted_anchor) {
218 if (i < anchorChain.size())
219 adjusted_anchor = anchorChain.at(i)->lastPosition() + 1;
220 } else {
221 if (i < anchorChain.size())
222 adjusted_anchor = anchorChain.at(i)->firstPosition() - 1;
223 }
224
225 f_position = positionChain.at(i-1);
226 }
227
228 // same frame, either need to adjust to cell boundaries or return
229 QTextTable *table = qobject_cast<QTextTable *>(f_position);
230 if (!table)
231 return;
232
233 QTextTableCell c_position = table->cellAt(position);
234 QTextTableCell c_anchor = table->cellAt(adjusted_anchor);
235 if (c_position != c_anchor) {
236 position = c_position.firstPosition();
237 if (position < adjusted_anchor)
238 adjusted_anchor = c_anchor.lastPosition();
239 else
240 adjusted_anchor = c_anchor.firstPosition();
241 }
242 currentCharFormat = -1;
243}
244
245void QTextCursorPrivate::aboutToRemoveCell(int from, int to)
246{
247 Q_ASSERT(from <= to);
248 if (position == anchor)
249 return;
250
251 QTextTable *t = qobject_cast<QTextTable *>(priv->frameAt(position));
252 if (!t)
253 return;
254 QTextTableCell removedCellFrom = t->cellAt(from);
255 QTextTableCell removedCellEnd = t->cellAt(to);
256 if (! removedCellFrom.isValid() || !removedCellEnd.isValid())
257 return;
258
259 int curFrom = position;
260 int curTo = adjusted_anchor;
261 if (curTo < curFrom)
262 qSwap(curFrom, curTo);
263
264 QTextTableCell cellStart = t->cellAt(curFrom);
265 QTextTableCell cellEnd = t->cellAt(curTo);
266
267 if (cellStart.row() >= removedCellFrom.row() && cellEnd.row() <= removedCellEnd.row()
268 && cellStart.column() >= removedCellFrom.column()
269 && cellEnd.column() <= removedCellEnd.column()) { // selection is completely removed
270 // find a new position, as close as possible to where we were.
271 QTextTableCell cell;
272 if (removedCellFrom.row() == 0 && removedCellEnd.row() == t->rows()-1) // removed n columns
273 cell = t->cellAt(cellStart.row(), removedCellEnd.column()+1);
274 else if (removedCellFrom.column() == 0 && removedCellEnd.column() == t->columns()-1) // removed n rows
275 cell = t->cellAt(removedCellEnd.row() + 1, cellStart.column());
276
277 int newPosition;
278 if (cell.isValid())
279 newPosition = cell.firstPosition();
280 else
281 newPosition = t->lastPosition()+1;
282
283 setPosition(newPosition);
284 anchor = newPosition;
285 adjusted_anchor = newPosition;
286 x = 0;
287 }
288 else if (cellStart.row() >= removedCellFrom.row() && cellStart.row() <= removedCellEnd.row()
289 && cellEnd.row() > removedCellEnd.row()) {
290 int newPosition = t->cellAt(removedCellEnd.row() + 1, cellStart.column()).firstPosition();
291 if (position < anchor)
292 position = newPosition;
293 else
294 anchor = adjusted_anchor = newPosition;
295 }
296 else if (cellStart.column() >= removedCellFrom.column() && cellStart.column() <= removedCellEnd.column()
297 && cellEnd.column() > removedCellEnd.column()) {
298 int newPosition = t->cellAt(cellStart.row(), removedCellEnd.column()+1).firstPosition();
299 if (position < anchor)
300 position = newPosition;
301 else
302 anchor = adjusted_anchor = newPosition;
303 }
304}
305
306bool QTextCursorPrivate::movePosition(QTextCursor::MoveOperation op, QTextCursor::MoveMode mode)
307{
308 currentCharFormat = -1;
309 bool adjustX = true;
310 QTextBlock blockIt = block();
311 bool visualMovement = priv->defaultCursorMoveStyle == Qt::VisualMoveStyle;
312
313 if (!blockIt.isValid())
314 return false;
315
316 const QTextLayout *layout = blockLayout(blockIt);
317
318 Qt::LayoutDirection blockDirection = layout->textOption().textDirection();
319 if (blockDirection == Qt::LayoutDirectionAuto)
320 blockDirection = blockIt.textDirection();
321
322 if (blockDirection == Qt::RightToLeft) {
323 if (op == QTextCursor::WordLeft)
324 op = QTextCursor::NextWord;
325 else if (op == QTextCursor::WordRight)
326 op = QTextCursor::PreviousWord;
327
328 if (!visualMovement) {
329 if (op == QTextCursor::Left)
330 op = QTextCursor::NextCharacter;
331 else if (op == QTextCursor::Right)
332 op = QTextCursor::PreviousCharacter;
333 }
334 }
335
336 int relativePos = position - blockIt.position();
337 QTextLine line;
338 if (!priv->isInEditBlock())
339 line = layout->lineForTextPosition(relativePos);
340
341 Q_ASSERT(priv->frameAt(position) == priv->frameAt(adjusted_anchor));
342
343 int newPosition = position;
344
345 if (mode == QTextCursor::KeepAnchor && complexSelectionTable() != nullptr) {
346 if ((op >= QTextCursor::EndOfLine && op <= QTextCursor::NextWord)
347 || (op >= QTextCursor::Right && op <= QTextCursor::WordRight)) {
348 QTextTable *t = qobject_cast<QTextTable *>(priv->frameAt(position));
349 Q_ASSERT(t); // as we have already made sure we have a complex selection
350 QTextTableCell cell_pos = t->cellAt(position);
351 if (cell_pos.column() + cell_pos.columnSpan() != t->columns())
352 op = QTextCursor::NextCell;
353 }
354 }
355
356 if (x == -1 && !priv->isInEditBlock() && (op == QTextCursor::Up || op == QTextCursor::Down))
357 setX();
358
359 switch(op) {
360 case QTextCursor::NoMove:
361 return true;
362
363 case QTextCursor::Start:
364 newPosition = 0;
365 break;
366 case QTextCursor::StartOfLine: {
367 newPosition = blockIt.position();
368 if (line.isValid())
369 newPosition += line.textStart();
370
371 break;
372 }
373 case QTextCursor::StartOfBlock: {
374 newPosition = blockIt.position();
375 break;
376 }
377 case QTextCursor::PreviousBlock: {
378 if (blockIt == priv->blocksBegin())
379 return false;
380 blockIt = blockIt.previous();
381
382 newPosition = blockIt.position();
383 break;
384 }
385 case QTextCursor::PreviousCharacter:
386 if (mode == QTextCursor::MoveAnchor && position != adjusted_anchor)
387 newPosition = qMin(position, adjusted_anchor);
388 else
389 newPosition = priv->previousCursorPosition(position, QTextLayout::SkipCharacters);
390 break;
391 case QTextCursor::Left:
392 if (mode == QTextCursor::MoveAnchor && position != adjusted_anchor)
393 newPosition = visualMovement ? qMax(position, adjusted_anchor)
394 : qMin(position, adjusted_anchor);
395 else
396 newPosition = visualMovement ? priv->leftCursorPosition(position)
397 : priv->previousCursorPosition(position, QTextLayout::SkipCharacters);
398 break;
399 case QTextCursor::StartOfWord: {
400 if (relativePos == 0)
401 break;
402
403 // skip if already at word start
404 QTextEngine *engine = layout->engine();
405 const QCharAttributes *attributes = engine->attributes();
406 if ((relativePos == blockIt.length() - 1)
407 && (attributes[relativePos - 1].whiteSpace || engine->atWordSeparator(relativePos - 1)))
408 return false;
409
410 if (relativePos < blockIt.length()-1)
411 ++position;
412
413 Q_FALLTHROUGH();
414 }
415 case QTextCursor::PreviousWord:
416 case QTextCursor::WordLeft:
417 newPosition = priv->previousCursorPosition(position, QTextLayout::SkipWords);
418 break;
419 case QTextCursor::Up: {
420 int i = line.lineNumber() - 1;
421 if (i == -1) {
422 if (blockIt == priv->blocksBegin())
423 return false;
424 int blockPosition = blockIt.position();
425 QTextTable *table = qobject_cast<QTextTable *>(priv->frameAt(blockPosition));
426 if (table) {
427 QTextTableCell cell = table->cellAt(blockPosition);
428 if (cell.firstPosition() == blockPosition) {
429 int row = cell.row() - 1;
430 if (row >= 0) {
431 blockPosition = table->cellAt(row, cell.column()).lastPosition();
432 } else {
433 // move to line above the table
434 blockPosition = table->firstPosition() - 1;
435 }
436 blockIt = priv->blocksFind(blockPosition);
437 } else {
438 blockIt = blockIt.previous();
439 }
440 } else {
441 blockIt = blockIt.previous();
442 }
443 layout = blockLayout(blockIt);
444 i = layout->lineCount()-1;
445 }
446 if (layout->lineCount()) {
447 QTextLine line = layout->lineAt(i);
448 newPosition = line.xToCursor(x) + blockIt.position();
449 } else {
450 newPosition = blockIt.position();
451 }
452 adjustX = false;
453 break;
454 }
455
456 case QTextCursor::End:
457 newPosition = priv->length() - 1;
458 break;
459 case QTextCursor::EndOfLine: {
460 if (!line.isValid() || line.textLength() == 0) {
461 if (blockIt.length() >= 1)
462 // position right before the block separator
463 newPosition = blockIt.position() + blockIt.length() - 1;
464 break;
465 }
466 newPosition = blockIt.position() + line.textStart() + line.textLength();
467 if (newPosition >= priv->length())
468 newPosition = priv->length() - 1;
469 if (line.lineNumber() < layout->lineCount() - 1) {
470 const QString text = blockIt.text();
471 // ###### this relies on spaces being the cause for linebreaks.
472 // this doesn't work with japanese
473 if (text.at(line.textStart() + line.textLength() - 1).isSpace())
474 --newPosition;
475 }
476 break;
477 }
478 case QTextCursor::EndOfWord: {
479 QTextEngine *engine = layout->engine();
480 const QCharAttributes *attributes = engine->attributes();
481 const int len = blockIt.length() - 1;
482 if (relativePos >= len)
483 return false;
484 if (engine->atWordSeparator(relativePos)) {
485 ++relativePos;
486 while (relativePos < len && engine->atWordSeparator(relativePos))
487 ++relativePos;
488 } else {
489 while (relativePos < len && !attributes[relativePos].whiteSpace && !engine->atWordSeparator(relativePos))
490 ++relativePos;
491 }
492 newPosition = blockIt.position() + relativePos;
493 break;
494 }
495 case QTextCursor::EndOfBlock:
496 if (blockIt.length() >= 1)
497 // position right before the block separator
498 newPosition = blockIt.position() + blockIt.length() - 1;
499 break;
500 case QTextCursor::NextBlock: {
501 blockIt = blockIt.next();
502 if (!blockIt.isValid())
503 return false;
504
505 newPosition = blockIt.position();
506 break;
507 }
508 case QTextCursor::NextCharacter:
509 if (mode == QTextCursor::MoveAnchor && position != adjusted_anchor)
510 newPosition = qMax(position, adjusted_anchor);
511 else
512 newPosition = priv->nextCursorPosition(position, QTextLayout::SkipCharacters);
513 break;
514 case QTextCursor::Right:
515 if (mode == QTextCursor::MoveAnchor && position != adjusted_anchor)
516 newPosition = visualMovement ? qMin(position, adjusted_anchor)
517 : qMax(position, adjusted_anchor);
518 else
519 newPosition = visualMovement ? priv->rightCursorPosition(position)
520 : priv->nextCursorPosition(position, QTextLayout::SkipCharacters);
521 break;
522 case QTextCursor::NextWord:
523 case QTextCursor::WordRight:
524 newPosition = priv->nextCursorPosition(position, QTextLayout::SkipWords);
525 break;
526
527 case QTextCursor::Down: {
528 int i = line.lineNumber() + 1;
529
530 if (i >= layout->lineCount()) {
531 int blockPosition = blockIt.position() + blockIt.length() - 1;
532 QTextTable *table = qobject_cast<QTextTable *>(priv->frameAt(blockPosition));
533 if (table) {
534 QTextTableCell cell = table->cellAt(blockPosition);
535 if (cell.lastPosition() == blockPosition) {
536 int row = cell.row() + cell.rowSpan();
537 if (row < table->rows()) {
538 blockPosition = table->cellAt(row, cell.column()).firstPosition();
539 } else {
540 // move to line below the table
541 blockPosition = table->lastPosition() + 1;
542 }
543 blockIt = priv->blocksFind(blockPosition);
544 } else {
545 blockIt = blockIt.next();
546 }
547 } else {
548 blockIt = blockIt.next();
549 }
550
551 if (blockIt == priv->blocksEnd())
552 return false;
553 layout = blockLayout(blockIt);
554 i = 0;
555 }
556 if (layout->lineCount()) {
557 QTextLine line = layout->lineAt(i);
558 newPosition = line.xToCursor(x) + blockIt.position();
559 } else {
560 newPosition = blockIt.position();
561 }
562 adjustX = false;
563 break;
564 }
565 case QTextCursor::NextCell:
566 case QTextCursor::PreviousCell:
567 case QTextCursor::NextRow:
568 case QTextCursor::PreviousRow: {
569 QTextTable *table = qobject_cast<QTextTable *>(priv->frameAt(position));
570 if (!table)
571 return false;
572
573 QTextTableCell cell = table->cellAt(position);
574 Q_ASSERT(cell.isValid());
575 int column = cell.column();
576 int row = cell.row();
577 const int currentRow = row;
578 if (op == QTextCursor::NextCell || op == QTextCursor::NextRow) {
579 do {
580 column += cell.columnSpan();
581 if (column >= table->columns()) {
582 column = 0;
583 ++row;
584 }
585 cell = table->cellAt(row, column);
586 // note we also continue while we have not reached a cell that's not merged with one above us
587 } while (cell.isValid()
588 && ((op == QTextCursor::NextRow && currentRow == cell.row())
589 || cell.row() < row));
590 }
591 else if (op == QTextCursor::PreviousCell || op == QTextCursor::PreviousRow) {
592 do {
593 --column;
594 if (column < 0) {
595 column = table->columns()-1;
596 --row;
597 }
598 cell = table->cellAt(row, column);
599 // note we also continue while we have not reached a cell that's not merged with one above us
600 } while (cell.isValid()
601 && ((op == QTextCursor::PreviousRow && currentRow == cell.row())
602 || cell.row() < row));
603 }
604 if (cell.isValid())
605 newPosition = cell.firstPosition();
606 break;
607 }
608 }
609
610 if (mode == QTextCursor::KeepAnchor) {
611 QTextTable *table = qobject_cast<QTextTable *>(priv->frameAt(position));
612 if (table && ((op >= QTextCursor::PreviousBlock && op <= QTextCursor::WordLeft)
613 || (op >= QTextCursor::NextBlock && op <= QTextCursor::WordRight))) {
614 int oldColumn = table->cellAt(position).column();
615
616 const QTextTableCell otherCell = table->cellAt(newPosition);
617 if (!otherCell.isValid())
618 return false;
619
620 int newColumn = otherCell.column();
621 if ((oldColumn > newColumn && op >= QTextCursor::End)
622 || (oldColumn < newColumn && op <= QTextCursor::WordLeft))
623 return false;
624 }
625 }
626
627 const bool moved = setPosition(newPosition);
628
629 if (mode == QTextCursor::MoveAnchor) {
630 anchor = position;
631 adjusted_anchor = position;
632 } else {
633 adjustCursor(op);
634 }
635
636 if (adjustX)
637 setX();
638
639 return moved;
640}
641
642QTextTable *QTextCursorPrivate::complexSelectionTable() const
643{
644 if (position == anchor)
645 return nullptr;
646
647 QTextTable *t = qobject_cast<QTextTable *>(priv->frameAt(position));
648 if (t) {
649 QTextTableCell cell_pos = t->cellAt(position);
650 QTextTableCell cell_anchor = t->cellAt(adjusted_anchor);
651
652 Q_ASSERT(cell_anchor.isValid());
653
654 if (cell_pos == cell_anchor)
655 t = nullptr;
656 }
657 return t;
658}
659
660void QTextCursorPrivate::selectedTableCells(int *firstRow, int *numRows, int *firstColumn, int *numColumns) const
661{
662 *firstRow = -1;
663 *firstColumn = -1;
664 *numRows = -1;
665 *numColumns = -1;
666
667 if (position == anchor)
668 return;
669
670 QTextTable *t = qobject_cast<QTextTable *>(priv->frameAt(position));
671 if (!t)
672 return;
673
674 QTextTableCell cell_pos = t->cellAt(position);
675 QTextTableCell cell_anchor = t->cellAt(adjusted_anchor);
676
677 Q_ASSERT(cell_anchor.isValid());
678
679 if (cell_pos == cell_anchor)
680 return;
681
682 *firstRow = qMin(cell_pos.row(), cell_anchor.row());
683 *firstColumn = qMin(cell_pos.column(), cell_anchor.column());
684 *numRows = qMax(cell_pos.row() + cell_pos.rowSpan(), cell_anchor.row() + cell_anchor.rowSpan()) - *firstRow;
685 *numColumns = qMax(cell_pos.column() + cell_pos.columnSpan(), cell_anchor.column() + cell_anchor.columnSpan()) - *firstColumn;
686}
687
688static void setBlockCharFormatHelper(QTextDocumentPrivate *priv, int pos1, int pos2,
689 const QTextCharFormat &format, QTextDocumentPrivate::FormatChangeMode changeMode)
690{
691 QTextBlock it = priv->blocksFind(pos1);
692 QTextBlock end = priv->blocksFind(pos2);
693 if (end.isValid())
694 end = end.next();
695
696 for (; it != end; it = it.next()) {
697 priv->setCharFormat(it.position() - 1, 1, format, changeMode);
698 }
699}
700
701void QTextCursorPrivate::setBlockCharFormat(const QTextCharFormat &_format,
702 QTextDocumentPrivate::FormatChangeMode changeMode)
703{
704 priv->beginEditBlock();
705
706 QTextCharFormat format = _format;
707 format.clearProperty(QTextFormat::ObjectIndex);
708
709 QTextTable *table = complexSelectionTable();
710 if (table) {
711 int row_start, col_start, num_rows, num_cols;
712 selectedTableCells(&row_start, &num_rows, &col_start, &num_cols);
713
714 Q_ASSERT(row_start != -1);
715 for (int r = row_start; r < row_start + num_rows; ++r) {
716 for (int c = col_start; c < col_start + num_cols; ++c) {
717 QTextTableCell cell = table->cellAt(r, c);
718 int rspan = cell.rowSpan();
719 int cspan = cell.columnSpan();
720 if (rspan != 1) {
721 int cr = cell.row();
722 if (cr != r)
723 continue;
724 }
725 if (cspan != 1) {
726 int cc = cell.column();
727 if (cc != c)
728 continue;
729 }
730
731 int pos1 = cell.firstPosition();
732 int pos2 = cell.lastPosition();
733 setBlockCharFormatHelper(priv, pos1, pos2, format, changeMode);
734 }
735 }
736 } else {
737 int pos1 = position;
738 int pos2 = adjusted_anchor;
739 if (pos1 > pos2) {
740 pos1 = adjusted_anchor;
741 pos2 = position;
742 }
743
744 setBlockCharFormatHelper(priv, pos1, pos2, format, changeMode);
745 }
746 priv->endEditBlock();
747}
748
749
750void QTextCursorPrivate::setBlockFormat(const QTextBlockFormat &format, QTextDocumentPrivate::FormatChangeMode changeMode)
751{
752 QTextTable *table = complexSelectionTable();
753 if (table) {
754 priv->beginEditBlock();
755 int row_start, col_start, num_rows, num_cols;
756 selectedTableCells(&row_start, &num_rows, &col_start, &num_cols);
757
758 Q_ASSERT(row_start != -1);
759 for (int r = row_start; r < row_start + num_rows; ++r) {
760 for (int c = col_start; c < col_start + num_cols; ++c) {
761 QTextTableCell cell = table->cellAt(r, c);
762 int rspan = cell.rowSpan();
763 int cspan = cell.columnSpan();
764 if (rspan != 1) {
765 int cr = cell.row();
766 if (cr != r)
767 continue;
768 }
769 if (cspan != 1) {
770 int cc = cell.column();
771 if (cc != c)
772 continue;
773 }
774
775 int pos1 = cell.firstPosition();
776 int pos2 = cell.lastPosition();
777 priv->setBlockFormat(priv->blocksFind(pos1), priv->blocksFind(pos2), format, changeMode);
778 }
779 }
780 priv->endEditBlock();
781 } else {
782 int pos1 = position;
783 int pos2 = adjusted_anchor;
784 if (pos1 > pos2) {
785 pos1 = adjusted_anchor;
786 pos2 = position;
787 }
788
789 priv->setBlockFormat(priv->blocksFind(pos1), priv->blocksFind(pos2), format, changeMode);
790 }
791}
792
793void QTextCursorPrivate::setCharFormat(const QTextCharFormat &_format, QTextDocumentPrivate::FormatChangeMode changeMode)
794{
795 Q_ASSERT(position != anchor);
796
797 QTextCharFormat format = _format;
798 format.clearProperty(QTextFormat::ObjectIndex);
799
800 QTextTable *table = complexSelectionTable();
801 if (table) {
802 priv->beginEditBlock();
803 int row_start, col_start, num_rows, num_cols;
804 selectedTableCells(&row_start, &num_rows, &col_start, &num_cols);
805
806 Q_ASSERT(row_start != -1);
807 for (int r = row_start; r < row_start + num_rows; ++r) {
808 for (int c = col_start; c < col_start + num_cols; ++c) {
809 QTextTableCell cell = table->cellAt(r, c);
810 int rspan = cell.rowSpan();
811 int cspan = cell.columnSpan();
812 if (rspan != 1) {
813 int cr = cell.row();
814 if (cr != r)
815 continue;
816 }
817 if (cspan != 1) {
818 int cc = cell.column();
819 if (cc != c)
820 continue;
821 }
822
823 int pos1 = cell.firstPosition();
824 int pos2 = cell.lastPosition();
825 priv->setCharFormat(pos1, pos2-pos1, format, changeMode);
826 }
827 }
828 priv->endEditBlock();
829 } else {
830 int pos1 = position;
831 int pos2 = adjusted_anchor;
832 if (pos1 > pos2) {
833 pos1 = adjusted_anchor;
834 pos2 = position;
835 }
836
837 priv->setCharFormat(pos1, pos2-pos1, format, changeMode);
838 }
839}
840
841
842QTextLayout *QTextCursorPrivate::blockLayout(QTextBlock &block) const{
843 QTextLayout *tl = block.layout();
844 if (!tl->lineCount() && priv->layout())
845 priv->layout()->blockBoundingRect(block);
846 return tl;
847}
848
849/*!
850 \class QTextCursor
851 \reentrant
852 \inmodule QtGui
853
854 \brief The QTextCursor class offers an API to access and modify QTextDocuments.
855
856 \ingroup richtext-processing
857 \ingroup shared
858
859 Text cursors are objects that are used to access and modify the
860 contents and underlying structure of text documents via a
861 programming interface that mimics the behavior of a cursor in a
862 text editor. QTextCursor contains information about both the
863 cursor's position within a QTextDocument and any selection that it
864 has made.
865
866 QTextCursor is modeled on the way a text cursor behaves in a text
867 editor, providing a programmatic means of performing standard
868 actions through the user interface. A document can be thought of
869 as a single string of characters. The cursor's current position()
870 then is always either \e between two consecutive characters in the
871 string, or else \e before the very first character or \e after the
872 very last character in the string. Documents can also contain
873 tables, lists, images, and other objects in addition to text but,
874 from the developer's point of view, the document can be treated as
875 one long string. Some portions of that string can be considered
876 to lie within particular blocks (e.g. paragraphs), or within a
877 table's cell, or a list's item, or other structural elements. When
878 we refer to "current character" we mean the character immediately
879 \e before the cursor position() in the document. Similarly, the
880 "current block" is the block that contains the cursor position().
881
882 A QTextCursor also has an anchor() position. The text that is
883 between the anchor() and the position() is the selection. If
884 anchor() == position() there is no selection.
885
886 The cursor position can be changed programmatically using
887 setPosition() and movePosition(); the latter can also be used to
888 select text. For selections see selectionStart(), selectionEnd(),
889 hasSelection(), clearSelection(), and removeSelectedText().
890
891 If the position() is at the start of a block, atBlockStart()
892 returns \c true; and if it is at the end of a block, atBlockEnd() returns
893 true. The format of the current character is returned by
894 charFormat(), and the format of the current block is returned by
895 blockFormat().
896
897 Formatting can be applied to the current text document using the
898 setCharFormat(), mergeCharFormat(), setBlockFormat() and
899 mergeBlockFormat() functions. The 'set' functions will replace the
900 cursor's current character or block format, while the 'merge'
901 functions add the given format properties to the cursor's current
902 format. If the cursor has a selection, the given format is applied
903 to the current selection. Note that when only a part of a block is
904 selected, the block format is applied to the entire block. The text
905 at the current character position can be turned into a list using
906 createList().
907
908 Deletions can be achieved using deleteChar(),
909 deletePreviousChar(), and removeSelectedText().
910
911 Text strings can be inserted into the document with the insertText()
912 function, blocks (representing new paragraphs) can be inserted with
913 insertBlock().
914
915 Existing fragments of text can be inserted with insertFragment() but,
916 if you want to insert pieces of text in various formats, it is usually
917 still easier to use insertText() and supply a character format.
918
919 Various types of higher-level structure can also be inserted into the
920 document with the cursor:
921
922 \list
923 \li Lists are ordered sequences of block elements that are decorated with
924 bullet points or symbols. These are inserted in a specified format
925 with insertList().
926 \li Tables are inserted with the insertTable() function, and can be
927 given an optional format. These contain an array of cells that can
928 be traversed using the cursor.
929 \li Inline images are inserted with insertImage(). The image to be
930 used can be specified in an image format, or by name.
931 \li Frames are inserted by calling insertFrame() with a specified format.
932 \endlist
933
934 Actions can be grouped (i.e. treated as a single action for
935 undo/redo) using beginEditBlock() and endEditBlock(). Grouping also
936 improves performance when making many changes, because the document
937 updates its layout once at the end of the group instead of after every
938 change.
939
940 Cursor movements are limited to valid cursor positions. In Latin
941 writing this is between any two consecutive characters in the
942 text, before the first character, or after the last character. In
943 some other writing systems cursor movements are limited to
944 "clusters" (e.g. a syllable in Devanagari, or a base letter plus
945 diacritics). Functions such as movePosition() and deleteChar()
946 limit cursor movement to these valid positions.
947
948 \sa {Rich Text Processing}
949
950*/
951
952/*!
953 \enum QTextCursor::MoveOperation
954
955 \value NoMove Keep the cursor where it is
956
957 \value Start Move to the start of the document.
958 \value StartOfLine Move to the start of the current line.
959 \value StartOfBlock Move to the start of the current block.
960 \value StartOfWord Move to the start of the current word.
961 \value PreviousBlock Move to the start of the previous block.
962 \value PreviousCharacter Move to the previous character.
963 \value PreviousWord Move to the beginning of the previous word.
964 \value Up Move up one line.
965 \value Left Move left one character.
966 \value WordLeft Move left one word.
967
968 \value End Move to the end of the document.
969 \value EndOfLine Move to the end of the current line.
970 \value EndOfWord Move to the end of the current word.
971 \value EndOfBlock Move to the end of the current block.
972 \value NextBlock Move to the beginning of the next block.
973 \value NextCharacter Move to the next character. If text is selected, the first call
974 to \c{movePosition(NextCharacter, MoveAnchor)} deselects the text without moving the cursor.
975 \value NextWord Move to the next word.
976 \value Down Move down one line.
977 \value Right Move right one character.
978 \value WordRight Move right one word.
979
980 \value NextCell Move to the beginning of the next table cell inside the
981 current table. If the current cell is the last cell in the row, the
982 cursor will move to the first cell in the next row.
983 \value PreviousCell Move to the beginning of the previous table cell
984 inside the current table. If the current cell is the first cell in
985 the row, the cursor will move to the last cell in the previous row.
986 \value NextRow Move to the first new cell of the next row in the current
987 table.
988 \value PreviousRow Move to the last cell of the previous row in the
989 current table.
990
991 \sa movePosition()
992*/
993
994/*!
995 \enum QTextCursor::MoveMode
996
997 \value MoveAnchor Moves the anchor to the same position as the cursor itself.
998 \value KeepAnchor Keeps the anchor where it is.
999
1000 If the anchor() is kept where it is and the position() is moved,
1001 the text in between will be selected.
1002*/
1003
1004/*!
1005 \enum QTextCursor::SelectionType
1006
1007 This enum describes the types of selection that can be applied with the
1008 select() function.
1009
1010 \value Document Selects the entire document.
1011 \value BlockUnderCursor Selects the block of text under the cursor.
1012 \value LineUnderCursor Selects the line of text under the cursor.
1013 \value WordUnderCursor Selects the word under the cursor. If the cursor
1014 is not positioned within a string of selectable characters, no
1015 text is selected.
1016*/
1017
1018/*!
1019 Constructs a null cursor.
1020 */
1021QTextCursor::QTextCursor()
1022 : d(nullptr)
1023{
1024}
1025
1026/*!
1027 Constructs a cursor pointing to the beginning of the \a document.
1028 */
1029QTextCursor::QTextCursor(QTextDocument *document)
1030 : d(new QTextCursorPrivate(QTextDocumentPrivate::get(document)))
1031{
1032}
1033
1034/*!
1035 Constructs a cursor pointing to the beginning of the \a frame.
1036*/
1037QTextCursor::QTextCursor(QTextFrame *frame)
1038 : d(new QTextCursorPrivate(QTextDocumentPrivate::get(frame->document())))
1039{
1040 d->adjusted_anchor = d->anchor = d->position = frame->firstPosition();
1041}
1042
1043
1044/*!
1045 Constructs a cursor pointing to the beginning of the \a block.
1046*/
1047QTextCursor::QTextCursor(const QTextBlock &block)
1048 : d(new QTextCursorPrivate(const_cast<QTextDocumentPrivate *>(QTextDocumentPrivate::get(block))))
1049{
1050 d->adjusted_anchor = d->anchor = d->position = block.position();
1051}
1052
1053
1054/*!
1055 \internal
1056 */
1057QTextCursor::QTextCursor(QTextDocumentPrivate *p, int pos)
1058 : d(new QTextCursorPrivate(p))
1059{
1060 d->adjusted_anchor = d->anchor = d->position = pos;
1061
1062 d->setX();
1063}
1064
1065/*!
1066 \internal
1067*/
1068QTextCursor::QTextCursor(QTextCursorPrivate *d)
1069{
1070 Q_ASSERT(d);
1071 this->d = d;
1072}
1073
1074/*!
1075 Constructs a new cursor that is a copy of \a cursor.
1076 */
1077QTextCursor::QTextCursor(const QTextCursor &cursor)
1078{
1079 d = cursor.d;
1080}
1081
1082/*!
1083 Makes a copy of \a cursor and assigns it to this QTextCursor. Note
1084 that QTextCursor is an \l{Implicitly Shared Classes}{implicitly
1085 shared} class.
1086
1087 */
1088QTextCursor &QTextCursor::operator=(const QTextCursor &cursor)
1089{
1090 d = cursor.d;
1091 return *this;
1092}
1093
1094/*!
1095 \fn void QTextCursor::swap(QTextCursor &other)
1096 \since 5.0
1097 \memberswap{text cursor instance}
1098*/
1099
1100/*!
1101 Destroys the QTextCursor.
1102 */
1103QTextCursor::~QTextCursor()
1104{
1105}
1106
1107/*!
1108 Returns \c true if the cursor is null; otherwise returns \c false. A null
1109 cursor is created by the default constructor.
1110 */
1111bool QTextCursor::isNull() const
1112{
1113 return !d || !d->priv;
1114}
1115
1116/*!
1117 Moves the cursor to the absolute position in the document specified by
1118 \a pos using a \c MoveMode specified by \a m. The cursor is positioned
1119 between characters.
1120
1121 \note The "characters" in this case refer to the string of QChar
1122 objects, i.e. 16-bit Unicode characters, and \a pos is considered
1123 an index into this string. This does not necessarily correspond to
1124 individual graphemes in the writing system, as a single grapheme may
1125 be represented by multiple Unicode characters, such as in the case
1126 of surrogate pairs, linguistic ligatures or diacritics. For a more
1127 generic approach to navigating the document, use movePosition(),
1128 which will respect the actual grapheme boundaries in the text.
1129
1130 \sa position(), movePosition(), anchor()
1131*/
1132void QTextCursor::setPosition(int pos, MoveMode m)
1133{
1134 if (!d || !d->priv)
1135 return;
1136
1137 if (pos < 0 || pos >= d->priv->length()) {
1138 qWarning("QTextCursor::setPosition: Position '%d' out of range", pos);
1139 return;
1140 }
1141
1142 d->setPosition(pos);
1143 if (m == MoveAnchor) {
1144 d->anchor = pos;
1145 d->adjusted_anchor = pos;
1146 } else { // keep anchor
1147 QTextCursor::MoveOperation op;
1148 if (pos < d->anchor)
1149 op = QTextCursor::Left;
1150 else
1151 op = QTextCursor::Right;
1152 d->adjustCursor(op);
1153 }
1154 d->setX();
1155}
1156
1157/*!
1158 Returns the absolute position of the cursor within the document.
1159 The cursor is positioned between characters.
1160
1161 \note The "characters" in this case refer to the string of QChar
1162 objects, i.e. 16-bit Unicode characters, and the position is considered
1163 an index into this string. This does not necessarily correspond to
1164 individual graphemes in the writing system, as a single grapheme may
1165 be represented by multiple Unicode characters, such as in the case
1166 of surrogate pairs, linguistic ligatures or diacritics.
1167
1168 \sa setPosition(), movePosition(), anchor(), positionInBlock()
1169*/
1170int QTextCursor::position() const
1171{
1172 if (!d || !d->priv)
1173 return -1;
1174 return d->position;
1175}
1176
1177/*!
1178 \since 4.7
1179 Returns the relative position of the cursor within the block.
1180 The cursor is positioned between characters.
1181
1182 This is equivalent to \c{ position() - block().position()}.
1183
1184 \note The "characters" in this case refer to the string of QChar
1185 objects, i.e. 16-bit Unicode characters, and the position is considered
1186 an index into this string. This does not necessarily correspond to
1187 individual graphemes in the writing system, as a single grapheme may
1188 be represented by multiple Unicode characters, such as in the case
1189 of surrogate pairs, linguistic ligatures or diacritics.
1190
1191 \sa position()
1192*/
1193int QTextCursor::positionInBlock() const
1194{
1195 if (!d || !d->priv)
1196 return 0;
1197 return d->position - d->block().position();
1198}
1199
1200/*!
1201 Returns the anchor position; this is the same as position() unless
1202 there is a selection in which case position() marks one end of the
1203 selection and anchor() marks the other end. Just like the cursor
1204 position, the anchor position is between characters.
1205
1206 \sa position(), setPosition(), movePosition(), selectionStart(), selectionEnd()
1207*/
1208int QTextCursor::anchor() const
1209{
1210 if (!d || !d->priv)
1211 return -1;
1212 return d->anchor;
1213}
1214
1215/*!
1216 \fn bool QTextCursor::movePosition(MoveOperation operation, MoveMode mode, int n)
1217
1218 Moves the cursor by performing the given \a operation \a n times, using the specified
1219 \a mode, and returns \c true if all operations were completed successfully; otherwise
1220 returns \c false.
1221
1222 For example, if this function is repeatedly used to seek to the end of the next
1223 word, it will eventually fail when the end of the document is reached.
1224
1225 By default, the move operation is performed once (\a n = 1).
1226
1227 If \a mode is \c KeepAnchor, the cursor selects the text it moves
1228 over. This is the same effect that the user achieves when they
1229 hold down the Shift key and move the cursor with the cursor keys.
1230
1231 \sa setVisualNavigation()
1232*/
1233bool QTextCursor::movePosition(MoveOperation op, MoveMode mode, int n)
1234{
1235 if (!d || !d->priv)
1236 return false;
1237 switch (op) {
1238 case Start:
1239 case StartOfLine:
1240 case End:
1241 case EndOfLine:
1242 n = 1;
1243 break;
1244 default: break;
1245 }
1246
1247 int previousPosition = d->position;
1248 for (; n > 0; --n) {
1249 if (!d->movePosition(op, mode))
1250 return false;
1251 }
1252
1253 if (d->visualNavigation && !d->block().isVisible()) {
1254 QTextBlock b = d->block();
1255 if (previousPosition < d->position) {
1256 while (!b.next().isVisible())
1257 b = b.next();
1258 d->setPosition(b.position() + b.length() - 1);
1259 } else {
1260 while (!b.previous().isVisible())
1261 b = b.previous();
1262 d->setPosition(b.position());
1263 }
1264 if (mode == QTextCursor::MoveAnchor)
1265 d->anchor = d->position;
1266 while (d->movePosition(op, mode)
1267 && !d->block().isVisible())
1268 ;
1269
1270 }
1271 return true;
1272}
1273
1274/*!
1275 \since 4.4
1276
1277 Returns \c true if the cursor does visual navigation; otherwise
1278 returns \c false.
1279
1280 Visual navigation means skipping over hidden text paragraphs. The
1281 default is false.
1282
1283 \sa setVisualNavigation(), movePosition()
1284 */
1285bool QTextCursor::visualNavigation() const
1286{
1287 return d ? d->visualNavigation : false;
1288}
1289
1290/*!
1291 \since 4.4
1292
1293 Sets visual navigation to \a b.
1294
1295 Visual navigation means skipping over hidden text paragraphs. The
1296 default is false.
1297
1298 \sa visualNavigation(), movePosition()
1299 */
1300void QTextCursor::setVisualNavigation(bool b)
1301{
1302 if (d)
1303 d->visualNavigation = b;
1304}
1305
1306
1307/*!
1308 \since 4.7
1309
1310 Sets the visual x position for vertical cursor movements to \a x.
1311
1312 The vertical movement x position is cleared automatically when the cursor moves horizontally, and kept
1313 unchanged when the cursor moves vertically. The mechanism allows the cursor to move up and down on a
1314 visually straight line with proportional fonts, and to gently "jump" over short lines.
1315
1316 A value of -1 indicates no predefined x position. It will then be set automatically the next time the
1317 cursor moves up or down.
1318
1319 \sa verticalMovementX()
1320 */
1321void QTextCursor::setVerticalMovementX(int x)
1322{
1323 if (d)
1324 d->x = x;
1325}
1326
1327/*! \since 4.7
1328
1329 Returns the visual x position for vertical cursor movements.
1330
1331 A value of -1 indicates no predefined x position. It will then be set automatically the next time the
1332 cursor moves up or down.
1333
1334 \sa setVerticalMovementX()
1335 */
1336int QTextCursor::verticalMovementX() const
1337{
1338 return d ? d->x : -1;
1339}
1340
1341/*!
1342 \since 4.7
1343
1344 Returns whether the cursor should keep its current position when text gets inserted at the position of the
1345 cursor.
1346
1347 The default is false;
1348
1349 \sa setKeepPositionOnInsert()
1350 */
1351bool QTextCursor::keepPositionOnInsert() const
1352{
1353 return d ? d->keepPositionOnInsert : false;
1354}
1355
1356/*!
1357 \since 4.7
1358
1359 Defines whether the cursor should keep its current position when text gets inserted at the current position of the
1360 cursor.
1361
1362 If \a b is true, the cursor keeps its current position when text gets inserted at the positing of the cursor.
1363 If \a b is false, the cursor moves along with the inserted text.
1364
1365 The default is false.
1366
1367 Note that a cursor always moves when text is inserted before the current position of the cursor, and it
1368 always keeps its position when text is inserted after the current position of the cursor.
1369
1370 \sa keepPositionOnInsert()
1371 */
1372void QTextCursor::setKeepPositionOnInsert(bool b)
1373{
1374 if (d)
1375 d->keepPositionOnInsert = b;
1376}
1377
1378
1379
1380/*!
1381 Inserts \a text at the current position, using the current
1382 character format.
1383
1384 If there is a selection, the selection is deleted and replaced by
1385 \a text, for example:
1386 \snippet code/src_gui_text_qtextcursor.cpp 0
1387 This clears any existing selection, selects the word at the cursor
1388 (i.e. from position() forward), and replaces the selection with
1389 the phrase "Hello World".
1390
1391 Any ASCII linefeed characters (\\n) in the inserted text are transformed
1392 into unicode block separators, corresponding to insertBlock() calls.
1393
1394 \sa charFormat(), hasSelection()
1395*/
1396void QTextCursor::insertText(const QString &text)
1397{
1398 QTextCharFormat fmt = charFormat();
1399 fmt.clearProperty(QTextFormat::ObjectType);
1400 insertText(text, fmt);
1401}
1402
1403/*!
1404 \fn void QTextCursor::insertText(const QString &text, const QTextCharFormat &format)
1405 \overload
1406
1407 Inserts \a text at the current position with the given \a format.
1408*/
1409void QTextCursor::insertText(const QString &text, const QTextCharFormat &_format)
1410{
1411 if (!d || !d->priv)
1412 return;
1413
1414 Q_ASSERT(_format.isValid());
1415
1416 QTextCharFormat format = _format;
1417 format.clearProperty(QTextFormat::ObjectIndex);
1418
1419 bool hasEditBlock = false;
1420
1421 if (d->anchor != d->position) {
1422 hasEditBlock = true;
1423 d->priv->beginEditBlock();
1424 d->remove();
1425 }
1426
1427 if (!text.isEmpty()) {
1428 QTextFormatCollection *formats = d->priv->formatCollection();
1429 int formatIdx = formats->indexForFormat(format);
1430 Q_ASSERT(formats->format(formatIdx).isCharFormat());
1431
1432 QTextBlockFormat blockFmt = blockFormat();
1433
1434
1435 int textStart = d->priv->text.size();
1436 int blockStart = 0;
1437 d->priv->text += text;
1438 int textEnd = d->priv->text.size();
1439
1440 for (int i = 0; i < text.size(); ++i) {
1441 QChar ch = text.at(i);
1442
1443 const int blockEnd = i;
1444
1445 if (ch == u'\r'
1446 && (i + 1) < text.size()
1447 && text.at(i + 1) == u'\n') {
1448 ++i;
1449 ch = text.at(i);
1450 }
1451
1452 if (ch == u'\n'
1453 || ch == QChar::ParagraphSeparator
1454 || ch == QTextBeginningOfFrame
1455 || ch == QTextEndOfFrame
1456 || ch == u'\r') {
1457
1458 if (!hasEditBlock) {
1459 hasEditBlock = true;
1460 d->priv->beginEditBlock();
1461 }
1462
1463 if (blockEnd > blockStart)
1464 d->priv->insert(d->position, textStart + blockStart, blockEnd - blockStart, formatIdx);
1465
1466 d->insertBlock(blockFmt, format);
1467 blockStart = i + 1;
1468 }
1469 }
1470 if (textStart + blockStart < textEnd)
1471 d->priv->insert(d->position, textStart + blockStart, textEnd - textStart - blockStart, formatIdx);
1472 }
1473 if (hasEditBlock)
1474 d->priv->endEditBlock();
1475 d->setX();
1476}
1477
1478/*!
1479 If there is no selected text, deletes the character \e at the
1480 current cursor position; otherwise deletes the selected text.
1481
1482 \sa deletePreviousChar(), hasSelection(), clearSelection()
1483*/
1484void QTextCursor::deleteChar()
1485{
1486 if (!d || !d->priv)
1487 return;
1488
1489 if (d->position != d->anchor) {
1490 removeSelectedText();
1491 return;
1492 }
1493
1494 if (!d->canDelete(d->position))
1495 return;
1496 d->adjusted_anchor = d->anchor =
1497 d->priv->nextCursorPosition(d->anchor, QTextLayout::SkipCharacters);
1498 d->remove();
1499 d->setX();
1500}
1501
1502/*!
1503 If there is no selected text, deletes the character \e before the
1504 current cursor position; otherwise deletes the selected text.
1505
1506 \sa deleteChar(), hasSelection(), clearSelection()
1507*/
1508void QTextCursor::deletePreviousChar()
1509{
1510 if (!d || !d->priv)
1511 return;
1512
1513 if (d->position != d->anchor) {
1514 removeSelectedText();
1515 return;
1516 }
1517
1518 if (d->anchor < 1 || !d->canDelete(d->anchor-1))
1519 return;
1520
1521 // For emoji sequences, backspace deletes the entire grapheme cluster,
1522 // since individual codepoints are meaningless to the user.
1523 // For other clusters (e.g. Devanagari consonant+vowel), we delete
1524 // only one codepoint at a time, matching the behavior of other major
1525 // text editors.
1526 const int clusterStart =
1527 d->priv->previousCursorPosition(d->anchor, QTextLayout::SkipCharacters);
1528 const int clusterCodeUnits = d->anchor - clusterStart;
1529
1530 if (clusterCodeUnits > 1) {
1531 // Multi-code-unit cluster: use QTextEngine's script analysis
1532 // to determine if this is an emoji sequence. The emoji segmenter
1533 // (run during itemization) tags emoji sequences with Script_Emoji.
1534 // Note: if Qt is built with QT_NO_EMOJISEGMENTER, Script_Emoji is
1535 // never assigned, and we fall through to the per-codepoint path.
1536 QTextBlock block = d->block();
1537 const int posInBlock = clusterStart - block.position();
1538 Q_ASSERT(posInBlock >= 0 && posInBlock < block.length());
1539
1540 QTextEngine *engine = d->blockLayout(block)->engine();
1541 const int itemIndex = engine->findItem(posInBlock);
1542
1543 if (itemIndex >= 0
1544 && engine->layoutData->items[itemIndex].analysis.script
1545 == QFontDatabasePrivate::Script_Emoji) {
1546 d->anchor = clusterStart;
1547 } else {
1548 --d->anchor;
1549 // Step over the high surrogate if we landed on a low surrogate
1550 const QStringView text = engine->layoutData->string;
1551 const int idx = d->anchor - block.position();
1552 if (idx > 0 && text.at(idx).isLowSurrogate()
1553 && text.at(idx - 1).isHighSurrogate()) {
1554 --d->anchor;
1555 }
1556 }
1557 } else {
1558 // Single code unit (ASCII/BMP): just step back one position
1559 --d->anchor;
1560 }
1561
1562 d->adjusted_anchor = d->anchor;
1563 d->remove();
1564 d->setX();
1565}
1566
1567/*!
1568 Selects text in the document according to the given \a selection.
1569*/
1570void QTextCursor::select(SelectionType selection)
1571{
1572 if (!d || !d->priv)
1573 return;
1574
1575 clearSelection();
1576
1577 const QTextBlock block = d->block();
1578
1579 switch (selection) {
1580 case LineUnderCursor:
1581 movePosition(StartOfLine);
1582 movePosition(EndOfLine, KeepAnchor);
1583 break;
1584 case WordUnderCursor:
1585 movePosition(StartOfWord);
1586 movePosition(EndOfWord, KeepAnchor);
1587 break;
1588 case BlockUnderCursor:
1589 if (block.length() == 1) // no content
1590 break;
1591 movePosition(StartOfBlock);
1592 // also select the paragraph separator
1593 if (movePosition(PreviousBlock)) {
1594 movePosition(EndOfBlock);
1595 movePosition(NextBlock, KeepAnchor);
1596 }
1597 movePosition(EndOfBlock, KeepAnchor);
1598 break;
1599 case Document:
1600 movePosition(Start);
1601 movePosition(End, KeepAnchor);
1602 break;
1603 }
1604}
1605
1606/*!
1607 Returns \c true if the cursor contains a selection; otherwise returns \c false.
1608*/
1609bool QTextCursor::hasSelection() const
1610{
1611 return !!d && d->position != d->anchor;
1612}
1613
1614
1615/*!
1616 Returns \c true if the cursor contains a selection that is not simply a
1617 range from selectionStart() to selectionEnd(); otherwise returns \c false.
1618
1619 Complex selections are ones that span at least two cells in a table;
1620 their extent is specified by selectedTableCells().
1621*/
1622bool QTextCursor::hasComplexSelection() const
1623{
1624 if (!d)
1625 return false;
1626
1627 return d->complexSelectionTable() != nullptr;
1628}
1629
1630/*!
1631 If the selection spans over table cells, \a firstRow is populated
1632 with the number of the first row in the selection, \a firstColumn
1633 with the number of the first column in the selection, and \a
1634 numRows and \a numColumns with the number of rows and columns in
1635 the selection. If the selection does not span any table cells the
1636 results are harmless but undefined.
1637*/
1638void QTextCursor::selectedTableCells(int *firstRow, int *numRows, int *firstColumn, int *numColumns) const
1639{
1640 *firstRow = -1;
1641 *firstColumn = -1;
1642 *numRows = -1;
1643 *numColumns = -1;
1644
1645 if (!d || d->position == d->anchor)
1646 return;
1647
1648 d->selectedTableCells(firstRow, numRows, firstColumn, numColumns);
1649}
1650
1651
1652/*!
1653 Clears the current selection by setting the anchor to the cursor position.
1654
1655 Note that it does \b{not} delete the text of the selection.
1656
1657 \sa removeSelectedText(), hasSelection()
1658*/
1659void QTextCursor::clearSelection()
1660{
1661 if (!d)
1662 return;
1663 d->adjusted_anchor = d->anchor = d->position;
1664 d->currentCharFormat = -1;
1665}
1666
1667/*!
1668 If there is a selection, its content is deleted; otherwise does
1669 nothing.
1670
1671 \sa hasSelection()
1672*/
1673void QTextCursor::removeSelectedText()
1674{
1675 if (!d || !d->priv || d->position == d->anchor)
1676 return;
1677
1678 d->priv->beginEditBlock();
1679 d->remove();
1680 d->priv->endEditBlock();
1681 d->setX();
1682}
1683
1684/*!
1685 Returns the start of the selection or position() if the
1686 cursor doesn't have a selection.
1687
1688 \sa selectionEnd(), position(), anchor()
1689*/
1690int QTextCursor::selectionStart() const
1691{
1692 if (!d || !d->priv)
1693 return -1;
1694 return qMin(d->position, d->adjusted_anchor);
1695}
1696
1697/*!
1698 Returns the end of the selection or position() if the cursor
1699 doesn't have a selection.
1700
1701 \sa selectionStart(), position(), anchor()
1702*/
1703int QTextCursor::selectionEnd() const
1704{
1705 if (!d || !d->priv)
1706 return -1;
1707 return qMax(d->position, d->adjusted_anchor);
1708}
1709
1710static void getText(QString &text, QTextDocumentPrivate *priv, const QString &docText, int pos, int end)
1711{
1712 while (pos < end) {
1713 QTextDocumentPrivate::FragmentIterator fragIt = priv->find(pos);
1714 const QTextFragmentData * const frag = fragIt.value();
1715
1716 const int offsetInFragment = qMax(0, pos - fragIt.position());
1717 const int len = qMin(int(frag->size_array[0] - offsetInFragment), end - pos);
1718
1719 text += QStringView(docText.constData() + frag->stringPosition + offsetInFragment, len);
1720 pos += len;
1721 }
1722}
1723
1724/*!
1725 Returns the current selection's text (which may be empty). This
1726 only returns the text, with no rich text formatting information.
1727 If you want a document fragment (i.e. formatted rich text) use
1728 selection() instead.
1729
1730 \note If the selection obtained from an editor spans a line break,
1731 the text will contain a Unicode U+2029 paragraph separator character
1732 instead of a newline \c{\n} character. Use QString::replace() to
1733 replace these characters with newlines.
1734*/
1735QString QTextCursor::selectedText() const
1736{
1737 if (!d || !d->priv || d->position == d->anchor)
1738 return QString();
1739
1740 const QString docText = d->priv->buffer();
1741 QString text;
1742
1743 QTextTable *table = d->complexSelectionTable();
1744 if (table) {
1745 int row_start, col_start, num_rows, num_cols;
1746 selectedTableCells(&row_start, &num_rows, &col_start, &num_cols);
1747
1748 Q_ASSERT(row_start != -1);
1749 for (int r = row_start; r < row_start + num_rows; ++r) {
1750 for (int c = col_start; c < col_start + num_cols; ++c) {
1751 QTextTableCell cell = table->cellAt(r, c);
1752 int rspan = cell.rowSpan();
1753 int cspan = cell.columnSpan();
1754 if (rspan != 1) {
1755 int cr = cell.row();
1756 if (cr != r)
1757 continue;
1758 }
1759 if (cspan != 1) {
1760 int cc = cell.column();
1761 if (cc != c)
1762 continue;
1763 }
1764
1765 getText(text, d->priv, docText, cell.firstPosition(), cell.lastPosition());
1766 }
1767 }
1768 } else {
1769 getText(text, d->priv, docText, selectionStart(), selectionEnd());
1770 }
1771
1772 return text;
1773}
1774
1775/*!
1776 Returns the current selection (which may be empty) with all its
1777 formatting information. If you just want the selected text (i.e.
1778 plain text) use selectedText() instead.
1779
1780 \note Unlike QTextDocumentFragment::toPlainText(),
1781 selectedText() may include special unicode characters such as
1782 QChar::ParagraphSeparator.
1783
1784 \sa QTextDocumentFragment::toPlainText()
1785*/
1786QTextDocumentFragment QTextCursor::selection() const
1787{
1788 return QTextDocumentFragment(*this);
1789}
1790
1791/*!
1792 Returns the block that contains the cursor.
1793*/
1794QTextBlock QTextCursor::block() const
1795{
1796 if (!d || !d->priv)
1797 return QTextBlock();
1798 return d->block();
1799}
1800
1801/*!
1802 Returns the block format of the block the cursor is in.
1803
1804 \sa setBlockFormat(), charFormat()
1805 */
1806QTextBlockFormat QTextCursor::blockFormat() const
1807{
1808 if (!d || !d->priv)
1809 return QTextBlockFormat();
1810
1811 return d->block().blockFormat();
1812}
1813
1814/*!
1815 Sets the block format of the current block (or all blocks that
1816 are contained in the selection) to \a format.
1817
1818 \sa blockFormat(), mergeBlockFormat()
1819*/
1820void QTextCursor::setBlockFormat(const QTextBlockFormat &format)
1821{
1822 if (!d || !d->priv)
1823 return;
1824
1825 d->setBlockFormat(format, QTextDocumentPrivate::SetFormat);
1826}
1827
1828/*!
1829 Modifies the block format of the current block (or all blocks that
1830 are contained in the selection) with the block format specified by
1831 \a modifier.
1832
1833 \sa setBlockFormat(), blockFormat()
1834*/
1835void QTextCursor::mergeBlockFormat(const QTextBlockFormat &modifier)
1836{
1837 if (!d || !d->priv)
1838 return;
1839
1840 d->setBlockFormat(modifier, QTextDocumentPrivate::MergeFormat);
1841}
1842
1843/*!
1844 Returns the block character format of the block the cursor is in.
1845
1846 The block char format is the format used when inserting text at the
1847 beginning of an empty block.
1848
1849 \sa setBlockCharFormat()
1850 */
1851QTextCharFormat QTextCursor::blockCharFormat() const
1852{
1853 if (!d || !d->priv)
1854 return QTextCharFormat();
1855
1856 return d->block().charFormat();
1857}
1858
1859/*!
1860 Sets the block char format of the current block (or all blocks that
1861 are contained in the selection) to \a format.
1862
1863 \sa blockCharFormat()
1864*/
1865void QTextCursor::setBlockCharFormat(const QTextCharFormat &format)
1866{
1867 if (!d || !d->priv)
1868 return;
1869
1870 d->setBlockCharFormat(format, QTextDocumentPrivate::SetFormatAndPreserveObjectIndices);
1871}
1872
1873/*!
1874 Modifies the block char format of the current block (or all blocks that
1875 are contained in the selection) with the block format specified by
1876 \a modifier.
1877
1878 \sa setBlockCharFormat()
1879*/
1880void QTextCursor::mergeBlockCharFormat(const QTextCharFormat &modifier)
1881{
1882 if (!d || !d->priv)
1883 return;
1884
1885 d->setBlockCharFormat(modifier, QTextDocumentPrivate::MergeFormat);
1886}
1887
1888/*!
1889 Returns the format of the character immediately before the cursor
1890 position(). If the cursor is positioned at the beginning of a text
1891 block that is not empty then the format of the character
1892 immediately after the cursor is returned.
1893
1894 \sa insertText(), blockFormat()
1895 */
1896QTextCharFormat QTextCursor::charFormat() const
1897{
1898 if (!d || !d->priv)
1899 return QTextCharFormat();
1900
1901 int idx = d->currentCharFormat;
1902 if (idx == -1) {
1903 QTextBlock block = d->block();
1904
1905 int pos;
1906 if (d->position == block.position()
1907 && block.length() > 1)
1908 pos = d->position;
1909 else
1910 pos = d->position - 1;
1911
1912 if (pos == -1) {
1913 idx = d->priv->blockCharFormatIndex(d->priv->blockMap().firstNode());
1914 } else {
1915 Q_ASSERT(pos >= 0 && pos < d->priv->length());
1916
1917 QTextDocumentPrivate::FragmentIterator it = d->priv->find(pos);
1918 Q_ASSERT(!it.atEnd());
1919 idx = it.value()->format;
1920 }
1921 }
1922
1923 QTextCharFormat cfmt = d->priv->formatCollection()->charFormat(idx);
1924 cfmt.clearProperty(QTextFormat::ObjectIndex);
1925
1926 Q_ASSERT(cfmt.isValid());
1927 return cfmt;
1928}
1929
1930/*!
1931 Sets the cursor's current character format to the given \a
1932 format. If the cursor has a selection, the given \a format is
1933 applied to the current selection.
1934
1935 \sa hasSelection(), mergeCharFormat()
1936*/
1937void QTextCursor::setCharFormat(const QTextCharFormat &format)
1938{
1939 if (!d || !d->priv)
1940 return;
1941 if (d->position == d->anchor) {
1942 d->currentCharFormat = d->priv->formatCollection()->indexForFormat(format);
1943 return;
1944 }
1945 d->setCharFormat(format, QTextDocumentPrivate::SetFormatAndPreserveObjectIndices);
1946}
1947
1948/*!
1949 Merges the cursor's current character format with the properties
1950 described by format \a modifier. If the cursor has a selection,
1951 this function applies all the properties set in \a modifier to all
1952 the character formats that are part of the selection.
1953
1954 \sa hasSelection(), setCharFormat()
1955*/
1956void QTextCursor::mergeCharFormat(const QTextCharFormat &modifier)
1957{
1958 if (!d || !d->priv)
1959 return;
1960 if (d->position == d->anchor) {
1961 QTextCharFormat format = charFormat();
1962 format.merge(modifier);
1963 d->currentCharFormat = d->priv->formatCollection()->indexForFormat(format);
1964 return;
1965 }
1966
1967 d->setCharFormat(modifier, QTextDocumentPrivate::MergeFormat);
1968}
1969
1970/*!
1971 Returns \c true if the cursor is at the start of a block; otherwise
1972 returns \c false.
1973
1974 \sa atBlockEnd(), atStart()
1975*/
1976bool QTextCursor::atBlockStart() const
1977{
1978 if (!d || !d->priv)
1979 return false;
1980
1981 return d->position == d->block().position();
1982}
1983
1984/*!
1985 Returns \c true if the cursor is at the end of a block; otherwise
1986 returns \c false.
1987
1988 \sa atBlockStart(), atEnd()
1989*/
1990bool QTextCursor::atBlockEnd() const
1991{
1992 if (!d || !d->priv)
1993 return false;
1994
1995 return d->position == d->block().position() + d->block().length() - 1;
1996}
1997
1998/*!
1999 Returns \c true if the cursor is at the start of the document;
2000 otherwise returns \c false.
2001
2002 \sa atBlockStart(), atEnd()
2003*/
2004bool QTextCursor::atStart() const
2005{
2006 if (!d || !d->priv)
2007 return false;
2008
2009 return d->position == 0;
2010}
2011
2012/*!
2013 \since 4.6
2014
2015 Returns \c true if the cursor is at the end of the document;
2016 otherwise returns \c false.
2017
2018 \sa atStart(), atBlockEnd()
2019*/
2020bool QTextCursor::atEnd() const
2021{
2022 if (!d || !d->priv)
2023 return false;
2024
2025 return d->position == d->priv->length() - 1;
2026}
2027
2028/*!
2029 Inserts a new empty block at the cursor position() with the
2030 current blockFormat() and charFormat().
2031
2032 \sa setBlockFormat()
2033*/
2034void QTextCursor::insertBlock()
2035{
2036 insertBlock(blockFormat());
2037}
2038
2039/*!
2040 \overload
2041
2042 Inserts a new empty block at the cursor position() with block
2043 format \a format and the current charFormat() as block char format.
2044
2045 \sa setBlockFormat()
2046*/
2047void QTextCursor::insertBlock(const QTextBlockFormat &format)
2048{
2049 QTextCharFormat charFmt = charFormat();
2050 charFmt.clearProperty(QTextFormat::ObjectType);
2051 insertBlock(format, charFmt);
2052}
2053
2054/*!
2055 \fn void QTextCursor::insertBlock(const QTextBlockFormat &format, const QTextCharFormat &charFormat)
2056 \overload
2057
2058 Inserts a new empty block at the cursor position() with block
2059 format \a format and \a charFormat as block char format.
2060
2061 \sa setBlockFormat()
2062*/
2063void QTextCursor::insertBlock(const QTextBlockFormat &format, const QTextCharFormat &_charFormat)
2064{
2065 if (!d || !d->priv)
2066 return;
2067
2068 QTextCharFormat charFormat = _charFormat;
2069 charFormat.clearProperty(QTextFormat::ObjectIndex);
2070
2071 d->priv->beginEditBlock();
2072 d->remove();
2073 d->insertBlock(format, charFormat);
2074 d->priv->endEditBlock();
2075 d->setX();
2076}
2077
2078/*!
2079 Inserts a new block at the current position and makes it the first
2080 list item of a newly created list with the given \a format. Returns
2081 the created list.
2082
2083 \sa currentList(), createList(), insertBlock()
2084 */
2085QTextList *QTextCursor::insertList(const QTextListFormat &format)
2086{
2087 insertBlock();
2088 return createList(format);
2089}
2090
2091/*!
2092 \overload
2093
2094 Inserts a new block at the current position and makes it the first
2095 list item of a newly created list with the given \a style. Returns
2096 the created list.
2097
2098 \sa currentList(), createList(), insertBlock()
2099 */
2100QTextList *QTextCursor::insertList(QTextListFormat::Style style)
2101{
2102 insertBlock();
2103 return createList(style);
2104}
2105
2106/*!
2107 Creates and returns a new list with the given \a format, and makes the
2108 current paragraph the cursor is in the first list item.
2109
2110 \sa insertList(), currentList()
2111 */
2112QTextList *QTextCursor::createList(const QTextListFormat &format)
2113{
2114 if (!d || !d->priv)
2115 return nullptr;
2116
2117 QTextList *list = static_cast<QTextList *>(d->priv->createObject(format));
2118 QTextBlockFormat modifier;
2119 modifier.setObjectIndex(list->objectIndex());
2120 mergeBlockFormat(modifier);
2121 return list;
2122}
2123
2124/*!
2125 \overload
2126
2127 Creates and returns a new list with the given \a style, making the
2128 cursor's current paragraph the first list item.
2129
2130 The style to be used is defined by the QTextListFormat::Style enum.
2131
2132 \sa insertList(), currentList()
2133 */
2134QTextList *QTextCursor::createList(QTextListFormat::Style style)
2135{
2136 QTextListFormat fmt;
2137 fmt.setStyle(style);
2138 return createList(fmt);
2139}
2140
2141/*!
2142 Returns the current list if the cursor position() is inside a
2143 block that is part of a list; otherwise returns \nullptr.
2144
2145 \sa insertList(), createList()
2146 */
2147QTextList *QTextCursor::currentList() const
2148{
2149 if (!d || !d->priv)
2150 return nullptr;
2151
2152 QTextBlockFormat b = blockFormat();
2153 QTextObject *o = d->priv->objectForFormat(b);
2154 return qobject_cast<QTextList *>(o);
2155}
2156
2157/*!
2158 \fn QTextTable *QTextCursor::insertTable(int rows, int columns)
2159
2160 \overload
2161
2162 Creates a new table with the given number of \a rows and \a columns,
2163 inserts it at the current cursor position() in the document, and returns
2164 the table object. The cursor is moved to the beginning of the first cell.
2165
2166 There must be at least one row and one column in the table.
2167
2168 \sa currentTable()
2169 */
2170QTextTable *QTextCursor::insertTable(int rows, int cols)
2171{
2172 return insertTable(rows, cols, QTextTableFormat());
2173}
2174
2175/*!
2176 \fn QTextTable *QTextCursor::insertTable(int rows, int columns, const QTextTableFormat &format)
2177
2178 Creates a new table with the given number of \a rows and \a columns
2179 in the specified \a format, inserts it at the current cursor position()
2180 in the document, and returns the table object. The cursor is moved to
2181 the beginning of the first cell.
2182
2183 There must be at least one row and one column in the table.
2184
2185 \sa currentTable()
2186*/
2187QTextTable *QTextCursor::insertTable(int rows, int cols, const QTextTableFormat &format)
2188{
2189 if (!d || !d->priv || rows <= 0 || cols <= 0)
2190 return nullptr;
2191
2192 // Sanity check input data
2193 int cellCount;
2194 int newLength;
2195 if (qMulOverflow(rows, cols, &cellCount)
2196 || qAddOverflow(d->priv->length(), cellCount, &newLength)
2197 || qAddOverflow(newLength, 1, &newLength)) {
2198 qWarning("QTextCursor::insertTable: Table with %d rows and %d columns is too large",
2199 rows, cols);
2200 return nullptr;
2201 }
2202
2203 int pos = d->position;
2204 QTextTable *t = QTextTablePrivate::createTable(d->priv, d->position, rows, cols, format);
2205 d->setPosition(pos+1);
2206 // ##### what should we do if we have a selection?
2207 d->anchor = d->position;
2208 d->adjusted_anchor = d->anchor;
2209 return t;
2210}
2211
2212/*!
2213 Returns a pointer to the current table if the cursor position()
2214 is inside a block that is part of a table; otherwise returns \nullptr.
2215
2216 \sa insertTable()
2217*/
2218QTextTable *QTextCursor::currentTable() const
2219{
2220 if (!d || !d->priv)
2221 return nullptr;
2222
2223 QTextFrame *frame = d->priv->frameAt(d->position);
2224 while (frame) {
2225 QTextTable *table = qobject_cast<QTextTable *>(frame);
2226 if (table)
2227 return table;
2228 frame = frame->parentFrame();
2229 }
2230 return nullptr;
2231}
2232
2233/*!
2234 Inserts a frame with the given \a format at the current cursor position(),
2235 moves the cursor position() inside the frame, and returns the frame.
2236
2237 If the cursor holds a selection, the whole selection is moved inside the
2238 frame.
2239
2240 \sa hasSelection()
2241*/
2242QTextFrame *QTextCursor::insertFrame(const QTextFrameFormat &format)
2243{
2244 if (!d || !d->priv)
2245 return nullptr;
2246
2247 return d->priv->insertFrame(selectionStart(), selectionEnd(), format);
2248}
2249
2250/*!
2251 Returns a pointer to the current frame. Returns \nullptr if the cursor is invalid.
2252
2253 \sa insertFrame()
2254*/
2255QTextFrame *QTextCursor::currentFrame() const
2256{
2257 if (!d || !d->priv)
2258 return nullptr;
2259
2260 return d->priv->frameAt(d->position);
2261}
2262
2263
2264/*!
2265 Inserts the text \a fragment at the current position().
2266*/
2267void QTextCursor::insertFragment(const QTextDocumentFragment &fragment)
2268{
2269 if (!d || !d->priv || fragment.isEmpty())
2270 return;
2271
2272 d->priv->beginEditBlock();
2273 d->remove();
2274 fragment.d->insert(*this);
2275 d->priv->endEditBlock();
2276 d->setX();
2277
2278 if (fragment.d && fragment.d->doc)
2279 d->priv->mergeCachedResources(QTextDocumentPrivate::get(fragment.d->doc));
2280}
2281
2282/*!
2283 \since 4.2
2284 Inserts the text \a html at the current position(). The text is interpreted as
2285 HTML.
2286
2287 \note When using this function with a style sheet, the style sheet will
2288 only apply to the current block in the document. In order to apply a style
2289 sheet throughout a document, use QTextDocument::setDefaultStyleSheet()
2290 instead.
2291*/
2292
2293#ifndef QT_NO_TEXTHTMLPARSER
2294
2295void QTextCursor::insertHtml(const QString &html)
2296{
2297 if (!d || !d->priv)
2298 return;
2299 QTextDocumentFragment fragment = QTextDocumentFragment::fromHtml(html, d->priv->document());
2300 insertFragment(fragment);
2301}
2302
2303#endif // QT_NO_TEXTHTMLPARSER
2304
2305/*!
2306 \since 6.4
2307 Inserts the \a markdown text at the current position(),
2308 with the specified Markdown \a features. The default is GitHub dialect.
2309*/
2310
2311#if QT_CONFIG(textmarkdownreader)
2312
2313void QTextCursor::insertMarkdown(const QString &markdown, QTextDocument::MarkdownFeatures features)
2314{
2315 if (!d || !d->priv)
2316 return;
2317 QTextDocumentFragment fragment = QTextDocumentFragment::fromMarkdown(markdown, features);
2318 if (markdown.startsWith(QLatin1Char('\n')))
2319 insertBlock(fragment.d->doc->firstBlock().blockFormat());
2320 insertFragment(fragment);
2321 if (!atEnd() && markdown.endsWith(QLatin1Char('\n')))
2322 insertText(QLatin1String("\n"));
2323}
2324
2325#endif // textmarkdownreader
2326
2327/*!
2328 \overload
2329 \since 4.2
2330
2331 Inserts the image defined by the given \a format at the cursor's current position
2332 with the specified \a alignment.
2333
2334 \sa position()
2335*/
2336void QTextCursor::insertImage(const QTextImageFormat &format, QTextFrameFormat::Position alignment)
2337{
2338 if (!d || !d->priv)
2339 return;
2340
2341 QTextFrameFormat ffmt;
2342 ffmt.setPosition(alignment);
2343 QTextObject *obj = d->priv->createObject(ffmt);
2344
2345 QTextImageFormat fmt = format;
2346 fmt.setObjectIndex(obj->objectIndex());
2347
2348 d->priv->beginEditBlock();
2349 d->remove();
2350 const int idx = d->priv->formatCollection()->indexForFormat(fmt);
2351 d->priv->insert(d->position, QChar(QChar::ObjectReplacementCharacter), idx);
2352 d->priv->endEditBlock();
2353}
2354
2355/*!
2356 Inserts the image defined by \a format at the current position().
2357*/
2358void QTextCursor::insertImage(const QTextImageFormat &format)
2359{
2360 insertText(QString(QChar::ObjectReplacementCharacter), format);
2361}
2362
2363/*!
2364 \overload
2365
2366 Convenience method for inserting the image with the given \a name at the
2367 current position().
2368
2369 \snippet code/src_gui_text_qtextcursor.cpp 1
2370*/
2371void QTextCursor::insertImage(const QString &name)
2372{
2373 QTextImageFormat format;
2374 format.setName(name);
2375 insertImage(format);
2376}
2377
2378/*!
2379 \since 4.5
2380 \overload
2381
2382 Convenience function for inserting the given \a image with an optional
2383 \a name at the current position().
2384*/
2385void QTextCursor::insertImage(const QImage &image, const QString &name)
2386{
2387 if (image.isNull()) {
2388 qWarning("QTextCursor::insertImage: attempt to add an invalid image");
2389 return;
2390 }
2391 QString imageName = name;
2392 if (name.isEmpty())
2393 imageName = QString::number(image.cacheKey());
2394 d->priv->document()->addResource(QTextDocument::ImageResource, QUrl(imageName), image);
2395 QTextImageFormat format;
2396 format.setName(imageName);
2397 insertImage(format);
2398}
2399
2400/*!
2401 \fn bool QTextCursor::operator!=(const QTextCursor &other) const
2402
2403 Returns \c true if the \a other cursor is at a different position in
2404 the document as this cursor; otherwise returns \c false.
2405*/
2406bool QTextCursor::operator!=(const QTextCursor &rhs) const
2407{
2408 return !operator==(rhs);
2409}
2410
2411/*!
2412 \fn bool QTextCursor::operator<(const QTextCursor &other) const
2413
2414 Returns \c true if the \a other cursor is positioned later in the
2415 document than this cursor; otherwise returns \c false.
2416*/
2417bool QTextCursor::operator<(const QTextCursor &rhs) const
2418{
2419 if (!d)
2420 return !!rhs.d;
2421
2422 if (!rhs.d)
2423 return false;
2424
2425 Q_ASSERT_X(d->priv == rhs.d->priv, "QTextCursor::operator<", "cannot compare cursors attached to different documents");
2426
2427 return d->position < rhs.d->position;
2428}
2429
2430/*!
2431 \fn bool QTextCursor::operator<=(const QTextCursor &other) const
2432
2433 Returns \c true if the \a other cursor is positioned later or at the
2434 same position in the document as this cursor; otherwise returns
2435 false.
2436*/
2437bool QTextCursor::operator<=(const QTextCursor &rhs) const
2438{
2439 if (!d)
2440 return true;
2441
2442 if (!rhs.d)
2443 return false;
2444
2445 Q_ASSERT_X(d->priv == rhs.d->priv, "QTextCursor::operator<=", "cannot compare cursors attached to different documents");
2446
2447 return d->position <= rhs.d->position;
2448}
2449
2450/*!
2451 \fn bool QTextCursor::operator==(const QTextCursor &other) const
2452
2453 Returns \c true if the \a other cursor is at the same position in the
2454 document as this cursor; otherwise returns \c false.
2455*/
2456bool QTextCursor::operator==(const QTextCursor &rhs) const
2457{
2458 if (!d)
2459 return !rhs.d;
2460
2461 if (!rhs.d)
2462 return false;
2463
2464 return d->position == rhs.d->position && d->priv == rhs.d->priv;
2465}
2466
2467/*!
2468 \fn bool QTextCursor::operator>=(const QTextCursor &other) const
2469
2470 Returns \c true if the \a other cursor is positioned earlier or at the
2471 same position in the document as this cursor; otherwise returns
2472 false.
2473*/
2474bool QTextCursor::operator>=(const QTextCursor &rhs) const
2475{
2476 if (!d)
2477 return false;
2478
2479 if (!rhs.d)
2480 return true;
2481
2482 Q_ASSERT_X(d->priv == rhs.d->priv, "QTextCursor::operator>=", "cannot compare cursors attached to different documents");
2483
2484 return d->position >= rhs.d->position;
2485}
2486
2487/*!
2488 \fn bool QTextCursor::operator>(const QTextCursor &other) const
2489
2490 Returns \c true if the \a other cursor is positioned earlier in the
2491 document than this cursor; otherwise returns \c false.
2492*/
2493bool QTextCursor::operator>(const QTextCursor &rhs) const
2494{
2495 if (!d)
2496 return false;
2497
2498 if (!rhs.d)
2499 return true;
2500
2501 Q_ASSERT_X(d->priv == rhs.d->priv, "QTextCursor::operator>", "cannot compare cursors attached to different documents");
2502
2503 return d->position > rhs.d->position;
2504}
2505
2506/*!
2507 Indicates the start of a block of editing operations on the
2508 document that should appear as a single operation from an
2509 undo/redo point of view.
2510
2511 For example:
2512
2513 \snippet code/src_gui_text_qtextcursor.cpp 2
2514
2515 The call to undo() will cause both insertions to be undone,
2516 causing both "World" and "Hello" to be removed.
2517
2518 It is possible to nest calls to beginEditBlock and endEditBlock. The
2519 top-most pair will determine the scope of the undo/redo operation.
2520
2521 While an edit block is open, the document postpones updating its layout
2522 and emitting QTextDocument::contentsChange() until the outermost
2523 endEditBlock() call. When you make many changes, such as inserting text
2524 in a loop or filling a table cell by cell, group them in an edit block.
2525 Otherwise, the document is laid out again after every change, which can
2526 be very slow, even for small documents.
2527
2528 \sa endEditBlock()
2529 */
2530void QTextCursor::beginEditBlock()
2531{
2532 if (!d || !d->priv)
2533 return;
2534
2535 if (d->priv->editBlock == 0) // we are the initial edit block, store current cursor position for undo
2536 d->priv->editBlockCursorPosition = d->position;
2537
2538 d->priv->beginEditBlock();
2539}
2540
2541/*!
2542 Like beginEditBlock() indicates the start of a block of editing operations
2543 that should appear as a single operation for undo/redo. However unlike
2544 beginEditBlock() it does not start a new block but reverses the previous call to
2545 endEditBlock() and therefore makes following operations part of the previous edit block created.
2546
2547 For example:
2548
2549 \snippet code/src_gui_text_qtextcursor.cpp 3
2550
2551 The call to undo() will cause all three insertions to be undone.
2552
2553 \sa beginEditBlock(), endEditBlock()
2554 */
2555void QTextCursor::joinPreviousEditBlock()
2556{
2557 if (!d || !d->priv)
2558 return;
2559
2560 d->priv->joinPreviousEditBlock();
2561}
2562
2563/*!
2564 Indicates the end of a block of editing operations on the document
2565 that should appear as a single operation from an undo/redo point
2566 of view.
2567
2568 \sa beginEditBlock()
2569 */
2570
2571void QTextCursor::endEditBlock()
2572{
2573 if (!d || !d->priv)
2574 return;
2575
2576 d->priv->endEditBlock();
2577}
2578
2579/*!
2580 Returns \c true if this cursor and \a other are copies of each other, i.e.
2581 one of them was created as a copy of the other and neither has moved since.
2582 This is much stricter than equality.
2583
2584 \sa operator=(), operator==()
2585*/
2586bool QTextCursor::isCopyOf(const QTextCursor &other) const
2587{
2588 return d == other.d;
2589}
2590
2591/*!
2592 \since 4.2
2593 Returns the number of the block the cursor is in, or 0 if the cursor is invalid.
2594
2595 Note that this function only makes sense in documents without complex objects such
2596 as tables or frames.
2597*/
2598int QTextCursor::blockNumber() const
2599{
2600 if (!d || !d->priv)
2601 return 0;
2602
2603 return d->block().blockNumber();
2604}
2605
2606
2607/*!
2608 \since 4.2
2609 Returns the position of the cursor within its containing line.
2610
2611 Note that this is the column number relative to a wrapped line,
2612 not relative to the block (i.e. the paragraph).
2613
2614 You probably want to call positionInBlock() instead.
2615
2616 \sa positionInBlock()
2617*/
2618int QTextCursor::columnNumber() const
2619{
2620 if (!d || !d->priv)
2621 return 0;
2622
2623 QTextBlock block = d->block();
2624 if (!block.isValid())
2625 return 0;
2626
2627 const QTextLayout *layout = d->blockLayout(block);
2628
2629 const int relativePos = d->position - block.position();
2630
2631 if (layout->lineCount() == 0)
2632 return relativePos;
2633
2634 QTextLine line = layout->lineForTextPosition(relativePos);
2635 if (!line.isValid())
2636 return 0;
2637 return relativePos - line.textStart();
2638}
2639
2640/*!
2641 \since 4.5
2642 Returns the document this cursor is associated with.
2643*/
2644QTextDocument *QTextCursor::document() const
2645{
2646 if (d->priv)
2647 return d->priv->document();
2648 return nullptr; // document went away
2649}
2650
2651QT_END_NAMESPACE
Combined button and popup list for selecting options.
static void getText(QString &text, QTextDocumentPrivate *priv, const QString &docText, int pos, int end)
static void setBlockCharFormatHelper(QTextDocumentPrivate *priv, int pos1, int pos2, const QTextCharFormat &format, QTextDocumentPrivate::FormatChangeMode changeMode)
@ AdjustDown
@ AdjustNext
@ AdjustPrev
@ AdjustUp
#define QTextBeginningOfFrame
#define QTextEndOfFrame