File: KoTextEditor.cpp

package info (click to toggle)
calligra 1%3A25.04.2%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 309,164 kB
  • sloc: cpp: 667,890; xml: 126,105; perl: 2,724; python: 2,497; yacc: 1,817; ansic: 1,326; sh: 1,223; lex: 1,107; javascript: 495; makefile: 24
file content (1629 lines) | stat: -rw-r--r-- 55,164 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
/* This file is part of the KDE project
 * SPDX-FileCopyrightText: 2009-2012 Pierre Stirnweiss <pstirnweiss@googlemail.com>
 * SPDX-FileCopyrightText: 2006-2010 Thomas Zander <zander@kde.org>
 * SPDX-FileCopyrightText: 2011 Boudewijn Rempt <boud@kogmbh.com>
 * SPDX-FileCopyrightText: 2011-2015 C. Boemann <cbo@boemann.dk>
 * SPDX-FileCopyrightText: 2014-2015 Denis Kuplyakov <dener.kup@gmail.com>
 * SPDX-FileCopyrightText: 2015 Soma Schliszka <soma.schliszka@gmail.com>
 *
 * SPDX-License-Identifier: LGPL-2.0-or-later
 */

#include "KoTextEditor.h"
#include "KoTextEditor_p.h"

#include "BibliographyGenerator.h"
#include "KoAnnotation.h"
#include "KoBibliographyInfo.h"
#include "KoBookmark.h"
#include "KoInlineCite.h"
#include "KoInlineNote.h"
#include "KoInlineTextObjectManager.h"
#include "KoList.h"
#include "KoShapeAnchor.h"
#include "KoTableColumnAndRowStyleManager.h"
#include "KoTableOfContentsGeneratorInfo.h"
#include "KoTextDocument.h"
#include "KoTextLocator.h"
#include "KoTextRangeManager.h"
#include "changetracker/KoChangeTracker.h"
#include "changetracker/KoChangeTrackerElement.h"
#include "commands/AddAnnotationCommand.h"
#include "commands/AddTextRangeCommand.h"
#include "commands/ChangeListCommand.h"
#include "commands/DeleteAnchorsCommand.h"
#include "commands/DeleteAnnotationsCommand.h"
#include "commands/DeleteCommand.h"
#include "commands/DeleteTableColumnCommand.h"
#include "commands/DeleteTableRowCommand.h"
#include "commands/InsertInlineObjectCommand.h"
#include "commands/InsertNoteCommand.h"
#include "commands/InsertTableColumnCommand.h"
#include "commands/InsertTableRowCommand.h"
#include "commands/ListItemNumberingCommand.h"
#include "commands/NewSectionCommand.h"
#include "commands/RenameSectionCommand.h"
#include "commands/ResizeTableCommand.h"
#include "commands/SplitSectionsCommand.h"
#include "commands/TextPasteCommand.h"
#include "styles/KoCharacterStyle.h"
#include "styles/KoParagraphStyle.h"
#include "styles/KoStyleManager.h"
#include "styles/KoTableCellStyle.h"
#include "styles/KoTableStyle.h"
#include <KoCanvasBase.h>
#include <KoSelection.h>
#include <KoShapeController.h>
#include <KoShapeManager.h>
#include <KoTextShapeDataBase.h>

#include <KLocalizedString>

#include <QRegularExpression>
#include <QTextBlock>
#include <QTextBlockFormat>
#include <QTextCharFormat>
#include <QTextDocument>
#include <QTextDocumentFragment>
#include <QTextFormat>
#include <QTextList>
#include <QTextTable>
#include <QTextTableCell>
#include <kundo2command.h>

#include "KoTextDebug.h"
#include "TextDebug.h"

Q_DECLARE_METATYPE(QTextFrame *)

/*Private*/

KoTextEditor::Private::Private(KoTextEditor *qq, QTextDocument *document)
    : q(qq)
    , document(document)
    , addNewCommand(true)
    , dummyMacroAdded(false)
    , customCommandCount(0)
    , editProtectionCached(false)
{
    caret = QTextCursor(document);
    editorState = NoOp;
}

void KoTextEditor::Private::emitTextFormatChanged()
{
    Q_EMIT q->textFormatChanged();
}

void KoTextEditor::Private::newLine(KUndo2Command *parent)
{
    // Handle if this is the special block before a table
    bool hiddenTableHandling = caret.blockFormat().hasProperty(KoParagraphStyle::HiddenByTable);
    if (hiddenTableHandling) {
        // Easy solution is to go back to the end of previous block and do the insertion from there.
        // However if there is no block before we have a problem. This may be the case if there is
        // a table before or we are at the beginning of a cell or a document.
        // So here is a better approach
        // 1) create block
        // 2) select the previous block so it get's deleted and replaced
        // 3) remove HiddenByTable from both new and previous block
        // 4) actually make new line replacing the block we just inserted
        // 5) set HiddenByTable on the block just before the table again
        caret.insertText("oops you should never see this");
        caret.insertBlock();
        caret.movePosition(QTextCursor::PreviousCharacter, QTextCursor::KeepAnchor);
        caret.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor);
        QTextBlockFormat bf = caret.blockFormat();
        bf.clearProperty(KoParagraphStyle::HiddenByTable);
        caret.setBlockFormat(bf);
    }

    if (caret.hasSelection()) {
        q->deleteChar(false, parent);
    }
    KoTextDocument textDocument(document);
    KoStyleManager *styleManager = textDocument.styleManager();
    KoParagraphStyle *nextStyle = nullptr;
    KoParagraphStyle *currentStyle = nullptr;
    if (styleManager) {
        int id = caret.blockFormat().intProperty(KoParagraphStyle::StyleId);
        currentStyle = styleManager->paragraphStyle(id);
        if (currentStyle == nullptr) // not a style based parag.  Lets make the next one correct.
            nextStyle = styleManager->defaultParagraphStyle();
        else
            nextStyle = styleManager->paragraphStyle(currentStyle->nextStyle());
        Q_ASSERT(nextStyle);
        if (currentStyle == nextStyle)
            nextStyle = nullptr;
    }

    QTextCharFormat format = caret.charFormat();
    if (format.hasProperty(KoCharacterStyle::ChangeTrackerId)) {
        format.clearProperty(KoCharacterStyle::ChangeTrackerId);
    }

    // Build the block format and subtract the properties that are not inherited
    QTextBlockFormat bf = caret.blockFormat();

    bf.clearProperty(KoParagraphStyle::BreakBefore);
    bf.clearProperty(KoParagraphStyle::ListStartValue);
    bf.clearProperty(KoParagraphStyle::UnnumberedListItem);
    bf.clearProperty(KoParagraphStyle::IsListHeader);
    bf.clearProperty(KoParagraphStyle::MasterPageName);
    bf.clearProperty(KoParagraphStyle::OutlineLevel);
    bf.clearProperty(KoParagraphStyle::HiddenByTable);

    // We should stay in the same section so we can't start new one.
    bf.clearProperty(KoParagraphStyle::SectionStartings);
    // But we move all the current endings to the next paragraph.
    QTextBlockFormat origin = caret.blockFormat();
    origin.clearProperty(KoParagraphStyle::SectionEndings);
    caret.setBlockFormat(origin);

    // Build the block char format which is just a copy
    QTextCharFormat bcf = caret.blockCharFormat();

    // Actually insert the new paragraph char
    int startPosition = caret.position();

    caret.insertBlock(bf, bcf);

    int endPosition = caret.position();

    // Mark the CR as a tracked change
    QTextCursor changeCursor(document);
    changeCursor.beginEditBlock();
    changeCursor.setPosition(startPosition);
    changeCursor.setPosition(endPosition, QTextCursor::KeepAnchor);
    changeCursor.endEditBlock();

    q->registerTrackedChange(changeCursor, KoGenChange::InsertChange, kundo2_i18n("New Paragraph"), format, format, false);

    // possibly change the style if requested
    if (nextStyle) {
        QTextBlock block = caret.block();
        if (currentStyle)
            currentStyle->unapplyStyle(block);
        nextStyle->applyStyle(block);
        format = block.charFormat();
    }

    caret.setCharFormat(format);

    if (hiddenTableHandling) {
        // see code and comment above
        QTextBlockFormat bf = caret.blockFormat();
        bf.setProperty(KoParagraphStyle::HiddenByTable, true);
        caret.setBlockFormat(bf);
        caret.movePosition(QTextCursor::PreviousCharacter);
    }
}

/*KoTextEditor*/

// TODO factor out the changeTracking charFormat setting from all individual slots to a public slot, which will be available for external commands (TextShape)

// The BlockFormatVisitor and CharFormatVisitor are used when a property needs to be modified relative to its current value (which could be different over the
// selection). For example: increase indentation by 10pt. The BlockFormatVisitor is also used for the change tracking of a blockFormat. The changeTracker stores
// the information about the changeId in the charFormat. The BlockFormatVisitor ensures that thd changeId is set on the whole block (even if only a part of the
// block is actually selected). Should such mechanisms be later provided directly by Qt, we could dispose of these classes.

KoTextEditor::KoTextEditor(QTextDocument *document)
    : QObject(document)
    , d(new Private(this, document))
{
    connect(d->document, &QTextDocument::undoCommandAdded, this, [this]() {
        d->documentCommandAdded();
    });
}

KoTextEditor::~KoTextEditor()
{
    delete d;
}

KoTextEditor *KoTextEditor::getTextEditorFromCanvas(KoCanvasBase *canvas)
{
    KoSelection *selection = canvas->shapeManager()->selection();
    if (selection) {
        foreach (KoShape *shape, selection->selectedShapes()) {
            if (KoTextShapeDataBase *textData = qobject_cast<KoTextShapeDataBase *>(shape->userData())) {
                KoTextDocument doc(textData->document());
                return doc.textEditor();
            }
        }
    }
    return nullptr;
}

QTextCursor *KoTextEditor::cursor()
{
    return &(d->caret);
}

const QTextCursor KoTextEditor::constCursor() const
{
    return QTextCursor(d->caret);
}

void KoTextEditor::registerTrackedChange(QTextCursor &selection,
                                         KoGenChange::Type changeType,
                                         const KUndo2MagicString &title,
                                         QTextFormat &format,
                                         QTextFormat &prevFormat,
                                         bool applyToWholeBlock)
{
    KoChangeTracker *changeTracker = KoTextDocument(d->document).changeTracker();
    if (!changeTracker || !changeTracker->recordChanges()) {
        // clear the ChangeTrackerId from the passed in selection, without recursively registering
        // change tracking again  ;)
        int start = qMin(selection.position(), selection.anchor());
        int end = qMax(selection.position(), selection.anchor());

        QTextBlock block = selection.block();
        if (block.position() > start)
            block = block.document()->findBlock(start);

        while (block.isValid() && block.position() < end) {
            QTextBlock::iterator iter = block.begin();
            while (!iter.atEnd()) {
                QTextFragment fragment = iter.fragment();
                if (fragment.position() > end) {
                    break;
                }

                if (fragment.position() + fragment.length() <= start) {
                    ++iter;
                    continue;
                }

                QTextCursor cursor(block);
                cursor.setPosition(fragment.position());
                QTextCharFormat fm = fragment.charFormat();

                if (fm.hasProperty(KoCharacterStyle::ChangeTrackerId)) {
                    fm.clearProperty(KoCharacterStyle::ChangeTrackerId);
                    int to = qMin(end, fragment.position() + fragment.length());
                    cursor.setPosition(to, QTextCursor::KeepAnchor);
                    cursor.setCharFormat(fm);
                    iter = block.begin();
                } else {
                    ++iter;
                }
            }
            block = block.next();
        }
    } else {
        if (changeType != KoGenChange::DeleteChange) {
            // first check if there already is an identical change registered just before or just after the selection. If so, merge appropriately.
            // TODO implement for format change. handle the prevFormat/newFormat check.
            QTextCursor checker = QTextCursor(selection);
            int idBefore = 0;
            int idAfter = 0;
            int changeId = 0;
            int selectionBegin = qMin(checker.anchor(), checker.position());
            int selectionEnd = qMax(checker.anchor(), checker.position());

            checker.setPosition(selectionBegin);
            if (!checker.atBlockStart()) {
                int changeId = checker.charFormat().property(KoCharacterStyle::ChangeTrackerId).toInt();
                if (changeId && changeTracker->elementById(changeId)->getChangeType() == changeType)
                    idBefore = changeId;
            } else {
                if (!checker.currentTable()) {
                    int changeId = checker.blockFormat().intProperty(KoCharacterStyle::ChangeTrackerId);
                    if (changeId && changeTracker->elementById(changeId)->getChangeType() == changeType)
                        idBefore = changeId;
                } else {
                    idBefore = checker.currentTable()->format().intProperty(KoCharacterStyle::ChangeTrackerId);
                    if (!idBefore) {
                        idBefore = checker.currentTable()->cellAt(checker).format().intProperty(KoCharacterStyle::ChangeTrackerId);
                    }
                }
            }

            checker.setPosition(selectionEnd);
            if (!checker.atEnd()) {
                checker.movePosition(QTextCursor::NextCharacter);
                idAfter = changeTracker->mergeableId(changeType, title, checker.charFormat().property(KoCharacterStyle::ChangeTrackerId).toInt());
            }
            changeId = (idBefore) ? idBefore : idAfter;

            switch (changeType) { // TODO: this whole thing actually needs to be done like a visitor. If the selection contains several change regions, the
                                  // parenting needs to be individualised.
            case KoGenChange::InsertChange:
                if (!changeId)
                    changeId = changeTracker->getInsertChangeId(title, 0);
                break;
            case KoGenChange::FormatChange:
                if (!changeId)
                    changeId = changeTracker->getFormatChangeId(title, format, prevFormat, 0);
                break;
            case KoGenChange::DeleteChange:
                // this should never be the case
                break;
            default:; // do nothing
            }

            if (applyToWholeBlock) {
                selection.movePosition(QTextCursor::StartOfBlock);
                selection.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);
            }

            QTextCharFormat f;
            f.setProperty(KoCharacterStyle::ChangeTrackerId, changeId);
            selection.mergeCharFormat(f);

            QTextBlock startBlock = selection.document()->findBlock(selection.anchor());
            QTextBlock endBlock = selection.document()->findBlock(selection.position());

            while (startBlock.isValid() && startBlock != endBlock) {
                startBlock = startBlock.next();
                QTextCursor cursor(startBlock);
                QTextBlockFormat blockFormat;
                blockFormat.setProperty(KoCharacterStyle::ChangeTrackerId, changeId);
                cursor.mergeBlockFormat(blockFormat);

                QTextCharFormat blockCharFormat = cursor.blockCharFormat();
                if (blockCharFormat.hasProperty(KoCharacterStyle::ChangeTrackerId)) {
                    blockCharFormat.clearProperty(KoCharacterStyle::ChangeTrackerId);
                    cursor.setBlockCharFormat(blockCharFormat);
                }
            }
        }
    }
}

// To figure out if a the blocks of the selection are write protected we need to
// traverse the entire document as sections build up the protectiveness recursively.
void KoTextEditor::recursivelyVisitSelection(QTextFrame::iterator it, KoTextVisitor &visitor) const
{
    do {
        if (visitor.abortVisiting())
            return;

        QTextBlock block = it.currentBlock();
        QTextTable *table = qobject_cast<QTextTable *>(it.currentFrame());
        QTextFrame *subFrame = it.currentFrame();
        if (table) {
            // There are 4 ways this table can be selected:
            //  - "before to mid"
            //  - "mid to after"
            //  - "complex mid to mid"
            //  - "simple mid to mid"
            // The 3 first are entire cells, the fourth is within a cell

            if (d->caret.selectionStart() <= table->lastPosition() && d->caret.selectionEnd() >= table->firstPosition()) {
                // We have a selection somewhere
                QTextTableCell cell1 = table->cellAt(d->caret.selectionStart());
                QTextTableCell cell2 = table->cellAt(d->caret.selectionEnd());
                if (cell1 != cell2 || !cell1.isValid() || !cell2.isValid()) {
                    // And the selection is complex or entire table
                    int selectionRow;
                    int selectionColumn;
                    int selectionRowSpan;
                    int selectionColumnSpan;
                    if (!cell1.isValid() || !cell2.isValid()) {
                        // entire table
                        visitor.visitTable(table, KoTextVisitor::Entirely);
                        selectionRow = selectionColumn = 0;
                        selectionRowSpan = table->rows();
                        selectionColumnSpan = table->columns();
                    } else {
                        visitor.visitTable(table, KoTextVisitor::Partly);
                        d->caret.selectedTableCells(&selectionRow, &selectionRowSpan, &selectionColumn, &selectionColumnSpan);
                    }

                    for (int r = selectionRow; r < selectionRow + selectionRowSpan; r++) {
                        for (int c = selectionColumn; c < selectionColumn + selectionColumnSpan; c++) {
                            QTextTableCell cell = table->cellAt(r, c);
                            if (!cell.format().boolProperty(KoTableCellStyle::CellIsProtected)) {
                                visitor.visitTableCell(&cell, KoTextVisitor::Partly);
                                recursivelyVisitSelection(cell.begin(), visitor);
                            } else {
                                visitor.nonVisit();
                            }

                            if (visitor.abortVisiting())
                                return;
                        }
                    }
                } else {
                    visitor.visitTable(table, KoTextVisitor::Partly);
                    // And the selection is simple
                    if (!cell1.format().boolProperty(KoTableCellStyle::CellIsProtected)) {
                        visitor.visitTableCell(&cell1, KoTextVisitor::Entirely);
                        recursivelyVisitSelection(cell1.begin(), visitor);
                    } else {
                        visitor.nonVisit();
                    }
                    return;
                }
            }
            if (d->caret.selectionEnd() <= table->lastPosition()) {
                return;
            }
        } else if (subFrame) {
            recursivelyVisitSelection(subFrame->begin(), visitor);
        } else {
            // TODO build up the section stack

            if (d->caret.selectionStart() < block.position() + block.length() && d->caret.selectionEnd() >= block.position()) {
                // We have a selection somewhere
                if (true) { // TODO don't change if block is protected by section
                    visitor.visitBlock(block, d->caret);
                } else {
                    visitor.nonVisit();
                }
            }

            // TODO tear down the section stack

            if (d->caret.selectionEnd() < block.position() + block.length()) {
                return;
            }
        }
        if (!it.atEnd()) {
            ++it;
        }
    } while (!it.atEnd());
}

KoBookmark *KoTextEditor::addBookmark(const QString &name)
{ // TODO changeTracking
    KUndo2Command *topCommand = beginEditBlock(kundo2_i18n("Add Bookmark"));

    KoBookmark *bookmark = new KoBookmark(d->caret);
    bookmark->setName(name);
    bookmark->setManager(KoTextDocument(d->document).textRangeManager());

    addCommand(new AddTextRangeCommand(bookmark, topCommand));

    endEditBlock();

    return bookmark;
}

KoAnnotation *KoTextEditor::addAnnotation(KoShape *annotationShape)
{
    KUndo2Command *topCommand = beginEditBlock(kundo2_i18n("Add Annotation"));

    KoAnnotation *annotation = new KoAnnotation(d->caret);
    KoTextRangeManager *textRangeManager = KoTextDocument(d->document).textRangeManager();
    annotation->setManager(textRangeManager);
    // FIXME: I need the name, a unique name, we can set selected text as annotation name or use createUniqueAnnotationName function
    //  to do it for us.
    QString name = annotation->createUniqueAnnotationName(textRangeManager->annotationManager(), "", false);
    annotation->setName(name);
    annotation->setAnnotationShape(annotationShape);

    addCommand(new AddAnnotationCommand(annotation, topCommand));

    endEditBlock();

    return annotation;
}

KoInlineObject *KoTextEditor::insertIndexMarker()
{ // TODO changeTracking
    if (isEditProtected()) {
        return nullptr;
    }

    d->updateState(KoTextEditor::Private::Custom, kundo2_i18n("Insert Index"));

    if (d->caret.blockFormat().hasProperty(KoParagraphStyle::HiddenByTable)) {
        d->newLine(nullptr);
    }

    QTextBlock block = d->caret.block();
    if (d->caret.position() >= block.position() + block.length() - 1)
        return nullptr; // can't insert one at end of text
    if (block.text().at(d->caret.position() - block.position()).isSpace())
        return nullptr; // can't insert one on a whitespace as that does not indicate a word.

    KoTextLocator *tl = new KoTextLocator();
    KoTextDocument(d->document).inlineTextObjectManager()->insertInlineObject(d->caret, tl);
    d->updateState(KoTextEditor::Private::NoOp);
    return tl;
}

void KoTextEditor::insertInlineObject(KoInlineObject *inliner, KUndo2Command *cmd)
{
    if (isEditProtected()) {
        return;
    }

    KUndo2Command *topCommand = cmd;
    if (!cmd) {
        topCommand = beginEditBlock(kundo2_i18n("Insert Variable"));
    }

    if (d->caret.hasSelection()) {
        deleteChar(false, topCommand);
    }
    d->caret.beginEditBlock();

    if (d->caret.blockFormat().hasProperty(KoParagraphStyle::HiddenByTable)) {
        d->newLine(nullptr);
    }

    QTextCharFormat format = d->caret.charFormat();
    if (format.hasProperty(KoCharacterStyle::ChangeTrackerId)) {
        format.clearProperty(KoCharacterStyle::ChangeTrackerId);
    }

    InsertInlineObjectCommand *insertInlineObjectCommand = new InsertInlineObjectCommand(inliner, d->document, topCommand);
    Q_UNUSED(insertInlineObjectCommand);
    d->caret.endEditBlock();

    if (!cmd) {
        addCommand(topCommand);
        endEditBlock();
    }

    Q_EMIT cursorPositionChanged();
}

void KoTextEditor::updateInlineObjectPosition(int start, int end)
{
    KoInlineTextObjectManager *inlineObjectManager = KoTextDocument(d->document).inlineTextObjectManager();
    // and, of course, every inline object after the current position has the wrong position
    QTextCursor cursor = d->document->find(QString(QChar::ObjectReplacementCharacter), start);
    while (!cursor.isNull() && (end > -1 && cursor.position() < end)) {
        QTextCharFormat fmt = cursor.charFormat();
        KoInlineObject *obj = inlineObjectManager->inlineTextObject(fmt);
        obj->updatePosition(d->document, cursor.position(), fmt);
        cursor = d->document->find(QString(QChar::ObjectReplacementCharacter), cursor.position());
    }
}

void KoTextEditor::removeAnchors(const QList<KoShapeAnchor *> &anchors, KUndo2Command *parent)
{
    Q_ASSERT(parent);
    addCommand(new DeleteAnchorsCommand(anchors, d->document, parent));
}

void KoTextEditor::removeAnnotations(const QList<KoAnnotation *> &annotations, KUndo2Command *parent)
{
    Q_ASSERT(parent);
    addCommand(new DeleteAnnotationsCommand(annotations, d->document, parent));
}

void KoTextEditor::insertFrameBreak()
{
    if (isEditProtected()) {
        return;
    }

    QTextCursor curr(d->caret.block());
    if (dynamic_cast<QTextTable *>(curr.currentFrame())) {
        return;
    }

    d->updateState(KoTextEditor::Private::KeyPress, kundo2_i18n("Insert Break"));
    QTextBlock block = d->caret.block();
    if (d->caret.position() == block.position() && block.length() > 0) { // start of parag
        QTextBlockFormat bf = d->caret.blockFormat();
        bf.setProperty(KoParagraphStyle::BreakBefore, KoText::PageBreak);
        d->caret.insertBlock(bf);
        if (block.textList())
            block.textList()->remove(block);
    } else {
        QTextBlockFormat bf = d->caret.blockFormat();
        if (!d->caret.blockFormat().hasProperty(KoParagraphStyle::HiddenByTable)) {
            newLine();
        }
        bf = d->caret.blockFormat();
        bf.setProperty(KoParagraphStyle::BreakBefore, KoText::PageBreak);
        d->caret.setBlockFormat(bf);
    }
    d->updateState(KoTextEditor::Private::NoOp);
    Q_EMIT cursorPositionChanged();
}

void KoTextEditor::paste(KoCanvasBase *canvas, const QMimeData *mimeData, bool pasteAsText)
{
    if (isEditProtected()) {
        return;
    }

    KoShapeController *shapeController = KoTextDocument(d->document).shapeController();

    addCommand(new TextPasteCommand(mimeData, d->document, shapeController, canvas, nullptr, pasteAsText));
}

void KoTextEditor::deleteChar(bool previous, KUndo2Command *parent)
{
    if (isEditProtected()) {
        return;
    }

    KoShapeController *shapeController = KoTextDocument(d->document).shapeController();

    // Find out if we should track changes or not
    //    KoChangeTracker *changeTracker = KoTextDocument(d->document).changeTracker();
    //    bool trackChanges = false;
    //    if (changeTracker && changeTracker->recordChanges()) {
    //        trackChanges = true;
    //    }

    if (previous) {
        if (!d->caret.hasSelection() && d->caret.block().blockFormat().hasProperty(KoParagraphStyle::HiddenByTable)) {
            movePosition(QTextCursor::PreviousCharacter);
            if (d->caret.block().length() <= 1) {
                movePosition(QTextCursor::NextCharacter);
            } else
                return; // it becomes just a cursor movement;
        }
    } else {
        if (!d->caret.hasSelection() && d->caret.block().length() > 1) {
            QTextCursor tmpCursor = d->caret;
            tmpCursor.movePosition(QTextCursor::NextCharacter);
            if (tmpCursor.block().blockFormat().hasProperty(KoParagraphStyle::HiddenByTable)) {
                movePosition(QTextCursor::NextCharacter);
                return; // it becomes just a cursor movement;
            }
        }
    }

    if (previous) {
        addCommand(new DeleteCommand(DeleteCommand::PreviousChar, d->document, shapeController, parent));
    } else {
        addCommand(new DeleteCommand(DeleteCommand::NextChar, d->document, shapeController, parent));
    }
}

void KoTextEditor::toggleListNumbering(bool numberingEnabled)
{
    if (isEditProtected()) {
        return;
    }

    addCommand(new ListItemNumberingCommand(block(), numberingEnabled));
    Q_EMIT textFormatChanged();
}

void KoTextEditor::setListProperties(const KoListLevelProperties &llp, ChangeListFlags flags, KUndo2Command *parent)
{
    if (isEditProtected()) {
        return;
    }

    if (flags & AutoListStyle && d->caret.block().textList() == nullptr) {
        flags = MergeWithAdjacentList;
    }

    if (KoList *list = KoTextDocument(d->document).list(d->caret.block().textList())) {
        KoListStyle *listStyle = list->style();
        if (KoStyleManager *styleManager = KoTextDocument(d->document).styleManager()) {
            QList<KoParagraphStyle *> paragraphStyles = styleManager->paragraphStyles();
            foreach (KoParagraphStyle *paragraphStyle, paragraphStyles) {
                if (paragraphStyle->listStyle() == listStyle || (paragraphStyle->list() && paragraphStyle->list()->style() == listStyle)) {
                    flags = NoFlags;
                    break;
                }
            }
        }
    }

    addCommand(new ChangeListCommand(d->caret, llp, flags, parent));
    Q_EMIT textFormatChanged();
}

int KoTextEditor::anchor() const
{
    return d->caret.anchor();
}

bool KoTextEditor::atBlockEnd() const
{
    return d->caret.atBlockEnd();
}

bool KoTextEditor::atBlockStart() const
{
    return d->caret.atBlockStart();
}

bool KoTextEditor::atEnd() const
{
    QTextCursor cursor(d->caret.document()->rootFrame()->lastCursorPosition());
    cursor.movePosition(QTextCursor::PreviousCharacter);
    QTextFrame *auxFrame = cursor.currentFrame();

    if (auxFrame->format().intProperty(KoText::SubFrameType) == KoText::AuxillaryFrameType) {
        // auxFrame really is the auxillary frame
        if (d->caret.position() == auxFrame->firstPosition() - 1) {
            return true;
        }
        return false;
    }
    return d->caret.atEnd();
}

bool KoTextEditor::atStart() const
{
    return d->caret.atStart();
}

QTextBlock KoTextEditor::block() const
{
    return d->caret.block();
}

int KoTextEditor::blockNumber() const
{
    return d->caret.blockNumber();
}

void KoTextEditor::clearSelection()
{
    d->caret.clearSelection();
}

int KoTextEditor::columnNumber() const
{
    return d->caret.columnNumber();
}

void KoTextEditor::deleteChar()
{
    if (isEditProtected()) {
        return;
    }

    if (!d->caret.hasSelection()) {
        if (d->caret.atEnd())
            return;

        // We alson need to refuse delete if we are at final pos in table cell
        if (QTextTable *table = d->caret.currentTable()) {
            QTextTableCell cell = table->cellAt(d->caret.position());
            if (d->caret.position() == cell.lastCursorPosition().position()) {
                return;
            }
        }

        // We also need to refuse delete if it will delete a note frame
        QTextCursor after(d->caret);
        after.movePosition(QTextCursor::NextCharacter);

        QTextFrame *beforeFrame = d->caret.currentFrame();
        while (qobject_cast<QTextTable *>(beforeFrame)) {
            beforeFrame = beforeFrame->parentFrame();
        }

        QTextFrame *afterFrame = after.currentFrame();
        while (qobject_cast<QTextTable *>(afterFrame)) {
            afterFrame = afterFrame->parentFrame();
        }
        if (beforeFrame != afterFrame) {
            return;
        }
    }

    deleteChar(false);

    Q_EMIT cursorPositionChanged();
}

void KoTextEditor::deletePreviousChar()
{
    if (isEditProtected()) {
        return;
    }

    if (!d->caret.hasSelection()) {
        if (d->caret.atStart())
            return;

        // We also need to refuse delete if we are at first pos in table cell
        if (QTextTable *table = d->caret.currentTable()) {
            QTextTableCell cell = table->cellAt(d->caret.position());
            if (d->caret.position() == cell.firstCursorPosition().position()) {
                return;
            }
        }

        // We also need to refuse delete if it will delete a note frame
        QTextCursor after(d->caret);
        after.movePosition(QTextCursor::PreviousCharacter);

        QTextFrame *beforeFrame = d->caret.currentFrame();
        while (qobject_cast<QTextTable *>(beforeFrame)) {
            beforeFrame = beforeFrame->parentFrame();
        }

        QTextFrame *afterFrame = after.currentFrame();
        while (qobject_cast<QTextTable *>(afterFrame)) {
            afterFrame = afterFrame->parentFrame();
        }

        if (beforeFrame != afterFrame) {
            return;
        }
    }

    deleteChar(true);

    Q_EMIT cursorPositionChanged();
}

QTextDocument *KoTextEditor::document() const
{
    return d->caret.document();
}

bool KoTextEditor::hasComplexSelection() const
{
    return d->caret.hasComplexSelection();
}

bool KoTextEditor::hasSelection() const
{
    return d->caret.hasSelection();
}

class ProtectionCheckVisitor : public KoTextVisitor
{
public:
    ProtectionCheckVisitor(const KoTextEditor *editor)
        : KoTextVisitor(const_cast<KoTextEditor *>(editor))
    {
    }

    // override super's implementation to not waste cpu cycles
    void visitBlock(QTextBlock &, const QTextCursor &) override
    {
    }

    void nonVisit() override
    {
        setAbortVisiting(true);
    }
};

bool KoTextEditor::isEditProtected(bool useCached) const
{
    ProtectionCheckVisitor visitor(this);

    if (useCached) {
        if (!d->editProtectionCached) {
            recursivelyVisitSelection(d->document->rootFrame()->begin(), visitor);
            d->editProtected = visitor.abortVisiting();
            d->editProtectionCached = true;
        }
        return d->editProtected;
    }
    d->editProtectionCached = false;
    recursivelyVisitSelection(d->document->rootFrame()->begin(), visitor);
    return visitor.abortVisiting();
}

void KoTextEditor::insertTable(int rows, int columns)
{
    if (isEditProtected() || rows <= 0 || columns <= 0) {
        return;
    }

    bool hasSelection = d->caret.hasSelection();
    if (!hasSelection) {
        d->updateState(KoTextEditor::Private::Custom, kundo2_i18n("Insert Table"));
    } else {
        KUndo2Command *topCommand = beginEditBlock(kundo2_i18n("Insert Table"));
        deleteChar(false, topCommand);
        d->caret.beginEditBlock();
    }

    QTextTableFormat tableFormat;

    tableFormat.setWidth(QTextLength(QTextLength::PercentageLength, 100));
    tableFormat.setProperty(KoTableStyle::CollapsingBorders, true);
    tableFormat.setMargin(5);

    KoChangeTracker *changeTracker = KoTextDocument(d->document).changeTracker();
    if (changeTracker && changeTracker->recordChanges()) {
        QTextCharFormat charFormat = d->caret.charFormat();
        QTextBlockFormat blockFormat = d->caret.blockFormat();
        KUndo2MagicString title = kundo2_i18n("Insert Table");

        int changeId;
        if (!d->caret.atBlockStart()) {
            changeId = changeTracker->mergeableId(KoGenChange::InsertChange, title, charFormat.intProperty(KoCharacterStyle::ChangeTrackerId));
        } else {
            changeId = changeTracker->mergeableId(KoGenChange::InsertChange, title, blockFormat.intProperty(KoCharacterStyle::ChangeTrackerId));
        }

        if (!changeId) {
            changeId = changeTracker->getInsertChangeId(title, 0);
        }

        tableFormat.setProperty(KoCharacterStyle::ChangeTrackerId, changeId);
    }

    QTextBlock currentBlock = d->caret.block();
    if (d->caret.position() != currentBlock.position()) {
        d->caret.insertBlock();
        currentBlock = d->caret.block();
    }

    QTextTable *table = d->caret.insertTable(rows, columns, tableFormat);

    // Get (and thus create) columnandrowstyle manager so it becomes part of undo
    // and not something that happens uncontrollably during layout
    KoTableColumnAndRowStyleManager::getManager(table);

    // 'Hide' the block before the table
    QTextBlockFormat blockFormat = currentBlock.blockFormat();
    QTextCursor cursor(currentBlock);
    blockFormat.setProperty(KoParagraphStyle::HiddenByTable, true);
    cursor.setBlockFormat(blockFormat);

    // Define the initial cell format
    QTextTableCellFormat format;
    KoTableCellStyle cellStyle;
    cellStyle.setEdge(KoBorder::TopBorder, KoBorder::BorderSolid, 2, QColor(Qt::black));
    cellStyle.setEdge(KoBorder::LeftBorder, KoBorder::BorderSolid, 2, QColor(Qt::black));
    cellStyle.setEdge(KoBorder::BottomBorder, KoBorder::BorderSolid, 2, QColor(Qt::black));
    cellStyle.setEdge(KoBorder::RightBorder, KoBorder::BorderSolid, 2, QColor(Qt::black));
    cellStyle.setPadding(5);
    cellStyle.applyStyle(format);

    // Apply formatting to all cells
    for (int row = 0; row < table->rows(); ++row) {
        for (int col = 0; col < table->columns(); ++col) {
            QTextTableCell cell = table->cellAt(row, col);
            cell.setFormat(format);
        }
    }

    if (hasSelection) {
        d->caret.endEditBlock();
        endEditBlock();
    } else {
        d->updateState(KoTextEditor::Private::NoOp);
    }

    Q_EMIT cursorPositionChanged();
}

void KoTextEditor::insertTableRowAbove()
{
    if (isEditProtected()) {
        return;
    }

    QTextTable *table = d->caret.currentTable();
    if (table) {
        addCommand(new InsertTableRowCommand(this, table, false));
    }
}

void KoTextEditor::insertTableRowBelow()
{
    if (isEditProtected()) {
        return;
    }

    QTextTable *table = d->caret.currentTable();
    if (table) {
        addCommand(new InsertTableRowCommand(this, table, true));
    }
}

void KoTextEditor::insertTableColumnLeft()
{
    if (isEditProtected()) {
        return;
    }

    QTextTable *table = d->caret.currentTable();
    if (table) {
        addCommand(new InsertTableColumnCommand(this, table, false));
    }
}

void KoTextEditor::insertTableColumnRight()
{
    if (isEditProtected()) {
        return;
    }

    QTextTable *table = d->caret.currentTable();
    if (table) {
        addCommand(new InsertTableColumnCommand(this, table, true));
    }
}

void KoTextEditor::deleteTableColumn()
{
    if (isEditProtected()) {
        return;
    }

    QTextTable *table = d->caret.currentTable();
    if (table) {
        addCommand(new DeleteTableColumnCommand(this, table));
    }
}

void KoTextEditor::deleteTableRow()
{
    if (isEditProtected()) {
        return;
    }

    QTextTable *table = d->caret.currentTable();
    if (table) {
        addCommand(new DeleteTableRowCommand(this, table));
    }
}

void KoTextEditor::mergeTableCells()
{
    if (isEditProtected()) {
        return;
    }

    d->updateState(KoTextEditor::Private::Custom, kundo2_i18n("Merge Cells"));

    QTextTable *table = d->caret.currentTable();

    if (table) {
        table->mergeCells(d->caret);
    }

    d->updateState(KoTextEditor::Private::NoOp);
}

void KoTextEditor::splitTableCells()
{
    if (isEditProtected()) {
        return;
    }

    d->updateState(KoTextEditor::Private::Custom, kundo2_i18n("Split Cells"));

    QTextTable *table = d->caret.currentTable();

    if (table) {
        QTextTableCell cell = table->cellAt(d->caret);
        table->splitCell(cell.row(), cell.column(), 1, 1);
    }

    d->updateState(KoTextEditor::Private::NoOp);
}

void KoTextEditor::adjustTableColumnWidth(QTextTable *table, int column, qreal width, KUndo2Command *parentCommand)
{
    ResizeTableCommand *cmd = new ResizeTableCommand(table, true, column, width, parentCommand);

    addCommand(cmd);
}

void KoTextEditor::adjustTableRowHeight(QTextTable *table, int column, qreal height, KUndo2Command *parentCommand)
{
    ResizeTableCommand *cmd = new ResizeTableCommand(table, false, column, height, parentCommand);

    addCommand(cmd);
}

void KoTextEditor::adjustTableWidth(QTextTable *table, qreal dLeft, qreal dRight)
{
    d->updateState(KoTextEditor::Private::Custom, kundo2_i18n("Adjust Table Width"));
    d->caret.beginEditBlock();
    QTextTableFormat fmt = table->format();
    if (dLeft) {
        fmt.setLeftMargin(fmt.leftMargin() + dLeft);
    }
    if (dRight) {
        fmt.setRightMargin(fmt.rightMargin() + dRight);
    }
    table->setFormat(fmt);
    d->caret.endEditBlock();
    d->updateState(KoTextEditor::Private::NoOp);
}

void KoTextEditor::setTableBorderData(QTextTable *table, int row, int column, KoBorder::BorderSide cellSide, const KoBorder::BorderData &data)
{
    d->updateState(KoTextEditor::Private::Custom, kundo2_i18n("Change Border Formatting"));
    d->caret.beginEditBlock();
    QTextTableCell cell = table->cellAt(row, column);
    QTextCharFormat fmt = cell.format();
    KoBorder border = fmt.property(KoTableCellStyle::Borders).value<KoBorder>();

    border.setBorderData(cellSide, data);
    fmt.setProperty(KoTableCellStyle::Borders, QVariant::fromValue<KoBorder>(border));
    cell.setFormat(fmt);
    d->caret.endEditBlock();
    d->updateState(KoTextEditor::Private::NoOp);
}

KoInlineNote *KoTextEditor::insertFootNote()
{
    if (isEditProtected()) {
        return nullptr;
    }

    InsertNoteCommand *cmd = new InsertNoteCommand(KoInlineNote::Footnote, d->document);
    addCommand(cmd);

    Q_EMIT cursorPositionChanged();
    return cmd->m_inlineNote;
}

KoInlineNote *KoTextEditor::insertEndNote()
{
    if (isEditProtected()) {
        return nullptr;
    }

    InsertNoteCommand *cmd = new InsertNoteCommand(KoInlineNote::Endnote, d->document);
    addCommand(cmd);

    Q_EMIT cursorPositionChanged();
    return cmd->m_inlineNote;
}

void KoTextEditor::insertTableOfContents(KoTableOfContentsGeneratorInfo *info)
{
    if (isEditProtected()) {
        return;
    }

    bool hasSelection = d->caret.hasSelection();
    if (!hasSelection) {
        d->updateState(KoTextEditor::Private::Custom, kundo2_i18n("Insert Table Of Contents"));
    } else {
        KUndo2Command *topCommand = beginEditBlock(kundo2_i18n("Insert Table Of Contents"));
        deleteChar(false, topCommand);
        d->caret.beginEditBlock();
    }

    QTextBlockFormat tocFormat;
    KoTableOfContentsGeneratorInfo *newToCInfo = info->clone();
    QTextDocument *tocDocument = new QTextDocument();
    tocFormat.setProperty(KoParagraphStyle::TableOfContentsData, QVariant::fromValue<KoTableOfContentsGeneratorInfo *>(newToCInfo));
    tocFormat.setProperty(KoParagraphStyle::GeneratedDocument, QVariant::fromValue<QTextDocument *>(tocDocument));

    // make sure we set up the textrangemanager on the subdocument as well
    KoTextDocument(tocDocument).setTextRangeManager(new KoTextRangeManager);

    KoChangeTracker *changeTracker = KoTextDocument(d->document).changeTracker();
    if (changeTracker && changeTracker->recordChanges()) {
        QTextCharFormat charFormat = d->caret.charFormat();
        QTextBlockFormat blockFormat = d->caret.blockFormat();
        KUndo2MagicString title = kundo2_i18n("Insert Table Of Contents");

        int changeId;
        if (!d->caret.atBlockStart()) {
            changeId = changeTracker->mergeableId(KoGenChange::InsertChange, title, charFormat.intProperty(KoCharacterStyle::ChangeTrackerId));
        } else {
            changeId = changeTracker->mergeableId(KoGenChange::InsertChange, title, blockFormat.intProperty(KoCharacterStyle::ChangeTrackerId));
        }

        if (!changeId) {
            changeId = changeTracker->getInsertChangeId(title, 0);
        }

        tocFormat.setProperty(KoCharacterStyle::ChangeTrackerId, changeId);
    }

    d->caret.insertBlock();
    d->caret.movePosition(QTextCursor::Left);
    d->caret.insertBlock(tocFormat);
    d->caret.movePosition(QTextCursor::Right);

    if (hasSelection) {
        d->caret.endEditBlock();
        endEditBlock();
    } else {
        d->updateState(KoTextEditor::Private::NoOp);
    }

    Q_EMIT cursorPositionChanged();
}

void KoTextEditor::setTableOfContentsConfig(KoTableOfContentsGeneratorInfo *info, const QTextBlock &block)
{
    if (isEditProtected()) {
        return;
    }

    KoTableOfContentsGeneratorInfo *newToCInfo = info->clone();

    d->updateState(KoTextEditor::Private::Custom, kundo2_i18n("Modify Table Of Contents"));

    QTextCursor cursor(block);
    QTextBlockFormat tocBlockFormat = block.blockFormat();

    tocBlockFormat.setProperty(KoParagraphStyle::TableOfContentsData, QVariant::fromValue<KoTableOfContentsGeneratorInfo *>(newToCInfo));
    cursor.setBlockFormat(tocBlockFormat);

    d->updateState(KoTextEditor::Private::NoOp);
    Q_EMIT cursorPositionChanged();
    const_cast<QTextDocument *>(document())->markContentsDirty(document()->firstBlock().position(), 0);
}

void KoTextEditor::insertBibliography(KoBibliographyInfo *info)
{
    bool hasSelection = d->caret.hasSelection();
    if (!hasSelection) {
        d->updateState(KoTextEditor::Private::Custom, kundo2_i18n("Insert Bibliography"));
    } else {
        KUndo2Command *topCommand = beginEditBlock(kundo2_i18n("Insert Bibliography"));
        deleteChar(false, topCommand);
        d->caret.beginEditBlock();
    }

    QTextBlockFormat bibFormat;
    KoBibliographyInfo *newBibInfo = info->clone();
    QTextDocument *bibDocument = new QTextDocument();

    bibFormat.setProperty(KoParagraphStyle::BibliographyData, QVariant::fromValue<KoBibliographyInfo *>(newBibInfo));
    bibFormat.setProperty(KoParagraphStyle::GeneratedDocument, QVariant::fromValue<QTextDocument *>(bibDocument));

    // make sure we set up the textrangemanager on the subdocument as well
    KoTextDocument(bibDocument).setTextRangeManager(new KoTextRangeManager);

    KoChangeTracker *changeTracker = KoTextDocument(d->document).changeTracker();
    if (changeTracker && changeTracker->recordChanges()) {
        QTextCharFormat charFormat = d->caret.charFormat();
        QTextBlockFormat blockFormat = d->caret.blockFormat();
        KUndo2MagicString title = kundo2_i18n("Insert Bibliography");

        int changeId;
        if (!d->caret.atBlockStart()) {
            changeId = changeTracker->mergeableId(KoGenChange::InsertChange, title, charFormat.intProperty(KoCharacterStyle::ChangeTrackerId));
        } else {
            changeId = changeTracker->mergeableId(KoGenChange::InsertChange, title, blockFormat.intProperty(KoCharacterStyle::ChangeTrackerId));
        }

        if (!changeId) {
            changeId = changeTracker->getInsertChangeId(title, 0);
        }

        bibFormat.setProperty(KoCharacterStyle::ChangeTrackerId, changeId);
    }

    d->caret.insertBlock();
    d->caret.movePosition(QTextCursor::Left);
    d->caret.insertBlock(bibFormat);
    d->caret.movePosition(QTextCursor::Right);

    new BibliographyGenerator(bibDocument, block(), newBibInfo);

    if (hasSelection) {
        d->caret.endEditBlock();
        endEditBlock();
    } else {
        d->updateState(KoTextEditor::Private::NoOp);
    }

    Q_EMIT cursorPositionChanged();
}

KoInlineCite *KoTextEditor::insertCitation()
{
    bool hasSelection = d->caret.hasSelection();
    if (!hasSelection) {
        d->updateState(KoTextEditor::Private::KeyPress, kundo2_i18n("Add Citation"));
    } else {
        KUndo2Command *topCommand = beginEditBlock(kundo2_i18n("Add Citation"));
        deleteChar(false, topCommand);
        d->caret.beginEditBlock();
    }

    KoInlineCite *cite = new KoInlineCite(KoInlineCite::Citation);
    KoInlineTextObjectManager *manager = KoTextDocument(d->document).inlineTextObjectManager();
    manager->insertInlineObject(d->caret, cite);

    if (hasSelection) {
        d->caret.endEditBlock();
        endEditBlock();
    } else {
        d->updateState(KoTextEditor::Private::NoOp);
    }

    return cite;
}

void KoTextEditor::insertText(const QString &text, const QString &hRef)
{
    if (isEditProtected()) {
        return;
    }

    bool hasSelection = d->caret.hasSelection();
    if (!hasSelection) {
        d->updateState(KoTextEditor::Private::KeyPress, kundo2_i18n("Typing"));
    } else {
        KUndo2Command *topCommand = beginEditBlock(kundo2_i18n("Typing"));
        deleteChar(false, topCommand);
        d->caret.beginEditBlock();
    }

    // first we make sure that we clear the inlineObject charProperty, if we have no selection
    if (!hasSelection && d->caret.charFormat().hasProperty(KoCharacterStyle::InlineInstanceId))
        d->clearCharFormatProperty(KoCharacterStyle::InlineInstanceId);

    int startPosition = d->caret.position();

    if (d->caret.blockFormat().hasProperty(KoParagraphStyle::HiddenByTable)) {
        d->newLine(nullptr);
        startPosition = d->caret.position();
    }

    QTextCharFormat format = d->caret.charFormat();
    if (format.hasProperty(KoCharacterStyle::ChangeTrackerId)) {
        format.clearProperty(KoCharacterStyle::ChangeTrackerId);
    }
    static QRegularExpression urlScanner("\\S+://\\S+");
    if (!hRef.isEmpty()) {
        format.setAnchor(true);
        format.setProperty(KoCharacterStyle::AnchorType, KoCharacterStyle::Anchor);
        if ((hRef.indexOf(urlScanner)) == 0) { // web url
            format.setAnchorHref(hRef);
        } else {
            format.setAnchorHref("#" + hRef);
        }
    }
    d->caret.insertText(text, format);

    int endPosition = d->caret.position();

    // Mark the inserted text
    d->caret.setPosition(startPosition);
    d->caret.setPosition(endPosition, QTextCursor::KeepAnchor);

    registerTrackedChange(d->caret, KoGenChange::InsertChange, kundo2_i18n("Typing"), format, format, false);

    d->caret.clearSelection();

    if (hasSelection) {
        d->caret.endEditBlock();
        endEditBlock();
    }
    if (!hRef.isEmpty()) {
        format.setAnchor(false);
        format.clearProperty(KoCharacterStyle::Anchor);
        format.clearProperty(KoCharacterStyle::AnchorType);
        d->caret.setCharFormat(format);
    }
    Q_EMIT cursorPositionChanged();
}

bool KoTextEditor::movePosition(QTextCursor::MoveOperation operation, QTextCursor::MoveMode mode, int n)
{
    d->editProtectionCached = false;

    // We need protection against moving in and out of note areas
    QTextCursor after(d->caret);
    bool b = after.movePosition(operation, mode, n);

    QTextFrame *beforeFrame = d->caret.currentFrame();
    while (qobject_cast<QTextTable *>(beforeFrame)) {
        beforeFrame = beforeFrame->parentFrame();
    }

    QTextFrame *afterFrame = after.currentFrame();
    while (qobject_cast<QTextTable *>(afterFrame)) {
        afterFrame = afterFrame->parentFrame();
    }

    if (beforeFrame == afterFrame) {
        if (after.selectionEnd() == after.document()->characterCount() - 1) {
            QTextCursor cursor(d->caret.document()->rootFrame()->lastCursorPosition());
            cursor.movePosition(QTextCursor::PreviousCharacter);
            QTextFrame *auxFrame = cursor.currentFrame();

            if (auxFrame->format().intProperty(KoText::SubFrameType) == KoText::AuxillaryFrameType) {
                if (operation == QTextCursor::End) {
                    d->caret.setPosition(auxFrame->firstPosition() - 1, mode);
                    Q_EMIT cursorPositionChanged();
                    return true;
                }
                return false;
            }
        }
        d->caret = after;
        Q_EMIT cursorPositionChanged();
        return b;
    }
    return false;
}

void KoTextEditor::newSection()
{
    if (isEditProtected()) {
        return;
    }

    NewSectionCommand *cmd = new NewSectionCommand(d->document);
    addCommand(cmd);
    Q_EMIT cursorPositionChanged();
}

void KoTextEditor::splitSectionsStartings(int sectionIdToInsertBefore)
{
    if (isEditProtected()) {
        return;
    }
    addCommand(new SplitSectionsCommand(d->document, SplitSectionsCommand::Startings, sectionIdToInsertBefore));
    Q_EMIT cursorPositionChanged();
}

void KoTextEditor::splitSectionsEndings(int sectionIdToInsertAfter)
{
    if (isEditProtected()) {
        return;
    }
    addCommand(new SplitSectionsCommand(d->document, SplitSectionsCommand::Endings, sectionIdToInsertAfter));
    Q_EMIT cursorPositionChanged();
}

void KoTextEditor::renameSection(KoSection *section, const QString &newName)
{
    if (isEditProtected()) {
        return;
    }
    addCommand(new RenameSectionCommand(section, newName, document()));
}

void KoTextEditor::newLine()
{
    if (isEditProtected()) {
        return;
    }

    bool hasSelection = d->caret.hasSelection();
    if (!hasSelection) {
        d->updateState(KoTextEditor::Private::Custom, kundo2_i18n("New Paragraph"));
    } else {
        KUndo2Command *topCommand = beginEditBlock(kundo2_i18n("New Paragraph"));
        deleteChar(false, topCommand);
    }
    d->caret.beginEditBlock();

    d->newLine(nullptr);

    d->caret.endEditBlock();

    if (hasSelection) {
        endEditBlock();
    } else {
        d->updateState(KoTextEditor::Private::NoOp);
    }

    Q_EMIT cursorPositionChanged();
}

class WithinSelectionVisitor : public KoTextVisitor
{
public:
    WithinSelectionVisitor(KoTextEditor *editor, int position)
        : KoTextVisitor(editor)
        , m_position(position)
        , m_returnValue(false)
    {
    }

    void visitBlock(QTextBlock &block, const QTextCursor &caret) override
    {
        if (m_position >= qMax(block.position(), caret.selectionStart()) && m_position <= qMin(block.position() + block.length(), caret.selectionEnd())) {
            m_returnValue = true;
            setAbortVisiting(true);
        }
    }
    int m_position; // the position we are searching for
    bool m_returnValue; // if position is within the selection
};

bool KoTextEditor::isWithinSelection(int position) const
{
    // we know the visitor doesn't do anything with the texteditor so let's const cast
    // to have a more beautiful outer api
    WithinSelectionVisitor visitor(const_cast<KoTextEditor *>(this), position);

    recursivelyVisitSelection(d->document->rootFrame()->begin(), visitor);
    return visitor.m_returnValue;
}

int KoTextEditor::position() const
{
    return d->caret.position();
}

void KoTextEditor::select(QTextCursor::SelectionType selection)
{
    // TODO add selection of previous/next char, and option about hasSelection
    d->caret.select(selection);
}

QString KoTextEditor::selectedText() const
{
    return d->caret.selectedText();
}

QTextDocumentFragment KoTextEditor::selection() const
{
    return d->caret.selection();
}

int KoTextEditor::selectionEnd() const
{
    return d->caret.selectionEnd();
}

int KoTextEditor::selectionStart() const
{
    return d->caret.selectionStart();
}

void KoTextEditor::setPosition(int pos, QTextCursor::MoveMode mode)
{
    d->editProtectionCached = false;

    if (pos == d->caret.document()->characterCount() - 1) {
        QTextCursor cursor(d->caret.document()->rootFrame()->lastCursorPosition());
        cursor.movePosition(QTextCursor::PreviousCharacter);
        QTextFrame *auxFrame = cursor.currentFrame();

        if (auxFrame->format().intProperty(KoText::SubFrameType) == KoText::AuxillaryFrameType) {
            return;
        }
    }

    if (mode == QTextCursor::MoveAnchor) {
        d->caret.setPosition(pos, mode);
        Q_EMIT cursorPositionChanged();
    }

    // We need protection against moving in and out of note areas
    QTextCursor after(d->caret);
    after.setPosition(pos, mode);

    QTextFrame *beforeFrame = d->caret.currentFrame();
    while (qobject_cast<QTextTable *>(beforeFrame)) {
        beforeFrame = beforeFrame->parentFrame();
    }

    QTextFrame *afterFrame = after.currentFrame();
    while (qobject_cast<QTextTable *>(afterFrame)) {
        afterFrame = afterFrame->parentFrame();
    }

    if (beforeFrame == afterFrame) {
        d->caret = after;
        Q_EMIT cursorPositionChanged();
    }
}

void KoTextEditor::setVisualNavigation(bool b)
{
    d->caret.setVisualNavigation(b);
}

bool KoTextEditor::visualNavigation() const
{
    return d->caret.visualNavigation();
}

const QTextFrame *KoTextEditor::currentFrame() const
{
    return d->caret.currentFrame();
}

const QTextList *KoTextEditor::currentList() const
{
    return d->caret.currentList();
}

const QTextTable *KoTextEditor::currentTable() const
{
    return d->caret.currentTable();
}

// have to include this because of Q_PRIVATE_SLOT
#include "moc_KoTextEditor.cpp"