summaryrefslogtreecommitdiffstats
path: root/sw/source/core/doc/DocumentContentOperationsManager.cxx
blob: 4b4404f4550e0f27ee3074f670b8bc2885bae258 (plain)
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
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */
#include <DocumentContentOperationsManager.hxx>
#include <doc.hxx>
#include <IDocumentUndoRedo.hxx>
#include <IDocumentMarkAccess.hxx>
#include <IDocumentState.hxx>
#include <IDocumentLayoutAccess.hxx>
#include <IDocumentRedlineAccess.hxx>
#include <IDocumentStylePoolAccess.hxx>
#include <IDocumentSettingAccess.hxx>
#include <UndoManager.hxx>
#include <docary.hxx>
#include <textboxhelper.hxx>
#include <dcontact.hxx>
#include <grfatr.hxx>
#include <numrule.hxx>
#include <charfmt.hxx>
#include <ndgrf.hxx>
#include <ndnotxt.hxx>
#include <ndole.hxx>
#include <breakit.hxx>
#include <frmfmt.hxx>
#include <fmtanchr.hxx>
#include <fmtcntnt.hxx>
#include <fmtinfmt.hxx>
#include <fmtpdsc.hxx>
#include <fmtcnct.hxx>
#include <SwStyleNameMapper.hxx>
#include <redline.hxx>
#include <txtfrm.hxx>
#include <rootfrm.hxx>
#include <frmtool.hxx>
#include <unocrsr.hxx>
#include <mvsave.hxx>
#include <ndtxt.hxx>
#include <poolfmt.hxx>
#include <paratr.hxx>
#include <txatbase.hxx>
#include <UndoRedline.hxx>
#include <undobj.hxx>
#include <UndoBookmark.hxx>
#include <UndoDelete.hxx>
#include <UndoSplitMove.hxx>
#include <UndoOverwrite.hxx>
#include <UndoInsert.hxx>
#include <UndoAttribute.hxx>
#include <rolbck.hxx>
#include <acorrect.hxx>
#include <bookmark.hxx>
#include <ftnidx.hxx>
#include <txtftn.hxx>
#include <hints.hxx>
#include <fmtflcnt.hxx>
#include <docedt.hxx>
#include <frameformats.hxx>
#include <o3tl/safeint.hxx>
#include <sal/log.hxx>
#include <unotools/charclass.hxx>
#include <unotools/configmgr.hxx>
#include <unotools/transliterationwrapper.hxx>
#include <i18nutil/transliteration.hxx>
#include <sfx2/Metadatable.hxx>
#include <sot/exchange.hxx>
#include <svl/stritem.hxx>
#include <svl/itemiter.hxx>
#include <svx/svdobj.hxx>
#include <svx/svdouno.hxx>
#include <tools/globname.hxx>
#include <editeng/formatbreakitem.hxx>
#include <com/sun/star/i18n/Boundary.hpp>
#include <com/sun/star/i18n/WordType.hpp>
#include <com/sun/star/i18n/XBreakIterator.hpp>
#include <com/sun/star/embed/XEmbeddedObject.hpp>

#include <tuple>
#include <memory>

using namespace ::com::sun::star::i18n;

namespace
{
    // Copy method from SwDoc
    // Prevent copying into Flys that are anchored in the range
    bool lcl_ChkFlyFly( SwDoc& rDoc, SwNodeOffset nSttNd, SwNodeOffset nEndNd,
                        SwNodeOffset nInsNd )
    {
        const SwFrameFormats& rFrameFormatTable = *rDoc.GetSpzFrameFormats();

        for( size_t n = 0; n < rFrameFormatTable.size(); ++n )
        {
            SwFrameFormat const*const  pFormat = rFrameFormatTable[n];
            SwFormatAnchor const*const pAnchor = &pFormat->GetAnchor();
            SwPosition const*const pAPos = pAnchor->GetContentAnchor();
            if (pAPos &&
                ((RndStdIds::FLY_AS_CHAR == pAnchor->GetAnchorId()) ||
                 (RndStdIds::FLY_AT_CHAR == pAnchor->GetAnchorId()) ||
                 (RndStdIds::FLY_AT_FLY  == pAnchor->GetAnchorId()) ||
                 (RndStdIds::FLY_AT_PARA == pAnchor->GetAnchorId())) &&
                nSttNd <= pAPos->nNode.GetIndex() &&
                pAPos->nNode.GetIndex() < nEndNd )
            {
                const SwFormatContent& rContent = pFormat->GetContent();
                SwStartNode* pSNd;
                if( !rContent.GetContentIdx() ||
                    nullptr == ( pSNd = rContent.GetContentIdx()->GetNode().GetStartNode() ))
                    continue;

                if( pSNd->GetIndex() < nInsNd &&
                    nInsNd < pSNd->EndOfSectionIndex() )
                    // Do not copy !
                    return true;

                if( lcl_ChkFlyFly( rDoc, pSNd->GetIndex(),
                            pSNd->EndOfSectionIndex(), nInsNd ) )
                    // Do not copy !
                    return true;
            }
        }

        return false;
    }

    SwNodeIndex InitDelCount(SwPaM const& rSourcePaM, SwNodeOffset & rDelCount)
    {
        SwNodeIndex const& rStart(rSourcePaM.Start()->nNode);
        // Special handling for SwDoc::AppendDoc
        if (rSourcePaM.GetDoc().GetNodes().GetEndOfExtras().GetIndex() + 1
                == rStart.GetIndex())
        {
            rDelCount = SwNodeOffset(1);
            return SwNodeIndex(rStart, +1);
        }
        else
        {
            rDelCount = SwNodeOffset(0);
            return rStart;
        }
    }

    /*
        The CopyBookmarks function has to copy bookmarks from the source to the destination nodes
        array. It is called after a call of the CopyNodes(..) function. But this function does not copy
        every node (at least at the moment: 2/08/2006 ), section start and end nodes will not be copied
        if the corresponding end/start node is outside the copied pam.
        The lcl_NonCopyCount function counts the number of these nodes, given the copied pam and a node
        index inside the pam.
        rPam is the original source pam, rLastIdx is the last calculated position, rDelCount the number
        of "non-copy" nodes between rPam.Start() and rLastIdx.
        nNewIdx is the new position of interest.
    */
    void lcl_NonCopyCount( const SwPaM& rPam, SwNodeIndex& rLastIdx, const SwNodeOffset nNewIdx, SwNodeOffset& rDelCount )
    {
        SwNodeOffset nStart = rPam.Start()->nNode.GetIndex();
        SwNodeOffset nEnd = rPam.End()->nNode.GetIndex();
        if( rLastIdx.GetIndex() < nNewIdx ) // Moving forward?
        {
            // We never copy the StartOfContent node
            do // count "non-copy" nodes
            {
                SwNode& rNode = rLastIdx.GetNode();
                if( ( rNode.IsSectionNode() && rNode.EndOfSectionIndex() >= nEnd )
                    || ( rNode.IsEndNode() && rNode.StartOfSectionNode()->GetIndex() < nStart ) )
                {
                    ++rDelCount;
                }
                ++rLastIdx;
            }
            while( rLastIdx.GetIndex() < nNewIdx );
        }
        else if( rDelCount ) // optimization: if there are no "non-copy" nodes until now,
                             // no move backward needed
        {
            while( rLastIdx.GetIndex() > nNewIdx )
            {
                SwNode& rNode = rLastIdx.GetNode();
                if( ( rNode.IsSectionNode() && rNode.EndOfSectionIndex() >= nEnd )
                    || ( rNode.IsEndNode() && rNode.StartOfSectionNode()->GetIndex() < nStart ) )
                {
                    --rDelCount;
                }
                rLastIdx--;
            }
        }
    }

    void lcl_SetCpyPos( const SwPosition& rOrigPos,
                        const SwPosition& rOrigStt,
                        const SwPosition& rCpyStt,
                        SwPosition& rChgPos,
                        SwNodeOffset nDelCount )
    {
        SwNodeOffset nNdOff = rOrigPos.nNode.GetIndex();
        nNdOff -= rOrigStt.nNode.GetIndex();
        nNdOff -= nDelCount;
        sal_Int32 nContentPos = rOrigPos.nContent.GetIndex();

        // Always adjust <nNode> at to be changed <SwPosition> instance <rChgPos>
        rChgPos.nNode = nNdOff + rCpyStt.nNode.GetIndex();
        if( !nNdOff )
        {
            // just adapt the content index
            if( nContentPos > rOrigStt.nContent.GetIndex() )
                nContentPos -= rOrigStt.nContent.GetIndex();
            else
                nContentPos = 0;
            nContentPos += rCpyStt.nContent.GetIndex();
        }
        rChgPos.nContent.Assign( rChgPos.nNode.GetNode().GetContentNode(), nContentPos );
    }

}

namespace sw
{
    // TODO: use SaveBookmark (from DelBookmarks)
    void CopyBookmarks(const SwPaM& rPam, const SwPosition& rCpyPam)
    {
        const SwDoc& rSrcDoc = rPam.GetDoc();
        SwDoc& rDestDoc =  rCpyPam.GetDoc();
        const IDocumentMarkAccess* const pSrcMarkAccess = rSrcDoc.getIDocumentMarkAccess();
        ::sw::UndoGuard const undoGuard(rDestDoc.GetIDocumentUndoRedo());

        const SwPosition &rStt = *rPam.Start(), &rEnd = *rPam.End();
        SwPosition const*const pCpyStt = &rCpyPam;

        std::vector< const ::sw::mark::IMark* > vMarksToCopy;
        for ( IDocumentMarkAccess::const_iterator_t ppMark = pSrcMarkAccess->getAllMarksBegin();
              ppMark != pSrcMarkAccess->getAllMarksEnd();
              ++ppMark )
        {
            const ::sw::mark::IMark* const pMark = *ppMark;

            const SwPosition& rMarkStart = pMark->GetMarkStart();
            const SwPosition& rMarkEnd = pMark->GetMarkEnd();
            // only include marks that are in the range and not touching both start and end
            // - not for annotation or checkbox marks.
            bool const isIncludeStart(
                   (rStt.nContent.GetIndex() == 0 // paragraph start selected?
                    // also: only if inserting at the start - cross reference
                    // marks require index to be 0, and there could be one
                    // on the target node already
                    && rCpyPam.nContent.GetIndex() == 0)
                || rMarkStart != rStt);
            bool const isIncludeEnd(
                   (rEnd.nNode.GetNode().IsTextNode() // paragraph end selected?
                    && rEnd.nContent.GetIndex() == rEnd.nNode.GetNode().GetTextNode()->Len())
                || rMarkEnd != rEnd);
            const bool bIsNotOnBoundary =
                pMark->IsExpanded()
                ? (isIncludeStart || isIncludeEnd)  // rMarkStart != rMarkEnd
                : (isIncludeStart && isIncludeEnd); // rMarkStart == rMarkEnd
            const IDocumentMarkAccess::MarkType aMarkType = IDocumentMarkAccess::GetType(*pMark);
            if ( rMarkStart >= rStt && rMarkEnd <= rEnd
                 && ( bIsNotOnBoundary
                      || aMarkType == IDocumentMarkAccess::MarkType::ANNOTATIONMARK
                      || aMarkType == IDocumentMarkAccess::MarkType::TEXT_FIELDMARK
                      || aMarkType == IDocumentMarkAccess::MarkType::CHECKBOX_FIELDMARK
                      || aMarkType == IDocumentMarkAccess::MarkType::DROPDOWN_FIELDMARK
                      || aMarkType == IDocumentMarkAccess::MarkType::DATE_FIELDMARK))
            {
                vMarksToCopy.push_back(pMark);
            }
        }
        // We have to count the "non-copied" nodes...
        SwNodeOffset nDelCount;
        SwNodeIndex aCorrIdx(InitDelCount(rPam, nDelCount));
        for(const sw::mark::IMark* const pMark : vMarksToCopy)
        {
            SwPaM aTmpPam(*pCpyStt);
            lcl_NonCopyCount(rPam, aCorrIdx, pMark->GetMarkPos().nNode.GetIndex(), nDelCount);
            lcl_SetCpyPos( pMark->GetMarkPos(), rStt, *pCpyStt, *aTmpPam.GetPoint(), nDelCount);
            if(pMark->IsExpanded())
            {
                aTmpPam.SetMark();
                lcl_NonCopyCount(rPam, aCorrIdx, pMark->GetOtherMarkPos().nNode.GetIndex(), nDelCount);
                lcl_SetCpyPos(pMark->GetOtherMarkPos(), rStt, *pCpyStt, *aTmpPam.GetMark(), nDelCount);
            }

            ::sw::mark::IMark* const pNewMark = rDestDoc.getIDocumentMarkAccess()->makeMark(
                aTmpPam,
                pMark->GetName(),
                IDocumentMarkAccess::GetType(*pMark),
                ::sw::mark::InsertMode::CopyText);
            // Explicitly try to get exactly the same name as in the source
            // because NavigatorReminders, DdeBookmarks etc. ignore the proposed name
            if (pNewMark == nullptr)
            {
                assert(IDocumentMarkAccess::GetType(*pMark) == IDocumentMarkAccess::MarkType::CROSSREF_NUMITEM_BOOKMARK
                    || IDocumentMarkAccess::GetType(*pMark) == IDocumentMarkAccess::MarkType::CROSSREF_HEADING_BOOKMARK);
                continue; // can't insert duplicate cross reference mark
            }
            rDestDoc.getIDocumentMarkAccess()->renameMark(pNewMark, pMark->GetName());

            // copying additional attributes for bookmarks or fieldmarks
            ::sw::mark::IBookmark* const pNewBookmark =
                dynamic_cast< ::sw::mark::IBookmark* const >(pNewMark);
            const ::sw::mark::IBookmark* const pOldBookmark =
                dynamic_cast< const ::sw::mark::IBookmark* >(pMark);
            if (pNewBookmark && pOldBookmark)
            {
                pNewBookmark->SetKeyCode(pOldBookmark->GetKeyCode());
                pNewBookmark->SetShortName(pOldBookmark->GetShortName());
                pNewBookmark->Hide(pOldBookmark->IsHidden());
                pNewBookmark->SetHideCondition(pOldBookmark->GetHideCondition());
            }
            ::sw::mark::IFieldmark* const pNewFieldmark =
                dynamic_cast< ::sw::mark::IFieldmark* const >(pNewMark);
            const ::sw::mark::IFieldmark* const pOldFieldmark =
                dynamic_cast< const ::sw::mark::IFieldmark* >(pMark);
            if (pNewFieldmark && pOldFieldmark)
            {
                pNewFieldmark->SetFieldname(pOldFieldmark->GetFieldname());
                pNewFieldmark->SetFieldHelptext(pOldFieldmark->GetFieldHelptext());
                ::sw::mark::IFieldmark::parameter_map_t* pNewParams = pNewFieldmark->GetParameters();
                const ::sw::mark::IFieldmark::parameter_map_t* pOldParams = pOldFieldmark->GetParameters();
                for (const auto& rEntry : *pOldParams )
                {
                    pNewParams->insert( rEntry );
                }
            }

            ::sfx2::Metadatable const*const pMetadatable(
                    dynamic_cast< ::sfx2::Metadatable const* >(pMark));
            ::sfx2::Metadatable      *const pNewMetadatable(
                    dynamic_cast< ::sfx2::Metadatable      * >(pNewMark));
            if (pMetadatable && pNewMetadatable)
            {
                pNewMetadatable->RegisterAsCopyOf(*pMetadatable);
            }
        }
    }
} // namespace sw

namespace
{
    void lcl_DeleteRedlines( const SwPaM& rPam, SwPaM& rCpyPam )
    {
        const SwDoc& rSrcDoc = rPam.GetDoc();
        const SwRedlineTable& rTable = rSrcDoc.getIDocumentRedlineAccess().GetRedlineTable();
        if( rTable.empty() )
            return;

        SwDoc& rDestDoc = rCpyPam.GetDoc();
        SwPosition* pCpyStt = rCpyPam.Start(), *pCpyEnd = rCpyPam.End();
        std::unique_ptr<SwPaM> pDelPam;
        const SwPosition *pStt = rPam.Start(), *pEnd = rPam.End();
        // We have to count the "non-copied" nodes
        SwNodeOffset nDelCount;
        SwNodeIndex aCorrIdx(InitDelCount(rPam, nDelCount));

        SwRedlineTable::size_type n = 0;
        rSrcDoc.getIDocumentRedlineAccess().GetRedline( *pStt, &n );
        for( ; n < rTable.size(); ++n )
        {
            const SwRangeRedline* pRedl = rTable[ n ];
            if( RedlineType::Delete == pRedl->GetType() && pRedl->IsVisible() )
            {
                const SwPosition *pRStt = pRedl->Start(), *pREnd = pRedl->End();

                SwComparePosition eCmpPos = ComparePosition( *pStt, *pEnd, *pRStt, *pREnd );
                switch( eCmpPos )
                {
                case SwComparePosition::CollideEnd:
                case SwComparePosition::Before:
                    // Pos1 is before Pos2
                    break;

                case SwComparePosition::CollideStart:
                case SwComparePosition::Behind:
                    // Pos1 is after Pos2
                    n = rTable.size();
                    break;

                default:
                    {
                        pDelPam.reset(new SwPaM( *pCpyStt, pDelPam.release() ));
                        if( *pStt < *pRStt )
                        {
                            lcl_NonCopyCount( rPam, aCorrIdx, pRStt->nNode.GetIndex(), nDelCount );
                            lcl_SetCpyPos( *pRStt, *pStt, *pCpyStt,
                                            *pDelPam->GetPoint(), nDelCount );
                        }
                        pDelPam->SetMark();

                        if( *pEnd < *pREnd )
                            *pDelPam->GetPoint() = *pCpyEnd;
                        else
                        {
                            lcl_NonCopyCount( rPam, aCorrIdx, pREnd->nNode.GetIndex(), nDelCount );
                            lcl_SetCpyPos( *pREnd, *pStt, *pCpyStt,
                                            *pDelPam->GetPoint(), nDelCount );
                        }

                        if (pDelPam->GetNext() != pDelPam.get()
                            && *pDelPam->GetNext()->End() == *pDelPam->Start())
                        {
                            *pDelPam->GetNext()->End() = *pDelPam->End();
                            pDelPam.reset(pDelPam->GetNext());
                        }
                    }
                }
            }
        }

        if( !pDelPam )
            return;

        RedlineFlags eOld = rDestDoc.getIDocumentRedlineAccess().GetRedlineFlags();
        rDestDoc.getIDocumentRedlineAccess().SetRedlineFlags_intern( eOld | RedlineFlags::Ignore );

        ::sw::UndoGuard const undoGuard(rDestDoc.GetIDocumentUndoRedo());

        do {
            rDestDoc.getIDocumentContentOperations().DeleteAndJoin( *pDelPam->GetNext() );
            if( !pDelPam->IsMultiSelection() )
                break;
            delete pDelPam->GetNext();
        } while( true );

        rDestDoc.getIDocumentRedlineAccess().SetRedlineFlags_intern( eOld );
    }

    void lcl_DeleteRedlines( const SwNodeRange& rRg, SwNodeRange const & rCpyRg )
    {
        SwDoc& rSrcDoc = rRg.aStart.GetNode().GetDoc();
        if( !rSrcDoc.getIDocumentRedlineAccess().GetRedlineTable().empty() )
        {
            SwPaM aRgTmp( rRg.aStart, rRg.aEnd );
            SwPaM aCpyTmp( rCpyRg.aStart, rCpyRg.aEnd );
            lcl_DeleteRedlines( aRgTmp, aCpyTmp );
        }
    }

    void lcl_ChainFormats( SwFlyFrameFormat *pSrc, SwFlyFrameFormat *pDest )
    {
        SwFormatChain aSrc( pSrc->GetChain() );
        if ( !aSrc.GetNext() )
        {
            aSrc.SetNext( pDest );
            pSrc->SetFormatAttr( aSrc );
        }
        SwFormatChain aDest( pDest->GetChain() );
        if ( !aDest.GetPrev() )
        {
            aDest.SetPrev( pSrc );
            pDest->SetFormatAttr( aDest );
        }
    }

    // #i86492#
    bool lcl_ContainsOnlyParagraphsInList( const SwPaM& rPam )
    {
        bool bRet = false;

        const SwTextNode* pTextNd = rPam.Start()->nNode.GetNode().GetTextNode();
        const SwTextNode* pEndTextNd = rPam.End()->nNode.GetNode().GetTextNode();
        if ( pTextNd && pTextNd->IsInList() &&
             pEndTextNd && pEndTextNd->IsInList() )
        {
            bRet = true;
            SwNodeIndex aIdx(rPam.Start()->nNode);

            do
            {
                ++aIdx;
                pTextNd = aIdx.GetNode().GetTextNode();

                if ( !pTextNd || !pTextNd->IsInList() )
                {
                    bRet = false;
                    break;
                }
            } while (pTextNd != pEndTextNd);
        }

        return bRet;
    }

    bool lcl_MarksWholeNode(const SwPaM & rPam)
    {
        bool bResult = false;
        const SwPosition* pStt = rPam.Start();
        const SwPosition* pEnd = rPam.End();

        if (nullptr != pStt && nullptr != pEnd)
        {
            const SwTextNode* pSttNd = pStt->nNode.GetNode().GetTextNode();
            const SwTextNode* pEndNd = pEnd->nNode.GetNode().GetTextNode();

            if (nullptr != pSttNd && nullptr != pEndNd &&
                pStt->nContent.GetIndex() == 0 &&
                pEnd->nContent.GetIndex() == pEndNd->Len())
            {
                bResult = true;
            }
        }

        return bResult;
    }
}

//local functions originally from sw/source/core/doc/docedt.cxx
namespace sw
{
    void CalcBreaks(std::vector<std::pair<SwNodeOffset, sal_Int32>> & rBreaks,
            SwPaM const & rPam, bool const isOnlyFieldmarks)
    {
        SwNodeOffset const nStartNode(rPam.Start()->nNode.GetIndex());
        SwNodeOffset const nEndNode(rPam.End()->nNode.GetIndex());
        SwNodes const& rNodes(rPam.GetPoint()->nNode.GetNodes());
        IDocumentMarkAccess const& rIDMA(*rPam.GetDoc().getIDocumentMarkAccess());

        std::stack<std::tuple<sw::mark::IFieldmark const*, bool, SwNodeOffset, sal_Int32>> startedFields;

        for (SwNodeOffset n = nStartNode; n <= nEndNode; ++n)
        {
            SwNode *const pNode(rNodes[n]);
            if (pNode->IsTextNode())
            {
                SwTextNode & rTextNode(*pNode->GetTextNode());
                sal_Int32 const nStart(n == nStartNode
                        ? rPam.Start()->nContent.GetIndex()
                        : 0);
                sal_Int32 const nEnd(n == nEndNode
                        ? rPam.End()->nContent.GetIndex()
                        : rTextNode.Len());
                for (sal_Int32 i = nStart; i < nEnd; ++i)
                {
                    const sal_Unicode c(rTextNode.GetText()[i]);
                    switch (c)
                    {
                        // note: CH_TXT_ATR_FORMELEMENT does not need handling
                        // not sure how CH_TXT_ATR_INPUTFIELDSTART/END are currently handled
                        case CH_TXTATR_INWORD:
                        case CH_TXTATR_BREAKWORD:
                        {
                            // META hints only have dummy char at the start, not
                            // at the end, so no need to check in nStartNode
                            if (n == nEndNode && !isOnlyFieldmarks)
                            {
                                SwTextAttr const* pAttr(rTextNode.GetTextAttrForCharAt(i));
                                if (pAttr && pAttr->End() && (nEnd  < *pAttr->End()))
                                {
                                    assert(pAttr->HasDummyChar());
                                    rBreaks.emplace_back(n, i);
                                }

                                if (!pAttr)
                                {
                                    // See if this is an end dummy character for a content control.
                                    pAttr = rTextNode.GetTextAttrForEndCharAt(i, RES_TXTATR_CONTENTCONTROL);
                                    if (pAttr && (nStart > pAttr->GetStart()))
                                    {
                                        rBreaks.emplace_back(n, i);
                                    }
                                }
                            }
                            break;
                        }
                        case CH_TXT_ATR_FIELDSTART:
                        {
                            auto const pFieldMark(rIDMA.getFieldmarkAt(SwPosition(rTextNode, i)));
                            startedFields.emplace(pFieldMark, false, 0, 0);
                            break;
                        }
                        case CH_TXT_ATR_FIELDSEP:
                        {
                            if (startedFields.empty())
                            {
                                rBreaks.emplace_back(n, i);
                            }
                            else
                            {   // no way to find the field via MarkManager...
                                assert(std::get<0>(startedFields.top())->IsCoveringPosition(SwPosition(rTextNode, i)));
                                std::get<1>(startedFields.top()) = true;
                                std::get<2>(startedFields.top()) = n;
                                std::get<3>(startedFields.top()) = i;
                            }
                            break;
                        }
                        case CH_TXT_ATR_FIELDEND:
                        {
                            if (startedFields.empty())
                            {
                                rBreaks.emplace_back(n, i);
                            }
                            else
                            {   // fieldmarks must not overlap => stack
                                assert(std::get<0>(startedFields.top()) == rIDMA.getFieldmarkAt(SwPosition(rTextNode, i)));
                                startedFields.pop();
                            }
                            break;
                        }
                    }
                }
            }
            else if (pNode->IsStartNode())
            {
                if (pNode->EndOfSectionIndex() <= nEndNode)
                {   // fieldmark cannot overlap node section
                    n = pNode->EndOfSectionIndex();
                }
            }
            else
            {   // EndNode can actually happen with sections :(
                assert(pNode->IsEndNode() || pNode->IsNoTextNode());
            }
        }
        while (!startedFields.empty())
        {
            SwPosition const& rStart(std::get<0>(startedFields.top())->GetMarkStart());
            std::pair<SwNodeOffset, sal_Int32> const pos(
                    rStart.nNode.GetIndex(), rStart.nContent.GetIndex());
            auto it = std::lower_bound(rBreaks.begin(), rBreaks.end(), pos);
            assert(it == rBreaks.end() || *it != pos);
            rBreaks.insert(it, pos);
            if (std::get<1>(startedFields.top()))
            {
                std::pair<SwNodeOffset, sal_Int32> const posSep(
                    std::get<2>(startedFields.top()),
                    std::get<3>(startedFields.top()));
                it = std::lower_bound(rBreaks.begin(), rBreaks.end(), posSep);
                assert(it == rBreaks.end() || *it != posSep);
                rBreaks.insert(it, posSep);
            }
            startedFields.pop();
        }
    }
}

namespace
{

    bool lcl_DoWithBreaks(::sw::DocumentContentOperationsManager & rDocumentContentOperations,
            SwPaM & rPam, SwDeleteFlags const flags,
            bool (::sw::DocumentContentOperationsManager::*pFunc)(SwPaM&, SwDeleteFlags))
    {
        std::vector<std::pair<SwNodeOffset, sal_Int32>> Breaks;

        sw::CalcBreaks(Breaks, rPam);

        if (Breaks.empty())
        {
            return (rDocumentContentOperations.*pFunc)(rPam, flags);
        }

        // Deletion must be split into several parts if the text node
        // contains a text attribute with end and with dummy character
        // and the selection does not contain the text attribute completely,
        // but overlaps its start (left), where the dummy character is.

        SwPosition const & rSelectionEnd( *rPam.End() );

        bool bRet( true );
        // iterate from end to start, to avoid invalidating the offsets!
        auto iter( Breaks.rbegin() );
        SwNodeOffset nOffset(0);
        SwNodes const& rNodes(rPam.GetPoint()->nNode.GetNodes());
        SwPaM aPam( rSelectionEnd, rSelectionEnd ); // end node!
        SwPosition & rEnd( *aPam.End() );
        SwPosition & rStart( *aPam.Start() );

        while (iter != Breaks.rend())
        {
            rStart = SwPosition(*rNodes[iter->first - nOffset]->GetTextNode(), iter->second + 1);
            if (rStart < rEnd) // check if part is empty
            {
                bRet &= (rDocumentContentOperations.*pFunc)(aPam, flags);
                nOffset = iter->first - rStart.nNode.GetIndex(); // deleted fly nodes...
            }
            rEnd = SwPosition(*rNodes[iter->first - nOffset]->GetTextNode(), iter->second);
            ++iter;
        }

        rStart = *rPam.Start(); // set to original start
        if (rStart < rEnd) // check if part is empty
        {
            bRet &= (rDocumentContentOperations.*pFunc)(aPam, flags);
        }

        return bRet;
    }

    bool lcl_StrLenOverflow( const SwPaM& rPam )
    {
        // If we try to merge two paragraphs we have to test if afterwards
        // the string doesn't exceed the allowed string length
        if( rPam.GetPoint()->nNode != rPam.GetMark()->nNode )
        {
            const SwPosition* pStt = rPam.Start(), *pEnd = rPam.End();
            const SwTextNode* pEndNd = pEnd->nNode.GetNode().GetTextNode();
            if( (nullptr != pEndNd) && pStt->nNode.GetNode().IsTextNode() )
            {
                const sal_uInt64 nSum = pStt->nContent.GetIndex() +
                    pEndNd->GetText().getLength() - pEnd->nContent.GetIndex();
                return nSum > o3tl::make_unsigned(SAL_MAX_INT32);
            }
        }
        return false;
    }

    struct SaveRedline
    {
        SwRangeRedline* pRedl;
        SwNodeOffset nStt, nEnd;
        sal_Int32 nSttCnt;
        sal_Int32 nEndCnt;

        SaveRedline( SwRangeRedline* pR, const SwNodeIndex& rSttIdx )
            : pRedl(pR)
            , nEnd(0)
            , nEndCnt(0)
        {
            const SwPosition* pStt = pR->Start(),
                            * pEnd = pR->End();
            SwNodeOffset nSttIdx = rSttIdx.GetIndex();
            nStt = pStt->nNode.GetIndex() - nSttIdx;
            nSttCnt = pStt->nContent.GetIndex();
            if( pR->HasMark() )
            {
                nEnd = pEnd->nNode.GetIndex() - nSttIdx;
                nEndCnt = pEnd->nContent.GetIndex();
            }

            pRedl->GetPoint()->nNode = SwNodeOffset(0);
            pRedl->GetPoint()->nContent.Assign( nullptr, 0 );
            pRedl->GetMark()->nNode = SwNodeOffset(0);
            pRedl->GetMark()->nContent.Assign( nullptr, 0 );
        }

        SaveRedline( SwRangeRedline* pR, const SwPosition& rPos )
            : pRedl(pR)
            , nEnd(0)
            , nEndCnt(0)
        {
            const SwPosition* pStt = pR->Start(),
                            * pEnd = pR->End();
            SwNodeOffset nSttIdx = rPos.nNode.GetIndex();
            nStt = pStt->nNode.GetIndex() - nSttIdx;
            nSttCnt = pStt->nContent.GetIndex();
            if( nStt == SwNodeOffset(0) )
                nSttCnt = nSttCnt - rPos.nContent.GetIndex();
            if( pR->HasMark() )
            {
                nEnd = pEnd->nNode.GetIndex() - nSttIdx;
                nEndCnt = pEnd->nContent.GetIndex();
                if( nEnd == SwNodeOffset(0) )
                    nEndCnt = nEndCnt - rPos.nContent.GetIndex();
            }

            pRedl->GetPoint()->nNode = SwNodeOffset(0);
            pRedl->GetPoint()->nContent.Assign( nullptr, 0 );
            pRedl->GetMark()->nNode = SwNodeOffset(0);
            pRedl->GetMark()->nContent.Assign( nullptr, 0 );
        }

        void SetPos( SwNodeOffset nInsPos )
        {
            pRedl->GetPoint()->nNode = nInsPos + nStt;
            pRedl->GetPoint()->nContent.Assign( pRedl->GetContentNode(), nSttCnt );
            if( pRedl->HasMark() )
            {
                pRedl->GetMark()->nNode = nInsPos + nEnd;
                pRedl->GetMark()->nContent.Assign( pRedl->GetContentNode(false), nEndCnt );
            }
        }

        void SetPos( const SwPosition& aPos )
        {
            pRedl->GetPoint()->nNode = aPos.nNode.GetIndex() + nStt;
            pRedl->GetPoint()->nContent.Assign( pRedl->GetContentNode(), nSttCnt + ( nStt == SwNodeOffset(0) ? aPos.nContent.GetIndex() : 0 ) );
            if( pRedl->HasMark() )
            {
                pRedl->GetMark()->nNode = aPos.nNode.GetIndex() + nEnd;
                pRedl->GetMark()->nContent.Assign( pRedl->GetContentNode(false), nEndCnt  + ( nEnd == SwNodeOffset(0) ? aPos.nContent.GetIndex() : 0 ) );
            }
        }
    };

    typedef std::vector< SaveRedline > SaveRedlines_t;

    void lcl_SaveRedlines(const SwPaM& aPam, SaveRedlines_t& rArr)
    {
        SwDoc& rDoc = aPam.GetNode().GetDoc();

        const SwPosition* pStart = aPam.Start();
        const SwPosition* pEnd = aPam.End();

        // get first relevant redline
        SwRedlineTable::size_type nCurrentRedline;
        rDoc.getIDocumentRedlineAccess().GetRedline( *pStart, &nCurrentRedline );
        if( nCurrentRedline > 0)
            nCurrentRedline--;

        // redline mode RedlineFlags::Ignore|RedlineFlags::On; save old mode
        RedlineFlags eOld = rDoc.getIDocumentRedlineAccess().GetRedlineFlags();
        rDoc.getIDocumentRedlineAccess().SetRedlineFlags_intern( ( eOld & ~RedlineFlags::Ignore) | RedlineFlags::On );

        // iterate over relevant redlines and decide for each whether it should
        // be saved, or split + saved
        SwRedlineTable& rRedlineTable = rDoc.getIDocumentRedlineAccess().GetRedlineTable();
        for( ; nCurrentRedline < rRedlineTable.size(); nCurrentRedline++ )
        {
            SwRangeRedline* pCurrent = rRedlineTable[ nCurrentRedline ];
            SwComparePosition eCompare =
                ComparePosition( *pCurrent->Start(), *pCurrent->End(),
                                 *pStart, *pEnd);

            // we must save this redline if it overlaps aPam
            // (we may have to split it, too)
            if( eCompare == SwComparePosition::OverlapBehind  ||
                eCompare == SwComparePosition::OverlapBefore  ||
                eCompare == SwComparePosition::Outside ||
                eCompare == SwComparePosition::Inside ||
                eCompare == SwComparePosition::Equal )
            {
                rRedlineTable.Remove( nCurrentRedline-- );

                // split beginning, if necessary
                if( eCompare == SwComparePosition::OverlapBefore  ||
                    eCompare == SwComparePosition::Outside )
                {
                    SwRangeRedline* pNewRedline = new SwRangeRedline( *pCurrent );
                    *pNewRedline->End() = *pStart;
                    *pCurrent->Start() = *pStart;
                    rDoc.getIDocumentRedlineAccess().AppendRedline( pNewRedline, true );
                }

                // split end, if necessary
                if( eCompare == SwComparePosition::OverlapBehind  ||
                    eCompare == SwComparePosition::Outside )
                {
                    SwRangeRedline* pNewRedline = new SwRangeRedline( *pCurrent );
                    *pNewRedline->Start() = *pEnd;
                    *pCurrent->End() = *pEnd;
                    rDoc.getIDocumentRedlineAccess().AppendRedline( pNewRedline, true );
                }

                // save the current redline
                rArr.emplace_back( pCurrent, *pStart );
            }
        }

        // restore old redline mode
        rDoc.getIDocumentRedlineAccess().SetRedlineFlags_intern( eOld );
    }

    void lcl_RestoreRedlines(SwDoc& rDoc, const SwPosition& rPos, SaveRedlines_t& rArr)
    {
        RedlineFlags eOld = rDoc.getIDocumentRedlineAccess().GetRedlineFlags();
        rDoc.getIDocumentRedlineAccess().SetRedlineFlags_intern( ( eOld & ~RedlineFlags::Ignore) | RedlineFlags::On );

        for(SaveRedline & rSvRedLine : rArr)
        {
            rSvRedLine.SetPos( rPos );
            rDoc.getIDocumentRedlineAccess().AppendRedline( rSvRedLine.pRedl, true );
        }

        rDoc.getIDocumentRedlineAccess().SetRedlineFlags_intern( eOld );
    }

    void lcl_SaveRedlines(const SwNodeRange& rRg, SaveRedlines_t& rArr)
    {
        SwDoc& rDoc = rRg.aStart.GetNode().GetDoc();
        SwRedlineTable::size_type nRedlPos;
        SwPosition aSrchPos( rRg.aStart ); aSrchPos.nNode--;
        aSrchPos.nContent.Assign( aSrchPos.nNode.GetNode().GetContentNode(), 0 );
        if( rDoc.getIDocumentRedlineAccess().GetRedline( aSrchPos, &nRedlPos ) && nRedlPos )
            --nRedlPos;
        else if( nRedlPos >= rDoc.getIDocumentRedlineAccess().GetRedlineTable().size() )
            return ;

        RedlineFlags eOld = rDoc.getIDocumentRedlineAccess().GetRedlineFlags();
        rDoc.getIDocumentRedlineAccess().SetRedlineFlags_intern( ( eOld & ~RedlineFlags::Ignore) | RedlineFlags::On );
        SwRedlineTable& rRedlTable = rDoc.getIDocumentRedlineAccess().GetRedlineTable();

        do {
            SwRangeRedline* pTmp = rRedlTable[ nRedlPos ];

            const SwPosition* pRStt = pTmp->Start(),
                            * pREnd = pTmp->End();

            if( pRStt->nNode < rRg.aStart )
            {
                if( pREnd->nNode > rRg.aStart && pREnd->nNode < rRg.aEnd )
                {
                    // Create a copy and set the end of the original to the end of the MoveArea.
                    // The copy is moved too.
                    SwRangeRedline* pNewRedl = new SwRangeRedline( *pTmp );
                    SwPosition* pTmpPos = pNewRedl->Start();
                    pTmpPos->nNode = rRg.aStart;
                    pTmpPos->nContent.Assign(
                                pTmpPos->nNode.GetNode().GetContentNode(), 0 );

                    rArr.emplace_back(pNewRedl, rRg.aStart);

                    pTmpPos = pTmp->End();
                    pTmpPos->nNode = rRg.aEnd;
                    pTmpPos->nContent.Assign(
                                pTmpPos->nNode.GetNode().GetContentNode(), 0 );
                }
                else if( pREnd->nNode == rRg.aStart )
                {
                    SwPosition* pTmpPos = pTmp->End();
                    pTmpPos->nNode = rRg.aEnd;
                    pTmpPos->nContent.Assign(
                                pTmpPos->nNode.GetNode().GetContentNode(), 0 );
                }
            }
            else if( pRStt->nNode < rRg.aEnd )
            {
                rRedlTable.Remove( nRedlPos-- );
                if( pREnd->nNode < rRg.aEnd ||
                    ( pREnd->nNode == rRg.aEnd && !pREnd->nContent.GetIndex()) )
                {
                    // move everything
                    rArr.emplace_back( pTmp, rRg.aStart );
                }
                else
                {
                    // split
                    SwRangeRedline* pNewRedl = new SwRangeRedline( *pTmp );
                    SwPosition* pTmpPos = pNewRedl->End();
                    pTmpPos->nNode = rRg.aEnd;
                    pTmpPos->nContent.Assign(
                                pTmpPos->nNode.GetNode().GetContentNode(), 0 );

                    rArr.emplace_back( pNewRedl, rRg.aStart );

                    pTmpPos = pTmp->Start();
                    pTmpPos->nNode = rRg.aEnd;
                    pTmpPos->nContent.Assign(
                                pTmpPos->nNode.GetNode().GetContentNode(), 0 );
                    rDoc.getIDocumentRedlineAccess().AppendRedline( pTmp, true );
                }
            }
            else
                break;

        } while( ++nRedlPos < rDoc.getIDocumentRedlineAccess().GetRedlineTable().size() );
        rDoc.getIDocumentRedlineAccess().SetRedlineFlags_intern( eOld );
    }

    void lcl_RestoreRedlines(SwDoc& rDoc, SwNodeOffset const nInsPos, SaveRedlines_t& rArr)
    {
        RedlineFlags eOld = rDoc.getIDocumentRedlineAccess().GetRedlineFlags();
        rDoc.getIDocumentRedlineAccess().SetRedlineFlags_intern( ( eOld & ~RedlineFlags::Ignore) | RedlineFlags::On );

        for(SaveRedline & rSvRedLine : rArr)
        {
            rSvRedLine.SetPos( nInsPos );
            IDocumentRedlineAccess::AppendResult const result(
                rDoc.getIDocumentRedlineAccess().AppendRedline( rSvRedLine.pRedl, true ));
            if ( IDocumentRedlineAccess::AppendResult::APPENDED == result &&
                rSvRedLine.pRedl->GetType() == RedlineType::Delete )
            {
                UpdateFramesForAddDeleteRedline(rDoc, *rSvRedLine.pRedl);
            }
        }

        rDoc.getIDocumentRedlineAccess().SetRedlineFlags_intern( eOld );
    }

    bool lcl_SaveFootnote( const SwNodeIndex& rSttNd, const SwNodeIndex& rEndNd,
                     const SwNodeIndex& rInsPos,
                     SwFootnoteIdxs& rFootnoteArr, SwFootnoteIdxs& rSaveArr,
                     const SwIndex* pSttCnt = nullptr, const SwIndex* pEndCnt = nullptr )
    {
        bool bUpdateFootnote = false;
        const SwNodes& rNds = rInsPos.GetNodes();
        const bool bDelFootnote = rInsPos.GetIndex() < rNds.GetEndOfAutotext().GetIndex() &&
                    rSttNd.GetIndex() >= rNds.GetEndOfAutotext().GetIndex();
        const bool bSaveFootnote = !bDelFootnote &&
                        rInsPos.GetIndex() >= rNds.GetEndOfExtras().GetIndex();
        if( !rFootnoteArr.empty() )
        {

            size_t nPos = 0;
            rFootnoteArr.SeekEntry( rSttNd, &nPos );
            SwTextFootnote* pSrch;
            const SwNode* pFootnoteNd;

            // Delete/save all that come after it
            while( nPos < rFootnoteArr.size() && ( pFootnoteNd =
                &( pSrch = rFootnoteArr[ nPos ] )->GetTextNode())->GetIndex()
                        <= rEndNd.GetIndex() )
            {
                const sal_Int32 nFootnoteSttIdx = pSrch->GetStart();
                if( ( pEndCnt && pSttCnt )
                    ? (( &rSttNd.GetNode() == pFootnoteNd &&
                         pSttCnt->GetIndex() > nFootnoteSttIdx) ||
                       ( &rEndNd.GetNode() == pFootnoteNd &&
                        nFootnoteSttIdx >= pEndCnt->GetIndex() ))
                    : ( &rEndNd.GetNode() == pFootnoteNd ))
                {
                    ++nPos;     // continue searching
                }
                else
                {
                    // delete it
                    if( bDelFootnote )
                    {
                        SwTextNode& rTextNd = const_cast<SwTextNode&>(pSrch->GetTextNode());
                        SwIndex aIdx( &rTextNd, nFootnoteSttIdx );
                        rTextNd.EraseText( aIdx, 1 );
                    }
                    else
                    {
                        pSrch->DelFrames(nullptr);
                        rFootnoteArr.erase( rFootnoteArr.begin() + nPos );
                        if( bSaveFootnote )
                            rSaveArr.insert( pSrch );
                    }
                    bUpdateFootnote = true;
                }
            }

            while( nPos-- && ( pFootnoteNd = &( pSrch = rFootnoteArr[ nPos ] )->
                    GetTextNode())->GetIndex() >= rSttNd.GetIndex() )
            {
                const sal_Int32 nFootnoteSttIdx = pSrch->GetStart();
                if( !pEndCnt || !pSttCnt ||
                    !  (( &rSttNd.GetNode() == pFootnoteNd &&
                        pSttCnt->GetIndex() > nFootnoteSttIdx ) ||
                        ( &rEndNd.GetNode() == pFootnoteNd &&
                        nFootnoteSttIdx >= pEndCnt->GetIndex() )) )
                {
                    if( bDelFootnote )
                    {
                        // delete it
                        SwTextNode& rTextNd = const_cast<SwTextNode&>(pSrch->GetTextNode());
                        SwIndex aIdx( &rTextNd, nFootnoteSttIdx );
                        rTextNd.EraseText( aIdx, 1 );
                    }
                    else
                    {
                        pSrch->DelFrames(nullptr);
                        rFootnoteArr.erase( rFootnoteArr.begin() + nPos );
                        if( bSaveFootnote )
                            rSaveArr.insert( pSrch );
                    }
                    bUpdateFootnote = true;
                }
            }
        }
        // When moving from redline section into document content section, e.g.
        // after loading a document with (delete-)redlines, the footnote array
        // has to be adjusted... (#i70572)
        if( bSaveFootnote )
        {
            SwNodeIndex aIdx( rSttNd );
            while( aIdx < rEndNd ) // Check the moved section
            {
                SwNode* pNode = &aIdx.GetNode();
                if( pNode->IsTextNode() ) // Looking for text nodes...
                {
                    SwpHints *pHints = pNode->GetTextNode()->GetpSwpHints();
                    if( pHints && pHints->HasFootnote() ) //...with footnotes
                    {
                        bUpdateFootnote = true; // Heureka
                        const size_t nCount = pHints->Count();
                        for( size_t i = 0; i < nCount; ++i )
                        {
                            SwTextAttr *pAttr = pHints->Get( i );
                            if ( pAttr->Which() == RES_TXTATR_FTN )
                            {
                                rSaveArr.insert( static_cast<SwTextFootnote*>(pAttr) );
                            }
                        }
                    }
                }
                ++aIdx;
            }
        }
        return bUpdateFootnote;
    }

    bool lcl_MayOverwrite( const SwTextNode *pNode, const sal_Int32 nPos )
    {
        sal_Unicode const cChr = pNode->GetText()[nPos];
        switch (cChr)
        {
            case CH_TXTATR_BREAKWORD:
            case CH_TXTATR_INWORD:
                return !pNode->GetTextAttrForCharAt(nPos);// how could there be none?
            case CH_TXT_ATR_INPUTFIELDSTART:
            case CH_TXT_ATR_INPUTFIELDEND:
            case CH_TXT_ATR_FIELDSTART:
            case CH_TXT_ATR_FIELDSEP:
            case CH_TXT_ATR_FIELDEND:
            case CH_TXT_ATR_FORMELEMENT:
                return false;
            default:
                return true;
        }
    }

    void lcl_SkipAttr( const SwTextNode *pNode, SwIndex &rIdx, sal_Int32 &rStart )
    {
        if( !lcl_MayOverwrite( pNode, rStart ) )
        {
            // skip all special attributes
            do {
                ++rIdx;
                rStart = rIdx.GetIndex();
            } while (rStart < pNode->GetText().getLength()
                   && !lcl_MayOverwrite(pNode, rStart) );
        }
    }

    bool lcl_GetTokenToParaBreak( OUString& rStr, OUString& rRet, bool bRegExpRplc )
    {
        if( bRegExpRplc )
        {
            sal_Int32 nPos = 0;
            static const OUStringLiteral sPara(u"\\n");
            for (;;)
            {
                nPos = rStr.indexOf( sPara, nPos );
                if (nPos<0)
                {
                    break;
                }
                // Has this been escaped?
                if( nPos && '\\' == rStr[nPos-1])
                {
                    ++nPos;
                    if( nPos >= rStr.getLength() )
                    {
                        break;
                    }
                }
                else
                {
                    rRet = rStr.copy( 0, nPos );
                    rStr = rStr.copy( nPos + sPara.getLength() );
                    return true;
                }
            }
        }
        rRet = rStr;
        rStr.clear();
        return false;
    }
}

namespace //local functions originally from docfmt.cxx
{

    bool lcl_ApplyOtherSet(
            SwContentNode & rNode,
            SwHistory *const pHistory,
            SfxItemSet const& rOtherSet,
            SfxItemSet const& rFirstSet,
            SfxItemSet const& rPropsSet,
            SwRootFrame const*const pLayout,
            SwNodeIndex *const o_pIndex = nullptr)
    {
        assert(rOtherSet.Count());

        bool ret(false);
        SwTextNode *const pTNd = rNode.GetTextNode();
        sw::MergedPara const* pMerged(nullptr);
        if (pLayout && pLayout->HasMergedParas() && pTNd)
        {
            SwTextFrame const*const pTextFrame(static_cast<SwTextFrame const*>(
                pTNd->getLayoutFrame(pLayout)));
            if (pTextFrame)
            {
                pMerged = pTextFrame->GetMergedPara();
            }
            if (pMerged)
            {
                if (rFirstSet.Count())
                {
                    if (pHistory)
                    {
                        SwRegHistory aRegH(pMerged->pFirstNode, *pMerged->pFirstNode, pHistory);
                        ret = pMerged->pFirstNode->SetAttr(rFirstSet);
                    }
                    else
                    {
                        ret = pMerged->pFirstNode->SetAttr(rFirstSet);
                    }
                }
                if (rPropsSet.Count())
                {
                    if (pHistory)
                    {
                        SwRegHistory aRegH(pMerged->pParaPropsNode, *pMerged->pParaPropsNode, pHistory);
                        ret = pMerged->pParaPropsNode->SetAttr(rPropsSet) || ret;
                    }
                    else
                    {
                        ret = pMerged->pParaPropsNode->SetAttr(rPropsSet) || ret;
                    }
                }
                if (o_pIndex)
                {
                    *o_pIndex = *pMerged->pLastNode; // skip hidden
                }
            }
        }

        // input cursor can't be on hidden node, and iteration skips them
        assert(!pLayout || !pLayout->HasMergedParas()
            || rNode.GetRedlineMergeFlag() != SwNode::Merge::Hidden);

        if (!pMerged)
        {
            if (pHistory)
            {
                SwRegHistory aRegH(&rNode, rNode, pHistory);
                ret = rNode.SetAttr( rOtherSet );
            }
            else
            {
                ret = rNode.SetAttr( rOtherSet );
            }
        }
        return ret;
    }

    #define DELETECHARSETS if ( bDelete ) { delete pCharSet; delete pOtherSet; }

    // set format redline with extra data for lcl_InsAttr()
    void lcl_SetRedline(
        SwDoc& rDoc,
        const SwPaM &rRg)
    {
        std::unique_ptr<SwRedlineExtraData_FormatColl> xExtra;

        // check existing redline on the same range, and use its extra data, if it exists
        SwRedlineTable::size_type nRedlPos = rDoc.getIDocumentRedlineAccess().GetRedlinePos(
                rRg.Start()->nNode.GetNode(), RedlineType::Format );
        if( SwRedlineTable::npos != nRedlPos )
        {
            const SwPosition *pRStt, *pREnd;
            do {
                SwRangeRedline* pTmp = rDoc.getIDocumentRedlineAccess().GetRedlineTable()[ nRedlPos ];
                pRStt = pTmp->Start();
                pREnd = pTmp->End();
                SwComparePosition eCompare = ComparePosition( *rRg.Start(), *rRg.End(), *pRStt, *pREnd );
                if ( eCompare == SwComparePosition::Inside || eCompare == SwComparePosition::Equal )
                {
                    if (pTmp->GetExtraData())
                    {
                        const SwRedlineExtraData* pExtraData = pTmp->GetExtraData();
                        const SwRedlineExtraData_FormatColl* pFormattingChanges =
                            dynamic_cast<const SwRedlineExtraData_FormatColl*>(pExtraData);
                        // Check if the extra data is of type 'formatting changes'
                        if (pFormattingChanges)
                        {
                            // Get the item set that holds all the changes properties
                            const SfxItemSet *pChangesSet = pFormattingChanges->GetItemSet();
                            xExtra.reset(new SwRedlineExtraData_FormatColl("", USHRT_MAX, pChangesSet));
                            break;
                        }
                    }
                }
            } while( pRStt <= rRg.Start() && ++nRedlPos < rDoc.getIDocumentRedlineAccess().GetRedlineTable().size());
        }

        SwRangeRedline * pRedline = new SwRangeRedline( RedlineType::Format, rRg );
        auto const result(rDoc.getIDocumentRedlineAccess().AppendRedline( pRedline, true));
        // store original text attributes to reject formatting change
        if (IDocumentRedlineAccess::AppendResult::IGNORED == result)
            return;

        // no existing format redline in the range
        if (!xExtra)
        {
            // Apply the first character's attributes to the ReplaceText
            SfxItemSetFixed<RES_CHRATR_BEGIN,     RES_TXTATR_WITHEND_END - 1,
                        RES_UNKNOWNATR_BEGIN, RES_UNKNOWNATR_END-1>  aSet( rDoc.GetAttrPool() );
            SwTextNode * pNode = rRg.Start()->nNode.GetNode().GetTextNode();
            pNode->GetParaAttr( aSet, rRg.Start()->nContent.GetIndex() + 1, rRg.End()->nContent.GetIndex() );

            aSet.ClearItem( RES_TXTATR_REFMARK );
            aSet.ClearItem( RES_TXTATR_TOXMARK );
            aSet.ClearItem( RES_TXTATR_CJK_RUBY );
            aSet.ClearItem( RES_TXTATR_INETFMT );
            aSet.ClearItem( RES_TXTATR_META );
            aSet.ClearItem( RES_TXTATR_METAFIELD );

            // After GetParaAttr aSet can contain INVALID_POOL_ITEM items, e.g. RES_TXTATR_CHARFMT
            // and (a copy of) this SfxItemSet can be passed to MSWordExportBase::OutputItemSet
            // which doesn't handle INVALID_POOL_ITEM items so clear InvalidItems here
            aSet.ClearInvalidItems();

            xExtra.reset(new SwRedlineExtraData_FormatColl("", USHRT_MAX, &aSet));
        }

        if (xExtra)
        {
            pRedline->SetExtraData(xExtra.get() );
        }
    }

    // create format redline(s) for the given range:
    // to track the original formatting stored in the
    // hints, create redlines for all parts of the
    // range partitioned by boundaries of the hints.
    void lcl_SetRedlines(
        SwDoc& rDoc,
        const SwPaM &rRg)
    {
        SwNodeIndex aIdx( rRg.Start()->nNode );
        const SwNodeIndex aEndNd( rRg.End()->nNode );
        while( aIdx <= aEndNd )
        {
            SwTextNode *pNode = aIdx.GetNode().GetTextNode();
            if( pNode )
            {
                const sal_Int32 nStart = aIdx == rRg.Start()->nNode
                        ? rRg.Start()->nContent.GetIndex()
                        : 0;
                const sal_Int32 nEnd = aIdx < aEndNd
                        ? pNode->GetText().getLength()
                        : rRg.End()->nContent.GetIndex();

                if( SwpHints *pHints = pNode->GetpSwpHints() )
                {
                    const size_t nCount = pHints->Count();
                    sal_Int32 nRedEnd = nStart;
                    for( size_t i = 0; i < nCount; ++i )
                    {
                        SwTextAttr *pAttr = pHints->Get( i );

                        if ( pAttr->GetStart() > nEnd )
                        {
                            break; // after the range
                        }

                        if ( !pAttr->GetEnd() || *pAttr->GetEnd() < nStart )
                        {
                            continue; // before the range
                        }

                        // range part before the hint
                        if ( nRedEnd < pAttr->GetStart() )
                        {
                            SwPaM aPam( *pNode, nRedEnd, *pNode, pAttr->GetStart() );
                            lcl_SetRedline(rDoc, aPam);
                        }

                        // range part at the hint
                        sal_Int32 nRedStart = std::max(pAttr->GetStart(), nStart);
                        nRedEnd = std::min(*pAttr->GetEnd(), nEnd);
                        SwPaM aPam2( *pNode, nRedStart, *pNode, nRedEnd );
                        lcl_SetRedline(rDoc, aPam2);
                    }

                    // range part after the last hint
                    if ( nRedEnd < nEnd )
                    {
                        SwPaM aPam( *pNode, nRedEnd, *pNode, nEnd );
                        lcl_SetRedline(rDoc, aPam);
                    }
                }
                else
                {
                    SwPaM aPam( *pNode, nStart, *pNode, nEnd );
                    lcl_SetRedline(rDoc, aPam);
                }
            }
            ++aIdx;
        }
    }

    /// Insert Hints according to content types;
    // Is used in SwDoc::Insert(..., SwFormatHint &rHt)

    bool lcl_InsAttr(
        SwDoc& rDoc,
        const SwPaM &rRg,
        const SfxItemSet& rChgSet,
        const SetAttrMode nFlags,
        SwUndoAttr *const pUndo,
        SwRootFrame const*const pLayout,
        SwTextAttr **ppNewTextAttr)
    {
        // Divide the Sets (for selections in Nodes)
        const SfxItemSet* pCharSet = nullptr;
        const SfxItemSet* pOtherSet = nullptr;
        bool bDelete = false;
        bool bCharAttr = false;
        bool bOtherAttr = false;

        // Check, if we can work with rChgSet or if we have to create additional SfxItemSets
        if ( 1 == rChgSet.Count() )
        {
            SfxItemIter aIter( rChgSet );
            const SfxPoolItem* pItem = aIter.GetCurItem();
            if (pItem && !IsInvalidItem(pItem))
            {
                const sal_uInt16 nWhich = pItem->Which();

                if ( isCHRATR(nWhich) ||
                     (RES_TXTATR_CHARFMT == nWhich) ||
                     (RES_TXTATR_INETFMT == nWhich) ||
                     (RES_TXTATR_AUTOFMT == nWhich) ||
                     (RES_TXTATR_UNKNOWN_CONTAINER == nWhich) )
                {
                    pCharSet  = &rChgSet;
                    bCharAttr = true;
                }

                if (    isPARATR(nWhich)
                     || isPARATR_LIST(nWhich)
                     || isFRMATR(nWhich)
                     || isGRFATR(nWhich)
                     || isUNKNOWNATR(nWhich)
                     || isDrawingLayerAttribute(nWhich) )
                {
                    pOtherSet = &rChgSet;
                    bOtherAttr = true;
                }
            }
        }

        // Build new itemset if either
        // - rChgSet.Count() > 1 or
        // - The attribute in rChgSet does not belong to one of the above categories
        if ( !bCharAttr && !bOtherAttr )
        {
            SfxItemSet* pTmpCharItemSet = new SfxItemSetFixed<
                    RES_CHRATR_BEGIN, RES_CHRATR_END - 1,
                    RES_TXTATR_AUTOFMT, RES_TXTATR_CHARFMT,
                    RES_TXTATR_UNKNOWN_CONTAINER,
                        RES_TXTATR_UNKNOWN_CONTAINER>( rDoc.GetAttrPool() );

            SfxItemSet* pTmpOtherItemSet = new SfxItemSetFixed<
                    RES_PARATR_BEGIN, RES_GRFATR_END - 1,
                    RES_UNKNOWNATR_BEGIN, RES_UNKNOWNATR_END - 1,
                    // FillAttribute support:
                    XATTR_FILL_FIRST, XATTR_FILL_LAST>( rDoc.GetAttrPool() );

            pTmpCharItemSet->Put( rChgSet );
            pTmpOtherItemSet->Put( rChgSet );

            pCharSet = pTmpCharItemSet;
            pOtherSet = pTmpOtherItemSet;

            bDelete = true;
        }

        SwHistory* pHistory = pUndo ? &pUndo->GetHistory() : nullptr;
        bool bRet = false;
        const SwPosition *pStt = rRg.Start(), *pEnd = rRg.End();
        SwContentNode* pNode = pStt->nNode.GetNode().GetContentNode();

        if( pNode && pNode->IsTextNode() )
        {
            // tdf#127606 at editing, remove different formatting of DOCX-like numbering symbol
            if (pLayout && pNode->GetTextNode()->getIDocumentSettingAccess()->
                    get(DocumentSettingId::APPLY_PARAGRAPH_MARK_FORMAT_TO_NUMBERING ))
            {
                SwContentNode* pEndNode = pEnd->nNode.GetNode().GetContentNode();
                SwContentNode* pCurrentNode = pEndNode;
                auto nStartIndex = pNode->GetIndex();
                auto nEndIndex = pEndNode->GetIndex();
                SwNodeIndex aIdx( pEnd->nNode.GetNode() );
                while ( pCurrentNode != nullptr && nStartIndex <= pCurrentNode->GetIndex() )
                {
                    if (pCurrentNode->GetSwAttrSet().HasItem(RES_PARATR_LIST_AUTOFMT) &&
                        // remove character formatting only on wholly selected paragraphs
                        (nStartIndex < pCurrentNode->GetIndex() || pStt->nContent.GetIndex() == 0) &&
                        (pCurrentNode->GetIndex() < nEndIndex || pEnd->nContent.GetIndex() == pEndNode->Len()))
                    {
                        pCurrentNode->ResetAttr(RES_PARATR_LIST_AUTOFMT);
                        // reset also paragraph marker
                        SwIndex nIdx( pCurrentNode, pCurrentNode->Len() );
                        pCurrentNode->GetTextNode()->RstTextAttr(nIdx, 1);
                    }
                    pCurrentNode = SwNodes::GoPrevious( &aIdx );
                }
            }
            // #i27615#
            if (rRg.IsInFrontOfLabel())
            {
                SwTextNode * pTextNd = pNode->GetTextNode();
                if (pLayout)
                {
                    pTextNd = sw::GetParaPropsNode(*pLayout, *pTextNd);
                }
                SwNumRule * pNumRule = pTextNd->GetNumRule();

                if ( !pNumRule )
                {
                    OSL_FAIL( "<InsAttr(..)> - PaM in front of label, but text node has no numbering rule set. This is a serious defect." );
                    DELETECHARSETS
                    return false;
                }

                int nLevel = pTextNd->GetActualListLevel();

                if (nLevel < 0)
                    nLevel = 0;

                if (nLevel >= MAXLEVEL)
                    nLevel = MAXLEVEL - 1;

                SwNumFormat aNumFormat = pNumRule->Get(o3tl::narrowing<sal_uInt16>(nLevel));
                SwCharFormat * pCharFormat =
                    rDoc.FindCharFormatByName(aNumFormat.GetCharFormatName());

                if (pCharFormat)
                {
                    if (pHistory)
                        pHistory->Add(pCharFormat->GetAttrSet(), *pCharFormat);

                    if ( pCharSet )
                        pCharFormat->SetFormatAttr(*pCharSet);
                }

                DELETECHARSETS
                return true;
            }

            const SwIndex& rSt = pStt->nContent;

            // Attributes without an end do not have a range
            if ( !bCharAttr && !bOtherAttr )
            {
                SfxItemSetFixed<RES_TXTATR_NOEND_BEGIN, RES_TXTATR_NOEND_END-1>
                    aTextSet( rDoc.GetAttrPool() );
                aTextSet.Put( rChgSet );
                if( aTextSet.Count() )
                {
                    SwRegHistory history( pNode, *pNode, pHistory );
                    bRet = history.InsertItems(
                        aTextSet, rSt.GetIndex(), rSt.GetIndex(), nFlags, /*ppNewTextAttr*/nullptr ) || bRet;

                    if (bRet && (rDoc.getIDocumentRedlineAccess().IsRedlineOn() || (!rDoc.getIDocumentRedlineAccess().IsIgnoreRedline()
                                    && !rDoc.getIDocumentRedlineAccess().GetRedlineTable().empty())))
                    {
                        SwPaM aPam( pStt->nNode, pStt->nContent.GetIndex()-1,
                                    pStt->nNode, pStt->nContent.GetIndex() );

                        if( pUndo )
                            pUndo->SaveRedlineData( aPam, true );

                        if( rDoc.getIDocumentRedlineAccess().IsRedlineOn() )
                            rDoc.getIDocumentRedlineAccess().AppendRedline( new SwRangeRedline( RedlineType::Insert, aPam ), true);
                        else
                            rDoc.getIDocumentRedlineAccess().SplitRedline( aPam );
                    }
                }
            }

            // TextAttributes with an end never expand their range
            if ( !bCharAttr && !bOtherAttr )
            {
                // CharFormat and URL attributes are treated separately!
                // TEST_TEMP ToDo: AutoFormat!
                SfxItemSetFixed<
                        RES_TXTATR_REFMARK, RES_TXTATR_METAFIELD,
                        RES_TXTATR_CJK_RUBY, RES_TXTATR_CJK_RUBY,
                        RES_TXTATR_INPUTFIELD, RES_TXTATR_CONTENTCONTROL>
                     aTextSet(rDoc.GetAttrPool());

                aTextSet.Put( rChgSet );
                if( aTextSet.Count() )
                {
                    const sal_Int32 nInsCnt = rSt.GetIndex();
                    const sal_Int32 nEnd = pStt->nNode == pEnd->nNode
                                    ? pEnd->nContent.GetIndex()
                                    : pNode->Len();
                    SwRegHistory history( pNode, *pNode, pHistory );
                    bRet = history.InsertItems( aTextSet, nInsCnt, nEnd, nFlags, ppNewTextAttr )
                           || bRet;

                    if (bRet && (rDoc.getIDocumentRedlineAccess().IsRedlineOn() || (!rDoc.getIDocumentRedlineAccess().IsIgnoreRedline()
                                    && !rDoc.getIDocumentRedlineAccess().GetRedlineTable().empty())))
                    {
                        // Was text content inserted? (RefMark/TOXMarks without an end)
                        bool bTextIns = nInsCnt != rSt.GetIndex();
                        // Was content inserted or set over the selection?
                        SwPaM aPam( pStt->nNode, bTextIns ? nInsCnt + 1 : nEnd,
                                    pStt->nNode, nInsCnt );
                        if( pUndo )
                            pUndo->SaveRedlineData( aPam, bTextIns );

                        if( rDoc.getIDocumentRedlineAccess().IsRedlineOn() )
                            rDoc.getIDocumentRedlineAccess().AppendRedline(
                                new SwRangeRedline(
                                    bTextIns ? RedlineType::Insert : RedlineType::Format, aPam ),
                                    true);
                        else if( bTextIns )
                            rDoc.getIDocumentRedlineAccess().SplitRedline( aPam );
                    }
                }
            }
        }

        // We always have to set the auto flag for PageDescs that are set at the Node!
        if( pOtherSet && pOtherSet->Count() )
        {
            SwTableNode* pTableNd;
            const SwFormatPageDesc* pDesc = pOtherSet->GetItemIfSet( RES_PAGEDESC, false );
            if( pDesc )
            {
                if( pNode )
                {
                    // Set auto flag. Only in the template it's without auto!
                    SwFormatPageDesc aNew( *pDesc );

                    // Tables now also know line breaks
                    if( !(nFlags & SetAttrMode::APICALL) &&
                        nullptr != ( pTableNd = pNode->FindTableNode() ) )
                    {
                        SwTableNode* pCurTableNd = pTableNd;
                        while ( nullptr != ( pCurTableNd = pCurTableNd->StartOfSectionNode()->FindTableNode() ) )
                            pTableNd = pCurTableNd;

                        // set the table format
                        SwFrameFormat* pFormat = pTableNd->GetTable().GetFrameFormat();
                        SwRegHistory aRegH( pFormat, *pTableNd, pHistory );
                        pFormat->SetFormatAttr( aNew );
                        bRet = true;
                    }
                    else
                    {
                        SwContentNode * pFirstNode(pNode);
                        if (pLayout && pLayout->HasMergedParas())
                        {
                            pFirstNode = sw::GetFirstAndLastNode(*pLayout, pStt->nNode).first;
                        }
                        SwRegHistory aRegH( pFirstNode, *pFirstNode, pHistory );
                        bRet = pFirstNode->SetAttr( aNew ) || bRet;
                    }
                }

                // bOtherAttr = true means that pOtherSet == rChgSet. In this case
                // we know, that there is only one attribute in pOtherSet. We cannot
                // perform the following operations, instead we return:
                if ( bOtherAttr )
                    return bRet;

                const_cast<SfxItemSet*>(pOtherSet)->ClearItem( RES_PAGEDESC );
                if( !pOtherSet->Count() )
                {
                    DELETECHARSETS
                    return bRet;
                }
            }

            // Tables now also know line breaks
            const SvxFormatBreakItem* pBreak;
            if( pNode && !(nFlags & SetAttrMode::APICALL) &&
                nullptr != (pTableNd = pNode->FindTableNode() ) &&
                (pBreak = pOtherSet->GetItemIfSet( RES_BREAK, false )) )
            {
                SwTableNode* pCurTableNd = pTableNd;
                while ( nullptr != ( pCurTableNd = pCurTableNd->StartOfSectionNode()->FindTableNode() ) )
                    pTableNd = pCurTableNd;

                 // set the table format
                SwFrameFormat* pFormat = pTableNd->GetTable().GetFrameFormat();
                SwRegHistory aRegH( pFormat, *pTableNd, pHistory );
                pFormat->SetFormatAttr( *pBreak );
                bRet = true;

                // bOtherAttr = true means that pOtherSet == rChgSet. In this case
                // we know, that there is only one attribute in pOtherSet. We cannot
                // perform the following operations, instead we return:
                if ( bOtherAttr )
                    return bRet;

                const_cast<SfxItemSet*>(pOtherSet)->ClearItem( RES_BREAK );
                if( !pOtherSet->Count() )
                {
                    DELETECHARSETS
                    return bRet;
                }
            }

            {
                // If we have a PoolNumRule, create it if needed
                sal_uInt16 nPoolId=0;
                const SwNumRuleItem* pRule = pOtherSet->GetItemIfSet( RES_PARATR_NUMRULE, false );
                if( pRule &&
                    !rDoc.FindNumRulePtr( pRule->GetValue() ) &&
                    USHRT_MAX != (nPoolId = SwStyleNameMapper::GetPoolIdFromUIName ( pRule->GetValue(),
                                    SwGetPoolIdFromName::NumRule )) )
                    rDoc.getIDocumentStylePoolAccess().GetNumRuleFromPool( nPoolId );
            }
        }

        SfxItemSetFixed<RES_PAGEDESC, RES_BREAK> firstSet(rDoc.GetAttrPool());
        if (pOtherSet && pOtherSet->Count())
        {   // actually only RES_BREAK is possible here...
            firstSet.Put(*pOtherSet);
        }
        SfxItemSetFixed
            <RES_PARATR_BEGIN, RES_PAGEDESC,
                       RES_BREAK+1, RES_FRMATR_END,
                       XATTR_FILL_FIRST, XATTR_FILL_LAST+1> propsSet(rDoc.GetAttrPool());
        if (pOtherSet && pOtherSet->Count())
        {
            propsSet.Put(*pOtherSet);
        }

        if( !rRg.HasMark() )        // no range
        {
            if( !pNode )
            {
                DELETECHARSETS
                return bRet;
            }

            if( pNode->IsTextNode() && pCharSet && pCharSet->Count() )
            {
                SwTextNode* pTextNd = pNode->GetTextNode();
                const SwIndex& rSt = pStt->nContent;
                sal_Int32 nMkPos, nPtPos = rSt.GetIndex();
                const OUString& rStr = pTextNd->GetText();

                // Special case: if the Cursor is located within a URL attribute, we take over it's area
                SwTextAttr const*const pURLAttr(
                    pTextNd->GetTextAttrAt(rSt.GetIndex(), RES_TXTATR_INETFMT));
                if (pURLAttr && !pURLAttr->GetINetFormat().GetValue().isEmpty())
                {
                    nMkPos = pURLAttr->GetStart();
                    nPtPos = *pURLAttr->End();
                }
                else
                {
                    assert(g_pBreakIt && g_pBreakIt->GetBreakIter().is());
                    Boundary aBndry = g_pBreakIt->GetBreakIter()->getWordBoundary(
                                        pTextNd->GetText(), nPtPos,
                                        g_pBreakIt->GetLocale( pTextNd->GetLang( nPtPos ) ),
                                        WordType::ANY_WORD /*ANYWORD_IGNOREWHITESPACES*/,
                                        true);

                    if( aBndry.startPos < nPtPos && nPtPos < aBndry.endPos )
                    {
                        nMkPos = aBndry.startPos;
                        nPtPos = aBndry.endPos;
                    }
                    else
                        nPtPos = nMkPos = rSt.GetIndex();
                }

                // Remove the overriding attributes from the SwpHintsArray,
                // if the selection spans across the whole paragraph.
                // These attributes are inserted as FormatAttributes and
                // never override the TextAttributes!
                if( !(nFlags & SetAttrMode::DONTREPLACE ) &&
                    pTextNd->HasHints() && !nMkPos && nPtPos == rStr.getLength())
                {
                    SwIndex aSt( pTextNd );
                    if( pHistory )
                    {
                        // Save all attributes for the Undo.
                        SwRegHistory aRHst( *pTextNd, pHistory );
                        pTextNd->GetpSwpHints()->Register( &aRHst );
                        pTextNd->RstTextAttr( aSt, nPtPos, 0, pCharSet );
                        if( pTextNd->GetpSwpHints() )
                            pTextNd->GetpSwpHints()->DeRegister();
                    }
                    else
                        pTextNd->RstTextAttr( aSt, nPtPos, 0, pCharSet );
                }

                if( rDoc.getIDocumentRedlineAccess().IsRedlineOn() )
                {
                    SwPaM aPam( *pNode, nMkPos, *pNode, nPtPos );

                    if( pUndo )
                        pUndo->SaveRedlineData( aPam, false );

                    lcl_SetRedlines(rDoc, aPam);
                }

                // the SwRegHistory inserts the attribute into the TextNode!
                SwRegHistory history( pNode, *pNode, pHistory );

                bRet = history.InsertItems( *pCharSet, nMkPos, nPtPos, nFlags, /*ppNewTextAttr*/nullptr )
                    || bRet;

            }
            if( pOtherSet && pOtherSet->Count() )
            {
                // Need to check for unique item for DrawingLayer items of type NameOrIndex
                // and evtl. correct that item to ensure unique names for that type. This call may
                // modify/correct entries inside of the given SfxItemSet
                SfxItemSet aTempLocalCopy(*pOtherSet);

                rDoc.CheckForUniqueItemForLineFillNameOrIndex(aTempLocalCopy);
                bRet = lcl_ApplyOtherSet(*pNode, pHistory, aTempLocalCopy, firstSet, propsSet, pLayout) || bRet;
            }

            DELETECHARSETS
            return bRet;
        }

        if( rDoc.getIDocumentRedlineAccess().IsRedlineOn() && pCharSet && pCharSet->Count() )
        {
            if( pUndo )
                pUndo->SaveRedlineData( rRg, false );

            lcl_SetRedlines(rDoc, rRg);
        }

        /* now if range */
        sal_uLong nNodes = 0;

        SwNodeIndex aSt( rDoc.GetNodes() );
        SwNodeIndex aEnd( rDoc.GetNodes() );
        SwIndex aCntEnd( pEnd->nContent );

        if( pNode )
        {
            const sal_Int32 nLen = pNode->Len();
            if( pStt->nNode != pEnd->nNode )
                aCntEnd.Assign( pNode, nLen );

            if( pStt->nContent.GetIndex() != 0 || aCntEnd.GetIndex() != nLen )
            {
                // the SwRegHistory inserts the attribute into the TextNode!
                if( pNode->IsTextNode() && pCharSet && pCharSet->Count() )
                {
                    SwRegHistory history( pNode, *pNode, pHistory );
                    bRet = history.InsertItems(*pCharSet,
                            pStt->nContent.GetIndex(), aCntEnd.GetIndex(), nFlags, /*ppNewTextAttr*/nullptr)
                        || bRet;
                }

                if( pOtherSet && pOtherSet->Count() )
                {
                    bRet = lcl_ApplyOtherSet(*pNode, pHistory, *pOtherSet, firstSet, propsSet, pLayout) || bRet;
                }

                // Only selection in a Node.
                if( pStt->nNode == pEnd->nNode )
                {
                    DELETECHARSETS
                    return bRet;
                }
                ++nNodes;
                aSt.Assign( pStt->nNode.GetNode(), +1 );
            }
            else
                aSt = pStt->nNode;
            aCntEnd = pEnd->nContent; // aEnd was changed!
        }
        else
            aSt.Assign( pStt->nNode.GetNode(), +1 );

        // aSt points to the first full Node now

        /*
         * The selection spans more than one Node.
         */
        if( pStt->nNode < pEnd->nNode )
        {
            pNode = pEnd->nNode.GetNode().GetContentNode();
            if(pNode)
            {
                if( aCntEnd.GetIndex() != pNode->Len() )
                {
                    // the SwRegHistory inserts the attribute into the TextNode!
                    if( pNode->IsTextNode() && pCharSet && pCharSet->Count() )
                    {
                        SwRegHistory history( pNode, *pNode, pHistory );
                        (void)history.InsertItems(*pCharSet,
                                0, aCntEnd.GetIndex(), nFlags, /*ppNewTextAttr*/nullptr);
                    }

                    if( pOtherSet && pOtherSet->Count() )
                    {
                        lcl_ApplyOtherSet(*pNode, pHistory, *pOtherSet, firstSet, propsSet, pLayout);
                    }

                    ++nNodes;
                    aEnd = pEnd->nNode;
                }
                else
                    aEnd.Assign( pEnd->nNode.GetNode(), +1 );
            }
            else
                aEnd = pEnd->nNode;
        }
        else
            aEnd.Assign( pEnd->nNode.GetNode(), +1 );

        // aEnd points BEHIND the last full node now

        /* Edit the fully selected Nodes. */
        // Reset all attributes from the set!
        if( pCharSet && pCharSet->Count() && !( SetAttrMode::DONTREPLACE & nFlags ) )
        {
            ::sw::DocumentContentOperationsManager::ParaRstFormat aPara(
                    pStt, pEnd, pHistory, pCharSet, pLayout);
            rDoc.GetNodes().ForEach( aSt, aEnd, ::sw::DocumentContentOperationsManager::lcl_RstTextAttr, &aPara );
        }

        bool bCreateSwpHints = pCharSet && (
            SfxItemState::SET == pCharSet->GetItemState( RES_TXTATR_CHARFMT, false ) ||
            SfxItemState::SET == pCharSet->GetItemState( RES_TXTATR_INETFMT, false ) );

        for (SwNodeIndex current = aSt; current < aEnd; ++current)
        {
            SwTextNode *const pTNd = current.GetNode().GetTextNode();
            if (!pTNd)
                continue;

            if (pLayout && pLayout->HasMergedParas()
                && pTNd->GetRedlineMergeFlag() == SwNode::Merge::Hidden)
            {   // not really sure what to do here, but applying to hidden
                continue; // nodes doesn't make sense...
            }

            if( pHistory )
            {
                SwRegHistory aRegH( pTNd, *pTNd, pHistory );

                if (pCharSet && pCharSet->Count())
                {
                    if (SwpHints *pSwpHints = bCreateSwpHints ? &pTNd->GetOrCreateSwpHints()
                                                : pTNd->GetpSwpHints())
                    {
                        pSwpHints->Register( &aRegH );
                    }

                    pTNd->SetAttr(*pCharSet, 0, pTNd->GetText().getLength(), nFlags);

                    // re-fetch as it may be deleted by SetAttr
                    if (SwpHints *pSwpHints = pTNd->GetpSwpHints())
                        pSwpHints->DeRegister();
                }
            }
            else
            {
                if (pCharSet && pCharSet->Count())
                    pTNd->SetAttr(*pCharSet, 0, pTNd->GetText().getLength(), nFlags);
            }
            ++nNodes;
        }

        if (pOtherSet && pOtherSet->Count())
        {
            for (; aSt < aEnd; ++aSt)
            {
                pNode = aSt.GetNode().GetContentNode();
                if (!pNode)
                    continue;

                lcl_ApplyOtherSet(*pNode, pHistory, *pOtherSet, firstSet, propsSet, pLayout, &aSt);
                ++nNodes;
            }
        }

        DELETECHARSETS
        return (nNodes != 0) || bRet;
    }
}

namespace sw
{

namespace mark
{
    bool IsFieldmarkOverlap(SwPaM const& rPaM)
    {
        std::vector<std::pair<SwNodeOffset, sal_Int32>> Breaks;
        sw::CalcBreaks(Breaks, rPaM);
        return !Breaks.empty();
    }
}

DocumentContentOperationsManager::DocumentContentOperationsManager( SwDoc& i_rSwdoc ) : m_rDoc( i_rSwdoc )
{
}

/**
 * Checks if rStart..rEnd mark a range that makes sense to copy.
 *
 * IsMoveToFly means the copy is a move to create a fly
 * and so existing flys at the edge must not be copied.
 */
static bool IsEmptyRange(const SwPosition& rStart, const SwPosition& rEnd,
        SwCopyFlags const flags)
{
    if (rStart == rEnd)
    {   // check if a fly anchored there would be copied - then copy...
        return !IsDestroyFrameAnchoredAtChar(rStart, rStart, rEnd,
                (flags & SwCopyFlags::IsMoveToFly)
                    ? DelContentType::WriterfilterHack|DelContentType::AllMask
                    : DelContentType::AllMask);
    }
    else
    {
        return rEnd < rStart;
    }
}

// Copy an area into this document or into another document
bool
DocumentContentOperationsManager::CopyRange( SwPaM& rPam, SwPosition& rPos,
        SwCopyFlags const flags) const
{
    const SwPosition *pStt = rPam.Start(), *pEnd = rPam.End();

    SwDoc& rDoc = rPos.nNode.GetNode().GetDoc();
    bool bColumnSel = rDoc.IsClipBoard() && rDoc.IsColumnSelection();

    // Catch if there's no copy to do
    if (!rPam.HasMark() || (IsEmptyRange(*pStt, *pEnd, flags) && !bColumnSel))
        return false;

    // Prevent copying into Flys that are anchored in the source range
    if (&rDoc == &m_rDoc && (flags & SwCopyFlags::CheckPosInFly))
    {
        // Correct the Start-/EndNode
        SwNodeOffset nStt = pStt->nNode.GetIndex(),
                nEnd = pEnd->nNode.GetIndex(),
                nDiff = nEnd - nStt +1;
        SwNode* pNd = m_rDoc.GetNodes()[ nStt ];
        if( pNd->IsContentNode() && pStt->nContent.GetIndex() )
        {
            ++nStt;
            --nDiff;
        }
        if( (pNd = m_rDoc.GetNodes()[ nEnd ])->IsContentNode() &&
            static_cast<SwContentNode*>(pNd)->Len() != pEnd->nContent.GetIndex() )
        {
            --nEnd;
            --nDiff;
        }
        if( nDiff &&
            lcl_ChkFlyFly( rDoc, nStt, nEnd, rPos.nNode.GetIndex() ) )
        {
            return false;
        }
    }

    SwPaM* pRedlineRange = nullptr;
    if( rDoc.getIDocumentRedlineAccess().IsRedlineOn() ||
        (!rDoc.getIDocumentRedlineAccess().IsIgnoreRedline() && !rDoc.getIDocumentRedlineAccess().GetRedlineTable().empty() ) )
        pRedlineRange = new SwPaM( rPos );

    RedlineFlags eOld = rDoc.getIDocumentRedlineAccess().GetRedlineFlags();

    bool bRet = false;

    if( &rDoc != &m_rDoc )
    {   // ordinary copy
        bRet = CopyImpl(rPam, rPos, flags & ~SwCopyFlags::CheckPosInFly, pRedlineRange);
    }
    else if( ! ( *pStt <= rPos && rPos < *pEnd &&
            ( pStt->nNode != pEnd->nNode ||
              !pStt->nNode.GetNode().IsTextNode() )) )
    {
        // Copy to a position outside of the area, or copy a single TextNode
        // Do an ordinary copy
        bRet = CopyImpl(rPam, rPos, flags & ~SwCopyFlags::CheckPosInFly, pRedlineRange);
    }
    else
    {
        // Copy the range in itself
        assert(!"mst: this is assumed to be dead code");
    }

    rDoc.getIDocumentRedlineAccess().SetRedlineFlags_intern( eOld );
    if( pRedlineRange )
    {
        if( rDoc.getIDocumentRedlineAccess().IsRedlineOn() )
            rDoc.getIDocumentRedlineAccess().AppendRedline( new SwRangeRedline( RedlineType::Insert, *pRedlineRange ), true);
        else
            rDoc.getIDocumentRedlineAccess().SplitRedline( *pRedlineRange );
        delete pRedlineRange;
    }

    return bRet;
}

static auto GetCorrPosition(SwPaM const& rPam) -> SwPosition
{
    // tdf#152710 target position must be on node that survives deletion
    // so that PaMCorrAbs can invalidate SwUnoCursors properly
    return rPam.GetPoint()->nNode.GetNode().IsContentNode()
            ? *rPam.GetPoint()
            : rPam.GetMark()->nNode.GetNode().IsContentNode()
                ? *rPam.GetMark()
                // this would be the result in SwNodes::RemoveNode()
                : SwPosition(SwNodeIndex(rPam.End()->nNode.GetNode(), SwNodeOffset(+1)));
}

/// Delete a full Section of the NodeArray.
/// The passed Node is located somewhere in the designated Section.
void DocumentContentOperationsManager::DeleteSection( SwNode *pNode )
{
    assert(pNode && "Didn't pass a Node.");

    SwStartNode* pSttNd = pNode->IsStartNode() ? static_cast<SwStartNode*>(pNode)
                                               : pNode->StartOfSectionNode();
    SwNodeIndex aSttIdx( *pSttNd ), aEndIdx( *pNode->EndOfSectionNode() );

    // delete all Flys, Bookmarks, ...
    DelFlyInRange( aSttIdx, aEndIdx );
    m_rDoc.getIDocumentRedlineAccess().DeleteRedline( *pSttNd, true, RedlineType::Any );
    DelBookmarks(aSttIdx, aEndIdx);

    {
        // move all Cursor/StackCursor/UnoCursor out of the to-be-deleted area
        SwPaM const range(aSttIdx, aEndIdx);
        SwPosition const pos(GetCorrPosition(range));
        ::PaMCorrAbs(range, pos);
    }

    m_rDoc.GetNodes().DelNodes( aSttIdx, aEndIdx.GetIndex() - aSttIdx.GetIndex() + 1 );
}

void DocumentContentOperationsManager::DeleteDummyChar(
        SwPosition const& rPos, sal_Unicode const cDummy)
{
    SwPaM aPam(rPos, rPos);
    ++aPam.GetPoint()->nContent;
    assert(aPam.GetText().getLength() == 1 && aPam.GetText()[0] == cDummy);
    (void) cDummy;

    DeleteRangeImpl(aPam, SwDeleteFlags::Default);

    if (!m_rDoc.getIDocumentRedlineAccess().IsIgnoreRedline()
        && !m_rDoc.getIDocumentRedlineAccess().GetRedlineTable().empty())
    {
        m_rDoc.getIDocumentRedlineAccess().CompressRedlines();
    }
}

void DocumentContentOperationsManager::DeleteRange( SwPaM & rPam )
{
    lcl_DoWithBreaks(*this, rPam, SwDeleteFlags::Default, &DocumentContentOperationsManager::DeleteRangeImpl);

    if (!m_rDoc.getIDocumentRedlineAccess().IsIgnoreRedline()
        && !m_rDoc.getIDocumentRedlineAccess().GetRedlineTable().empty())
    {
        m_rDoc.getIDocumentRedlineAccess().CompressRedlines();
    }
}

bool DocumentContentOperationsManager::DelFullPara( SwPaM& rPam )
{
    const SwPosition &rStt = *rPam.Start(), &rEnd = *rPam.End();
    const SwNode* pNd = &rStt.nNode.GetNode();
    SwNodeOffset nSectDiff = pNd->StartOfSectionNode()->EndOfSectionIndex() -
                        pNd->StartOfSectionIndex();
    SwNodeOffset nNodeDiff = rEnd.nNode.GetIndex() - rStt.nNode.GetIndex();

    if ( nSectDiff-SwNodeOffset(2) <= nNodeDiff || m_rDoc.getIDocumentRedlineAccess().IsRedlineOn() ||
         /* #i9185# Prevent getting the node after the end node (see below) */
        rEnd.nNode.GetIndex() + 1 == m_rDoc.GetNodes().Count() )
    {
        return false;
    }

    {
        SwPaM temp(rPam, nullptr);
        if (!temp.HasMark())
        {
            temp.SetMark();
        }
        if (SwTextNode *const pNode = temp.Start()->nNode.GetNode().GetTextNode())
        { // rPam may not have nContent set but IsFieldmarkOverlap requires it
            pNode->MakeStartIndex(&temp.Start()->nContent);
        }
        if (SwTextNode *const pNode = temp.End()->nNode.GetNode().GetTextNode())
        {
            pNode->MakeEndIndex(&temp.End()->nContent);
        }
        if (sw::mark::IsFieldmarkOverlap(temp))
        {   // a bit of a problem: we want to completely remove the nodes
            // but then how can the CH_TXT_ATR survive?
            return false;
        }
    }

    // Move hard page breaks to the following Node.
    bool bSavePageBreak = false, bSavePageDesc = false;

    /* #i9185# This would lead to a segmentation fault if not caught above. */
    SwNodeOffset nNextNd = rEnd.nNode.GetIndex() + 1;
    SwTableNode *const pTableNd = m_rDoc.GetNodes()[ nNextNd ]->GetTableNode();

    if( pTableNd && pNd->IsContentNode() )
    {
        SwFrameFormat* pTableFormat = pTableNd->GetTable().GetFrameFormat();

        {
            const SfxPoolItem *pItem;
            const SfxItemSet* pSet = static_cast<const SwContentNode*>(pNd)->GetpSwAttrSet();
            if( pSet && SfxItemState::SET == pSet->GetItemState( RES_PAGEDESC,
                false, &pItem ) )
            {
                pTableFormat->SetFormatAttr( *pItem );
                bSavePageDesc = true;
            }

            if( pSet && SfxItemState::SET == pSet->GetItemState( RES_BREAK,
                false, &pItem ) )
            {
                pTableFormat->SetFormatAttr( *pItem );
                bSavePageBreak = true;
            }
        }
    }

    bool const bDoesUndo = m_rDoc.GetIDocumentUndoRedo().DoesUndo();
    if( bDoesUndo )
    {
        if( !rPam.HasMark() )
            rPam.SetMark();
        else if( rPam.GetPoint() == &rStt )
            rPam.Exchange();
        rPam.GetPoint()->nNode++;

        SwContentNode *pTmpNode = rPam.GetPoint()->nNode.GetNode().GetContentNode();
        rPam.GetPoint()->nContent.Assign( pTmpNode, 0 );
        bool bGoNext = (nullptr == pTmpNode);
        pTmpNode = rPam.GetMark()->nNode.GetNode().GetContentNode();
        rPam.GetMark()->nContent.Assign( pTmpNode, 0 );

        m_rDoc.GetIDocumentUndoRedo().ClearRedo();

        SwPaM aDelPam( *rPam.GetMark(), *rPam.GetPoint() );
        {
            SwPosition aTmpPos( *aDelPam.GetPoint() );
            if( bGoNext )
            {
                pTmpNode = m_rDoc.GetNodes().GoNext( &aTmpPos.nNode );
                aTmpPos.nContent.Assign( pTmpNode, 0 );
            }
            ::PaMCorrAbs( aDelPam, aTmpPos );
        }

        std::unique_ptr<SwUndoDelete> pUndo(new SwUndoDelete(aDelPam, SwDeleteFlags::Default, true));

        *rPam.GetPoint() = *aDelPam.GetPoint();
        pUndo->SetPgBrkFlags( bSavePageBreak, bSavePageDesc );
        m_rDoc.GetIDocumentUndoRedo().AppendUndo(std::move(pUndo));
        rPam.DeleteMark();
    }
    else
    {
        SwNodeRange aRg( rStt.nNode, rEnd.nNode );
        rPam.Normalize(false);

        // Try to move past the End
        if( !rPam.Move( fnMoveForward, GoInNode ) )
        {
            // Fair enough, at the Beginning then
            rPam.Exchange();
            if( !rPam.Move( fnMoveBackward, GoInNode ))
            {
                SAL_WARN("sw.core", "DelFullPara: no more Nodes");
                return false;
            }
        }

        // must delete all fieldmarks before CorrAbs(), or they'll remain
        // moved to wrong node without their CH_TXT_ATR_FIELD*
        // (note: deleteMarks() doesn't help here, in case of partially
        // selected fieldmarks; let's delete these as re-inserting their chars
        // elsewhere looks difficult)
        ::std::set<::sw::mark::IFieldmark*> fieldmarks;
        for (SwNodeIndex i = aRg.aStart; i <= aRg.aEnd; ++i)
        {
            if (SwTextNode *const pTextNode = i.GetNode().GetTextNode())
            {
                for (sal_Int32 j = 0; j < pTextNode->GetText().getLength(); ++j)
                {
                    switch (pTextNode->GetText()[j])
                    {
                        case CH_TXT_ATR_FIELDSTART:
                        case CH_TXT_ATR_FIELDEND:
                            fieldmarks.insert(m_rDoc.getIDocumentMarkAccess()->getFieldmarkAt(SwPosition(*pTextNode, j)));
                        break;
                        case CH_TXT_ATR_FIELDSEP:
                            fieldmarks.insert(m_rDoc.getIDocumentMarkAccess()->getFieldmarkFor(SwPosition(*pTextNode, j)));
                        break;
                    }
                }
            }
        }
        for (auto const pFieldMark : fieldmarks)
        {
            m_rDoc.getIDocumentMarkAccess()->deleteMark(pFieldMark);
        }

        // move bookmarks, redlines etc.
        if (aRg.aStart == aRg.aEnd) // only first CorrAbs variant handles this
        {
            m_rDoc.CorrAbs( aRg.aStart, *rPam.GetPoint(), 0, true );
        }
        else
        {
            SwDoc::CorrAbs( aRg.aStart, aRg.aEnd, *rPam.GetPoint(), true );
        }

            // What's with Flys?
        {
            // If there are FlyFrames left, delete these too
            for( size_t n = 0; n < m_rDoc.GetSpzFrameFormats()->size(); ++n )
            {
                SwFrameFormat* pFly = (*m_rDoc.GetSpzFrameFormats())[n];
                const SwFormatAnchor* pAnchor = &pFly->GetAnchor();
                SwPosition const*const pAPos = pAnchor->GetContentAnchor();
                if (pAPos &&
                    ((RndStdIds::FLY_AT_PARA == pAnchor->GetAnchorId()) ||
                     (RndStdIds::FLY_AT_CHAR == pAnchor->GetAnchorId())) &&
                    // note: here use <= not < like in
                    // IsDestroyFrameAnchoredAtChar() because of the increment
                    // of rPam in the bDoesUndo path above!
                    aRg.aStart <= pAPos->nNode && pAPos->nNode <= aRg.aEnd )
                {
                    m_rDoc.getIDocumentLayoutAccess().DelLayoutFormat( pFly );
                    --n;
                }
            }
        }

        rPam.DeleteMark();
        m_rDoc.GetNodes().Delete( aRg.aStart, nNodeDiff+1 );
    }
    m_rDoc.getIDocumentState().SetModified();

    return true;
}

bool DocumentContentOperationsManager::DeleteAndJoin(SwPaM & rPam, SwDeleteFlags const flags)
{
    if ( lcl_StrLenOverflow( rPam ) )
        return false;

    bool const ret = lcl_DoWithBreaks( *this, rPam, flags, (m_rDoc.getIDocumentRedlineAccess().IsRedlineOn())
                ? &DocumentContentOperationsManager::DeleteAndJoinWithRedlineImpl
                : &DocumentContentOperationsManager::DeleteAndJoinImpl );

    return ret;
}

// It seems that this is mostly used by SwDoc internals; the only
// way to call this from the outside seems to be the special case in
// SwDoc::CopyRange (but I have not managed to actually hit that case).
bool DocumentContentOperationsManager::MoveRange( SwPaM& rPaM, SwPosition& rPos, SwMoveFlags eMvFlags )
{
    // nothing moved: return
    const SwPosition *pStt = rPaM.Start(), *pEnd = rPaM.End();
    if( !rPaM.HasMark() || *pStt >= *pEnd || (*pStt <= rPos && rPos < *pEnd))
        return false;

    assert(!sw::mark::IsFieldmarkOverlap(rPaM)); // probably an invalid redline was created?

    // Save the paragraph anchored Flys, so that they can be moved.
    SaveFlyArr aSaveFlyArr;
    SaveFlyInRange( rPaM, rPos, aSaveFlyArr, bool( SwMoveFlags::ALLFLYS & eMvFlags ) );

    // save redlines (if DOC_MOVEREDLINES is used)
    SaveRedlines_t aSaveRedl;
    if( SwMoveFlags::REDLINES & eMvFlags && !m_rDoc.getIDocumentRedlineAccess().GetRedlineTable().empty() )
    {
        lcl_SaveRedlines( rPaM, aSaveRedl );

        // #i17764# unfortunately, code below relies on undos being
        //          in a particular order, and presence of bookmarks
        //          will change this order. Hence, we delete bookmarks
        //          here without undo.
        ::sw::UndoGuard const undoGuard(m_rDoc.GetIDocumentUndoRedo());
        DelBookmarks(
            pStt->nNode,
            pEnd->nNode,
            nullptr,
            &pStt->nContent,
            &pEnd->nContent);
    }

    bool bUpdateFootnote = false;
    SwFootnoteIdxs aTmpFntIdx;

    std::unique_ptr<SwUndoMove> pUndoMove;
    if (m_rDoc.GetIDocumentUndoRedo().DoesUndo())
    {
        m_rDoc.GetIDocumentUndoRedo().ClearRedo();
        pUndoMove.reset(new SwUndoMove( rPaM, rPos ));
        pUndoMove->SetMoveRedlines( eMvFlags == SwMoveFlags::REDLINES );
    }
    else
    {
        bUpdateFootnote = lcl_SaveFootnote( pStt->nNode, pEnd->nNode, rPos.nNode,
                                    m_rDoc.GetFootnoteIdxs(), aTmpFntIdx,
                                    &pStt->nContent, &pEnd->nContent );
    }

    bool bSplit = false;
    SwPaM aSavePam( rPos, rPos );

    // Move the SPoint to the beginning of the range
    if( rPaM.GetPoint() == pEnd )
        rPaM.Exchange();

    // If there is a TextNode before and after the Move, create a JoinNext in the EditShell.
    SwTextNode* pSrcNd = rPaM.GetPoint()->nNode.GetNode().GetTextNode();
    bool bCorrSavePam = pSrcNd && pStt->nNode != pEnd->nNode;

    // If one or more TextNodes are moved, SwNodes::Move will do a SplitNode.
    // However, this does not update the cursor. So we create a TextNode to keep
    // updating the indices. After the Move the Node is optionally deleted.
    SwTextNode * pTNd = rPos.nNode.GetNode().GetTextNode();
    if( pTNd && rPaM.GetPoint()->nNode != rPaM.GetMark()->nNode &&
        ( rPos.nContent.GetIndex() || ( pTNd->Len() && bCorrSavePam  )) )
    {
        bSplit = true;
        const sal_Int32 nMkContent = rPaM.GetMark()->nContent.GetIndex();

        const std::shared_ptr<sw::mark::ContentIdxStore> pContentStore(sw::mark::ContentIdxStore::Create());
        pContentStore->Save( m_rDoc, rPos.nNode.GetIndex(), rPos.nContent.GetIndex(), true );

        SwTextNode * pOrigNode = pTNd;
        assert(*aSavePam.GetPoint() == *aSavePam.GetMark() &&
               *aSavePam.GetPoint() == rPos);
        assert(aSavePam.GetPoint()->nContent.GetIdxReg() == pOrigNode);
        assert(aSavePam.GetPoint()->nNode == rPos.nNode.GetIndex());
        assert(rPos.nNode.GetIndex() == pOrigNode->GetIndex());

        std::function<void (SwTextNode *, sw::mark::RestoreMode, bool)> restoreFunc(
            [&](SwTextNode *const, sw::mark::RestoreMode const eMode, bool)
            {
                if (!pContentStore->Empty())
                {
                    pContentStore->Restore(m_rDoc, pOrigNode->GetIndex()-SwNodeOffset(1), 0, true, false, eMode);
                }
            });
        pTNd = pTNd->SplitContentNode(rPos, &restoreFunc)->GetTextNode();

        //A new node was inserted before the orig pTNd and the content up to
        //rPos moved into it. The old node is returned with the remainder
        //of the content in it.
        //
        //aSavePam was created with rPos, it continues to point to the
        //old node, but with the *original* content index into the node.
        //Seeing as all the orignode content before that index has
        //been removed, the new index into the original node should now be set
        //to 0 and the content index of rPos should also be adapted to the
        //truncated node
        assert(*aSavePam.GetPoint() == *aSavePam.GetMark() &&
               *aSavePam.GetPoint() == rPos);
        assert(aSavePam.GetPoint()->nContent.GetIdxReg() == pOrigNode);
        assert(aSavePam.GetPoint()->nNode == rPos.nNode.GetIndex());
        assert(rPos.nNode.GetIndex() == pOrigNode->GetIndex());
        aSavePam.GetPoint()->nContent.Assign(pOrigNode, 0);
        rPos = *aSavePam.GetMark() = *aSavePam.GetPoint();

        // correct the PaM!
        if( rPos.nNode == rPaM.GetMark()->nNode )
        {
            rPaM.GetMark()->nNode = rPos.nNode.GetIndex()-SwNodeOffset(1);
            rPaM.GetMark()->nContent.Assign( pTNd, nMkContent );
        }
    }

    // Put back the Pam by one "content"; so that it's always outside of
    // the manipulated range.
    // tdf#99692 don't Move() back if that would end up in another node
    // because moving backward is not necessarily the inverse of forward then.
    // (but do Move() back if we have split the node)
    const bool bNullContent = !bSplit && aSavePam.GetPoint()->nContent == 0;
    if( bNullContent )
    {
        aSavePam.GetPoint()->nNode--;
        aSavePam.GetPoint()->nContent.Assign(aSavePam.GetContentNode(), 0);
    }
    else
    {
        bool const success(aSavePam.Move(fnMoveBackward, GoInContent));
        assert(success);
        (void) success;
    }

    // Copy all Bookmarks that are within the Move range into an array,
    // that saves the position as an offset.
    std::vector< ::sw::mark::SaveBookmark> aSaveBkmks;
    DelBookmarks(
        pStt->nNode,
        pEnd->nNode,
        &aSaveBkmks,
        &pStt->nContent,
        &pEnd->nContent);

    // If there is no range anymore due to the above deletions (e.g. the
    // footnotes got deleted), it's still a valid Move!
    if( *rPaM.GetPoint() != *rPaM.GetMark() )
    {
        // now do the actual move
        m_rDoc.GetNodes().MoveRange( rPaM, rPos, m_rDoc.GetNodes() );

        // after a MoveRange() the Mark is deleted
        if ( rPaM.HasMark() ) // => no Move occurred!
        {
            return false;
        }
    }
    else
        rPaM.DeleteMark();

    OSL_ENSURE( *aSavePam.GetMark() == rPos ||
            ( aSavePam.GetMark()->nNode.GetNode().GetContentNode() == nullptr ),
            "PaM was not moved. Aren't there ContentNodes at the beginning/end?" );
    *aSavePam.GetMark() = rPos;

    rPaM.SetMark();         // create a Sel. around the new range
    pTNd = aSavePam.GetNode().GetTextNode();
    assert(!m_rDoc.GetIDocumentUndoRedo().DoesUndo());
    bool bRemove = true;
    // Do two Nodes have to be joined at the SavePam?
    if (bSplit && pTNd)
    {
        if (pTNd->CanJoinNext())
        {
            // Always join next, because <pTNd> has to stay as it is.
            // A join previous from its next would more or less delete <pTNd>
            pTNd->JoinNext();
            bRemove = false;
        }
    }
    if (bNullContent)
    {
        aSavePam.GetPoint()->nNode++;
        aSavePam.GetPoint()->nContent.Assign( aSavePam.GetContentNode(), 0 );
    }
    else if (bRemove) // No move forward after joining with next paragraph
    {
        aSavePam.Move( fnMoveForward, GoInContent );
    }

    // Insert the Bookmarks back into the Document.
    *rPaM.GetMark() = *aSavePam.Start();
    for(auto& rBkmk : aSaveBkmks)
        rBkmk.SetInDoc(
            &m_rDoc,
            rPaM.GetMark()->nNode,
            &rPaM.GetMark()->nContent);
    *rPaM.GetPoint() = *aSavePam.End();

    // Move the Flys to the new position.
    // note: rPos is at the end here; can't really tell flys that used to be
    // at the start of rPam from flys that used to be at the end of rPam
    // unfortunately, so some of them are going to end up with wrong anchor...
    RestFlyInRange( aSaveFlyArr, *rPaM.Start(), &(rPos.nNode) );

    // restore redlines (if DOC_MOVEREDLINES is used)
    if( !aSaveRedl.empty() )
    {
        lcl_RestoreRedlines( m_rDoc, *aSavePam.Start(), aSaveRedl );
    }

    if( bUpdateFootnote )
    {
        if( !aTmpFntIdx.empty() )
        {
            m_rDoc.GetFootnoteIdxs().insert( aTmpFntIdx );
            aTmpFntIdx.clear();
        }

        m_rDoc.GetFootnoteIdxs().UpdateAllFootnote();
    }

    m_rDoc.getIDocumentState().SetModified();
    return true;
}

bool DocumentContentOperationsManager::MoveNodeRange( SwNodeRange& rRange, SwNodeIndex& rPos,
        SwMoveFlags eMvFlags )
{
    // Moves all Nodes to the new position.
    // Bookmarks are moved too (currently without Undo support).

    // If footnotes are being moved to the special section, remove them now.

    // Or else delete the Frames for all footnotes that are being moved
    // and have it rebuild after the Move (footnotes can change pages).
    // Additionally we have to correct the FootnoteIdx array's sorting.
    bool bUpdateFootnote = false;
    SwFootnoteIdxs aTmpFntIdx;

    std::unique_ptr<SwUndoMove> pUndo;
    if ((SwMoveFlags::CREATEUNDOOBJ & eMvFlags ) && m_rDoc.GetIDocumentUndoRedo().DoesUndo())
    {
        pUndo.reset(new SwUndoMove( m_rDoc, rRange, rPos ));
    }
    else
    {
        bUpdateFootnote = lcl_SaveFootnote( rRange.aStart, rRange.aEnd, rPos,
                                    m_rDoc.GetFootnoteIdxs(), aTmpFntIdx );
    }

    SaveRedlines_t aSaveRedl;
    std::vector<SwRangeRedline*> aSavRedlInsPosArr;
    if( SwMoveFlags::REDLINES & eMvFlags && !m_rDoc.getIDocumentRedlineAccess().GetRedlineTable().empty() )
    {
        lcl_SaveRedlines( rRange, aSaveRedl );

        // Find all RedLines that end at the InsPos.
        // These have to be moved back to the "old" position after the Move.
        SwRedlineTable::size_type nRedlPos = m_rDoc.getIDocumentRedlineAccess().GetRedlinePos( rPos.GetNode(), RedlineType::Any );
        if( SwRedlineTable::npos != nRedlPos )
        {
            const SwPosition *pRStt, *pREnd;
            do {
                SwRangeRedline* pTmp = m_rDoc.getIDocumentRedlineAccess().GetRedlineTable()[ nRedlPos ];
                pRStt = pTmp->Start();
                pREnd = pTmp->End();
                if( pREnd->nNode == rPos && pRStt->nNode < rPos )
                {
                    aSavRedlInsPosArr.push_back( pTmp );
                }
            } while( pRStt->nNode < rPos && ++nRedlPos < m_rDoc.getIDocumentRedlineAccess().GetRedlineTable().size());
        }
    }

    // Copy all Bookmarks that are within the Move range into an array
    // that stores all references to positions as an offset.
    // The final mapping happens after the Move.
    std::vector< ::sw::mark::SaveBookmark> aSaveBkmks;
    DelBookmarks(rRange.aStart, rRange.aEnd, &aSaveBkmks);

    // Save the paragraph-bound Flys, so that they can be moved.
    SaveFlyArr aSaveFlyArr;
    if( !m_rDoc.GetSpzFrameFormats()->empty() )
        SaveFlyInRange( rRange, aSaveFlyArr );

    // Set it to before the Position, so that it cannot be moved further.
    SwNodeIndex aIdx( rPos, -1 );

    std::unique_ptr<SwNodeIndex> pSaveInsPos;
    if( pUndo )
        pSaveInsPos.reset(new SwNodeIndex( rRange.aStart, -1 ));

    // move the Nodes
    bool bNoDelFrames = bool(SwMoveFlags::NO_DELFRMS & eMvFlags);
    if( m_rDoc.GetNodes().MoveNodes( rRange, m_rDoc.GetNodes(), rPos, !bNoDelFrames ) )
    {
        ++aIdx;     // again back to old position
        if( pSaveInsPos )
            ++(*pSaveInsPos);
    }
    else
    {
        aIdx = rRange.aStart;
        pUndo.reset();
    }

    // move the Flys to the new position
    if( !aSaveFlyArr.empty() )
    {
        SwPosition const tmp(aIdx);
        RestFlyInRange(aSaveFlyArr, tmp, nullptr);
    }

    // Add the Bookmarks back to the Document
    for(auto& rBkmk : aSaveBkmks)
        rBkmk.SetInDoc(&m_rDoc, aIdx);

    if( !aSavRedlInsPosArr.empty() )
    {
        SwNode* pNewNd = &aIdx.GetNode();
        for(SwRangeRedline* pTmp : aSavRedlInsPosArr)
        {
            if( m_rDoc.getIDocumentRedlineAccess().GetRedlineTable().Contains( pTmp ) )
            {
                SwPosition* pEnd = pTmp->End();
                pEnd->nNode = aIdx;
                pEnd->nContent.Assign( pNewNd->GetContentNode(), 0 );
            }
        }
    }

    if( !aSaveRedl.empty() )
        lcl_RestoreRedlines( m_rDoc, aIdx.GetIndex(), aSaveRedl );

    if( pUndo )
    {
        pUndo->SetDestRange( aIdx, rPos, *pSaveInsPos );
        m_rDoc.GetIDocumentUndoRedo().AppendUndo(std::move(pUndo));
    }

    pSaveInsPos.reset();

    if( bUpdateFootnote )
    {
        if( !aTmpFntIdx.empty() )
        {
            m_rDoc.GetFootnoteIdxs().insert( aTmpFntIdx );
            aTmpFntIdx.clear();
        }

        m_rDoc.GetFootnoteIdxs().UpdateAllFootnote();
    }

    m_rDoc.getIDocumentState().SetModified();
    return true;
}

void DocumentContentOperationsManager::MoveAndJoin( SwPaM& rPaM, SwPosition& rPos )
{
    SwNodeIndex aIdx( rPaM.Start()->nNode );
    bool bJoinText = aIdx.GetNode().IsTextNode();
    bool bOneNode = rPaM.GetPoint()->nNode == rPaM.GetMark()->nNode;
    aIdx--;             // in front of the move area!

    bool bRet = MoveRange( rPaM, rPos, SwMoveFlags::DEFAULT );
    if( !bRet || bOneNode )
        return;

    if( bJoinText )
        ++aIdx;
    SwTextNode * pTextNd = aIdx.GetNode().GetTextNode();
    SwNodeIndex aNxtIdx( aIdx );
    if( pTextNd && pTextNd->CanJoinNext( &aNxtIdx ) )
    {
        {   // Block so SwIndex into node is deleted before Join
            m_rDoc.CorrRel( aNxtIdx, SwPosition( aIdx, SwIndex(pTextNd,
                        pTextNd->GetText().getLength()) ), 0, true );
        }
        pTextNd->JoinNext();
    }
}

// Overwrite only uses the point of the PaM, the mark is ignored; characters
// are replaced from point until the end of the node; at the end of the node,
// characters are inserted.
bool DocumentContentOperationsManager::Overwrite( const SwPaM &rRg, const OUString &rStr )
{
    assert(rStr.getLength());
    SwPosition& rPt = *const_cast<SwPosition*>(rRg.GetPoint());
    if( m_rDoc.GetAutoCorrExceptWord() )                  // Add to AutoCorrect
    {
        if( 1 == rStr.getLength() )
            m_rDoc.GetAutoCorrExceptWord()->CheckChar( rPt, rStr[ 0 ] );
        m_rDoc.DeleteAutoCorrExceptWord();
    }

    SwTextNode *pNode = rPt.nNode.GetNode().GetTextNode();
    if (!pNode || rStr.getLength() > pNode->GetSpaceLeft()) // worst case: no erase
    {
        return false;
    }

    if (m_rDoc.GetIDocumentUndoRedo().DoesUndo())
    {
        m_rDoc.GetIDocumentUndoRedo().ClearRedo(); // AppendUndo not always called
    }

    const size_t nOldAttrCnt = pNode->GetpSwpHints()
                                ? pNode->GetpSwpHints()->Count() : 0;
    SwDataChanged aTmp( rRg );
    SwIndex& rIdx = rPt.nContent;
    sal_Int32 const nActualStart(rIdx.GetIndex());
    sal_Int32 nStart = 0;

    bool bOldExpFlg = pNode->IsIgnoreDontExpand();
    pNode->SetIgnoreDontExpand( true );

    for( sal_Int32 nCnt = 0; nCnt < rStr.getLength(); ++nCnt )
    {
        // start behind the characters (to fix the attributes!)
        nStart = rIdx.GetIndex();
        if  (nStart < pNode->GetText().getLength())
        {
            lcl_SkipAttr( pNode, rIdx, nStart );
        }
        sal_Unicode c = rStr[ nCnt ];
        if (m_rDoc.GetIDocumentUndoRedo().DoesUndo())
        {
            bool bMerged(false);
            if (m_rDoc.GetIDocumentUndoRedo().DoesGroupUndo())
            {
                SwUndo *const pUndo = m_rDoc.GetUndoManager().GetLastUndo();
                SwUndoOverwrite *const pUndoOW(
                    dynamic_cast<SwUndoOverwrite *>(pUndo) );
                if (pUndoOW)
                {
                    // if CanGrouping() returns true it's already merged
                    bMerged = pUndoOW->CanGrouping(m_rDoc, rPt, c);
                }
            }
            if (!bMerged)
            {
                m_rDoc.GetIDocumentUndoRedo().AppendUndo(
                    std::make_unique<SwUndoOverwrite>(m_rDoc, rPt, c) );
            }
        }
        else
        {
            // start behind the characters (to fix the attributes!)
            if (nStart < pNode->GetText().getLength())
                ++rIdx;
            pNode->InsertText( OUString(c), rIdx, SwInsertFlags::EMPTYEXPAND );
            if( nStart+1 < rIdx.GetIndex() )
            {
                rIdx = nStart;
                pNode->EraseText( rIdx, 1 );
                ++rIdx;
            }
        }
    }
    pNode->SetIgnoreDontExpand( bOldExpFlg );

    const size_t nNewAttrCnt = pNode->GetpSwpHints()
                                ? pNode->GetpSwpHints()->Count() : 0;
    if( nOldAttrCnt != nNewAttrCnt )
    {
        const SwUpdateAttr aHint(0,0,0);
        pNode->TriggerNodeUpdate(sw::LegacyModifyHint(&aHint, &aHint));
    }

    if (!m_rDoc.GetIDocumentUndoRedo().DoesUndo() &&
        !m_rDoc.getIDocumentRedlineAccess().IsIgnoreRedline() && !m_rDoc.getIDocumentRedlineAccess().GetRedlineTable().empty())
    {
        SwPaM aPam(rPt.nNode, nActualStart, rPt.nNode, rPt.nContent.GetIndex());
        m_rDoc.getIDocumentRedlineAccess().DeleteRedline( aPam, true, RedlineType::Any );
    }
    else if( m_rDoc.getIDocumentRedlineAccess().IsRedlineOn() )
    {
        // FIXME: this redline is WRONG: there is no DELETE, and the skipped
        // characters are also included in aPam
        SwPaM aPam(rPt.nNode, nActualStart, rPt.nNode, rPt.nContent.GetIndex());
        m_rDoc.getIDocumentRedlineAccess().AppendRedline( new SwRangeRedline( RedlineType::Insert, aPam ), true);
    }

    m_rDoc.getIDocumentState().SetModified();
    return true;
}

bool DocumentContentOperationsManager::InsertString( const SwPaM &rRg, const OUString &rStr,
        const SwInsertFlags nInsertMode )
{
    // tdf#119019 accept tracked paragraph formatting to do not hide new insertions
    if( m_rDoc.getIDocumentRedlineAccess().IsRedlineOn() )
    {
        RedlineFlags eOld = m_rDoc.getIDocumentRedlineAccess().GetRedlineFlags();
        m_rDoc.getIDocumentRedlineAccess().AcceptRedlineParagraphFormatting( rRg );
        if (eOld != m_rDoc.getIDocumentRedlineAccess().GetRedlineFlags())
            m_rDoc.getIDocumentRedlineAccess().SetRedlineFlags( eOld );
    }

    // fetching DoesUndo is surprisingly expensive
    bool bDoesUndo = m_rDoc.GetIDocumentUndoRedo().DoesUndo();
    if (bDoesUndo)
        m_rDoc.GetIDocumentUndoRedo().ClearRedo(); // AppendUndo not always called!

    const SwPosition& rPos = *rRg.GetPoint();

    if( m_rDoc.GetAutoCorrExceptWord() )                  // add to auto correction
    {
        if( 1 == rStr.getLength() && m_rDoc.GetAutoCorrExceptWord()->IsDeleted() )
        {
            m_rDoc.GetAutoCorrExceptWord()->CheckChar( rPos, rStr[ 0 ] );
        }
        m_rDoc.DeleteAutoCorrExceptWord();
    }

    SwTextNode *const pNode = rPos.nNode.GetNode().GetTextNode();
    if(!pNode)
        return false;

    SwDataChanged aTmp( rRg );

    if (!bDoesUndo || !m_rDoc.GetIDocumentUndoRedo().DoesGroupUndo())
    {
        OUString const ins(pNode->InsertText(rStr, rPos.nContent, nInsertMode));
        if (bDoesUndo)
        {
            m_rDoc.GetIDocumentUndoRedo().AppendUndo(
                std::make_unique<SwUndoInsert>(rPos.nNode,
                        rPos.nContent.GetIndex(), ins.getLength(), nInsertMode));
        }
    }
    else
    {   // if Undo and grouping is enabled, everything changes!
        SwUndoInsert * pUndo = nullptr;

        // don't group the start if hints at the start should be expanded
        if (!(nInsertMode & SwInsertFlags::FORCEHINTEXPAND))
        {
            SwUndo *const pLastUndo = m_rDoc.GetUndoManager().GetLastUndo();
            SwUndoInsert *const pUndoInsert(
                dynamic_cast<SwUndoInsert *>(pLastUndo) );
            if (pUndoInsert && pUndoInsert->CanGrouping(rPos))
            {
                pUndo = pUndoInsert;
            }
        }

        CharClass const& rCC = GetAppCharClass();
        sal_Int32 nInsPos = rPos.nContent.GetIndex();

        if (!pUndo)
        {
            pUndo = new SwUndoInsert( rPos.nNode, nInsPos, 0, nInsertMode,
                            !rCC.isLetterNumeric( rStr, 0 ) );
            m_rDoc.GetIDocumentUndoRedo().AppendUndo( std::unique_ptr<SwUndo>(pUndo) );
        }

        OUString const ins(pNode->InsertText(rStr, rPos.nContent, nInsertMode));

        for (sal_Int32 i = 0; i < ins.getLength(); ++i)
        {
            nInsPos++;
            // if CanGrouping() returns true, everything has already been done
            if (!pUndo->CanGrouping(ins[i]))
            {
                pUndo = new SwUndoInsert(rPos.nNode, nInsPos, 1, nInsertMode,
                            !rCC.isLetterNumeric(ins, i));
                m_rDoc.GetIDocumentUndoRedo().AppendUndo( std::unique_ptr<SwUndo>(pUndo) );
            }
        }
    }

    // To-Do - add 'SwExtraRedlineTable' also ?
    if( m_rDoc.getIDocumentRedlineAccess().IsRedlineOn() || (!m_rDoc.getIDocumentRedlineAccess().IsIgnoreRedline() && !m_rDoc.getIDocumentRedlineAccess().GetRedlineTable().empty() ))
    {
        SwPaM aPam( rPos.nNode, aTmp.GetContent(),
                    rPos.nNode, rPos.nContent.GetIndex());
        if( m_rDoc.getIDocumentRedlineAccess().IsRedlineOn() )
        {
            m_rDoc.getIDocumentRedlineAccess().AppendRedline(
                new SwRangeRedline( RedlineType::Insert, aPam ), true);
        }
        else
        {
            m_rDoc.getIDocumentRedlineAccess().SplitRedline( aPam );
        }
    }

    m_rDoc.getIDocumentState().SetModified();
    return true;
}

void DocumentContentOperationsManager::SetIME(bool bIME)
{
    m_bIME = bIME;
}

bool DocumentContentOperationsManager::GetIME() const
{
    return m_bIME;
}

void DocumentContentOperationsManager::TransliterateText(
    const SwPaM& rPaM,
    utl::TransliterationWrapper& rTrans )
{
    std::unique_ptr<SwUndoTransliterate> pUndo;
    if (m_rDoc.GetIDocumentUndoRedo().DoesUndo())
        pUndo.reset(new SwUndoTransliterate( rPaM, rTrans ));

    const SwPosition* pStt = rPaM.Start(),
                       * pEnd = rPaM.End();
    SwNodeOffset nSttNd = pStt->nNode.GetIndex(),
          nEndNd = pEnd->nNode.GetIndex();
    sal_Int32 nSttCnt = pStt->nContent.GetIndex();
    sal_Int32 nEndCnt = pEnd->nContent.GetIndex();

    SwTextNode* pTNd = pStt->nNode.GetNode().GetTextNode();
    if( (pStt == pEnd) && pTNd )  // no selection?
    {
        /* Check if cursor is inside of a word */
        assert(g_pBreakIt && g_pBreakIt->GetBreakIter().is());
        Boundary aBndry = g_pBreakIt->GetBreakIter()->getWordBoundary(
                            pTNd->GetText(), nSttCnt,
                            g_pBreakIt->GetLocale( pTNd->GetLang( nSttCnt ) ),
                            WordType::ANY_WORD /*ANYWORD_IGNOREWHITESPACES*/,
                            true);

        if( aBndry.startPos < nSttCnt && nSttCnt < aBndry.endPos )
        {
            /* Cursor is inside of a word */
            if (rTrans.getType() == TransliterationFlags::SENTENCE_CASE) {
                /* set current sentence as 'area of effect' */
                nSttCnt = g_pBreakIt->GetBreakIter()->beginOfSentence(
                            pTNd->GetText(), nSttCnt,
                            g_pBreakIt->GetLocale( pTNd->GetLang( nSttCnt ) ) );
                nEndCnt = g_pBreakIt->GetBreakIter()->endOfSentence(
                            pTNd->GetText(), nEndCnt,
                            g_pBreakIt->GetLocale( pTNd->GetLang( nEndCnt ) ) );
            } else {
                /* Set current word as 'area of effect' */
                nSttCnt = aBndry.startPos;
                nEndCnt = aBndry.endPos;
            }
        } else {
            /* Cursor is not inside of a word. Nothing should happen. */
            return;
        }
    }

    bool bUseRedlining = m_rDoc.getIDocumentRedlineAccess().IsRedlineOn();
    // as a workaround for a known performance problem, switch off redlining
    // to avoid freezing, if transliteration could result too many redlines
    if ( bUseRedlining )
    {
        const sal_uLong nMaxRedlines = 500;
        const bool bIsTitleCase = rTrans.getType() == TransliterationFlags::TITLE_CASE;
        sal_uLong nAffectedNodes = 0;
        sal_uLong nAffectedChars = nEndCnt;
        SwNodeIndex aIdx( pStt->nNode );
        for( ; aIdx.GetIndex() <= nEndNd; ++aIdx )
        {
            SwTextNode* pAffectedNode = aIdx.GetNode().GetTextNode();

            // don't count not text nodes or empty text nodes
            if( !pAffectedNode || pAffectedNode->GetText().isEmpty() )
                continue;

            nAffectedNodes++;

            // count characters of the node (the last - maybe partially
            // selected - node was counted at initialization of nAffectedChars)
            if( aIdx.GetIndex() < nEndNd )
                nAffectedChars += pAffectedNode->GetText().getLength();

            // transliteration creates n redlines for n nodes, except in the
            // case of title case, where it creates n redlines for n words
            if( nAffectedNodes > nMaxRedlines ||
                    // estimate word count based on the character count, where
                    // 6 = average English word length is ~5 letters + space
                    ( bIsTitleCase && (nAffectedChars - nSttCnt)/6 > nMaxRedlines ) )
            {
                bUseRedlining = false;
                break;
            }
        }
    }

    if( nSttNd != nEndNd )  // is more than one text node involved?
    {
        // iterate over all affected text nodes, the first and the last one
        // may be incomplete because the selection starts and/or ends there

        SwNodeIndex aIdx( pStt->nNode );
        if( nSttCnt )
        {
            ++aIdx;
            if( pTNd )
            {
                pTNd->TransliterateText(
                        rTrans, nSttCnt, pTNd->GetText().getLength(), pUndo.get(), bUseRedlining);
            }
        }

        for( ; aIdx.GetIndex() < nEndNd; ++aIdx )
        {
            pTNd = aIdx.GetNode().GetTextNode();
            if (pTNd)
            {
                pTNd->TransliterateText(
                        rTrans, 0, pTNd->GetText().getLength(), pUndo.get(), bUseRedlining);
            }
        }

        if( nEndCnt && nullptr != ( pTNd = pEnd->nNode.GetNode().GetTextNode() ))
        {
            pTNd->TransliterateText( rTrans, 0, nEndCnt, pUndo.get(), bUseRedlining );
        }
    }
    else if( pTNd && nSttCnt < nEndCnt )
    {
        pTNd->TransliterateText( rTrans, nSttCnt, nEndCnt, pUndo.get(), bUseRedlining );
    }
    if( pUndo && pUndo->HasData() )
    {
        m_rDoc.GetIDocumentUndoRedo().AppendUndo(std::move(pUndo));
    }
    m_rDoc.getIDocumentState().SetModified();
}

SwFlyFrameFormat* DocumentContentOperationsManager::InsertGraphic(
        const SwPaM &rRg,
                            const OUString& rGrfName,
                            const OUString& rFltName,
                            const Graphic* pGraphic,
                            const SfxItemSet* pFlyAttrSet,
                            const SfxItemSet* pGrfAttrSet,
                            SwFrameFormat* pFrameFormat )
{
    if( !pFrameFormat )
        pFrameFormat = m_rDoc.getIDocumentStylePoolAccess().GetFrameFormatFromPool( RES_POOLFRM_GRAPHIC );
    SwGrfNode* pSwGrfNode = SwNodes::MakeGrfNode(
                            SwNodeIndex( m_rDoc.GetNodes().GetEndOfAutotext() ),
                            rGrfName, rFltName, pGraphic,
                            m_rDoc.GetDfltGrfFormatColl() );
    SwFlyFrameFormat* pSwFlyFrameFormat = InsNoTextNode( *rRg.GetPoint(), pSwGrfNode,
                            pFlyAttrSet, pGrfAttrSet, pFrameFormat );
    return pSwFlyFrameFormat;
}

SwFlyFrameFormat* DocumentContentOperationsManager::InsertGraphicObject(
        const SwPaM &rRg, const GraphicObject& rGrfObj,
                            const SfxItemSet* pFlyAttrSet,
                            const SfxItemSet* pGrfAttrSet )
{
    SwFrameFormat* pFrameFormat = m_rDoc.getIDocumentStylePoolAccess().GetFrameFormatFromPool( RES_POOLFRM_GRAPHIC );
    SwGrfNode* pSwGrfNode = SwNodes::MakeGrfNode(
                            SwNodeIndex( m_rDoc.GetNodes().GetEndOfAutotext() ),
                            rGrfObj, m_rDoc.GetDfltGrfFormatColl() );
    SwFlyFrameFormat* pSwFlyFrameFormat = InsNoTextNode( *rRg.GetPoint(), pSwGrfNode,
                            pFlyAttrSet, pGrfAttrSet, pFrameFormat );
    return pSwFlyFrameFormat;
}

SwFlyFrameFormat* DocumentContentOperationsManager::InsertEmbObject(
        const SwPaM &rRg, const svt::EmbeddedObjectRef& xObj,
                        SfxItemSet* pFlyAttrSet)
{
    sal_uInt16 nId = RES_POOLFRM_OLE;
    if (xObj.is())
    {
        SvGlobalName aClassName( xObj->getClassID() );
        if (SotExchange::IsMath(aClassName))
        {
            nId = RES_POOLFRM_FORMEL;
        }
    }

    SwFrameFormat* pFrameFormat = m_rDoc.getIDocumentStylePoolAccess().GetFrameFormatFromPool( nId );

    return InsNoTextNode( *rRg.GetPoint(), m_rDoc.GetNodes().MakeOLENode(
                            SwNodeIndex( m_rDoc.GetNodes().GetEndOfAutotext() ),
                            xObj,
                            m_rDoc.GetDfltGrfFormatColl() ),
                            pFlyAttrSet, nullptr,
                            pFrameFormat );
}

SwFlyFrameFormat* DocumentContentOperationsManager::InsertOLE(const SwPaM &rRg, const OUString& rObjName,
                        sal_Int64 nAspect,
                        const SfxItemSet* pFlyAttrSet,
                        const SfxItemSet* pGrfAttrSet)
{
    SwFrameFormat* pFrameFormat = m_rDoc.getIDocumentStylePoolAccess().GetFrameFormatFromPool( RES_POOLFRM_OLE );

    return InsNoTextNode( *rRg.GetPoint(),
                            m_rDoc.GetNodes().MakeOLENode(
                                SwNodeIndex( m_rDoc.GetNodes().GetEndOfAutotext() ),
                                rObjName,
                                nAspect,
                                m_rDoc.GetDfltGrfFormatColl(),
                                nullptr ),
                            pFlyAttrSet, pGrfAttrSet,
                            pFrameFormat );
}

void DocumentContentOperationsManager::ReRead( SwPaM& rPam, const OUString& rGrfName,
                    const OUString& rFltName, const Graphic* pGraphic )
{
    SwGrfNode *pGrfNd;
    if( !(( !rPam.HasMark()
         || rPam.GetPoint()->nNode.GetIndex() == rPam.GetMark()->nNode.GetIndex() )
         && nullptr != ( pGrfNd = rPam.GetPoint()->nNode.GetNode().GetGrfNode() )) )
        return;

    if (m_rDoc.GetIDocumentUndoRedo().DoesUndo())
    {
        m_rDoc.GetIDocumentUndoRedo().AppendUndo(std::make_unique<SwUndoReRead>(rPam, *pGrfNd));
    }

    // Because we don't know if we can mirror the graphic, the mirror attribute is always reset
    if( MirrorGraph::Dont != pGrfNd->GetSwAttrSet().
                                            GetMirrorGrf().GetValue() )
        pGrfNd->SetAttr( SwMirrorGrf() );

    pGrfNd->ReRead( rGrfName, rFltName, pGraphic );
    m_rDoc.getIDocumentState().SetModified();
}

// Insert drawing object, which has to be already inserted in the DrawModel
SwDrawFrameFormat* DocumentContentOperationsManager::InsertDrawObj(
    const SwPaM &rRg,
    SdrObject& rDrawObj,
    const SfxItemSet& rFlyAttrSet )
{
    SwDrawFrameFormat* pFormat = m_rDoc.MakeDrawFrameFormat( OUString(), m_rDoc.GetDfltFrameFormat() );

    const SwFormatAnchor* pAnchor = rFlyAttrSet.GetItemIfSet( RES_ANCHOR, false );
    pFormat->SetFormatAttr( rFlyAttrSet );

    // Didn't set the Anchor yet?
    // DrawObjecte must never end up in the Header/Footer!
    RndStdIds eAnchorId = pAnchor != nullptr ? pAnchor->GetAnchorId() : pFormat->GetAnchor().GetAnchorId();
    const bool bIsAtContent = (RndStdIds::FLY_AT_PAGE != eAnchorId);

    const SwNodeIndex* pChkIdx = nullptr;
    if ( pAnchor == nullptr )
    {
        pChkIdx = &rRg.GetPoint()->nNode;
    }
    else if ( bIsAtContent )
    {
        pChkIdx =
            pAnchor->GetContentAnchor() ? &pAnchor->GetContentAnchor()->nNode : &rRg.GetPoint()->nNode;
    }

    // allow drawing objects in header/footer, but control objects aren't allowed in header/footer.
    if( pChkIdx != nullptr
        && ::CheckControlLayer( &rDrawObj )
        && m_rDoc.IsInHeaderFooter( *pChkIdx ) )
    {
        // apply at-page anchor format
        eAnchorId = RndStdIds::FLY_AT_PAGE;
        pFormat->SetFormatAttr( SwFormatAnchor( eAnchorId ) );
    }
    else if( pAnchor == nullptr
             || ( bIsAtContent
                  && pAnchor->GetContentAnchor() == nullptr ) )
    {
        // apply anchor format
        SwFormatAnchor aAnch( pAnchor != nullptr ? *pAnchor : pFormat->GetAnchor() );
        eAnchorId = aAnch.GetAnchorId();
        if ( eAnchorId == RndStdIds::FLY_AT_FLY )
        {
            const SwStartNode* pStartNode = rRg.GetNode().FindFlyStartNode();
            assert(pStartNode);
            SwPosition aPos(*pStartNode);
            aAnch.SetAnchor( &aPos );
        }
        else
        {
            aAnch.SetAnchor( rRg.GetPoint() );
            if ( eAnchorId == RndStdIds::FLY_AT_PAGE )
            {
                eAnchorId = dynamic_cast<const SdrUnoObj*>( &rDrawObj) !=  nullptr ? RndStdIds::FLY_AS_CHAR : RndStdIds::FLY_AT_PARA;
                aAnch.SetType( eAnchorId );
            }
        }
        pFormat->SetFormatAttr( aAnch );
    }

    // insert text attribute for as-character anchored drawing object
    if ( eAnchorId == RndStdIds::FLY_AS_CHAR )
    {
        bool bAnchorAtPageAsFallback = true;
        const SwFormatAnchor& rDrawObjAnchorFormat = pFormat->GetAnchor();
        if ( rDrawObjAnchorFormat.GetContentAnchor() != nullptr )
        {
            SwTextNode* pAnchorTextNode =
                    rDrawObjAnchorFormat.GetContentAnchor()->nNode.GetNode().GetTextNode();
            if ( pAnchorTextNode != nullptr )
            {
                const sal_Int32 nStt = rDrawObjAnchorFormat.GetContentAnchor()->nContent.GetIndex();
                SwFormatFlyCnt aFormat( pFormat );
                pAnchorTextNode->InsertItem( aFormat, nStt, nStt );
                bAnchorAtPageAsFallback = false;
            }
        }

        if ( bAnchorAtPageAsFallback )
        {
            OSL_ENSURE( false, "DocumentContentOperationsManager::InsertDrawObj(..) - missing content anchor for as-character anchored drawing object --> anchor at-page" );
            pFormat->SetFormatAttr( SwFormatAnchor( RndStdIds::FLY_AT_PAGE ) );
        }
    }

    SwDrawContact* pContact = new SwDrawContact( pFormat, &rDrawObj );

    // Create Frames if necessary
    if( m_rDoc.getIDocumentLayoutAccess().GetCurrentViewShell() )
    {
        // create layout representation
        pFormat->MakeFrames();
        // #i42319# - follow-up of #i35635#
        // move object to visible layer
        // #i79391#
        if ( pContact->GetAnchorFrame() )
        {
            pContact->MoveObjToVisibleLayer( &rDrawObj );
        }
    }

    if (m_rDoc.GetIDocumentUndoRedo().DoesUndo())
    {
        m_rDoc.GetIDocumentUndoRedo().AppendUndo( std::make_unique<SwUndoInsLayFormat>(pFormat, SwNodeOffset(0), 0) );
    }

    m_rDoc.getIDocumentState().SetModified();
    return pFormat;
}

bool DocumentContentOperationsManager::SplitNode( const SwPosition &rPos, bool bChkTableStart )
{
    SwContentNode *pNode = rPos.nNode.GetNode().GetContentNode();
    if(nullptr == pNode)
        return false;

    {
        // BUG 26675: Send DataChanged before deleting, so that we notice which objects are in scope.
        //            After that they can be before/after the position.
        SwDataChanged aTmp( m_rDoc, rPos );
    }

    SwUndoSplitNode* pUndo = nullptr;
    if (m_rDoc.GetIDocumentUndoRedo().DoesUndo())
    {
        m_rDoc.GetIDocumentUndoRedo().ClearRedo();
        // insert the Undo object (currently only for TextNode)
        if( pNode->IsTextNode() )
        {
            pUndo = new SwUndoSplitNode( m_rDoc, rPos, bChkTableStart );
            m_rDoc.GetIDocumentUndoRedo().AppendUndo(std::unique_ptr<SwUndo>(pUndo));
        }
    }

    // Update the rsid of the old and the new node unless
    // the old node is split at the beginning or at the end
    SwTextNode *pTextNode =  rPos.nNode.GetNode().GetTextNode();
    const sal_Int32 nPos = rPos.nContent.GetIndex();
    if( pTextNode && nPos && nPos != pTextNode->Len() )
    {
        m_rDoc.UpdateParRsid( pTextNode );
    }

    //JP 28.01.97: Special case for SplitNode at table start:
    //             If it is at the beginning of a Doc/Fly/Footer/... or right at after a table
    //             then insert a paragraph before it.
    if( bChkTableStart && !rPos.nContent.GetIndex() && pNode->IsTextNode() )
    {
        SwNodeOffset nPrevPos = rPos.nNode.GetIndex() - 1;
        const SwTableNode* pTableNd;
        const SwNode* pNd = m_rDoc.GetNodes()[ nPrevPos ];
        if( pNd->IsStartNode() &&
            SwTableBoxStartNode == static_cast<const SwStartNode*>(pNd)->GetStartNodeType() &&
            nullptr != ( pTableNd = m_rDoc.GetNodes()[ --nPrevPos ]->GetTableNode() ) &&
            ((( pNd = m_rDoc.GetNodes()[ --nPrevPos ])->IsStartNode() &&
               SwTableBoxStartNode != static_cast<const SwStartNode*>(pNd)->GetStartNodeType() )
               || ( pNd->IsEndNode() && pNd->StartOfSectionNode()->IsTableNode() )
               || pNd->IsContentNode() ))
        {
            if( pNd->IsContentNode() )
            {
                //JP 30.04.99 Bug 65660:
                // There are no page breaks outside of the normal body area,
                // so this is not a valid condition to insert a paragraph.
                if( nPrevPos < m_rDoc.GetNodes().GetEndOfExtras().GetIndex() )
                    pNd = nullptr;
                else
                {
                    // Only if the table has page breaks!
                    const SwFrameFormat* pFrameFormat = pTableNd->GetTable().GetFrameFormat();
                    if( SfxItemState::SET != pFrameFormat->GetItemState(RES_PAGEDESC, false) &&
                        SfxItemState::SET != pFrameFormat->GetItemState( RES_BREAK, false ) )
                        pNd = nullptr;
                }
            }

            if( pNd )
            {
                SwTextNode* pTextNd = m_rDoc.GetNodes().MakeTextNode(
                                        SwNodeIndex( *pTableNd ),
                                        m_rDoc.getIDocumentStylePoolAccess().GetTextCollFromPool( RES_POOLCOLL_TEXT ));
                if( pTextNd )
                {
                    const_cast<SwPosition&>(rPos).nNode = pTableNd->GetIndex()-SwNodeOffset(1);
                    const_cast<SwPosition&>(rPos).nContent.Assign( pTextNd, 0 );

                    // only add page breaks/styles to the body area
                    if( nPrevPos > m_rDoc.GetNodes().GetEndOfExtras().GetIndex() )
                    {
                        SwFrameFormat* pFrameFormat = pTableNd->GetTable().GetFrameFormat();
                        const SfxPoolItem *pItem;
                        if( SfxItemState::SET == pFrameFormat->GetItemState( RES_PAGEDESC,
                            false, &pItem ) )
                        {
                            pTextNd->SetAttr( *pItem );
                            pFrameFormat->ResetFormatAttr( RES_PAGEDESC );
                        }
                        if( SfxItemState::SET == pFrameFormat->GetItemState( RES_BREAK,
                            false, &pItem ) )
                        {
                            pTextNd->SetAttr( *pItem );
                            pFrameFormat->ResetFormatAttr( RES_BREAK );
                        }
                    }

                    if( pUndo )
                        pUndo->SetTableFlag();
                    m_rDoc.getIDocumentState().SetModified();
                    return true;
                }
            }
        }
    }

    const std::shared_ptr<sw::mark::ContentIdxStore> pContentStore(sw::mark::ContentIdxStore::Create());
    pContentStore->Save( m_rDoc, rPos.nNode.GetIndex(), rPos.nContent.GetIndex(), true );
    assert(pNode->IsTextNode());
    std::function<void (SwTextNode *, sw::mark::RestoreMode, bool bAtStart)> restoreFunc(
        [&](SwTextNode *const, sw::mark::RestoreMode const eMode, bool const bAtStart)
        {
            if (!pContentStore->Empty())
            {   // move all bookmarks, TOXMarks, FlyAtCnt
                pContentStore->Restore(m_rDoc, rPos.nNode.GetIndex()-SwNodeOffset(1), 0, true, bAtStart && (eMode & sw::mark::RestoreMode::Flys), eMode);
            }
            if (eMode & sw::mark::RestoreMode::NonFlys)
            {
                // To-Do - add 'SwExtraRedlineTable' also ?
                if (m_rDoc.getIDocumentRedlineAccess().IsRedlineOn() ||
                    (!m_rDoc.getIDocumentRedlineAccess().IsIgnoreRedline() &&
                     !m_rDoc.getIDocumentRedlineAccess().GetRedlineTable().empty()))
                {
                    SwPaM aPam( rPos );
                    aPam.SetMark();
                    aPam.Move( fnMoveBackward );
                    if (m_rDoc.getIDocumentRedlineAccess().IsRedlineOn())
                    {
                        m_rDoc.getIDocumentRedlineAccess().AppendRedline(
                            new SwRangeRedline(RedlineType::Insert, aPam), true);
                    }
                    else
                    {
                        m_rDoc.getIDocumentRedlineAccess().SplitRedline(aPam);
                    }
                }
            }
        });
    pNode->GetTextNode()->SplitContentNode(rPos, &restoreFunc);

    m_rDoc.getIDocumentState().SetModified();
    return true;
}

bool DocumentContentOperationsManager::AppendTextNode( SwPosition& rPos )
{
    // create new node before EndOfContent
    SwTextNode * pCurNode = rPos.nNode.GetNode().GetTextNode();
    if( !pCurNode )
    {
        // so then one can be created!
        SwNodeIndex aIdx( rPos.nNode, 1 );
        pCurNode = m_rDoc.GetNodes().MakeTextNode( aIdx,
                        m_rDoc.getIDocumentStylePoolAccess().GetTextCollFromPool( RES_POOLCOLL_STANDARD ));
    }
    else
        pCurNode = pCurNode->AppendNode( rPos )->GetTextNode();

    rPos.nNode++;
    rPos.nContent.Assign( pCurNode, 0 );

    if (m_rDoc.GetIDocumentUndoRedo().DoesUndo())
    {
        m_rDoc.GetIDocumentUndoRedo().AppendUndo( std::make_unique<SwUndoInsert>( rPos.nNode ) );
    }

    // To-Do - add 'SwExtraRedlineTable' also ?
    if( m_rDoc.getIDocumentRedlineAccess().IsRedlineOn() || (!m_rDoc.getIDocumentRedlineAccess().IsIgnoreRedline() && !m_rDoc.getIDocumentRedlineAccess().GetRedlineTable().empty() ))
    {
        SwPaM aPam( rPos );
        aPam.SetMark();
        aPam.Move( fnMoveBackward );
        if( m_rDoc.getIDocumentRedlineAccess().IsRedlineOn() )
            m_rDoc.getIDocumentRedlineAccess().AppendRedline( new SwRangeRedline( RedlineType::Insert, aPam ), true);
        else
            m_rDoc.getIDocumentRedlineAccess().SplitRedline( aPam );
    }

    m_rDoc.getIDocumentState().SetModified();
    return true;
}

bool DocumentContentOperationsManager::ReplaceRange( SwPaM& rPam, const OUString& rStr,
        const bool bRegExReplace )
{
    // unfortunately replace works slightly differently from delete,
    // so we cannot use lcl_DoWithBreaks here...

    std::vector<std::pair<SwNodeOffset, sal_Int32>> Breaks;

    SwPaM aPam( *rPam.GetMark(), *rPam.GetPoint() );
    aPam.Normalize(false);
    if (aPam.GetPoint()->nNode != aPam.GetMark()->nNode)
    {
        aPam.Move(fnMoveBackward);
    }
    OSL_ENSURE((aPam.GetPoint()->nNode == aPam.GetMark()->nNode), "invalid pam?");

    sw::CalcBreaks(Breaks, aPam);

    while (!Breaks.empty() // skip over prefix of dummy chars
            && (aPam.GetMark()->nNode.GetIndex() == Breaks.begin()->first)
            && (aPam.GetMark()->nContent.GetIndex() == Breaks.begin()->second))
    {
        // skip!
        ++aPam.GetMark()->nContent; // always in bounds if Breaks valid
        Breaks.erase(Breaks.begin());
    }
    *rPam.Start() = *aPam.GetMark(); // update start of original pam w/ prefix

    if (Breaks.empty())
    {
        // park aPam somewhere so it does not point to node that is deleted
        aPam.DeleteMark();
        *aPam.GetPoint() = SwPosition(m_rDoc.GetNodes().GetEndOfContent());
        return ReplaceRangeImpl(rPam, rStr, bRegExReplace); // original pam!
    }

    // Deletion must be split into several parts if the text node
    // contains a text attribute with end and with dummy character
    // and the selection does not contain the text attribute completely,
    // but overlaps its start (left), where the dummy character is.

    bool bRet( true );
    // iterate from end to start, to avoid invalidating the offsets!
    auto iter( Breaks.rbegin() );
    SwNodeOffset nOffset(0);
    SwNodes const& rNodes(rPam.GetPoint()->nNode.GetNodes());
    OSL_ENSURE(aPam.GetPoint() == aPam.End(), "wrong!");
    SwPosition & rEnd( *aPam.End() );
    SwPosition & rStart( *aPam.Start() );

    // set end of temp pam to original end (undo Move backward above)
    rEnd = *rPam.End();
    // after first deletion, rEnd will point into the original text node again!

    while (iter != Breaks.rend())
    {
        rStart = SwPosition(*rNodes[iter->first - nOffset]->GetTextNode(), iter->second + 1);
        if (rStart < rEnd) // check if part is empty
        {
            bRet &= (m_rDoc.getIDocumentRedlineAccess().IsRedlineOn())
                ? DeleteAndJoinWithRedlineImpl(aPam, SwDeleteFlags::Default)
                : DeleteAndJoinImpl(aPam, SwDeleteFlags::Default);
            nOffset = iter->first - rStart.nNode.GetIndex(); // deleted fly nodes...
        }
        rEnd = SwPosition(*rNodes[iter->first - nOffset]->GetTextNode(), iter->second);
        ++iter;
    }

    rStart = *rPam.Start(); // set to original start
    assert(rStart < rEnd && "replace part empty!");
    if (rStart < rEnd) // check if part is empty
    {
        bRet &= ReplaceRangeImpl(aPam, rStr, bRegExReplace);
    }

    rPam = aPam; // update original pam (is this required?)

    return bRet;
}

bool DocumentContentOperationsManager::InsertPoolItem(
    const SwPaM &rRg,
    const SfxPoolItem &rHt,
    const SetAttrMode nFlags,
    SwRootFrame const*const pLayout,
    SwTextAttr **ppNewTextAttr)
{
    if (utl::ConfigManager::IsFuzzing())
        return false;

    SwDataChanged aTmp( rRg );
    std::unique_ptr<SwUndoAttr> pUndoAttr;
    if (m_rDoc.GetIDocumentUndoRedo().DoesUndo())
    {
        m_rDoc.GetIDocumentUndoRedo().ClearRedo();
        pUndoAttr.reset(new SwUndoAttr( rRg, rHt, nFlags ));
    }

    SfxItemSet aSet( m_rDoc.GetAttrPool(), rHt.Which(), rHt.Which() );
    aSet.Put( rHt );
    const bool bRet = lcl_InsAttr(m_rDoc, rRg, aSet, nFlags, pUndoAttr.get(), pLayout, ppNewTextAttr);

    if (m_rDoc.GetIDocumentUndoRedo().DoesUndo())
    {
        m_rDoc.GetIDocumentUndoRedo().AppendUndo( std::move(pUndoAttr) );
    }

    if( bRet )
    {
        m_rDoc.getIDocumentState().SetModified();
    }
    return bRet;
}

void DocumentContentOperationsManager::InsertItemSet ( const SwPaM &rRg, const SfxItemSet &rSet,
        const SetAttrMode nFlags, SwRootFrame const*const pLayout)
{
    SwDataChanged aTmp( rRg );
    std::unique_ptr<SwUndoAttr> pUndoAttr;
    if (m_rDoc.GetIDocumentUndoRedo().DoesUndo())
    {
        m_rDoc.GetIDocumentUndoRedo().ClearRedo();
        pUndoAttr.reset(new SwUndoAttr( rRg, rSet, nFlags ));
    }

    bool bRet = lcl_InsAttr(m_rDoc, rRg, rSet, nFlags, pUndoAttr.get(), pLayout, /*ppNewTextAttr*/nullptr );

    if (m_rDoc.GetIDocumentUndoRedo().DoesUndo())
    {
        m_rDoc.GetIDocumentUndoRedo().AppendUndo( std::move(pUndoAttr) );
    }

    if( bRet )
        m_rDoc.getIDocumentState().SetModified();
}

void DocumentContentOperationsManager::RemoveLeadingWhiteSpace(const SwPosition & rPos )
{
    const SwTextNode* pTNd = rPos.nNode.GetNode().GetTextNode();
    if ( !pTNd )
        return;

    const OUString& rText = pTNd->GetText();
    sal_Int32 nIdx = 0;
    while (nIdx < rText.getLength())
    {
        sal_Unicode const cCh = rText[nIdx];
        if (('\t' != cCh) && (' ' != cCh))
        {
            break;
        }
        ++nIdx;
    }

    if ( nIdx > 0 )
    {
        SwPaM aPam(rPos);
        aPam.GetPoint()->nContent = 0;
        aPam.SetMark();
        aPam.GetMark()->nContent = nIdx;
        DeleteRange( aPam );
    }
}

// Copy method from SwDoc - "copy Flys in Flys"
/// note: rRg/rInsPos *exclude* a partially selected start text node;
///       pCopiedPaM *includes* a partially selected start text node
void DocumentContentOperationsManager::CopyWithFlyInFly(
    const SwNodeRange& rRg,
    const SwNodeIndex& rInsPos,
    const std::pair<const SwPaM&, const SwPosition&>* pCopiedPaM /*and real insert pos*/,
    const bool bMakeNewFrames,
    const bool bDelRedlines,
    const bool bCopyFlyAtFly,
    SwCopyFlags const flags) const
{
    assert(!pCopiedPaM || pCopiedPaM->first.End()->nNode == rRg.aEnd);
    assert(!pCopiedPaM || pCopiedPaM->second.nNode <= rInsPos);

    SwDoc& rDest = rInsPos.GetNode().GetDoc();
    SwNodeIndex aSavePos( rInsPos );

    if (rRg.aStart != rRg.aEnd)
    {
        bool bEndIsEqualEndPos = rInsPos == rRg.aEnd;
        --aSavePos;
        SaveRedlEndPosForRestore aRedlRest( rInsPos, 0 );

        // insert behind the already copied start node
        m_rDoc.GetNodes().CopyNodes( rRg, rInsPos, false, true );
        aRedlRest.Restore();

        if (bEndIsEqualEndPos)
        {
            const_cast<SwNodeIndex&>(rRg.aEnd).Assign(aSavePos.GetNode(), +1);
        }
    }

    // Also copy all bookmarks
    // guess this must be done before the DelDummyNodes below as that
    // deletes nodes so would mess up the index arithmetic
    // sw_fieldmarkhide: also needs to be done before making frames
    if (m_rDoc.getIDocumentMarkAccess()->getAllMarksCount())
    {
        SwPaM aRgTmp( rRg.aStart, rRg.aEnd );
        SwPosition targetPos(SwNodeIndex(aSavePos,
                                         SwNodeOffset(rRg.aStart != rRg.aEnd ? +1 : 0)));
        if (pCopiedPaM && rRg.aStart != pCopiedPaM->first.Start()->nNode)
        {
            // there is 1 (partially selected, maybe) paragraph before
            assert(SwNodeIndex(rRg.aStart, -1) == pCopiedPaM->first.Start()->nNode);
            // only use the passed in target SwPosition if the source PaM point
            // is on a different node; if it was the same node then the target
            // position was likely moved along by the copy operation and now
            // points to the end of the range!
            targetPos = pCopiedPaM->second;
        }

        sw::CopyBookmarks(pCopiedPaM ? pCopiedPaM->first : aRgTmp, targetPos);
    }

    if (rRg.aStart != rRg.aEnd)
    {
        bool isRecreateEndNode(false);
        if (bMakeNewFrames) // tdf#130685 only after aRedlRest
        {   // recreate from previous node (could be merged now)
            o3tl::sorted_vector<SwTextFrame*> frames;
            SwTextNode * pNode = aSavePos.GetNode().GetTextNode();
            SwTextNode *const pEndNode = rInsPos.GetNode().GetTextNode();
            if (pEndNode)
            {
                SwIterator<SwTextFrame, SwTextNode, sw::IteratorMode::UnwrapMulti> aIter(*pEndNode);
                for (SwTextFrame* pFrame = aIter.First(); pFrame; pFrame = aIter.Next())
                {
                    if (pFrame->getRootFrame()->HasMergedParas())
                    {
                        frames.insert(pFrame);
                        // tdf#135061 check if end node is merged to a preceding node
                        if (pNode == nullptr && pFrame->GetMergedPara()
                            && pFrame->GetMergedPara()->pFirstNode->GetIndex() < aSavePos.GetIndex())
                        {
                            pNode = pFrame->GetMergedPara()->pFirstNode;
                        }
                    }
                }
            }
            if (pNode != nullptr)
            {
                sw::RecreateStartTextFrames(*pNode);
                if (!frames.empty())
                {   // tdf#132187 check if the end node needs new frames
                    SwIterator<SwTextFrame, SwTextNode, sw::IteratorMode::UnwrapMulti> aIter(*pEndNode);
                    for (SwTextFrame* pFrame = aIter.First(); pFrame; pFrame = aIter.Next())
                    {
                        if (pFrame->getRootFrame()->HasMergedParas())
                        {
                            auto const it = frames.find(pFrame);
                            if (it != frames.end())
                            {
                                frames.erase(it);
                            }
                        }
                    }
                    if (!frames.empty()) // existing frame was deleted
                    {   // all layouts because MakeFrames recreates all layouts
                        pEndNode->DelFrames(nullptr);
                        isRecreateEndNode = true;
                    }
                }
            }
        }
        bool const isAtStartOfSection(aSavePos.GetNode().IsStartNode());
        ++aSavePos;
        if (bMakeNewFrames)
        {
            // it's possible that CheckParaRedlineMerge() deleted frames
            // on rInsPos so have to include it, but it must not be included
            // if it was the first node in the document so that MakeFrames()
            // will find the existing (wasn't deleted) frame on it
            SwNodeIndex const end(rInsPos,
                    SwNodeOffset((!isRecreateEndNode || isAtStartOfSection)
                    ? 0 : +1));
            ::MakeFrames(&rDest, aSavePos, end);
        }
    }

#if OSL_DEBUG_LEVEL > 0
    {
        //JP 17.06.99: Bug 66973 - check count only if the selection is in
        // the same section or there's no section, because sections that are
        // not fully selected are not copied.
        const SwSectionNode* pSSectNd = rRg.aStart.GetNode().FindSectionNode();
        SwNodeIndex aTmpI( rRg.aEnd, -1 );
        const SwSectionNode* pESectNd = aTmpI.GetNode().FindSectionNode();
        if( pSSectNd == pESectNd &&
            !rRg.aStart.GetNode().IsSectionNode() &&
            !aTmpI.GetNode().IsEndNode() )
        {
            // If the range starts with a SwStartNode, it isn't copied
            SwNodeOffset offset( (rRg.aStart.GetNode().GetNodeType() != SwNodeType::Start) ? 1 : 0 );
            OSL_ENSURE( rInsPos.GetIndex() - aSavePos.GetIndex() ==
                    rRg.aEnd.GetIndex() - rRg.aStart.GetIndex() - 1 + offset,
                    "An insufficient number of nodes were copied!" );
        }
    }
#endif

    {
        ::sw::UndoGuard const undoGuard(rDest.GetIDocumentUndoRedo());
        CopyFlyInFlyImpl(rRg, pCopiedPaM ? &pCopiedPaM->first : nullptr,
            // see comment below regarding use of pCopiedPaM->second
            (pCopiedPaM && rRg.aStart != pCopiedPaM->first.Start()->nNode)
                ? pCopiedPaM->second.nNode
                : aSavePos,
            bCopyFlyAtFly,
            flags);
    }

    SwNodeRange aCpyRange( aSavePos, rInsPos );

    if( bDelRedlines && ( RedlineFlags::DeleteRedlines & rDest.getIDocumentRedlineAccess().GetRedlineFlags() ))
        lcl_DeleteRedlines( rRg, aCpyRange );

    rDest.GetNodes().DelDummyNodes( aCpyRange );
}

// note: for the redline Show/Hide this must be in sync with
// SwRangeRedline::CopyToSection()/DelCopyOfSection()/MoveFromSection()
void DocumentContentOperationsManager::CopyFlyInFlyImpl(
    const SwNodeRange& rRg,
    SwPaM const*const pCopiedPaM,
    const SwNodeIndex& rStartIdx,
    const bool bCopyFlyAtFly,
    SwCopyFlags const flags) const
{
    assert(!pCopiedPaM || pCopiedPaM->End()->nNode == rRg.aEnd);

    // First collect all Flys, sort them according to their ordering number,
    // and then only copy them. This maintains the ordering numbers (which are only
    // managed in the DrawModel).
    SwDoc& rDest = rStartIdx.GetNode().GetDoc();
    std::set< ZSortFly > aSet;
    const size_t nArrLen = m_rDoc.GetSpzFrameFormats()->size();

    SwTextBoxHelper::SavedLink aOldTextBoxes;
    SwTextBoxHelper::saveLinks(*m_rDoc.GetSpzFrameFormats(), aOldTextBoxes);

    for ( size_t n = 0; n < nArrLen; ++n )
    {
        SwFrameFormat* pFormat = (*m_rDoc.GetSpzFrameFormats())[n];
        SwFormatAnchor const*const pAnchor = &pFormat->GetAnchor();
        SwPosition const*const pAPos = pAnchor->GetContentAnchor();
        if ( !pAPos )
            continue;
        bool bAdd = false;
        SwNodeOffset nSkipAfter = pAPos->nNode.GetIndex();
        SwNodeOffset nStart = rRg.aStart.GetIndex();
        switch ( pAnchor->GetAnchorId() )
        {
            case RndStdIds::FLY_AT_FLY:
                if(bCopyFlyAtFly)
                    ++nSkipAfter;
                else if(m_rDoc.getIDocumentRedlineAccess().IsRedlineMove())
                    ++nStart;
            break;
            case RndStdIds::FLY_AT_PARA:
                {
                    bAdd = IsSelectFrameAnchoredAtPara(*pAPos,
                        pCopiedPaM ? *pCopiedPaM->Start() : SwPosition(rRg.aStart),
                        pCopiedPaM ? *pCopiedPaM->End() : SwPosition(rRg.aEnd),
                        (flags & SwCopyFlags::IsMoveToFly)
                            ? DelContentType::AllMask|DelContentType::WriterfilterHack
                            : DelContentType::AllMask);
                }
            break;
            case RndStdIds::FLY_AT_CHAR:
                {
                    bAdd = IsDestroyFrameAnchoredAtChar(*pAPos,
                        pCopiedPaM ? *pCopiedPaM->Start() : SwPosition(rRg.aStart),
                        pCopiedPaM ? *pCopiedPaM->End() : SwPosition(rRg.aEnd),
                        (flags & SwCopyFlags::IsMoveToFly)
                            ? DelContentType::AllMask|DelContentType::WriterfilterHack
                            : DelContentType::AllMask);
                }
            break;
            default:
                continue;
        }
        if (RndStdIds::FLY_AT_FLY == pAnchor->GetAnchorId())
        {
            if (nStart > nSkipAfter)
                continue;
            if (pAPos->nNode > rRg.aEnd)
                continue;
            //frames at the last source node are not always copied:
            //- if the node is empty and is the last node of the document or a table cell
            //  or a text frame then they have to be copied
            //- if the content index in this node is > 0 then paragraph and frame bound objects are copied
            //- to-character bound objects are copied if their index is <= nEndContentIndex
            if (pAPos->nNode < rRg.aEnd)
                bAdd = true;
            if (!bAdd && !m_rDoc.getIDocumentRedlineAccess().IsRedlineMove()) // fdo#40599: not for redline move
            {
                if (!bAdd)
                {
                    // technically old code checked nContent of AT_FLY which is pointless
                    bAdd = pCopiedPaM && 0 < pCopiedPaM->End()->nContent.GetIndex();
                }
            }
        }
        if( bAdd )
        {
            aSet.insert( ZSortFly( pFormat, pAnchor, nArrLen + aSet.size() ));
        }
    }

    // Store all copied (and also the newly created) frames in another array.
    // They are stored as matching the originals, so that we will be later
    // able to build the chains accordingly.
    std::vector< SwFrameFormat* > aVecSwFrameFormat;
    std::set< ZSortFly >::const_iterator it=aSet.begin();

    while (it != aSet.end())
    {
        // #i59964#
        // correct determination of new anchor position
        SwFormatAnchor aAnchor( *(*it).GetAnchor() );
        assert( aAnchor.GetContentAnchor() != nullptr );
        SwPosition newPos = *aAnchor.GetContentAnchor();
        // for at-paragraph and at-character anchored objects the new anchor
        // position can *not* be determined by the difference of the current
        // anchor position to the start of the copied range, because not
        // complete selected sections in the copied range aren't copied - see
        // method <SwNodes::CopyNodes(..)>.
        // Thus, the new anchor position in the destination document is found
        // by counting the text nodes.
        if ((aAnchor.GetAnchorId() == RndStdIds::FLY_AT_PARA) ||
            (aAnchor.GetAnchorId() == RndStdIds::FLY_AT_CHAR) )
        {
            // First, determine number of anchor text node in the copied range.
            // Note: The anchor text node *have* to be inside the copied range.
            sal_uLong nAnchorTextNdNumInRange( 0 );
            bool bAnchorTextNdFound( false );
            // start at the first node for which flys are copied
            SwNodeIndex aIdx(pCopiedPaM ? pCopiedPaM->Start()->nNode : rRg.aStart);
            while ( !bAnchorTextNdFound && aIdx <= rRg.aEnd )
            {
                if ( aIdx.GetNode().IsTextNode() )
                {
                    ++nAnchorTextNdNumInRange;
                    bAnchorTextNdFound = aAnchor.GetContentAnchor()->nNode == aIdx;
                }

                ++aIdx;
            }

            if ( !bAnchorTextNdFound )
            {
                // This case can *not* happen, but to be robust take the first
                // text node in the destination document.
                OSL_FAIL( "<SwDoc::_CopyFlyInFly(..)> - anchor text node in copied range not found" );
                nAnchorTextNdNumInRange = 1;
            }
            // Second, search corresponding text node in destination document
            // by counting forward from start insert position <rStartIdx> the
            // determined number of text nodes.
            aIdx = rStartIdx;
            SwNodeIndex aAnchorNdIdx( rStartIdx );
            const SwNode& aEndOfContentNd =
                                    aIdx.GetNode().GetNodes().GetEndOfContent();
            while ( nAnchorTextNdNumInRange > 0 &&
                    &(aIdx.GetNode()) != &aEndOfContentNd )
            {
                if ( aIdx.GetNode().IsTextNode() )
                {
                    --nAnchorTextNdNumInRange;
                    aAnchorNdIdx = aIdx;
                }

                ++aIdx;
            }
            if ( !aAnchorNdIdx.GetNode().IsTextNode() )
            {
                // This case can *not* happen, but to be robust take the first
                // text node in the destination document.
                OSL_FAIL( "<SwDoc::_CopyFlyInFly(..)> - found anchor node index isn't a text node" );
                aAnchorNdIdx = rStartIdx;
                while ( !aAnchorNdIdx.GetNode().IsTextNode() )
                {
                    ++aAnchorNdIdx;
                }
            }
            // apply found anchor text node as new anchor position
            newPos.nNode = aAnchorNdIdx;
        }
        else
        {
            SwNodeOffset nOffset = newPos.nNode.GetIndex() - rRg.aStart.GetIndex();
            SwNodeIndex aIdx( rStartIdx, nOffset );
            newPos.nNode = aIdx;
        }
        // Set the character bound Flys back at the original character
        if ((RndStdIds::FLY_AT_CHAR == aAnchor.GetAnchorId()) &&
             newPos.nNode.GetNode().IsTextNode() )
        {
            // only if pCopiedPaM: care about partially selected start node
            sal_Int32 const nContent = pCopiedPaM && pCopiedPaM->Start()->nNode == aAnchor.GetContentAnchor()->nNode
                ? newPos.nContent.GetIndex() - pCopiedPaM->Start()->nContent.GetIndex()
                : newPos.nContent.GetIndex();
            newPos.nContent.Assign(newPos.nNode.GetNode().GetTextNode(), nContent);
        }
        else
        {
            newPos.nContent.Assign( nullptr, 0 );
        }
        aAnchor.SetAnchor( &newPos );

        // Check recursion: if copying content inside the same frame, then don't copy the format.
        if( &rDest == &m_rDoc )
        {
            const SwFormatContent& rContent = (*it).GetFormat()->GetContent();
            const SwStartNode* pSNd;
            if( rContent.GetContentIdx() &&
                nullptr != ( pSNd = rContent.GetContentIdx()->GetNode().GetStartNode() ) &&
                pSNd->GetIndex() < rStartIdx.GetIndex() &&
                rStartIdx.GetIndex() < pSNd->EndOfSectionIndex() )
            {
                it = aSet.erase(it);
                continue;
            }
        }

        // Ignore TextBoxes, they are already handled in
        // sw::DocumentLayoutManager::CopyLayoutFormat().
        if (SwTextBoxHelper::isTextBox(it->GetFormat(), RES_FLYFRMFMT))
        {
            it = aSet.erase(it);
            continue;
        }

        // Copy the format and set the new anchor
        aVecSwFrameFormat.push_back( rDest.getIDocumentLayoutAccess().CopyLayoutFormat( *(*it).GetFormat(),
                aAnchor, false, true ) );
        ++it;
    }

    // Rebuild as much as possible of all chains that are available in the original,
    OSL_ENSURE( aSet.size() == aVecSwFrameFormat.size(), "Missing new Flys" );
    if ( aSet.size() != aVecSwFrameFormat.size() )
        return;

    size_t n = 0;
    for (const auto& rFlyN : aSet)
    {
        const SwFrameFormat *pFormatN = rFlyN.GetFormat();
        const SwFormatChain &rChain = pFormatN->GetChain();
        size_t k = 0;
        for (const auto& rFlyK : aSet)
        {
            const SwFrameFormat *pFormatK = rFlyK.GetFormat();
            if ( rChain.GetPrev() == pFormatK )
            {
                ::lcl_ChainFormats( static_cast< SwFlyFrameFormat* >(aVecSwFrameFormat[k]),
                                 static_cast< SwFlyFrameFormat* >(aVecSwFrameFormat[n]) );
            }
            else if ( rChain.GetNext() == pFormatK )
            {
                ::lcl_ChainFormats( static_cast< SwFlyFrameFormat* >(aVecSwFrameFormat[n]),
                                 static_cast< SwFlyFrameFormat* >(aVecSwFrameFormat[k]) );
            }
            ++k;
        }
        ++n;
    }

    // Re-create content property of draw formats, knowing how old shapes
    // were paired with old fly formats (aOldTextBoxes) and that aSet is
    // parallel with aVecSwFrameFormat.
    SwTextBoxHelper::restoreLinks(aSet, aVecSwFrameFormat, aOldTextBoxes);
}

/*
 * Reset the text's hard formatting
 */
/** @params pArgs contains the document's ChrFormatTable
 *                Is need for selections at the beginning/end and with no SSelection.
 */
bool DocumentContentOperationsManager::lcl_RstTextAttr( SwNode* pNd, void* pArgs )
{
    ParaRstFormat* pPara = static_cast<ParaRstFormat*>(pArgs);
    if (pPara->pLayout && pPara->pLayout->HasMergedParas()
        && pNd->GetRedlineMergeFlag() == SwNode::Merge::Hidden)
    {
        return true; // skip hidden, since new items aren't applied
    }
    SwTextNode * pTextNode = pNd->GetTextNode();
    if( pTextNode && pTextNode->GetpSwpHints() )
    {
        SwIndex aSt( pTextNode, 0 );
        sal_Int32 nEnd = pTextNode->Len();

        if( &pPara->pSttNd->nNode.GetNode() == pTextNode &&
            pPara->pSttNd->nContent.GetIndex() )
            aSt = pPara->pSttNd->nContent.GetIndex();

        if( &pPara->pEndNd->nNode.GetNode() == pNd )
            nEnd = pPara->pEndNd->nContent.GetIndex();

        if( pPara->pHistory )
        {
            // Save all attributes for the Undo.
            SwRegHistory aRHst( *pTextNode, pPara->pHistory );
            pTextNode->GetpSwpHints()->Register( &aRHst );
            pTextNode->RstTextAttr( aSt, nEnd - aSt.GetIndex(), pPara->nWhich,
                                  pPara->pDelSet, pPara->bInclRefToxMark, pPara->bExactRange );
            if( pTextNode->GetpSwpHints() )
                pTextNode->GetpSwpHints()->DeRegister();
        }
        else
            pTextNode->RstTextAttr( aSt, nEnd - aSt.GetIndex(), pPara->nWhich,
                                  pPara->pDelSet, pPara->bInclRefToxMark, pPara->bExactRange );
    }
    return true;
}

DocumentContentOperationsManager::~DocumentContentOperationsManager()
{
}
//Private methods

bool DocumentContentOperationsManager::DeleteAndJoinWithRedlineImpl(SwPaM & rPam, SwDeleteFlags const flags)
{
    assert(m_rDoc.getIDocumentRedlineAccess().IsRedlineOn());

    RedlineFlags eOld = m_rDoc.getIDocumentRedlineAccess().GetRedlineFlags();

    if (*rPam.GetPoint() == *rPam.GetMark())
    {
        return false; // do not add empty redlines
    }

    std::vector<SwRangeRedline*> redlines;
    {
        auto pRedline(std::make_unique<SwRangeRedline>(RedlineType::Delete, rPam));
        if (pRedline->HasValidRange())
        {
            redlines.push_back(pRedline.release());
        }
        else // sigh ... why is such a selection even possible...
        {    // split it up so we get one SwUndoRedlineDelete per inserted RL
            redlines = GetAllValidRanges(std::move(pRedline));
        }
    }

    if (redlines.empty())
    {
        return false;
    }

    // tdf#54819 current redlining needs also modification of paragraph style and
    // attributes added to the same grouped Undo
    if (m_rDoc.GetIDocumentUndoRedo().DoesGroupUndo())
        m_rDoc.GetIDocumentUndoRedo().StartUndo(SwUndoId::EMPTY, nullptr);

    auto & rDMA(*m_rDoc.getIDocumentMarkAccess());
    std::vector<std::unique_ptr<SwUndo>> MarkUndos;
    for (auto iter = rDMA.getAnnotationMarksBegin();
              iter != rDMA.getAnnotationMarksEnd(); )
    {
        // tdf#111524 remove annotation marks that have their field
        // characters deleted
        SwPosition const& rEndPos((**iter).GetMarkEnd());
        if (*rPam.Start() < rEndPos && rEndPos <= *rPam.End())
        {
            if (m_rDoc.GetIDocumentUndoRedo().DoesUndo())
            {
                MarkUndos.emplace_back(std::make_unique<SwUndoDeleteBookmark>(**iter));
            }
            // iter is into annotation mark vector so must be dereferenced!
            rDMA.deleteMark(&**iter);
            // this invalidates iter, have to start over...
            iter = rDMA.getAnnotationMarksBegin();
        }
        else
        {   // marks are sorted by start
            if (*rPam.End() < (**iter).GetMarkStart())
            {
                break;
            }
            ++iter;
        }
    }

    // tdf#119019 accept tracked paragraph formatting to do not hide new deletions
    if (*rPam.GetPoint() != *rPam.GetMark())
        m_rDoc.getIDocumentRedlineAccess().AcceptRedlineParagraphFormatting(rPam);

    std::vector<std::unique_ptr<SwUndoRedlineDelete>> undos;
    if (m_rDoc.GetIDocumentUndoRedo().DoesUndo())
    {
        // this should no longer happen in calls from the UI but maybe via API
        // (randomTest and testTdf54819 triggers it)
        SAL_WARN_IF((eOld & RedlineFlags::ShowMask) != RedlineFlags::ShowMask,
                "sw.core", "redlines will be moved in DeleteAndJoin");
        m_rDoc.getIDocumentRedlineAccess().SetRedlineFlags(
            RedlineFlags::On | RedlineFlags::ShowInsert | RedlineFlags::ShowDelete);

        for (SwRangeRedline * pRedline : redlines)
        {
            assert(pRedline->HasValidRange());
            undos.emplace_back(std::make_unique<SwUndoRedlineDelete>(
                        *pRedline, SwUndoId::DELETE, flags));
        }
        const SwRewriter aRewriter = undos.front()->GetRewriter();
        // can only group a single undo action
        if (MarkUndos.empty() && undos.size() == 1
            && m_rDoc.GetIDocumentUndoRedo().DoesGroupUndo())
        {
            SwUndo * const pLastUndo( m_rDoc.GetUndoManager().GetLastUndo() );
            SwUndoRedlineDelete *const pUndoRedlineDel(dynamic_cast<SwUndoRedlineDelete*>(pLastUndo));
            bool const bMerged = pUndoRedlineDel
                && pUndoRedlineDel->CanGrouping(*undos.front());
            if (!bMerged)
            {
                m_rDoc.GetIDocumentUndoRedo().AppendUndo(std::move(undos.front()));
            }
            undos.clear(); // prevent unmatched EndUndo
        }
        else
        {
            m_rDoc.GetIDocumentUndoRedo().StartUndo(SwUndoId::DELETE, &aRewriter);
            for (auto& it : MarkUndos)
            {
                m_rDoc.GetIDocumentUndoRedo().AppendUndo(std::move(it));
            }
            for (auto & it : undos)
            {
                m_rDoc.GetIDocumentUndoRedo().AppendUndo(std::move(it));
            }
        }
    }

    for (SwRangeRedline *const pRedline : redlines)
    {
        // note: 1. the pRedline can still be merged & deleted
        //       2. the impl. can even DeleteAndJoin the range => no plain PaM
        std::shared_ptr<SwUnoCursor> const pCursor(m_rDoc.CreateUnoCursor(*pRedline->GetMark()));
        pCursor->SetMark();
        *pCursor->GetPoint() = *pRedline->GetPoint();
        m_rDoc.getIDocumentRedlineAccess().AppendRedline(pRedline, true);
        // sw_redlinehide: 2 reasons why this is needed:
        // 1. it's the first redline in node => RedlineDelText was sent but ignored
        // 2. redline spans multiple nodes => must merge text frames
        sw::UpdateFramesForAddDeleteRedline(m_rDoc, *pCursor);
    }
    m_rDoc.getIDocumentState().SetModified();

    if (m_rDoc.GetIDocumentUndoRedo().DoesUndo())
    {
        if (!undos.empty())
        {
            m_rDoc.GetIDocumentUndoRedo().EndUndo(SwUndoId::EMPTY, nullptr);
        }
        m_rDoc.getIDocumentRedlineAccess().SetRedlineFlags( eOld );
    }

    if (m_rDoc.GetIDocumentUndoRedo().DoesGroupUndo())
        m_rDoc.GetIDocumentUndoRedo().EndUndo(SwUndoId::EMPTY, nullptr);

    return true;
}

bool DocumentContentOperationsManager::DeleteAndJoinImpl(SwPaM & rPam, SwDeleteFlags const flags)
{
    bool bJoinText, bJoinPrev;
    ::sw_GetJoinFlags( rPam, bJoinText, bJoinPrev );

    bool const bSuccess( DeleteRangeImpl(rPam, flags) );
    if (!bSuccess)
        return false;

    if( bJoinText )
    {
        ::sw_JoinText( rPam, bJoinPrev );
    }

    if (!m_rDoc.getIDocumentRedlineAccess().IsIgnoreRedline()
        && !m_rDoc.getIDocumentRedlineAccess().GetRedlineTable().empty())
    {
        m_rDoc.getIDocumentRedlineAccess().CompressRedlines();
    }

    return true;
}

bool DocumentContentOperationsManager::DeleteRangeImpl(SwPaM & rPam, SwDeleteFlags const flags)
{
    // Move all cursors out of the deleted range, but first copy the
    // passed PaM, because it could be a cursor that would be moved!
    SwPaM aDelPam( *rPam.GetMark(), *rPam.GetPoint() );
    {
        SwPosition const pos(GetCorrPosition(aDelPam));
        ::PaMCorrAbs(aDelPam, pos);
    }

    bool const bSuccess( DeleteRangeImplImpl(aDelPam, flags) );
    if (bSuccess)
    {   // now copy position from temp copy to given PaM
        *rPam.GetPoint() = *aDelPam.GetPoint();
    }

    return bSuccess;
}

bool DocumentContentOperationsManager::DeleteRangeImplImpl(SwPaM & rPam, SwDeleteFlags const flags)
{
    SwPosition *pStt = rPam.Start(), *pEnd = rPam.End();

    if (!rPam.HasMark()
        || (*pStt == *pEnd && !IsFlySelectedByCursor(m_rDoc, *pStt, *pEnd)))
    {
        return false;
    }

    if( m_rDoc.GetAutoCorrExceptWord() )
    {
        // if necessary the saved Word for the exception
        if( m_rDoc.GetAutoCorrExceptWord()->IsDeleted() ||  pStt->nNode != pEnd->nNode ||
            pStt->nContent.GetIndex() + 1 != pEnd->nContent.GetIndex() ||
            !m_rDoc.GetAutoCorrExceptWord()->CheckDelChar( *pStt ))
                { m_rDoc.DeleteAutoCorrExceptWord(); }
    }

    {
        // Delete all empty TextHints at the Mark's position
        SwTextNode* pTextNd = rPam.GetMark()->nNode.GetNode().GetTextNode();
        SwpHints* pHts;
        if( pTextNd &&  nullptr != ( pHts = pTextNd->GetpSwpHints()) && pHts->Count() )
        {
            const sal_Int32 nMkCntPos = rPam.GetMark()->nContent.GetIndex();
            for( size_t n = pHts->Count(); n; )
            {
                const SwTextAttr* pAttr = pHts->Get( --n );
                if( nMkCntPos > pAttr->GetStart() )
                    break;

                const sal_Int32 *pEndIdx;
                if( nMkCntPos == pAttr->GetStart() &&
                    nullptr != (pEndIdx = pAttr->End()) &&
                    *pEndIdx == pAttr->GetStart() )
                    pTextNd->DestroyAttr( pHts->Cut( n ) );
            }
        }
    }

    {
        // Send DataChanged before deletion, so that we still know
        // which objects are in the range.
        // Afterwards they could be before/after the Position.
        SwDataChanged aTmp( rPam );
    }

    if (m_rDoc.GetIDocumentUndoRedo().DoesUndo())
    {
        m_rDoc.GetIDocumentUndoRedo().ClearRedo();
        bool bMerged(false);
        if (m_rDoc.GetIDocumentUndoRedo().DoesGroupUndo())
        {
            SwUndo *const pLastUndo( m_rDoc.GetUndoManager().GetLastUndo() );
            SwUndoDelete *const pUndoDelete(
                    dynamic_cast<SwUndoDelete *>(pLastUndo) );
            if (pUndoDelete)
            {
                bMerged = pUndoDelete->CanGrouping(m_rDoc, rPam);
                // if CanGrouping() returns true it's already merged
            }
        }
        if (!bMerged)
        {
            m_rDoc.GetIDocumentUndoRedo().AppendUndo(std::make_unique<SwUndoDelete>(rPam, flags));
        }

        m_rDoc.getIDocumentState().SetModified();

        return true;
    }

    if( !m_rDoc.getIDocumentRedlineAccess().IsIgnoreRedline() && !m_rDoc.getIDocumentRedlineAccess().GetRedlineTable().empty() )
        m_rDoc.getIDocumentRedlineAccess().DeleteRedline( rPam, true, RedlineType::Any );

    // Delete and move all "Flys at the paragraph", which are within the Selection
    if (!(flags & SwDeleteFlags::ArtificialSelection))
    {
        DelFlyInRange(rPam.GetMark()->nNode, rPam.GetPoint()->nNode,
            &rPam.GetMark()->nContent, &rPam.GetPoint()->nContent);
    }
    DelBookmarks(
        pStt->nNode,
        pEnd->nNode,
        nullptr,
        &pStt->nContent,
        &pEnd->nContent);

    SwNodeIndex aSttIdx( pStt->nNode );
    SwContentNode * pCNd = aSttIdx.GetNode().GetContentNode();

    do {        // middle checked loop!
        if( pCNd )
        {
            SwTextNode * pStartTextNode( pCNd->GetTextNode() );
            if ( pStartTextNode )
            {
                // now move the Content to the new Node
                bool bOneNd = pStt->nNode == pEnd->nNode;
                const sal_Int32 nLen = ( bOneNd ? pEnd->nContent.GetIndex()
                                           : pCNd->Len() )
                                        - pStt->nContent.GetIndex();

                // Don't call again, if already empty
                if( nLen )
                {
                    pStartTextNode->EraseText( pStt->nContent, nLen );

                    if( !pStartTextNode->Len() )
                    {
                // METADATA: remove reference if empty (consider node deleted)
                        pStartTextNode->RemoveMetadataReference();
                    }
                }

                if( bOneNd )        // that's it
                    break;

                ++aSttIdx;
            }
            else
            {
                // So that there are no indices left registered when deleted,
                // we remove a SwPaM from the Content here.
                pStt->nContent.Assign( nullptr, 0 );
            }
        }

        pCNd = pEnd->nNode.GetNode().GetContentNode();
        if( pCNd )
        {
            SwTextNode * pEndTextNode( pCNd->GetTextNode() );
            if( pEndTextNode )
            {
                // if already empty, don't call again
                if( pEnd->nContent.GetIndex() )
                {
                    SwIndex aIdx( pCNd, 0 );
                    pEndTextNode->EraseText( aIdx, pEnd->nContent.GetIndex() );

                    if( !pEndTextNode->Len() )
                    {
                        // METADATA: remove reference if empty (consider node deleted)
                        pEndTextNode->RemoveMetadataReference();
                    }
                }
            }
            else
            {
                // So that there are no indices left registered when deleted,
                // we remove a SwPaM from the Content here.
                pEnd->nContent.Assign( nullptr, 0 );
            }
        }

        // if the end is not a content node, delete it as well
        SwNodeOffset nEnd = pEnd->nNode.GetIndex();
        if( pCNd == nullptr )
            nEnd++;

        if( aSttIdx != nEnd )
        {
            // tdf#134436 delete section nodes like SwUndoDelete::SwUndoDelete
            SwNode *pTmpNd;
            while (pEnd == rPam.GetPoint()
                && nEnd + SwNodeOffset(2) < m_rDoc.GetNodes().Count()
                && (pTmpNd = m_rDoc.GetNodes()[nEnd + 1])->IsEndNode()
                && pTmpNd->StartOfSectionNode()->IsSectionNode()
                && aSttIdx <= pTmpNd->StartOfSectionNode()->GetIndex())
            {
                SwNodeRange range(*pTmpNd->StartOfSectionNode(), *pTmpNd);
                m_rDoc.GetNodes().SectionUp(&range);
                --nEnd; // account for deleted start node
            }

            // delete the Nodes from the NodesArray
            m_rDoc.GetNodes().Delete( aSttIdx, nEnd - aSttIdx.GetIndex() );
        }

        // If the Node that contained the Cursor has been deleted,
        // the Content has to be assigned to the current Content.
        pStt->nContent.Assign( pStt->nNode.GetNode().GetContentNode(),
                                pStt->nContent.GetIndex() );

        // If we deleted across Node boundaries we have to correct the PaM,
        // because they are in different Nodes now.
        // Also, the Selection is revoked.
        *pEnd = *pStt;
        rPam.DeleteMark();

    } while( false );

    m_rDoc.getIDocumentState().SetModified();

    return true;
}

// It's possible to call Replace with a PaM that spans 2 paragraphs:
// search with regex for "$", then replace _all_
bool DocumentContentOperationsManager::ReplaceRangeImpl( SwPaM& rPam, const OUString& rStr,
        const bool bRegExReplace )
{
    if (!rPam.HasMark())
        return false;

    bool bJoinText, bJoinPrev;
    ::sw_GetJoinFlags( rPam, bJoinText, bJoinPrev );

    {
        // Create a copy of the Cursor in order to move all Pams from
        // the other views out of the deletion range.
        // Except for itself!
        SwPaM aDelPam( *rPam.GetMark(), *rPam.GetPoint() );
        ::PaMCorrAbs( aDelPam, *aDelPam.GetPoint() );

        SwPosition *pStt = aDelPam.Start(),
                   *pEnd = aDelPam.End();
        bool bOneNode = pStt->nNode == pEnd->nNode;

        // Own Undo?
        OUString sRepl( rStr );
        SwTextNode* pTextNd = pStt->nNode.GetNode().GetTextNode();
        sal_Int32 nStt = pStt->nContent.GetIndex();
        sal_Int32 nEnd;

        SwDataChanged aTmp( aDelPam );

        if( m_rDoc.getIDocumentRedlineAccess().IsRedlineOn() )
        {
            RedlineFlags eOld = m_rDoc.getIDocumentRedlineAccess().GetRedlineFlags();
            if (m_rDoc.GetIDocumentUndoRedo().DoesUndo())
            {
                // this should no longer happen in calls from the UI but maybe via API
                SAL_WARN_IF((eOld & RedlineFlags::ShowMask) != RedlineFlags::ShowMask,
                        "sw.core", "redlines will be moved in ReplaceRange");

                m_rDoc.GetIDocumentUndoRedo().StartUndo(SwUndoId::EMPTY, nullptr);

                // If any Redline will change (split!) the node
                const ::sw::mark::IMark* pBkmk =
                    m_rDoc.getIDocumentMarkAccess()->makeMark( aDelPam,
                        OUString(), IDocumentMarkAccess::MarkType::UNO_BOOKMARK,
                        ::sw::mark::InsertMode::New);

                m_rDoc.getIDocumentRedlineAccess().SetRedlineFlags(
                    RedlineFlags::On | RedlineFlags::ShowInsert | RedlineFlags::ShowDelete );

                *aDelPam.GetPoint() = pBkmk->GetMarkPos();
                if(pBkmk->IsExpanded())
                    *aDelPam.GetMark() = pBkmk->GetOtherMarkPos();
                m_rDoc.getIDocumentMarkAccess()->deleteMark(pBkmk);
                pStt = aDelPam.Start();
                pTextNd = pStt->nNode.GetNode().GetTextNode();
                nStt = pStt->nContent.GetIndex();
            }

            if( !sRepl.isEmpty() )
            {
                // Apply the first character's attributes to the ReplaceText
                SfxItemSetFixed
                            <RES_CHRATR_BEGIN,     RES_TXTATR_WITHEND_END - 1,
                            RES_UNKNOWNATR_BEGIN, RES_UNKNOWNATR_END-1>  aSet( m_rDoc.GetAttrPool() );
                pTextNd->GetParaAttr( aSet, nStt+1, nStt+1 );

                aSet.ClearItem( RES_TXTATR_REFMARK );
                aSet.ClearItem( RES_TXTATR_TOXMARK );
                aSet.ClearItem( RES_TXTATR_CJK_RUBY );
                aSet.ClearItem( RES_TXTATR_INETFMT );
                aSet.ClearItem( RES_TXTATR_META );
                aSet.ClearItem( RES_TXTATR_METAFIELD );

                if( aDelPam.GetPoint() != aDelPam.End() )
                    aDelPam.Exchange();

                // Remember the End
                SwNodeIndex aPtNd( aDelPam.GetPoint()->nNode, -1 );
                const sal_Int32 nPtCnt = aDelPam.GetPoint()->nContent.GetIndex();

                bool bFirst = true;
                OUString sIns;
                while ( lcl_GetTokenToParaBreak( sRepl, sIns, bRegExReplace ) )
                {
                    InsertString( aDelPam, sIns );
                    if( bFirst )
                    {
                        SwNodeIndex aMkNd( aDelPam.GetMark()->nNode, -1 );
                        const sal_Int32 nMkCnt = aDelPam.GetMark()->nContent.GetIndex();

                        SplitNode( *aDelPam.GetPoint(), false );

                        ++aMkNd;
                        aDelPam.GetMark()->nNode = aMkNd;
                        aDelPam.GetMark()->nContent.Assign(
                                    aMkNd.GetNode().GetContentNode(), nMkCnt );
                        bFirst = false;
                    }
                    else
                        SplitNode( *aDelPam.GetPoint(), false );
                }
                if( !sIns.isEmpty() )
                {
                    InsertString( aDelPam, sIns );
                }

                SwPaM aTmpRange( *aDelPam.GetPoint() );
                aTmpRange.SetMark();

                ++aPtNd;
                aDelPam.GetPoint()->nNode = aPtNd;
                aDelPam.GetPoint()->nContent.Assign( aPtNd.GetNode().GetContentNode(),
                                                    nPtCnt);
                *aTmpRange.GetMark() = *aDelPam.GetPoint();

                m_rDoc.RstTextAttrs( aTmpRange );
                InsertItemSet( aTmpRange, aSet );
            }

            // tdf#139982: Appending the redline may immediately delete flys
            // anchored in the previous text if it's inside an insert redline.
            // Also flys will be deleted if the redline is accepted. Move them
            // to the position between the previous text and the new text,
            // there the chance of surviving both accept and reject is best.
            SaveFlyArr flys;
            SaveFlyInRange(aDelPam, *aDelPam.End(), flys, false);

            if (m_rDoc.GetIDocumentUndoRedo().DoesUndo())
            {
                m_rDoc.GetIDocumentUndoRedo().AppendUndo(
                    std::make_unique<SwUndoRedlineDelete>( aDelPam, SwUndoId::REPLACE ));
            }
            // add redline similar to DeleteAndJoinWithRedlineImpl()
            std::shared_ptr<SwUnoCursor> const pCursor(m_rDoc.CreateUnoCursor(*aDelPam.GetMark()));
            pCursor->SetMark();
            *pCursor->GetPoint() = *aDelPam.GetPoint();
            m_rDoc.getIDocumentRedlineAccess().AppendRedline( new SwRangeRedline( RedlineType::Delete, aDelPam ), true);
            RestFlyInRange(flys, *aDelPam.End(), &aDelPam.End()->nNode, true);
            sw::UpdateFramesForAddDeleteRedline(m_rDoc, *pCursor);

            *rPam.GetMark() = *aDelPam.GetMark();
            if (m_rDoc.GetIDocumentUndoRedo().DoesUndo())
            {
                *aDelPam.GetPoint() = *rPam.GetPoint();
                m_rDoc.GetIDocumentUndoRedo().EndUndo(SwUndoId::EMPTY, nullptr);

                // If any Redline will change (split!) the node
                const ::sw::mark::IMark* pBkmk =
                    m_rDoc.getIDocumentMarkAccess()->makeMark( aDelPam,
                        OUString(), IDocumentMarkAccess::MarkType::UNO_BOOKMARK,
                        ::sw::mark::InsertMode::New);

                SwIndex& rIdx = aDelPam.GetPoint()->nContent;
                rIdx.Assign( nullptr, 0 );
                aDelPam.GetMark()->nContent = rIdx;
                rPam.GetPoint()->nNode = SwNodeOffset(0);
                rPam.GetPoint()->nContent = rIdx;
                *rPam.GetMark() = *rPam.GetPoint();
                m_rDoc.getIDocumentRedlineAccess().SetRedlineFlags( eOld );

                *rPam.GetPoint() = pBkmk->GetMarkPos();
                *rPam.GetMark() = pBkmk->IsExpanded() ? pBkmk->GetOtherMarkPos() : pBkmk->GetMarkPos();

                m_rDoc.getIDocumentMarkAccess()->deleteMark(pBkmk);
            }
            bJoinText = false;
        }
        else
        {
            assert((pStt->nNode == pEnd->nNode ||
                    ( pStt->nNode.GetIndex() + 1 == pEnd->nNode.GetIndex() &&
                        !pEnd->nContent.GetIndex() )) &&
                    "invalid range: Point and Mark on different nodes" );

            if( !m_rDoc.getIDocumentRedlineAccess().IsIgnoreRedline() && !m_rDoc.getIDocumentRedlineAccess().GetRedlineTable().empty() )
                m_rDoc.getIDocumentRedlineAccess().DeleteRedline( aDelPam, true, RedlineType::Any );

            SwUndoReplace* pUndoRpl = nullptr;
            bool const bDoesUndo = m_rDoc.GetIDocumentUndoRedo().DoesUndo();
            if (bDoesUndo)
            {
                pUndoRpl = new SwUndoReplace(aDelPam, sRepl, bRegExReplace);
                m_rDoc.GetIDocumentUndoRedo().AppendUndo(std::unique_ptr<SwUndo>(pUndoRpl));
            }
            ::sw::UndoGuard const undoGuard(m_rDoc.GetIDocumentUndoRedo());

            if( aDelPam.GetPoint() != pStt )
                aDelPam.Exchange();

            SwNodeIndex aPtNd( pStt->nNode, -1 );
            const sal_Int32 nPtCnt = pStt->nContent.GetIndex();

            // Set the values again, if Frames or footnotes on the Text have been removed.
            nStt = nPtCnt;
            nEnd = bOneNode ? pEnd->nContent.GetIndex()
                            : pTextNd->GetText().getLength();

            bool bFirst = true;
            OUString sIns;
            while ( lcl_GetTokenToParaBreak( sRepl, sIns, bRegExReplace ) )
            {
                if (!bFirst || nStt == pTextNd->GetText().getLength())
                {
                    InsertString( aDelPam, sIns );
                }
                else if( nStt < nEnd || !sIns.isEmpty() )
                {
                    pTextNd->ReplaceText( pStt->nContent, nEnd - nStt, sIns );
                }
                SplitNode( *pStt, false);
                bFirst = false;
            }

            if( bFirst || !sIns.isEmpty() )
            {
                if (!bFirst || nStt == pTextNd->GetText().getLength())
                {
                    InsertString( aDelPam, sIns );
                }
                else if( nStt < nEnd || !sIns.isEmpty() )
                {
                    pTextNd->ReplaceText( pStt->nContent, nEnd - nStt, sIns );
                }
            }

            *rPam.GetPoint() = *aDelPam.GetMark();
            ++aPtNd;
            rPam.GetMark()->nNode = aPtNd;
            rPam.GetMark()->nContent.Assign( aPtNd.GetNode().GetContentNode(),
                                                nPtCnt );

            if (bJoinText)
            {
                assert(rPam.GetPoint() == rPam.End());
                // move so that SetEnd remembers position after sw_JoinText
                rPam.Move(fnMoveBackward);
            }
            else if (aDelPam.GetPoint() == pStt) // backward selection?
            {
                assert(*rPam.GetMark() <= *rPam.GetPoint());
                rPam.Exchange(); // swap so that rPam is backwards
            }

            if( pUndoRpl )
            {
                pUndoRpl->SetEnd(rPam);
            }
        }
    }

    bool bRet(true);
    if (bJoinText)
    {
        bRet = ::sw_JoinText(rPam, bJoinPrev);
    }

    m_rDoc.getIDocumentState().SetModified();
    return bRet;
}

SwFlyFrameFormat* DocumentContentOperationsManager::InsNoTextNode( const SwPosition& rPos, SwNoTextNode* pNode,
                                    const SfxItemSet* pFlyAttrSet,
                                    const SfxItemSet* pGrfAttrSet,
                                    SwFrameFormat* pFrameFormat)
{
    SwFlyFrameFormat *pFormat = nullptr;
    if( pNode )
    {
        pFormat = m_rDoc.MakeFlySection_( rPos, *pNode, RndStdIds::FLY_AT_PARA,
                                pFlyAttrSet, pFrameFormat );
        if( pGrfAttrSet )
            pNode->SetAttr( *pGrfAttrSet );
    }
    return pFormat;
}

#define NUMRULE_STATE \
    std::shared_ptr<SwNumRuleItem> aNumRuleItemHolderIfSet; \
    std::shared_ptr<SfxStringItem> aListIdItemHolderIfSet; \

#define PUSH_NUMRULE_STATE \
     lcl_PushNumruleState( aNumRuleItemHolderIfSet, aListIdItemHolderIfSet, pDestTextNd );

#define POP_NUMRULE_STATE \
     lcl_PopNumruleState( aNumRuleItemHolderIfSet, aListIdItemHolderIfSet, pDestTextNd, rPam );

static void lcl_PushNumruleState(
    std::shared_ptr<SwNumRuleItem>& aNumRuleItemHolderIfSet,
    std::shared_ptr<SfxStringItem>& aListIdItemHolderIfSet,
    const SwTextNode *pDestTextNd )
{
    // Safe numrule item at destination.
    // #i86492# - Safe also <ListId> item of destination.
    const SfxItemSet * pAttrSet = pDestTextNd->GetpSwAttrSet();
    if (pAttrSet == nullptr)
        return;

    if (const SwNumRuleItem* pItem = pAttrSet->GetItemIfSet(RES_PARATR_NUMRULE, false))
    {
        aNumRuleItemHolderIfSet.reset(pItem->Clone());
    }

    if (const SfxStringItem* pItem = pAttrSet->GetItemIfSet(RES_PARATR_LIST_ID, false))
    {
        aListIdItemHolderIfSet.reset(pItem->Clone());
    }
}

static void lcl_PopNumruleState(
    const std::shared_ptr<SwNumRuleItem>& aNumRuleItemHolderIfSet,
    const std::shared_ptr<SfxStringItem>& aListIdItemHolderIfSet,
    SwTextNode *pDestTextNd, const SwPaM& rPam )
{
    /* If only a part of one paragraph is copied
       restore the numrule at the destination. */
    // #i86492# - restore also <ListId> item
    if ( lcl_MarksWholeNode(rPam) )
        return;

    if (aNumRuleItemHolderIfSet)
    {
        pDestTextNd->SetAttr(*aNumRuleItemHolderIfSet);
    }
    else
    {
        pDestTextNd->ResetAttr(RES_PARATR_NUMRULE);
    }

    if (aListIdItemHolderIfSet)
    {
        pDestTextNd->SetAttr(*aListIdItemHolderIfSet);
    }
    else
    {
        pDestTextNd->ResetAttr(RES_PARATR_LIST_ID);
    }
}

bool DocumentContentOperationsManager::CopyImpl(SwPaM& rPam, SwPosition& rPos,
        SwCopyFlags const flags,
        SwPaM *const pCopyRange) const
{
    std::vector<std::pair<SwNodeOffset, sal_Int32>> Breaks;

    sw::CalcBreaks(Breaks, rPam, true);

    if (Breaks.empty())
    {
        return CopyImplImpl(rPam, rPos, flags, pCopyRange);
    }

    SwPosition const & rSelectionEnd( *rPam.End() );

    bool bRet(true);
    bool bFirst(true);
    // iterate from end to start, ... don't think it's necessary here?
    auto iter( Breaks.rbegin() );
    SwNodeOffset nOffset(0);
    SwNodes const& rNodes(rPam.GetPoint()->nNode.GetNodes());
    SwPaM aPam( rSelectionEnd, rSelectionEnd ); // end node!
    SwPosition & rEnd( *aPam.End() );
    SwPosition & rStart( *aPam.Start() );
    SwPaM copyRange(rPos, rPos);

    while (iter != Breaks.rend())
    {
        rStart = SwPosition(*rNodes[iter->first - nOffset]->GetTextNode(), iter->second + 1);
        if (rStart < rEnd) // check if part is empty
        {
            // pass in copyRange member as rPos; should work ...
            bRet &= CopyImplImpl(aPam, *copyRange.Start(), flags & ~SwCopyFlags::IsMoveToFly, &copyRange);
            nOffset = iter->first - rStart.nNode.GetIndex(); // fly nodes...
            if (pCopyRange)
            {
                if (bFirst)
                {
                    pCopyRange->SetMark();
                    *pCopyRange->GetMark() = *copyRange.End();
                }
                *pCopyRange->GetPoint() = *copyRange.Start();
            }
            bFirst = false;
        }
        rEnd = SwPosition(*rNodes[iter->first - nOffset]->GetTextNode(), iter->second);
        ++iter;
    }

    rStart = *rPam.Start(); // set to original start
    if (rStart < rEnd) // check if part is empty
    {
        bRet &= CopyImplImpl(aPam, *copyRange.Start(), flags & ~SwCopyFlags::IsMoveToFly, &copyRange);
        if (pCopyRange)
        {
            if (bFirst)
            {
                pCopyRange->SetMark();
                *pCopyRange->GetMark() = *copyRange.End();
            }
            *pCopyRange->GetPoint() = *copyRange.Start();
        }
    }

    return bRet;
}

bool DocumentContentOperationsManager::CopyImplImpl(SwPaM& rPam, SwPosition& rPos,
        SwCopyFlags const flags,
        SwPaM *const pCpyRange) const
{
    SwDoc& rDoc = rPos.nNode.GetNode().GetDoc();
    const bool bColumnSel = rDoc.IsClipBoard() && rDoc.IsColumnSelection();

    SwPosition const*const pStt = rPam.Start();
    SwPosition *const pEnd = rPam.End();

    // Catch when there's no copy to do.
    if (!rPam.HasMark() || (IsEmptyRange(*pStt, *pEnd, flags) && !bColumnSel) ||
        //JP 29.6.2001: 88963 - don't copy if inspos is in region of start to end
        //JP 15.11.2001: don't test inclusive the end, ever exclusive
        ( &rDoc == &m_rDoc && *pStt <= rPos && rPos < *pEnd ))
    {
        return false;
    }

    const bool bEndEqualIns = &rDoc == &m_rDoc && rPos == *pEnd;

    // If Undo is enabled, create the UndoCopy object
    SwUndoCpyDoc* pUndo = nullptr;
    // lcl_DeleteRedlines may delete the start or end node of the cursor when
    // removing the redlines so use cursor that is corrected by PaMCorrAbs
    std::shared_ptr<SwUnoCursor> const pCopyPam(rDoc.CreateUnoCursor(rPos));

    SwTableNumFormatMerge aTNFM( m_rDoc, rDoc );
    std::optional<std::vector<SwFrameFormat*>> pFlys;
    std::vector<SwFrameFormat*> const* pFlysAtInsPos;

    if (rDoc.GetIDocumentUndoRedo().DoesUndo())
    {
        pUndo = new SwUndoCpyDoc(*pCopyPam);
        pFlysAtInsPos = pUndo->GetFlysAnchoredAt();
    }
    else
    {
        pFlys = sw::GetFlysAnchoredAt(rDoc, rPos.nNode.GetIndex());
        pFlysAtInsPos = pFlys ? &*pFlys : nullptr;
    }

    RedlineFlags eOld = rDoc.getIDocumentRedlineAccess().GetRedlineFlags();
    rDoc.getIDocumentRedlineAccess().SetRedlineFlags_intern(eOld | RedlineFlags::Ignore);

    // Move the PaM one node back from the insert position, so that
    // the position doesn't get moved
    pCopyPam->SetMark();
    bool bCanMoveBack = pCopyPam->Move(fnMoveBackward, GoInContent);
    // If the position was shifted from more than one node, an end node has been skipped
    bool bAfterTable = false;
    if ((rPos.nNode.GetIndex() - pCopyPam->GetPoint()->nNode.GetIndex()) > SwNodeOffset(1))
    {
        // First go back to the original place
        pCopyPam->GetPoint()->nNode = rPos.nNode;
        pCopyPam->GetPoint()->nContent = rPos.nContent;

        bCanMoveBack = false;
        bAfterTable = true;
    }
    if( !bCanMoveBack )
    {
        pCopyPam->GetPoint()->nNode--;
        assert(pCopyPam->GetPoint()->nContent.GetIndex() == 0);
    }

    SwNodeRange aRg( pStt->nNode, pEnd->nNode );
    SwNodeIndex aInsPos( rPos.nNode );
    const bool bOneNode = pStt->nNode == pEnd->nNode;
    SwTextNode* pSttTextNd = pStt->nNode.GetNode().GetTextNode();
    SwTextNode* pEndTextNd = pEnd->nNode.GetNode().GetTextNode();
    SwTextNode* pDestTextNd = aInsPos.GetNode().GetTextNode();
    bool bCopyCollFormat = !rDoc.IsInsOnlyTextGlossary() &&
                        ( (pDestTextNd && !pDestTextNd->GetText().getLength()) ||
                          ( !bOneNode && !rPos.nContent.GetIndex() ) );
    bool bCopyBookmarks = true;
    bool bCopyPageSource  = false;
    SwNodeOffset nDeleteTextNodes(0);

    // #i104585# copy outline num rule to clipboard (for ASCII filter)
    if (rDoc.IsClipBoard() && m_rDoc.GetOutlineNumRule())
    {
        rDoc.SetOutlineNumRule(*m_rDoc.GetOutlineNumRule());
    }

    // #i86492#
    // Correct the search for a previous list:
    // First search for non-outline numbering list. Then search for non-outline
    // bullet list.
    // Keep also the <ListId> value for possible propagation.
    OUString aListIdToPropagate;
    const SwNumRule* pNumRuleToPropagate =
        rDoc.SearchNumRule( rPos, false, true, false, 0, aListIdToPropagate, nullptr, true );
    if ( !pNumRuleToPropagate )
    {
        pNumRuleToPropagate =
            rDoc.SearchNumRule( rPos, false, false, false, 0, aListIdToPropagate, nullptr, true );
    }
    // #i86492#
    // Do not propagate previous found list, if
    // - destination is an empty paragraph which is not in a list and
    // - source contains at least one paragraph which is not in a list
    if ( pNumRuleToPropagate &&
         pDestTextNd && !pDestTextNd->GetText().getLength() &&
         !pDestTextNd->IsInList() &&
         !lcl_ContainsOnlyParagraphsInList( rPam ) )
    {
        pNumRuleToPropagate = nullptr;
    }

    // This do/while block is only there so that we can break out of it!
    do {
        if( pSttTextNd )
        {
            ++nDeleteTextNodes; // must be joined in Undo
            // Don't copy the beginning completely?
            if( !bCopyCollFormat || bColumnSel || pStt->nContent.GetIndex() )
            {
                SwIndex aDestIdx( rPos.nContent );
                bool bCopyOk = false;
                if( !pDestTextNd )
                {
                    if( pStt->nContent.GetIndex() || bOneNode )
                        pDestTextNd = rDoc.GetNodes().MakeTextNode( aInsPos,
                            rDoc.getIDocumentStylePoolAccess().GetTextCollFromPool(RES_POOLCOLL_STANDARD));
                    else
                    {
                        pDestTextNd = pSttTextNd->MakeCopy(rDoc, aInsPos, true)->GetTextNode();
                        bCopyOk = true;
                    }
                    aDestIdx.Assign( pDestTextNd, 0 );
                    bCopyCollFormat = true;
                }
                else if( !bOneNode || bColumnSel )
                {
                    const sal_Int32 nContentEnd = pEnd->nContent.GetIndex();
                    {
                        ::sw::UndoGuard const ug(rDoc.GetIDocumentUndoRedo());
                        rDoc.getIDocumentContentOperations().SplitNode( rPos, false );
                    }

                    if (bCanMoveBack && rPos == *pCopyPam->GetPoint())
                    {
                        // after the SplitNode, span the CpyPam correctly again
                        pCopyPam->Move( fnMoveBackward, GoInContent );
                        pCopyPam->Move( fnMoveBackward, GoInContent );
                    }

                    pDestTextNd = rDoc.GetNodes()[ aInsPos.GetIndex()-SwNodeOffset(1) ]->GetTextNode();
                    aDestIdx.Assign(
                            pDestTextNd, pDestTextNd->GetText().getLength());

                    // Correct the area again
                    if( bEndEqualIns )
                    {
                        bool bChg = pEnd != rPam.GetPoint();
                        if( bChg )
                            rPam.Exchange();
                        rPam.Move( fnMoveBackward, GoInContent );
                        if( bChg )
                            rPam.Exchange();
                    }
                    else if( rPos == *pEnd )
                    {
                        // The end was also moved
                        pEnd->nNode--;
                        pEnd->nContent.Assign( pDestTextNd, nContentEnd );
                    }
                    // tdf#63022 always reset pEndTextNd after SplitNode
                    aRg.aEnd = pEnd->nNode;
                    pEndTextNd = pEnd->nNode.GetNode().GetTextNode();
                }

                NUMRULE_STATE
                if( bCopyCollFormat && bOneNode )
                {
                    PUSH_NUMRULE_STATE
                }

                if( !bCopyOk )
                {
                    const sal_Int32 nCpyLen = ( bOneNode
                                           ? pEnd->nContent.GetIndex()
                                           : pSttTextNd->GetText().getLength())
                                         - pStt->nContent.GetIndex();
                    pSttTextNd->CopyText( pDestTextNd, aDestIdx,
                                            pStt->nContent, nCpyLen );
                    if( bEndEqualIns )
                        pEnd->nContent -= nCpyLen;
                }

                aRg.aStart++;

                if( bOneNode )
                {
                    if (bCopyCollFormat)
                    {
                        // tdf#138897 no Undo for applying style, SwUndoInserts does it
                        pSttTextNd->CopyCollFormat(*pDestTextNd, false);
                        POP_NUMRULE_STATE
                    }

                    // copy at-char flys in rPam
                    SwNodeIndex temp(*pDestTextNd); // update to new (start) node for flys
                    // tdf#126626 prevent duplicate Undos
                    ::sw::UndoGuard const ug(rDoc.GetIDocumentUndoRedo());
                    CopyFlyInFlyImpl(aRg, &rPam, temp, false);

                    break;
                }
            }
        }
        else if( pDestTextNd )
        {
            // Problems with insertion of table selections into "normal" text solved.
            // We have to set the correct PaM for Undo, if this PaM starts in a textnode,
            // the undo operation will try to merge this node after removing the table.
            // If we didn't split a textnode, the PaM should start at the inserted table node
            if( rPos.nContent.GetIndex() == pDestTextNd->Len() )
            {    // Insertion at the last position of a textnode (empty or not)
                ++aInsPos; // The table will be inserted behind the text node
            }
            else if( rPos.nContent.GetIndex() )
            {   // Insertion in the middle of a text node, it has to be split
                // (and joined from undo)
                ++nDeleteTextNodes;

                const sal_Int32 nContentEnd = pEnd->nContent.GetIndex();
                {
                    ::sw::UndoGuard const ug(rDoc.GetIDocumentUndoRedo());
                    rDoc.getIDocumentContentOperations().SplitNode( rPos, false );
                }

                if (bCanMoveBack && rPos == *pCopyPam->GetPoint())
                {
                    // after the SplitNode, span the CpyPam correctly again
                    pCopyPam->Move( fnMoveBackward, GoInContent );
                    pCopyPam->Move( fnMoveBackward, GoInContent );
                }

                // Correct the area again
                if( bEndEqualIns )
                    aRg.aEnd--;
                // The end would also be moved
                else if( rPos == *pEnd )
                {
                    rPos.nNode-=SwNodeOffset(2);
                    rPos.nContent.Assign( rPos.nNode.GetNode().GetContentNode(),
                                            nContentEnd );
                    rPos.nNode++;
                    aRg.aEnd--;
                }
            }
            else if( bCanMoveBack )
            {   // Insertion at the first position of a text node. It will not be split, the table
                // will be inserted before the text node.
                // See below, before the SetInsertRange function of the undo object will be called,
                // the CpyPam would be moved to the next content position. This has to be avoided
                // We want to be moved to the table node itself thus we have to set bCanMoveBack
                // and to manipulate pCopyPam.
                bCanMoveBack = false;
                pCopyPam->GetPoint()->nNode--;
            }
        }

        pDestTextNd = aInsPos.GetNode().GetTextNode();
        if (pEndTextNd)
        {
            SwIndex aDestIdx( rPos.nContent );
            if( !pDestTextNd )
            {
                pDestTextNd = rDoc.GetNodes().MakeTextNode( aInsPos,
                            rDoc.getIDocumentStylePoolAccess().GetTextCollFromPool(RES_POOLCOLL_STANDARD));
                aDestIdx.Assign( pDestTextNd, 0  );
                aInsPos--;

                // if we have to insert an extra text node
                // at the destination, this node will be our new destination
                // (text) node, and thus we increment nDeleteTextNodes. This
                // will ensure that this node will be deleted during Undo.
                ++nDeleteTextNodes; // must be deleted
            }

            const bool bEmptyDestNd = pDestTextNd->GetText().isEmpty();

            NUMRULE_STATE
            if( bCopyCollFormat && ( bOneNode || bEmptyDestNd ))
            {
                PUSH_NUMRULE_STATE
            }

            pEndTextNd->CopyText( pDestTextNd, aDestIdx, SwIndex( pEndTextNd ),
                            pEnd->nContent.GetIndex() );

            // Also copy all format templates
            if( bCopyCollFormat && ( bOneNode || bEmptyDestNd ))
            {
                // tdf#138897 no Undo for applying style, SwUndoInserts does it
                pEndTextNd->CopyCollFormat(*pDestTextNd, false);
                if ( bOneNode )
                {
                    POP_NUMRULE_STATE
                }
            }
        }

        SfxItemSet aBrkSet( rDoc.GetAttrPool(), aBreakSetRange );
        if ((flags & SwCopyFlags::CopyAll) || aRg.aStart != aRg.aEnd)
        {
            if (pSttTextNd && bCopyCollFormat && pDestTextNd->HasSwAttrSet())
            {
                aBrkSet.Put( *pDestTextNd->GetpSwAttrSet() );
                if( SfxItemState::SET == aBrkSet.GetItemState( RES_BREAK, false ) )
                    pDestTextNd->ResetAttr( RES_BREAK );
                if( SfxItemState::SET == aBrkSet.GetItemState( RES_PAGEDESC, false ) )
                    pDestTextNd->ResetAttr( RES_PAGEDESC );
            }
        }

        {
            SwPosition startPos(SwNodeIndex(pCopyPam->GetPoint()->nNode, +1),
                SwIndex(SwNodeIndex(pCopyPam->GetPoint()->nNode, +1).GetNode().GetContentNode()));
            if (bCanMoveBack)
            {   // pCopyPam is actually 1 before the copy range so move it fwd
                SwPaM temp(*pCopyPam->GetPoint());
                temp.Move(fnMoveForward, GoInContent);
                startPos = *temp.GetPoint();
            }
            assert(startPos.nNode.GetNode().IsContentNode());
            std::pair<SwPaM const&, SwPosition const&> tmp(rPam, startPos);
            if( aInsPos == pEnd->nNode )
            {
                SwNodeIndex aSaveIdx( aInsPos, -1 );
                assert(pStt->nNode != pEnd->nNode);
                pEnd->nContent = 0; // TODO why this?
                CopyWithFlyInFly(aRg, aInsPos, &tmp, /*bMakeNewFrames*/true, false, /*bCopyFlyAtFly=*/false, flags);
                ++aSaveIdx;
                pEnd->nNode = aSaveIdx;
                pEnd->nContent.Assign( aSaveIdx.GetNode().GetTextNode(), 0 );
            }
            else
                CopyWithFlyInFly(aRg, aInsPos, &tmp, /*bMakeNewFrames*/true, false, /*bCopyFlyAtFly=*/false, flags);

            bCopyBookmarks = false;
        }

        // at-char anchors post SplitNode are on index 0 of 2nd node and will
        // remain there - move them back to the start (end would also work?)
        // ... also for at-para anchors; here start is preferable because
        // it's consistent with SplitNode from SwUndoInserts::RedoImpl()
        if (pFlysAtInsPos)
        {
            // init *again* - because CopyWithFlyInFly moved startPos
            SwPosition startPos(SwNodeIndex(pCopyPam->GetPoint()->nNode, +1),
                SwIndex(SwNodeIndex(pCopyPam->GetPoint()->nNode, +1).GetNode().GetContentNode()));
            if (bCanMoveBack)
            {   // pCopyPam is actually 1 before the copy range so move it fwd
                SwPaM temp(*pCopyPam->GetPoint());
                temp.Move(fnMoveForward, GoInContent);
                startPos = *temp.GetPoint();
            }
            assert(startPos.nNode.GetNode().IsContentNode());
            SwPosition startPosAtPara(startPos);
            startPosAtPara.nContent.Assign(nullptr, 0);

            for (SwFrameFormat * pFly : *pFlysAtInsPos)
            {
                SwFormatAnchor const*const pAnchor = &pFly->GetAnchor();
                if (pAnchor->GetAnchorId() == RndStdIds::FLY_AT_CHAR)
                {
                    SwFormatAnchor anchor(*pAnchor);
                    anchor.SetAnchor( &startPos );
                    pFly->SetFormatAttr(anchor);
                }
                else if (pAnchor->GetAnchorId() == RndStdIds::FLY_AT_PARA)
                {
                    SwFormatAnchor anchor(*pAnchor);
                    anchor.SetAnchor( &startPosAtPara );
                    pFly->SetFormatAttr(anchor);
                }
            }
        }

        if ((flags & SwCopyFlags::CopyAll) || aRg.aStart != aRg.aEnd)
        {
            // Put the breaks back into the first node
            if( aBrkSet.Count() && nullptr != ( pDestTextNd = rDoc.GetNodes()[
                    pCopyPam->GetPoint()->nNode.GetIndex()+1 ]->GetTextNode()))
            {
                pDestTextNd->SetAttr( aBrkSet );
                bCopyPageSource = true;
            }
        }
    } while( false );


    // it is not possible to make this test when copy from the clipBoard to document
    //  in this case the PageNum not exist anymore
    // tdf#39400 and tdf#97526
    // when copy from document to ClipBoard, and it is from the first page
    //  and not the source has the page break
    if (rDoc.IsClipBoard() && (rPam.GetPageNum(pStt == rPam.GetPoint()) == 1) && !bCopyPageSource)
    {
        if (pDestTextNd)
        {
            pDestTextNd->ResetAttr(RES_BREAK);        // remove the page-break
            pDestTextNd->ResetAttr(RES_PAGEDESC);
        }
    }


    // Adjust position (in case it was moved / in another node)
    rPos.nContent.Assign( rPos.nNode.GetNode().GetContentNode(),
                            rPos.nContent.GetIndex() );

    if( rPos.nNode != aInsPos )
    {
        pCopyPam->GetMark()->nNode = aInsPos;
        if (aInsPos < rPos.nNode)
        {   // tdf#134250 decremented in (pEndTextNd && !pDestTextNd) above
            pCopyPam->GetContentNode(false)->MakeEndIndex(&pCopyPam->GetMark()->nContent);
        }
        else // incremented in (!pSttTextNd && pDestTextNd) above
        {
            pCopyPam->GetMark()->nContent.Assign(pCopyPam->GetContentNode(false), 0);
        }
        rPos = *pCopyPam->GetMark();
    }
    else
        *pCopyPam->GetMark() = rPos;

    if ( !bAfterTable )
        pCopyPam->Move( fnMoveForward, bCanMoveBack ? GoInContent : GoInNode );
    else
    {
        pCopyPam->GetPoint()->nNode++;

        // Reset the offset to 0 as it was before the insertion
        pCopyPam->GetPoint()->nContent.Assign(pCopyPam->GetPoint()->nNode.GetNode().GetContentNode(), 0);
        // If the next node is a start node, then step back: the start node
        // has been copied and needs to be in the selection for the undo
        if (pCopyPam->GetPoint()->nNode.GetNode().IsStartNode())
            pCopyPam->GetPoint()->nNode--;

    }
    pCopyPam->Exchange();

    // Also copy all bookmarks
    if( bCopyBookmarks && m_rDoc.getIDocumentMarkAccess()->getAllMarksCount() )
    {
        sw::CopyBookmarks(rPam, *pCopyPam->Start());
    }

    if( RedlineFlags::DeleteRedlines & eOld )
    {
        assert(*pCopyPam->GetPoint() == rPos);
        // the Node rPos points to may be deleted so unregister ...
        rPos.nContent.Assign(nullptr, 0);
        lcl_DeleteRedlines(rPam, *pCopyPam);
        rPos = *pCopyPam->GetPoint(); // ... and restore.
    }

    // If Undo is enabled, store the inserted area
    if (rDoc.GetIDocumentUndoRedo().DoesUndo())
    {
        // append it after styles have been copied when copying nodes
        rDoc.GetIDocumentUndoRedo().AppendUndo( std::unique_ptr<SwUndo>(pUndo) );
        pUndo->SetInsertRange(*pCopyPam, true, nDeleteTextNodes);
    }

    if( pCpyRange )
    {
        pCpyRange->SetMark();
        *pCpyRange->GetPoint() = *pCopyPam->GetPoint();
        *pCpyRange->GetMark() = *pCopyPam->GetMark();
    }

    if ( pNumRuleToPropagate != nullptr )
    {
        // #i86492# - use <SwDoc::SetNumRule(..)>, because it also handles the <ListId>
        // Don't reset indent attributes, that would mean loss of direct
        // formatting.
        rDoc.SetNumRule( *pCopyPam, *pNumRuleToPropagate, false, nullptr,
                          aListIdToPropagate, true, /*bResetIndentAttrs=*/false );
    }

    rDoc.getIDocumentRedlineAccess().SetRedlineFlags_intern( eOld );
    rDoc.getIDocumentState().SetModified();

    return true;
}


}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */