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
/* -*- 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 <stdlib.h>

#include <memory>
#include <set>

#include <com/sun/star/drawing/XDrawPageSupplier.hpp>
#include <com/sun/star/text/ControlCharacter.hpp>
#include <com/sun/star/text/TableColumnSeparator.hpp>
#include <com/sun/star/lang/IndexOutOfBoundsException.hpp>
#include <com/sun/star/lang/WrappedTargetRuntimeException.hpp>

#include <svl/listener.hxx>
#include <vcl/svapp.hxx>
#include <comphelper/profilezone.hxx>
#include <comphelper/sequence.hxx>
#include <comphelper/servicehelper.hxx>
#include <cppuhelper/exc_hlp.hxx>
#include <cppuhelper/supportsservice.hxx>
#include <sal/log.hxx>

#include <cmdid.h>
#include <unotextbodyhf.hxx>
#include <unotext.hxx>
#include <unotextrange.hxx>
#include <unotextcursor.hxx>
#include <unosection.hxx>
#include <unobookmark.hxx>
#include <unorefmark.hxx>
#include <unoport.hxx>
#include <unotbl.hxx>
#include <unoidx.hxx>
#include <unocoll.hxx>
#include <unoframe.hxx>
#include <unofield.hxx>
#include <unometa.hxx>
#include <unomap.hxx>
#include <unoprnms.hxx>
#include <unoparagraph.hxx>
#include <unocrsrhelper.hxx>
#include <docary.hxx>
#include <doc.hxx>
#include <IDocumentUndoRedo.hxx>
#include <redline.hxx>
#include <swundo.hxx>
#include <section.hxx>
#include <fmtanchr.hxx>
#include <fmtcntnt.hxx>
#include <ndtxt.hxx>
#include <SwRewriter.hxx>
#include <strings.hrc>
#include <frameformats.hxx>

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

const char cInvalidObject[] = "this object is invalid";

class SwXText::Impl
{

public:
    SwXText &                   m_rThis;
    SfxItemPropertySet const&   m_rPropSet;
    const CursorType            m_eType;
    SwDoc *                     m_pDoc;
    bool                        m_bIsValid;

    Impl(   SwXText & rThis,
            SwDoc *const pDoc, const CursorType eType)
        : m_rThis(rThis)
        , m_rPropSet(*aSwMapProvider.GetPropertySet(PROPERTY_MAP_TEXT))
        , m_eType(eType)
        , m_pDoc(pDoc)
        , m_bIsValid(nullptr != pDoc)
    {
    }

    /// @throws lang::IllegalArgumentException
    /// @throws uno::RuntimeException
    uno::Reference< text::XTextRange >
        finishOrAppendParagraph(
            const uno::Sequence< beans::PropertyValue >&
                rCharacterAndParagraphProperties,
            const uno::Reference< text::XTextRange >& xInsertPosition);

    /// @throws lang::IllegalArgumentException
    /// @throws uno::RuntimeException
    sal_Int16 ComparePositions(
            const uno::Reference<text::XTextRange>& xPos1,
            const uno::Reference<text::XTextRange>& xPos2);

    /// @throws lang::IllegalArgumentException
    /// @throws uno::RuntimeException
    bool CheckForOwnMember(const SwPaM & rPaM);

    void ConvertCell(
            const uno::Sequence< uno::Reference< text::XTextRange > > & rCell,
            std::vector<SwNodeRange> & rRowNodes,
            SwNodeRange *const pLastCell);

};

SwXText::SwXText(SwDoc *const pDoc, const CursorType eType)
    : m_pImpl( new SwXText::Impl(*this, pDoc, eType) )
{
}

SwXText::~SwXText()
{
}

const SwDoc * SwXText::GetDoc() const
{
    return m_pImpl->m_pDoc;
}
      SwDoc * SwXText::GetDoc()
{
    return m_pImpl->m_pDoc;
}

bool SwXText::IsValid() const
{
    return m_pImpl->m_bIsValid;
}

void SwXText::Invalidate()
{
    m_pImpl->m_bIsValid = false;
}

void SwXText::SetDoc(SwDoc *const pDoc)
{
    OSL_ENSURE(!m_pImpl->m_pDoc || !pDoc,
        "SwXText::SetDoc: already have a doc?");
    m_pImpl->m_pDoc = pDoc;
    m_pImpl->m_bIsValid = (nullptr != pDoc);
}

void
SwXText::PrepareForAttach(uno::Reference< text::XTextRange > &, const SwPaM &)
{
}

bool SwXText::CheckForOwnMemberMeta(const SwPaM &, const bool)
{
    OSL_ENSURE(CursorType::Meta != m_pImpl->m_eType, "should not be called!");
    return false;
}

const SwStartNode *SwXText::GetStartNode() const
{
    return GetDoc()->GetNodes().GetEndOfContent().StartOfSectionNode();
}

uno::Reference< text::XTextCursor >
SwXText::CreateCursor()
{
    uno::Reference< text::XTextCursor >  xRet;
    if(IsValid())
    {
        SwNode& rNode = GetDoc()->GetNodes().GetEndOfContent();
        SwPosition aPos(rNode);
        xRet = static_cast<text::XWordCursor*>(
                new SwXTextCursor(*GetDoc(), this, m_pImpl->m_eType, aPos));
        xRet->gotoStart(false);
    }
    return xRet;
}

uno::Any SAL_CALL
SwXText::queryInterface(const uno::Type& rType)
{
    uno::Any aRet;
    if (rType == cppu::UnoType<text::XText>::get())
    {
        aRet <<= uno::Reference< text::XText >(this);
    }
    else if (rType == cppu::UnoType<text::XSimpleText>::get())
    {
        aRet <<= uno::Reference< text::XSimpleText >(this);
    }
    else if (rType == cppu::UnoType<text::XTextRange>::get())
    {
        aRet <<= uno::Reference< text::XTextRange>(this);
    }
    else if (rType == cppu::UnoType<text::XTextRangeCompare>::get())
    {
        aRet <<= uno::Reference< text::XTextRangeCompare >(this);
    }
    else if (rType == cppu::UnoType<lang::XTypeProvider>::get())
    {
        aRet <<= uno::Reference< lang::XTypeProvider >(this);
    }
    else if (rType == cppu::UnoType<text::XRelativeTextContentInsert>::get())
    {
        aRet <<= uno::Reference< text::XRelativeTextContentInsert >(this);
    }
    else if (rType == cppu::UnoType<text::XRelativeTextContentRemove>::get())
    {
        aRet <<= uno::Reference< text::XRelativeTextContentRemove >(this);
    }
    else if (rType == cppu::UnoType<beans::XPropertySet>::get())
    {
        aRet <<= uno::Reference< beans::XPropertySet >(this);
    }
    else if (rType == cppu::UnoType<lang::XUnoTunnel>::get())
    {
        aRet <<= uno::Reference< lang::XUnoTunnel >(this);
    }
    else if (rType == cppu::UnoType<text::XTextAppendAndConvert>::get())
    {
        aRet <<= uno::Reference< text::XTextAppendAndConvert >(this);
    }
    else if (rType == cppu::UnoType<text::XTextAppend>::get())
    {
        aRet <<= uno::Reference< text::XTextAppend >(this);
    }
    else if (rType == cppu::UnoType<text::XTextPortionAppend>::get())
    {
        aRet <<= uno::Reference< text::XTextPortionAppend >(this);
    }
    else if (rType == cppu::UnoType<text::XParagraphAppend>::get())
    {
        aRet <<= uno::Reference< text::XParagraphAppend >(this);
    }
    else if (rType == cppu::UnoType<text::XTextConvert>::get() )
    {
        aRet <<= uno::Reference< text::XTextConvert >(this);
    }
    else if (rType == cppu::UnoType<text::XTextContentAppend>::get())
    {
        aRet <<= uno::Reference< text::XTextContentAppend >(this);
    }
    else if(rType == cppu::UnoType<text::XTextCopy>::get())
    {
        aRet <<= uno::Reference< text::XTextCopy >( this );
    }
    return aRet;
}

uno::Sequence< uno::Type > SAL_CALL
SwXText::getTypes()
{
    static const uno::Sequence< uno::Type > aTypes {
        cppu::UnoType<text::XText>::get(),
        cppu::UnoType<text::XTextRangeCompare>::get(),
        cppu::UnoType<text::XRelativeTextContentInsert>::get(),
        cppu::UnoType<text::XRelativeTextContentRemove>::get(),
        cppu::UnoType<lang::XUnoTunnel>::get(),
        cppu::UnoType<beans::XPropertySet>::get(),
        cppu::UnoType<text::XTextPortionAppend>::get(),
        cppu::UnoType<text::XParagraphAppend>::get(),
        cppu::UnoType<text::XTextContentAppend>::get(),
        cppu::UnoType<text::XTextConvert>::get(),
        cppu::UnoType<text::XTextAppend>::get(),
        cppu::UnoType<text::XTextAppendAndConvert>::get()
    };
    return aTypes;
}

// belongs the range in the text ? insert it then.
void SAL_CALL
SwXText::insertString(const uno::Reference< text::XTextRange >& xTextRange,
    const OUString& rString, sal_Bool bAbsorb)
{
    SolarMutexGuard aGuard;
    comphelper::ProfileZone aZone("SwXText::insertString");

    if (!xTextRange.is())
    {
        throw uno::RuntimeException();
    }
    if (!GetDoc())
    {
        throw uno::RuntimeException();
    }
    const uno::Reference<lang::XUnoTunnel> xRangeTunnel(xTextRange,
            uno::UNO_QUERY);
    SwXTextRange *const pRange =
        ::sw::UnoTunnelGetImplementation<SwXTextRange>(xRangeTunnel);
    OTextCursorHelper *const pCursor =
        ::sw::UnoTunnelGetImplementation<OTextCursorHelper>(xRangeTunnel);
    if ((!pRange  || &pRange ->GetDoc() != GetDoc()) &&
        (!pCursor || pCursor->GetDoc() != GetDoc()))
    {
        throw uno::RuntimeException();
    }

    const SwStartNode *const pOwnStartNode = GetStartNode();
    SwPaM aPam(GetDoc()->GetNodes());
    const SwPaM * pPam(nullptr);
    if (pCursor)
    {
        pPam = pCursor->GetPaM();
    }
    else // pRange
    {
        if (pRange->GetPositions(aPam))
        {
            pPam = &aPam;
        }
    }
    if (!pPam)
    {
        throw uno::RuntimeException();
    }

    const SwStartNode* pTmp(pPam->GetNode().StartOfSectionNode());
    while (pTmp && pTmp->IsSectionNode())
    {
        pTmp = pTmp->StartOfSectionNode();
    }
    if (!pOwnStartNode || (pOwnStartNode != pTmp))
    {
        throw uno::RuntimeException();
    }

    bool bForceExpandHints( false );
    if (CursorType::Meta == m_pImpl->m_eType)
    {
        try
        {
            bForceExpandHints = CheckForOwnMemberMeta(*pPam, bAbsorb);
        }
        catch (const lang::IllegalArgumentException& iae)
        {
            // stupid method not allowed to throw iae
            css::uno::Any anyEx = cppu::getCaughtException();
            throw lang::WrappedTargetRuntimeException( iae.Message,
                            uno::Reference< uno::XInterface >(), anyEx );
        }
    }
    if (bAbsorb)
    {
        //!! scan for CR characters and inserting the paragraph breaks
        //!! has to be done in the called function.
        //!! Implemented in SwXTextRange::DeleteAndInsert
        if (pCursor)
        {
            SwXTextCursor * const pTextCursor(
                dynamic_cast<SwXTextCursor*>(pCursor) );
            if (pTextCursor)
            {
                pTextCursor->DeleteAndInsert(rString, bForceExpandHints);
            }
            else
            {
                xTextRange->setString(rString);
            }
        }
        else
        {
            pRange->DeleteAndInsert(rString, bForceExpandHints);
        }
    }
    else
    {
        // create a PaM positioned before the parameter PaM,
        // so the text is inserted before
        UnoActionContext aContext(GetDoc());
        SwPaM aInsertPam(*pPam->Start());
        ::sw::GroupUndoGuard const undoGuard(GetDoc()->GetIDocumentUndoRedo());
        SwUnoCursorHelper::DocInsertStringSplitCR(
            *GetDoc(), aInsertPam, rString, bForceExpandHints );
    }
}

void SAL_CALL
SwXText::insertControlCharacter(
        const uno::Reference< text::XTextRange > & xTextRange,
        sal_Int16 nControlCharacter, sal_Bool bAbsorb)
{
    SolarMutexGuard aGuard;

    if (!xTextRange.is())
    {
        throw lang::IllegalArgumentException();
    }
    if (!GetDoc())
    {
        throw uno::RuntimeException();
    }

    SwUnoInternalPaM aPam(*GetDoc());
    if (!::sw::XTextRangeToSwPaM(aPam, xTextRange))
    {
        throw uno::RuntimeException();
    }
    const bool bForceExpandHints(CheckForOwnMemberMeta(aPam, bAbsorb));

    const SwInsertFlags nInsertFlags =
        bForceExpandHints
        ? ( SwInsertFlags::FORCEHINTEXPAND | SwInsertFlags::EMPTYEXPAND)
        : SwInsertFlags::EMPTYEXPAND;

    if (bAbsorb && aPam.HasMark())
    {
        m_pImpl->m_pDoc->getIDocumentContentOperations().DeleteAndJoin(aPam);
        aPam.DeleteMark();
    }

    sal_Unicode cIns = 0;
    switch (nControlCharacter)
    {
        case text::ControlCharacter::PARAGRAPH_BREAK :
            // a table cell now becomes an ordinary text cell!
            m_pImpl->m_pDoc->ClearBoxNumAttrs(aPam.GetPoint()->nNode);
            m_pImpl->m_pDoc->getIDocumentContentOperations().SplitNode(*aPam.GetPoint(), false);
            break;
        case text::ControlCharacter::APPEND_PARAGRAPH:
        {
            m_pImpl->m_pDoc->ClearBoxNumAttrs(aPam.GetPoint()->nNode);
            m_pImpl->m_pDoc->getIDocumentContentOperations().AppendTextNode(*aPam.GetPoint());

            const uno::Reference<lang::XUnoTunnel> xRangeTunnel(
                    xTextRange, uno::UNO_QUERY);
            SwXTextRange *const pRange =
                ::sw::UnoTunnelGetImplementation<SwXTextRange>(xRangeTunnel);
            OTextCursorHelper *const pCursor =
                ::sw::UnoTunnelGetImplementation<OTextCursorHelper>(
                            xRangeTunnel);
            if (pRange)
            {
                pRange->SetPositions(aPam);
            }
            else if (pCursor)
            {
                SwPaM *const pCursorPam = pCursor->GetPaM();
                *pCursorPam->GetPoint() = *aPam.GetPoint();
                pCursorPam->DeleteMark();
            }
        }
        break;
        case text::ControlCharacter::LINE_BREAK:  cIns = 10;              break;
        case text::ControlCharacter::SOFT_HYPHEN: cIns = CHAR_SOFTHYPHEN; break;
        case text::ControlCharacter::HARD_HYPHEN: cIns = CHAR_HARDHYPHEN; break;
        case text::ControlCharacter::HARD_SPACE:  cIns = CHAR_HARDBLANK;  break;
    }
    if (cIns)
    {
        m_pImpl->m_pDoc->getIDocumentContentOperations().InsertString(
                aPam, OUString(cIns), nInsertFlags);
    }

    if (bAbsorb)
    {
        const uno::Reference<lang::XUnoTunnel> xRangeTunnel(
                xTextRange, uno::UNO_QUERY);
        SwXTextRange *const pRange =
            ::sw::UnoTunnelGetImplementation<SwXTextRange>(xRangeTunnel);
        OTextCursorHelper *const pCursor =
            ::sw::UnoTunnelGetImplementation<OTextCursorHelper>(xRangeTunnel);

        SwCursor aCursor(*aPam.GetPoint(), nullptr);
        SwUnoCursorHelper::SelectPam(aCursor, true);
        aCursor.Left(1);
        // here, the PaM needs to be moved:
        if (pRange)
        {
            pRange->SetPositions(aCursor);
        }
        else
        {
            SwPaM *const pUnoCursor = pCursor->GetPaM();
            *pUnoCursor->GetPoint() = *aCursor.GetPoint();
            if (aCursor.HasMark())
            {
                pUnoCursor->SetMark();
                *pUnoCursor->GetMark() = *aCursor.GetMark();
            }
            else
            {
                pUnoCursor->DeleteMark();
            }
        }
    }
}

void SAL_CALL
SwXText::insertTextContent(
        const uno::Reference< text::XTextRange > & xRange,
        const uno::Reference< text::XTextContent > & xContent,
        sal_Bool bAbsorb)
{
    SolarMutexGuard aGuard;
    comphelper::ProfileZone aZone("SwXText::insertTextContent");

    if (!xRange.is())
    {
        lang::IllegalArgumentException aIllegal;
        aIllegal.Message = "first parameter invalid;";
        throw aIllegal;
    }
    if (!xContent.is())
    {
        lang::IllegalArgumentException aIllegal;
        aIllegal.Message = "second parameter invalid";
        throw aIllegal;
    }
    if(!GetDoc())
    {
        uno::RuntimeException aRuntime;
        aRuntime.Message = cInvalidObject;
        throw aRuntime;
    }

    SwUnoInternalPaM aPam(*GetDoc());
    if (!::sw::XTextRangeToSwPaM(aPam, xRange))
    {
        lang::IllegalArgumentException aIllegal;
        aIllegal.Message = "first parameter invalid";
        throw aIllegal;
    }

    // first test if the range is at the right position, then call
    // xContent->attach
    const SwStartNode* pOwnStartNode = GetStartNode();
    SwStartNodeType eSearchNodeType = SwNormalStartNode;
    switch (m_pImpl->m_eType)
    {
        case CursorType::Frame:      eSearchNodeType = SwFlyStartNode;       break;
        case CursorType::TableText:    eSearchNodeType = SwTableBoxStartNode;  break;
        case CursorType::Footnote:   eSearchNodeType = SwFootnoteStartNode;  break;
        case CursorType::Header:     eSearchNodeType = SwHeaderStartNode;    break;
        case CursorType::Footer:     eSearchNodeType = SwFooterStartNode;    break;
        //case CURSOR_INVALID:
        //case CursorType::Body:
        default:
            break;
    }

    const SwStartNode* pTmp =
        aPam.GetNode().FindSttNodeByType(eSearchNodeType);

    // ignore SectionNodes
    while (pTmp && pTmp->IsSectionNode())
    {
        pTmp = pTmp->StartOfSectionNode();
    }
    // if the document starts with a section
    while (pOwnStartNode && pOwnStartNode->IsSectionNode())
    {
        pOwnStartNode = pOwnStartNode->StartOfSectionNode();
    }
    // this checks if (this) and xRange are in the same text::XText interface
    if (pOwnStartNode != pTmp)
    {
        uno::RuntimeException aRunException;
        aRunException.Message = "text interface and cursor not related";
        throw aRunException;
    }

    const bool bForceExpandHints(CheckForOwnMemberMeta(aPam, bAbsorb));

    // special treatment for Contents that do not replace the range, but
    // instead are "overlaid"
    const uno::Reference<lang::XUnoTunnel> xContentTunnel(xContent,
            uno::UNO_QUERY);
    if (!xContentTunnel.is())
    {
        lang::IllegalArgumentException aArgException;
        aArgException.Message = "text content does not support lang::XUnoTunnel";
        throw aArgException;
    }
    SwXDocumentIndexMark *const pDocumentIndexMark =
        ::sw::UnoTunnelGetImplementation<SwXDocumentIndexMark>(xContentTunnel);
    SwXTextSection *const pSection =
        ::sw::UnoTunnelGetImplementation<SwXTextSection>(xContentTunnel);
    SwXBookmark *const pBookmark =
        ::sw::UnoTunnelGetImplementation<SwXBookmark>(xContentTunnel);
    SwXReferenceMark *const pReferenceMark =
        ::sw::UnoTunnelGetImplementation<SwXReferenceMark>(xContentTunnel);
    SwXMeta *const pMeta =
        ::sw::UnoTunnelGetImplementation<SwXMeta>(xContentTunnel);
    SwXTextField* pTextField =
        ::sw::UnoTunnelGetImplementation<SwXTextField>(xContentTunnel);
    if (pTextField && pTextField->GetServiceId() != SwServiceType::FieldTypeAnnotation)
        pTextField = nullptr;

    const bool bAttribute = pBookmark || pDocumentIndexMark
        || pSection || pReferenceMark || pMeta || pTextField;

    if (bAbsorb && !bAttribute)
    {
        xRange->setString(OUString());
    }
    uno::Reference< text::XTextRange > xTempRange =
        (bAttribute && bAbsorb) ? xRange : xRange->getStart();
    if (bForceExpandHints)
    {
        // if necessary, replace xTempRange with a new SwXTextCursor
        PrepareForAttach(xTempRange, aPam);
    }
    xContent->attach(xTempRange);
}

void SAL_CALL
SwXText::insertTextContentBefore(
    const uno::Reference< text::XTextContent>& xNewContent,
    const uno::Reference< text::XTextContent>& xSuccessor)
{
    SolarMutexGuard aGuard;

    if(!GetDoc())
    {
        uno::RuntimeException aRuntime;
        aRuntime.Message = cInvalidObject;
        throw aRuntime;
    }

    SwXParagraph *const pPara =
            comphelper::getUnoTunnelImplementation<SwXParagraph>(xNewContent);
    if (!pPara || !pPara->IsDescriptor() || !xSuccessor.is())
    {
        throw lang::IllegalArgumentException();
    }

    bool bRet = false;
    const uno::Reference<lang::XUnoTunnel> xSuccTunnel(xSuccessor,
            uno::UNO_QUERY);
    SwXTextSection *const pXSection =
            ::sw::UnoTunnelGetImplementation<SwXTextSection>(xSuccTunnel);
    SwXTextTable *const pXTable =
            ::sw::UnoTunnelGetImplementation<SwXTextTable>(xSuccTunnel);
    SwFrameFormat *const pTableFormat = pXTable ? pXTable->GetFrameFormat() : nullptr;
    SwTextNode * pTextNode = nullptr;
    if(pTableFormat && pTableFormat->GetDoc() == GetDoc())
    {
        SwTable *const pTable = SwTable::FindTable( pTableFormat );
        SwTableNode *const pTableNode = pTable->GetTableNode();

        const SwNodeIndex aTableIdx( *pTableNode, -1 );
        SwPosition aBefore(aTableIdx);
        bRet = GetDoc()->getIDocumentContentOperations().AppendTextNode( aBefore );
        pTextNode = aBefore.nNode.GetNode().GetTextNode();
    }
    else if (pXSection && pXSection->GetFormat() &&
            pXSection->GetFormat()->GetDoc() == GetDoc())
    {
        SwSectionFormat *const pSectFormat = pXSection->GetFormat();
        SwSectionNode *const pSectNode = pSectFormat->GetSectionNode();

        const SwNodeIndex aSectIdx( *pSectNode, -1 );
        SwPosition aBefore(aSectIdx);
        bRet = GetDoc()->getIDocumentContentOperations().AppendTextNode( aBefore );
        pTextNode = aBefore.nNode.GetNode().GetTextNode();
    }
    if (!bRet || !pTextNode)
    {
        throw lang::IllegalArgumentException();
    }
    pPara->attachToText(*this, *pTextNode);
}

void SAL_CALL
SwXText::insertTextContentAfter(
    const uno::Reference< text::XTextContent>& xNewContent,
    const uno::Reference< text::XTextContent>& xPredecessor)
{
    SolarMutexGuard aGuard;

    if(!GetDoc())
    {
        throw uno::RuntimeException();
    }

    SwXParagraph *const pPara =
            comphelper::getUnoTunnelImplementation<SwXParagraph>(xNewContent);
    if(!pPara || !pPara->IsDescriptor() || !xPredecessor.is())
    {
        throw lang::IllegalArgumentException();
    }

    const uno::Reference<lang::XUnoTunnel> xPredTunnel(xPredecessor,
            uno::UNO_QUERY);
    SwXTextSection *const pXSection =
            ::sw::UnoTunnelGetImplementation<SwXTextSection>(xPredTunnel);
    SwXTextTable *const pXTable =
            ::sw::UnoTunnelGetImplementation<SwXTextTable>(xPredTunnel);
    SwFrameFormat *const pTableFormat = pXTable ? pXTable->GetFrameFormat() : nullptr;
    bool bRet = false;
    SwTextNode * pTextNode = nullptr;
    if(pTableFormat && pTableFormat->GetDoc() == GetDoc())
    {
        SwTable *const pTable = SwTable::FindTable( pTableFormat );
        SwTableNode *const pTableNode = pTable->GetTableNode();

        SwEndNode *const pTableEnd = pTableNode->EndOfSectionNode();
        SwPosition aTableEnd(*pTableEnd);
        bRet = GetDoc()->getIDocumentContentOperations().AppendTextNode( aTableEnd );
        pTextNode = aTableEnd.nNode.GetNode().GetTextNode();
    }
    else if (pXSection && pXSection->GetFormat() &&
            pXSection->GetFormat()->GetDoc() == GetDoc())
    {
        SwSectionFormat *const pSectFormat = pXSection->GetFormat();
        SwSectionNode *const pSectNode = pSectFormat->GetSectionNode();
        SwEndNode *const pEnd = pSectNode->EndOfSectionNode();
        SwPosition aEnd(*pEnd);
        bRet = GetDoc()->getIDocumentContentOperations().AppendTextNode( aEnd );
        pTextNode = aEnd.nNode.GetNode().GetTextNode();
    }
    if (!bRet || !pTextNode)
    {
        throw lang::IllegalArgumentException();
    }
    pPara->attachToText(*this, *pTextNode);
}

void SAL_CALL
SwXText::removeTextContentBefore(
    const uno::Reference< text::XTextContent>& xSuccessor)
{
    SolarMutexGuard aGuard;

    if(!GetDoc())
    {
        uno::RuntimeException aRuntime;
        aRuntime.Message = cInvalidObject;
        throw aRuntime;
    }

    bool bRet = false;
    const uno::Reference<lang::XUnoTunnel> xSuccTunnel(xSuccessor,
            uno::UNO_QUERY);
    SwXTextSection *const pXSection =
            ::sw::UnoTunnelGetImplementation<SwXTextSection>(xSuccTunnel);
    SwXTextTable *const pXTable =
            ::sw::UnoTunnelGetImplementation<SwXTextTable>(xSuccTunnel);
    SwFrameFormat *const pTableFormat = pXTable ? pXTable->GetFrameFormat() : nullptr;
    if(pTableFormat && pTableFormat->GetDoc() == GetDoc())
    {
        SwTable *const pTable = SwTable::FindTable( pTableFormat );
        SwTableNode *const pTableNode = pTable->GetTableNode();

        const SwNodeIndex aTableIdx( *pTableNode, -1 );
        if(aTableIdx.GetNode().IsTextNode())
        {
            SwPaM aBefore(aTableIdx);
            bRet = GetDoc()->getIDocumentContentOperations().DelFullPara( aBefore );
        }
    }
    else if (pXSection && pXSection->GetFormat() &&
            pXSection->GetFormat()->GetDoc() == GetDoc())
    {
        SwSectionFormat *const pSectFormat = pXSection->GetFormat();
        SwSectionNode *const pSectNode = pSectFormat->GetSectionNode();

        const SwNodeIndex aSectIdx(  *pSectNode, -1 );
        if(aSectIdx.GetNode().IsTextNode())
        {
            SwPaM aBefore(aSectIdx);
            bRet = GetDoc()->getIDocumentContentOperations().DelFullPara( aBefore );
        }
    }
    if(!bRet)
    {
        throw lang::IllegalArgumentException();
    }
}

void SAL_CALL
SwXText::removeTextContentAfter(
        const uno::Reference< text::XTextContent>& xPredecessor)
{
    SolarMutexGuard aGuard;

    if(!GetDoc())
    {
        uno::RuntimeException aRuntime;
        aRuntime.Message = cInvalidObject;
        throw aRuntime;
    }

    bool bRet = false;
    const uno::Reference<lang::XUnoTunnel> xPredTunnel(xPredecessor,
            uno::UNO_QUERY);
    SwXTextSection *const pXSection =
            ::sw::UnoTunnelGetImplementation<SwXTextSection>(xPredTunnel);
    SwXTextTable *const pXTable =
            ::sw::UnoTunnelGetImplementation<SwXTextTable>(xPredTunnel);
    SwFrameFormat *const pTableFormat = pXTable ? pXTable->GetFrameFormat() : nullptr;
    if(pTableFormat && pTableFormat->GetDoc() == GetDoc())
    {
        SwTable *const pTable = SwTable::FindTable( pTableFormat );
        SwTableNode *const pTableNode = pTable->GetTableNode();
        SwEndNode *const pTableEnd = pTableNode->EndOfSectionNode();

        const SwNodeIndex aTableIdx( *pTableEnd, 1 );
        if(aTableIdx.GetNode().IsTextNode())
        {
            SwPaM aPaM(aTableIdx);
            bRet = GetDoc()->getIDocumentContentOperations().DelFullPara( aPaM );
        }
    }
    else if (pXSection && pXSection->GetFormat() &&
            pXSection->GetFormat()->GetDoc() == GetDoc())
    {
        SwSectionFormat *const pSectFormat = pXSection->GetFormat();
        SwSectionNode *const pSectNode = pSectFormat->GetSectionNode();
        SwEndNode *const pEnd = pSectNode->EndOfSectionNode();
        const SwNodeIndex aSectIdx(  *pEnd, 1 );
        if(aSectIdx.GetNode().IsTextNode())
        {
            SwPaM aAfter(aSectIdx);
            bRet = GetDoc()->getIDocumentContentOperations().DelFullPara( aAfter );
        }
    }
    if(!bRet)
    {
        throw lang::IllegalArgumentException();
    }
}

void SAL_CALL
SwXText::removeTextContent(
        const uno::Reference< text::XTextContent > & xContent)
{
    // forward: need no solar mutex here
    if(!xContent.is())
    {
        uno::RuntimeException aRuntime;
        aRuntime.Message = "first parameter invalid";
        throw aRuntime;
    }
    xContent->dispose();
}

uno::Reference< text::XText > SAL_CALL
SwXText::getText()
{
    SolarMutexGuard aGuard;
    comphelper::ProfileZone aZone("SwXText::getText");

    const uno::Reference< text::XText > xRet(this);
    return xRet;
}

uno::Reference< text::XTextRange > SAL_CALL
SwXText::getStart()
{
    SolarMutexGuard aGuard;

    const uno::Reference< text::XTextCursor > xRef = CreateCursor();
    if(!xRef.is())
    {
        uno::RuntimeException aRuntime;
        aRuntime.Message = cInvalidObject;
        throw aRuntime;
    }
    xRef->gotoStart(false);
    return xRef;
}

uno::Reference< text::XTextRange > SAL_CALL
SwXText::getEnd()
{
    SolarMutexGuard aGuard;

    const uno::Reference< text::XTextCursor > xRef = CreateCursor();
    if(!xRef.is())
    {
        uno::RuntimeException aRuntime;
        aRuntime.Message = cInvalidObject;
        throw aRuntime;
    }
    xRef->gotoEnd(false);
    return xRef;
}

OUString SAL_CALL SwXText::getString()
{
    SolarMutexGuard aGuard;

    const uno::Reference< text::XTextCursor > xRet = CreateCursor();
    if(!xRet.is())
    {
        SAL_WARN("sw.uno", "cursor was not created in getString() call. Returning empty string.");
        return OUString();
    }
    xRet->gotoEnd(true);
    return xRet->getString();
}

void SAL_CALL
SwXText::setString(const OUString& rString)
{
    SolarMutexGuard aGuard;

    if (!GetDoc())
    {
        uno::RuntimeException aRuntime;
        aRuntime.Message = cInvalidObject;
        throw aRuntime;
    }

    const SwStartNode* pStartNode = GetStartNode();
    if (!pStartNode)
    {
        throw uno::RuntimeException();
    }

    GetDoc()->GetIDocumentUndoRedo().StartUndo(SwUndoId::START, nullptr);
    //insert an empty paragraph at the start and at the end to ensure that
    //all tables and sections can be removed by the selecting text::XTextCursor
    if (CursorType::Meta != m_pImpl->m_eType)
    {
        SwPosition aStartPos(*pStartNode);
        const SwEndNode* pEnd = pStartNode->EndOfSectionNode();
        SwNodeIndex aEndIdx(*pEnd);
        --aEndIdx;
        //the inserting of nodes should only be done if really necessary
        //to prevent #97924# (removes paragraph attributes when setting the text
        //e.g. of a table cell
        bool bInsertNodes = false;
        SwNodeIndex aStartIdx(*pStartNode);
        do
        {
            ++aStartIdx;
            SwNode& rCurrentNode = aStartIdx.GetNode();
            if(rCurrentNode.GetNodeType() == SwNodeType::Section
                ||rCurrentNode.GetNodeType() == SwNodeType::Table)
            {
                bInsertNodes = true;
                break;
            }
        }
        while(aStartIdx < aEndIdx);
        if(bInsertNodes)
        {
            GetDoc()->getIDocumentContentOperations().AppendTextNode( aStartPos );
            SwPosition aEndPos(aEndIdx.GetNode());
            SwPaM aPam(aEndPos);
            GetDoc()->getIDocumentContentOperations().AppendTextNode( *aPam.Start() );
        }
    }

    const uno::Reference< text::XTextCursor > xRet = CreateCursor();
    if(!xRet.is())
    {
        GetDoc()->GetIDocumentUndoRedo().EndUndo(SwUndoId::END, nullptr);
        uno::RuntimeException aRuntime;
        aRuntime.Message = cInvalidObject;
        throw aRuntime;
    }
    xRet->gotoEnd(true);
    xRet->setString(rString);
    GetDoc()->GetIDocumentUndoRedo().EndUndo(SwUndoId::END, nullptr);
}

//FIXME why is CheckForOwnMember duplicated in some insert methods?
//  Description: Checks if pRange/pCursor are member of the same text interface.
//              Only one of the pointers has to be set!
bool SwXText::Impl::CheckForOwnMember(
    const SwPaM & rPaM)
{
    const uno::Reference<text::XTextCursor> xOwnCursor(m_rThis.CreateCursor());

    OTextCursorHelper *const pOwnCursor =
            comphelper::getUnoTunnelImplementation<OTextCursorHelper>(xOwnCursor);
    OSL_ENSURE(pOwnCursor, "OTextCursorHelper::getUnoTunnelId() ??? ");
    const SwStartNode* pOwnStartNode =
        pOwnCursor->GetPaM()->GetNode().StartOfSectionNode();
    SwStartNodeType eSearchNodeType = SwNormalStartNode;
    switch (m_eType)
    {
        case CursorType::Frame:      eSearchNodeType = SwFlyStartNode;       break;
        case CursorType::TableText:    eSearchNodeType = SwTableBoxStartNode;  break;
        case CursorType::Footnote:   eSearchNodeType = SwFootnoteStartNode;  break;
        case CursorType::Header:     eSearchNodeType = SwHeaderStartNode;    break;
        case CursorType::Footer:     eSearchNodeType = SwFooterStartNode;    break;
        //case CURSOR_INVALID:
        //case CursorType::Body:
        default:
            ;
    }

    const SwNode& rSrcNode = rPaM.GetNode();
    const SwStartNode* pTmp = rSrcNode.FindSttNodeByType(eSearchNodeType);

    // skip SectionNodes / TableNodes to be able to compare across table/section boundaries
    while (pTmp
           && (pTmp->IsSectionNode() || pTmp->IsTableNode()
               || (m_eType != CursorType::TableText
                   && pTmp->GetStartNodeType() == SwTableBoxStartNode)))
    {
        pTmp = pTmp->StartOfSectionNode();
    }

    while (pOwnStartNode->IsSectionNode() || pOwnStartNode->IsTableNode()
           || (m_eType != CursorType::TableText
               && pOwnStartNode->GetStartNodeType() == SwTableBoxStartNode))
    {
        pOwnStartNode = pOwnStartNode->StartOfSectionNode();
    }

    //this checks if (this) and xRange are in the same text::XText interface
    return (pOwnStartNode == pTmp);
}

sal_Int16
SwXText::Impl::ComparePositions(
    const uno::Reference<text::XTextRange>& xPos1,
    const uno::Reference<text::XTextRange>& xPos2)
{
    SwUnoInternalPaM aPam1(*m_pDoc);
    SwUnoInternalPaM aPam2(*m_pDoc);

    if (!::sw::XTextRangeToSwPaM(aPam1, xPos1) ||
        !::sw::XTextRangeToSwPaM(aPam2, xPos2))
    {
        throw lang::IllegalArgumentException();
    }
    if (!CheckForOwnMember(aPam1) || !CheckForOwnMember(aPam2))
    {
        throw lang::IllegalArgumentException();
    }

    sal_Int16 nCompare = 0;
    SwPosition const*const pStart1 = aPam1.Start();
    SwPosition const*const pStart2 = aPam2.Start();
    if (*pStart1 < *pStart2)
    {
        nCompare = 1;
    }
    else if (*pStart1 > *pStart2)
    {
        nCompare = -1;
    }
    else
    {
        OSL_ENSURE(*pStart1 == *pStart2,
                "SwPositions should be equal here");
        nCompare = 0;
    }

    return nCompare;
}

sal_Int16 SAL_CALL
SwXText::compareRegionStarts(
    const uno::Reference<text::XTextRange>& xRange1,
    const uno::Reference<text::XTextRange>& xRange2)
{
    SolarMutexGuard aGuard;

    if (!xRange1.is() || !xRange2.is())
    {
        throw lang::IllegalArgumentException();
    }
    const uno::Reference<text::XTextRange> xStart1 = xRange1->getStart();
    const uno::Reference<text::XTextRange> xStart2 = xRange2->getStart();

    return m_pImpl->ComparePositions(xStart1, xStart2);
}

sal_Int16 SAL_CALL
SwXText::compareRegionEnds(
    const uno::Reference<text::XTextRange>& xRange1,
    const uno::Reference<text::XTextRange>& xRange2)
{
    SolarMutexGuard aGuard;

    if (!xRange1.is() || !xRange2.is())
    {
        throw lang::IllegalArgumentException();
    }
    uno::Reference<text::XTextRange> xEnd1 = xRange1->getEnd();
    uno::Reference<text::XTextRange> xEnd2 = xRange2->getEnd();

    return m_pImpl->ComparePositions(xEnd1, xEnd2);
}

uno::Reference< beans::XPropertySetInfo > SAL_CALL
SwXText::getPropertySetInfo()
{
    SolarMutexGuard g;

    static uno::Reference< beans::XPropertySetInfo > xInfo =
        m_pImpl->m_rPropSet.getPropertySetInfo();
    return xInfo;
}

void SAL_CALL
SwXText::setPropertyValue(const OUString& /*aPropertyName*/,
        const uno::Any& /*aValue*/)
{
    throw lang::IllegalArgumentException();
}

uno::Any SAL_CALL
SwXText::getPropertyValue(
    const OUString& rPropertyName)
{
    SolarMutexGuard aGuard;

    if(!IsValid())
    {
        throw  uno::RuntimeException();
    }

    SfxItemPropertySimpleEntry const*const pEntry =
        m_pImpl->m_rPropSet.getPropertyMap().getByName(rPropertyName);
    if (!pEntry)
    {
        beans::UnknownPropertyException aExcept;
        aExcept.Message = "Unknown property: " + rPropertyName;
        throw aExcept;
    }

    uno::Any aRet;
    switch (pEntry->nWID)
    {
//          no code necessary - the redline is always located at the end node
//            case FN_UNO_REDLINE_NODE_START:
//            break;
        case FN_UNO_REDLINE_NODE_END:
        {
            const SwRedlineTable& rRedTable = GetDoc()->getIDocumentRedlineAccess().GetRedlineTable();
            const size_t nRedTableCount = rRedTable.size();
            if (nRedTableCount > 0)
            {
                SwStartNode const*const pStartNode = GetStartNode();
                const sal_uLong nOwnIndex = pStartNode->EndOfSectionIndex();
                for (size_t nRed = 0; nRed < nRedTableCount; ++nRed)
                {
                    SwRangeRedline const*const pRedline = rRedTable[nRed];
                    SwPosition const*const pRedStart = pRedline->Start();
                    const SwNodeIndex nRedNode = pRedStart->nNode;
                    if (nOwnIndex == nRedNode.GetIndex())
                    {
                        aRet <<= SwXRedlinePortion::CreateRedlineProperties(
                                *pRedline, true);
                        break;
                    }
                }
            }
        }
        break;
    }
    return aRet;
}

void SAL_CALL
SwXText::addPropertyChangeListener(
        const OUString& /*rPropertyName*/,
        const uno::Reference< beans::XPropertyChangeListener >& /*xListener*/)
{
    OSL_FAIL("SwXText::addPropertyChangeListener(): not implemented");
}

void SAL_CALL
SwXText::removePropertyChangeListener(
        const OUString& /*rPropertyName*/,
        const uno::Reference< beans::XPropertyChangeListener >& /*xListener*/)
{
    OSL_FAIL("SwXText::removePropertyChangeListener(): not implemented");
}

void SAL_CALL
SwXText::addVetoableChangeListener(
        const OUString& /*rPropertyName*/,
        const uno::Reference< beans::XVetoableChangeListener >& /*xListener*/)
{
    OSL_FAIL("SwXText::addVetoableChangeListener(): not implemented");
}

void SAL_CALL
SwXText::removeVetoableChangeListener(
        const OUString& /*rPropertyName*/,
        const uno::Reference< beans::XVetoableChangeListener >& /*xListener*/)
{
    OSL_FAIL("SwXText::removeVetoableChangeListener(): not implemented");
}

namespace
{
    class theSwXTextUnoTunnelId : public rtl::Static< UnoTunnelIdInit, theSwXTextUnoTunnelId > {};
}

const uno::Sequence< sal_Int8 > & SwXText::getUnoTunnelId()
{
    return theSwXTextUnoTunnelId::get().getSeq();
}

sal_Int64 SAL_CALL
SwXText::getSomething(const uno::Sequence< sal_Int8 >& rId)
{
    return ::sw::UnoTunnelImpl<SwXText>(rId, this);
}

uno::Reference< text::XTextRange > SAL_CALL
SwXText::finishParagraph(
        const uno::Sequence< beans::PropertyValue > & rProperties)
{
    SolarMutexGuard g;

    return m_pImpl->finishOrAppendParagraph(rProperties, uno::Reference< text::XTextRange >());
}

uno::Reference< text::XTextRange > SAL_CALL
SwXText::finishParagraphInsert(
        const uno::Sequence< beans::PropertyValue > & rProperties,
        const uno::Reference< text::XTextRange >& xInsertPosition)
{
    SolarMutexGuard g;

    return m_pImpl->finishOrAppendParagraph(rProperties, xInsertPosition);
}

uno::Reference< text::XTextRange >
SwXText::Impl::finishOrAppendParagraph(
        const uno::Sequence< beans::PropertyValue > & rProperties,
        const uno::Reference< text::XTextRange >& xInsertPosition)
{
    if (!m_bIsValid)
    {
        throw  uno::RuntimeException();
    }

    const SwStartNode* pStartNode = m_rThis.GetStartNode();
    if(!pStartNode)
    {
        throw  uno::RuntimeException();
    }

    uno::Reference< text::XTextRange > xRet;
    bool bIllegalException = false;
    bool bRuntimeException = false;
    OUString sMessage;
    m_pDoc->GetIDocumentUndoRedo().StartUndo(SwUndoId::START , nullptr);
    // find end node, go backward - don't skip tables because the new
    // paragraph has to be the last node
    //aPam.Move( fnMoveBackward, GoInNode );
    SwPosition aInsertPosition(
            SwNodeIndex( *pStartNode->EndOfSectionNode(), -1 ) );
    SwPaM aPam(aInsertPosition);
    // If we got a position reference, then the insert point is not the end of
    // the document.
    if (xInsertPosition.is())
    {
        SwUnoInternalPaM aStartPam(*m_rThis.GetDoc());
        ::sw::XTextRangeToSwPaM(aStartPam, xInsertPosition);
        aPam = aStartPam;
        aPam.SetMark();
    }
    m_pDoc->getIDocumentContentOperations().AppendTextNode( *aPam.GetPoint() );
    // remove attributes from the previous paragraph
    m_pDoc->ResetAttrs(aPam);
    // in case of finishParagraph the PaM needs to be moved to the
    // previous paragraph
    aPam.Move( fnMoveBackward, GoInNode );

    try
    {
        SfxItemPropertySet const*const pParaPropSet =
            aSwMapProvider.GetPropertySet(PROPERTY_MAP_PARAGRAPH);

        SwUnoCursorHelper::SetPropertyValues(aPam, *pParaPropSet, rProperties);

        // tdf#127616 keep direct character formatting of empty paragraphs,
        // if character style of the paragraph sets also the same attributes
        if (aPam.Start()->nNode.GetNode().GetTextNode()->Len() == 0)
        {
            auto itCharStyle = std::find_if(rProperties.begin(), rProperties.end(), [](const beans::PropertyValue& rValue)
            {
                return rValue.Name == "CharStyleName";
            });
            if ( itCharStyle != rProperties.end() )
            {
                for (const auto& rValue : rProperties)
                {
                    if ( rValue != *itCharStyle && rValue.Name.startsWith("Char") )
                    {
                        SwUnoCursorHelper::SetPropertyValue(aPam, *pParaPropSet, rValue.Name, rValue.Value);
                    }
                }
            }
        }
    }
    catch (const lang::IllegalArgumentException& rIllegal)
    {
        sMessage = rIllegal.Message;
        bIllegalException = true;
    }
    catch (const uno::RuntimeException& rRuntime)
    {
        sMessage = rRuntime.Message;
        bRuntimeException = true;
    }
    catch (const uno::Exception& rEx)
    {
        sMessage = rEx.Message;
        bRuntimeException = true;
    }

    m_pDoc->GetIDocumentUndoRedo().EndUndo(SwUndoId::END, nullptr);
    if (bIllegalException || bRuntimeException)
    {
        m_pDoc->GetIDocumentUndoRedo().Undo();
        if (bIllegalException)
        {
            lang::IllegalArgumentException aEx;
            aEx.Message = sMessage;
            throw aEx;
        }
        else
        {
            uno::RuntimeException aEx;
            aEx.Message = sMessage;
            throw aEx;
        }
    }
    SwTextNode *const pTextNode( aPam.Start()->nNode.GetNode().GetTextNode() );
    OSL_ENSURE(pTextNode, "no SwTextNode?");
    if (pTextNode)
    {
        xRet.set(SwXParagraph::CreateXParagraph(*m_pDoc, pTextNode, &m_rThis),
                uno::UNO_QUERY);
    }

    return xRet;
}

uno::Reference< text::XTextRange > SAL_CALL
SwXText::insertTextPortion(
        const OUString& rText,
        const uno::Sequence< beans::PropertyValue > &
            rCharacterAndParagraphProperties,
        const uno::Reference<text::XTextRange>& xInsertPosition)
{
    SolarMutexGuard aGuard;

    if(!IsValid())
    {
        throw  uno::RuntimeException();
    }
    uno::Reference< text::XTextRange > xRet;
    const uno::Reference< text::XTextCursor > xTextCursor = CreateCursor();
    xTextCursor->gotoRange(xInsertPosition, false);

    const uno::Reference< lang::XUnoTunnel > xRangeTunnel(
            xTextCursor, uno::UNO_QUERY_THROW );
    SwXTextCursor *const pTextCursor =
        ::sw::UnoTunnelGetImplementation<SwXTextCursor>(xRangeTunnel);

    bool bIllegalException = false;
    bool bRuntimeException = false;
    OUString sMessage;
    m_pImpl->m_pDoc->GetIDocumentUndoRedo().StartUndo(SwUndoId::INSERT, nullptr);

    auto& rCursor(pTextCursor->GetCursor());
    m_pImpl->m_pDoc->DontExpandFormat( *rCursor.Start() );

    if (!rText.isEmpty())
    {
        SwNodeIndex const nodeIndex(rCursor.GetPoint()->nNode, -1);
        const sal_Int32 nContentPos = rCursor.GetPoint()->nContent.GetIndex();
        SwUnoCursorHelper::DocInsertStringSplitCR(
            *m_pImpl->m_pDoc, rCursor, rText, false);
        SwUnoCursorHelper::SelectPam(rCursor, true);
        rCursor.GetPoint()->nNode.Assign(nodeIndex.GetNode(), +1);
        rCursor.GetPoint()->nContent = nContentPos;
    }

    try
    {
      SfxItemPropertySet const*const pCursorPropSet =
          aSwMapProvider.GetPropertySet(PROPERTY_MAP_TEXT_CURSOR);
      SwUnoCursorHelper::SetPropertyValues(rCursor, *pCursorPropSet,
                                           rCharacterAndParagraphProperties,
                                           SetAttrMode::NOFORMATATTR);
    }
    catch (const lang::IllegalArgumentException& rIllegal)
    {
        sMessage = rIllegal.Message;
        bIllegalException = true;
    }
    catch (const uno::RuntimeException& rRuntime)
    {
        sMessage = rRuntime.Message;
        bRuntimeException = true;
    }
    m_pImpl->m_pDoc->GetIDocumentUndoRedo().EndUndo(SwUndoId::INSERT, nullptr);
    if (bIllegalException || bRuntimeException)
    {
        m_pImpl->m_pDoc->GetIDocumentUndoRedo().Undo();
        if (bIllegalException)
        {
            lang::IllegalArgumentException aEx;
            aEx.Message = sMessage;
            throw aEx;
        }
        else
        {
            uno::RuntimeException aEx;
            aEx.Message = sMessage;
            throw aEx;
        }
    }
    xRet = new SwXTextRange(rCursor, this);
    return xRet;
}

// Append text portions at the end of the last paragraph of the text interface.
// Support of import filters.
uno::Reference< text::XTextRange > SAL_CALL
SwXText::appendTextPortion(
        const OUString& rText,
        const uno::Sequence< beans::PropertyValue > &
            rCharacterAndParagraphProperties)
{
    // Right now this doesn't need a guard, as it's just calling the insert
    // version, that has it already.
    uno::Reference<text::XTextRange> xInsertPosition = getEnd();
    return insertTextPortion(rText, rCharacterAndParagraphProperties, xInsertPosition);
}

// enable inserting/appending text contents like graphic objects, shapes and so on to
// support import filters
uno::Reference< text::XTextRange > SAL_CALL
SwXText::insertTextContentWithProperties(
    const uno::Reference< text::XTextContent >& xTextContent,
    const uno::Sequence< beans::PropertyValue >&
        rCharacterAndParagraphProperties,
    const uno::Reference< text::XTextRange >& xInsertPosition)
{
    SolarMutexGuard aGuard;

    if (!IsValid())
    {
        throw  uno::RuntimeException();
    }

    SwUnoInternalPaM aPam(*GetDoc());
    if (!::sw::XTextRangeToSwPaM(aPam, xInsertPosition))
    {
        throw lang::IllegalArgumentException("invalid position", nullptr, 2);
    }

    SwRewriter aRewriter;
    aRewriter.AddRule(UndoArg1, SwResId(STR_UNDO_INSERT_TEXTBOX));

    m_pImpl->m_pDoc->GetIDocumentUndoRedo().StartUndo(SwUndoId::INSERT, &aRewriter);

    // Any direct formatting ending at the insert position (xRange) should not
    // be expanded to cover the inserted content (xContent)
    // (insertTextContent() shouldn't do this, only ...WithProperties()!)
    GetDoc()->DontExpandFormat( *aPam.Start() );

    // now attach the text content here
    insertTextContent( xInsertPosition, xTextContent, false );
    // now apply the properties to the anchor
    if (rCharacterAndParagraphProperties.hasElements())
    {
        try
        {
            const uno::Reference< beans::XPropertySet > xAnchor(
                xTextContent->getAnchor(), uno::UNO_QUERY);
            if (xAnchor.is())
            {
                for (const auto& rProperty : rCharacterAndParagraphProperties)
                {
                    xAnchor->setPropertyValue(rProperty.Name, rProperty.Value);
                }
            }
        }
        catch (const uno::Exception& e)
        {
            css::uno::Any anyEx = cppu::getCaughtException();
            m_pImpl->m_pDoc->GetIDocumentUndoRedo().EndUndo(SwUndoId::INSERT, &aRewriter);
            throw lang::WrappedTargetRuntimeException( e.Message,
                            uno::Reference< uno::XInterface >(), anyEx );
        }
    }
    m_pImpl->m_pDoc->GetIDocumentUndoRedo().EndUndo(SwUndoId::INSERT, &aRewriter);
    return xInsertPosition;
}

uno::Reference< text::XTextRange > SAL_CALL
SwXText::appendTextContent(
    const uno::Reference< text::XTextContent >& xTextContent,
    const uno::Sequence< beans::PropertyValue >& rCharacterAndParagraphProperties
    )
{
    // Right now this doesn't need a guard, as it's just calling the insert
    // version, that has it already.
    uno::Reference<text::XTextRange> xInsertPosition = getEnd();
    return insertTextContentWithProperties(xTextContent, rCharacterAndParagraphProperties, xInsertPosition);
}

// determine whether SwFrameFormat is a graphic node
static bool isGraphicNode(const SwFrameFormat* pFrameFormat)
{
    // safety
    if( !pFrameFormat->GetContent().GetContentIdx() )
    {
        return false;
    }
    auto index = *pFrameFormat->GetContent().GetContentIdx();
    // consider the next node -> there is the graphic stored
    index++;
    return index.GetNode().IsGrfNode();
}

// move previously appended paragraphs into a text frames
// to support import filters
uno::Reference< text::XTextContent > SAL_CALL
SwXText::convertToTextFrame(
    const uno::Reference< text::XTextRange >& xStart,
    const uno::Reference< text::XTextRange >& xEnd,
    const uno::Sequence< beans::PropertyValue >& rFrameProperties)
{
    SolarMutexGuard aGuard;

    if(!IsValid())
    {
        throw  uno::RuntimeException();
    }
    uno::Reference< text::XTextContent > xRet;
    std::unique_ptr<SwUnoInternalPaM> pTempStartPam(new SwUnoInternalPaM(*GetDoc()));
    std::unique_ptr< SwUnoInternalPaM > pEndPam(new SwUnoInternalPaM(*GetDoc()));
    if (!::sw::XTextRangeToSwPaM(*pTempStartPam, xStart) ||
        !::sw::XTextRangeToSwPaM(*pEndPam, xEnd))
    {
        throw lang::IllegalArgumentException();
    }
    auto pStartPam(GetDoc()->CreateUnoCursor(*pTempStartPam->GetPoint()));
    if (pTempStartPam->HasMark())
    {
        pStartPam->SetMark();
        *pStartPam->GetMark() = *pTempStartPam->GetMark();
    }
    pTempStartPam.reset();

    SwXTextRange *const pStartRange =
        comphelper::getUnoTunnelImplementation<SwXTextRange>(xStart);
    SwXTextRange *const pEndRange   =
        comphelper::getUnoTunnelImplementation<SwXTextRange>(xEnd);
    // bookmarks have to be removed before the referenced text node
    // is deleted in DelFullPara
    if (pStartRange)
    {
        pStartRange->Invalidate();
    }
    if (pEndRange)
    {
        pEndRange->Invalidate();
    }

    m_pImpl->m_pDoc->GetIDocumentUndoRedo().StartUndo( SwUndoId::START, nullptr );
    bool bIllegalException = false;
    bool bRuntimeException = false;
    OUString sMessage;
    SwStartNode* pStartStartNode = pStartPam->GetNode().StartOfSectionNode();
    while (pStartStartNode && pStartStartNode->IsSectionNode())
    {
        pStartStartNode = pStartStartNode->StartOfSectionNode();
    }
    SwStartNode* pEndStartNode = pEndPam->GetNode().StartOfSectionNode();
    while (pEndStartNode && pEndStartNode->IsSectionNode())
    {
        pEndStartNode = pEndStartNode->StartOfSectionNode();
    }
    bool bParaAfterInserted = false;
    bool bParaBeforeInserted = false;
    if (
        pStartStartNode && pEndStartNode &&
        (pStartStartNode != pEndStartNode || pStartStartNode != GetStartNode())
       )
    {
        // todo: if the start/end is in a table then insert a paragraph
        // before/after, move the start/end nodes, then convert and
        // remove the additional paragraphs in the end
        SwTableNode * pStartTableNode(nullptr);
        if (pStartStartNode->GetStartNodeType() == SwTableBoxStartNode)
        {
            pStartTableNode = pStartStartNode->FindTableNode();
            // Is it the same table start node than the end?
            SwTableNode *const pEndStartTableNode(pEndStartNode->FindTableNode());
            while (pEndStartTableNode && pStartTableNode &&
                   pEndStartTableNode->GetIndex() < pStartTableNode->GetIndex())
            {
                SwStartNode* pStartStartTableNode = pStartTableNode->StartOfSectionNode();
                pStartTableNode = pStartStartTableNode->FindTableNode();
            }
        }
        if (pStartTableNode)
        {
            const SwNodeIndex aTableIdx(  *pStartTableNode, -1 );
            SwPosition aBefore(aTableIdx);
            bParaBeforeInserted = GetDoc()->getIDocumentContentOperations().AppendTextNode( aBefore );
            pStartPam->DeleteMark();
            *pStartPam->GetPoint() = aBefore;
            pStartStartNode = pStartPam->GetNode().StartOfSectionNode();
        }
        if (pEndStartNode->GetStartNodeType() == SwTableBoxStartNode)
        {
            SwTableNode *const pEndTableNode = pEndStartNode->FindTableNode();
            SwEndNode *const pTableEnd = pEndTableNode->EndOfSectionNode();
            SwPosition aTableEnd(*pTableEnd);
            bParaAfterInserted = GetDoc()->getIDocumentContentOperations().AppendTextNode( aTableEnd );
            pEndPam->DeleteMark();
            *pEndPam->GetPoint() = aTableEnd;
            pEndStartNode = pEndPam->GetNode().StartOfSectionNode();
        }
        // now we should have the positions in the same hierarchy
        if ((pStartStartNode != pEndStartNode) ||
            (pStartStartNode != GetStartNode()))
        {
            // if not - remove the additional paragraphs and throw
            if (bParaBeforeInserted)
            {
                SwCursor aDelete(*pStartPam->GetPoint(), nullptr);
                *pStartPam->GetPoint() = // park it because node is deleted
                    SwPosition(GetDoc()->GetNodes().GetEndOfContent());
                aDelete.MovePara(GoCurrPara, fnParaStart);
                aDelete.SetMark();
                aDelete.MovePara(GoCurrPara, fnParaEnd);
                GetDoc()->getIDocumentContentOperations().DelFullPara(aDelete);
            }
            if (bParaAfterInserted)
            {
                SwCursor aDelete(*pEndPam->GetPoint(), nullptr);
                *pEndPam->GetPoint() = // park it because node is deleted
                    SwPosition(GetDoc()->GetNodes().GetEndOfContent());
                aDelete.MovePara(GoCurrPara, fnParaStart);
                aDelete.SetMark();
                aDelete.MovePara(GoCurrPara, fnParaEnd);
                GetDoc()->getIDocumentContentOperations().DelFullPara(aDelete);
            }
            throw lang::IllegalArgumentException();
        }
    }

    // make a selection from pStartPam to pEndPam
    // If there is no content in the frame the shape is in
    // it gets deleted in the DelFullPara call below,
    // In this case insert a tmp text node ( we delete it later )
    if (pStartPam->Start()->nNode == pEndPam->Start()->nNode
        && pStartPam->End()->nNode == pEndPam->End()->nNode)
    {
        SwPosition aEnd(*pStartPam->End());
        bParaAfterInserted = GetDoc()->getIDocumentContentOperations().AppendTextNode( aEnd );
        pEndPam->DeleteMark();
        *pEndPam->GetPoint() = aEnd;
    }
    pStartPam->SetMark();
    *pStartPam->End() = *pEndPam->End();
    pEndPam.reset();

    // see if there are frames already anchored to this node
    // we have to work with the SdrObjects, as unique name is not guaranteed in their frame format
    // tdf#115094: do nothing if we have a graphic node
    o3tl::sorted_vector<const SdrObject*> aAnchoredObjectsByPtr;
    std::set<OUString> aAnchoredObjectsByName;
    for (size_t i = 0; i < m_pImpl->m_pDoc->GetSpzFrameFormats()->size(); ++i)
    {
        const SwFrameFormat* pFrameFormat = (*m_pImpl->m_pDoc->GetSpzFrameFormats())[i];
        const SwFormatAnchor& rAnchor = pFrameFormat->GetAnchor();
        if ( !isGraphicNode(pFrameFormat) &&
                (RndStdIds::FLY_AT_PARA == rAnchor.GetAnchorId() || RndStdIds::FLY_AT_CHAR == rAnchor.GetAnchorId()) &&
                pStartPam->Start()->nNode.GetIndex() <= rAnchor.GetContentAnchor()->nNode.GetIndex() &&
                pStartPam->End()->nNode.GetIndex() >= rAnchor.GetContentAnchor()->nNode.GetIndex())
        {
            if (pFrameFormat->GetName().isEmpty())
            {
                aAnchoredObjectsByPtr.insert(pFrameFormat->FindSdrObject());
            }
            else
            {
                aAnchoredObjectsByName.insert(pFrameFormat->GetName());
            }
        }
    }

    const uno::Reference<text::XTextFrame> xNewFrame(
            SwXTextFrame::CreateXTextFrame(*m_pImpl->m_pDoc, nullptr));
    SwXTextFrame& rNewFrame = dynamic_cast<SwXTextFrame&>(*xNewFrame);
    try
    {
        for (const beans::PropertyValue& rValue : rFrameProperties)
        {
            rNewFrame.SwXFrame::setPropertyValue(rValue.Name, rValue.Value);
        }

        {   // has to be in a block to remove the SwIndexes before
            // DelFullPara is called
            const uno::Reference< text::XTextRange> xInsertTextRange =
                new SwXTextRange(*pStartPam, this);
            assert(rNewFrame.IsDescriptor());
            rNewFrame.attachToRange(xInsertTextRange, pStartPam.get());
            rNewFrame.setName(m_pImpl->m_pDoc->GetUniqueFrameName());
        }

        SwTextNode *const pTextNode(pStartPam->GetNode().GetTextNode());
        assert(pTextNode);
        if (!pTextNode || !pTextNode->Len()) // don't remove if it contains text!
        {
            {   // has to be in a block to remove the SwIndexes before
                // DelFullPara is called
                SwPaM aMovePam( pStartPam->GetNode() );
                if (aMovePam.Move( fnMoveForward, GoInContent ))
                {
                    // move the anchor to the next paragraph
                    SwFormatAnchor aNewAnchor(rNewFrame.GetFrameFormat()->GetAnchor());
                    aNewAnchor.SetAnchor( aMovePam.Start() );
                    m_pImpl->m_pDoc->SetAttr(
                        aNewAnchor, *rNewFrame.GetFrameFormat() );

                    // also move frames anchored to us
                    for (size_t i = 0; i < m_pImpl->m_pDoc->GetSpzFrameFormats()->size(); ++i)
                    {
                        SwFrameFormat* pFrameFormat = (*m_pImpl->m_pDoc->GetSpzFrameFormats())[i];
                        if ((!pFrameFormat->GetName().isEmpty() && aAnchoredObjectsByName.find(pFrameFormat->GetName()) != aAnchoredObjectsByName.end() ) ||
                            ( pFrameFormat->GetName().isEmpty() && aAnchoredObjectsByPtr.find(pFrameFormat->FindSdrObject()) != aAnchoredObjectsByPtr.end()) )
                        {
                            // copy the anchor to the next paragraph
                            SwFormatAnchor aAnchor(pFrameFormat->GetAnchor());
                            aAnchor.SetAnchor(aMovePam.Start());
                            m_pImpl->m_pDoc->SetAttr(aAnchor, *pFrameFormat);
                        }
                    }
                }
            }
            m_pImpl->m_pDoc->getIDocumentContentOperations().DelFullPara(*pStartPam);
        }
    }
    catch (const lang::IllegalArgumentException& rIllegal)
    {
        sMessage = rIllegal.Message;
        bIllegalException = true;
    }
    catch (const uno::RuntimeException& rRuntime)
    {
        sMessage = rRuntime.Message;
        bRuntimeException = true;
    }
    xRet = xNewFrame;
    if (bParaBeforeInserted || bParaAfterInserted)
    {
        const uno::Reference<text::XTextCursor> xFrameTextCursor =
            rNewFrame.createTextCursor();
        SwXTextCursor *const pFrameCursor =
            comphelper::getUnoTunnelImplementation<SwXTextCursor>(xFrameTextCursor);
        if (bParaBeforeInserted)
        {
            // todo: remove paragraph before frame
            m_pImpl->m_pDoc->getIDocumentContentOperations().DelFullPara(*pFrameCursor->GetPaM());
        }
        if (bParaAfterInserted)
        {
            xFrameTextCursor->gotoEnd(false);
            if (!bParaBeforeInserted)
                m_pImpl->m_pDoc->getIDocumentContentOperations().DelFullPara(*pFrameCursor->GetPaM());
            else
            {
                // In case the frame has a table only, the cursor points to the end of the first cell of the table.
                SwPaM aPaM(*pFrameCursor->GetPaM()->GetNode().FindSttNodeByType(SwFlyStartNode)->EndOfSectionNode());
                // Now we have the end of the frame -- the node before that will be the paragraph we want to remove.
                --aPaM.GetPoint()->nNode;
                m_pImpl->m_pDoc->getIDocumentContentOperations().DelFullPara(aPaM);
            }
        }
    }

    m_pImpl->m_pDoc->GetIDocumentUndoRedo().EndUndo(SwUndoId::END, nullptr);
    if (bIllegalException || bRuntimeException)
    {
        m_pImpl->m_pDoc->GetIDocumentUndoRedo().Undo();
        if (bIllegalException)
        {
            lang::IllegalArgumentException aEx;
            aEx.Message = sMessage;
            throw aEx;
        }
        else
        {
            uno::RuntimeException aEx;
            aEx.Message = sMessage;
            throw aEx;
        }
    }
    return xRet;
}

namespace {

// Move previously imported paragraphs into a new text table.
struct VerticallyMergedCell
{
    std::vector<uno::Reference< beans::XPropertySet > > aCells;
    sal_Int32                                           nLeftPosition;
    bool                                                bOpen;

    VerticallyMergedCell(uno::Reference< beans::XPropertySet > const& rxCell,
            const sal_Int32 nLeft)
        : nLeftPosition( nLeft )
        , bOpen( true )
    {
        aCells.push_back( rxCell );
    }
};

}

#define COL_POS_FUZZY 2

static bool lcl_SimilarPosition( const sal_Int32 nPos1, const sal_Int32 nPos2 )
{
    return abs( nPos1 - nPos2 ) < COL_POS_FUZZY;
}

void SwXText::Impl::ConvertCell(
    const uno::Sequence< uno::Reference< text::XTextRange > > & rCell,
    std::vector<SwNodeRange> & rRowNodes,
    SwNodeRange *const pLastCell)
{
    if (rCell.getLength() != 2)
    {
        throw lang::IllegalArgumentException(
                "rCell needs to contain 2 elements",
                uno::Reference< text::XTextCopy >( &m_rThis ), sal_Int16( 2 ) );
    }
    const uno::Reference<text::XTextRange> xStartRange = rCell[0];
    const uno::Reference<text::XTextRange> xEndRange = rCell[1];
    SwUnoInternalPaM aStartCellPam(*m_pDoc);
    SwUnoInternalPaM aEndCellPam(*m_pDoc);

    // !!! TODO - PaMs in tables and sections do not work here -
    //     the same applies to PaMs in frames !!!

    if (!::sw::XTextRangeToSwPaM(aStartCellPam, xStartRange) ||
        !::sw::XTextRangeToSwPaM(aEndCellPam, xEndRange))
    {
        throw lang::IllegalArgumentException(
                "Start or End range cannot be resolved to a SwPaM",
                uno::Reference< text::XTextCopy >( &m_rThis ), sal_Int16( 2 ) );
    }

    SwNodeRange aTmpRange(aStartCellPam.Start()->nNode,
                          aEndCellPam.End()->nNode);
    std::unique_ptr<SwNodeRange> pCorrectedRange =
        m_pDoc->GetNodes().ExpandRangeForTableBox(aTmpRange);

    if (pCorrectedRange)
    {
        SwPaM aNewStartPaM(pCorrectedRange->aStart, 0);
        aStartCellPam = aNewStartPaM;

        sal_Int32 nEndLen = 0;
        SwTextNode * pTextNode = pCorrectedRange->aEnd.GetNode().GetTextNode();
        if (pTextNode != nullptr)
            nEndLen = pTextNode->Len();

        SwPaM aNewEndPaM(pCorrectedRange->aEnd, nEndLen);
        aEndCellPam = aNewEndPaM;

        pCorrectedRange.reset();
    }

    /** check the nodes between start and end
        it is allowed to have pairs of StartNode/EndNodes
     */
    if (aStartCellPam.Start()->nNode < aEndCellPam.End()->nNode)
    {
        // increment on each StartNode and decrement on each EndNode
        // we must reach zero at the end and must not go below zero
        long nOpenNodeBlock = 0;
        SwNodeIndex aCellIndex = aStartCellPam.Start()->nNode;
        while (aCellIndex < aEndCellPam.End()->nNode.GetIndex())
        {
            if (aCellIndex.GetNode().IsStartNode())
            {
                ++nOpenNodeBlock;
            }
            else if (aCellIndex.GetNode().IsEndNode())
            {
                --nOpenNodeBlock;
            }
            if (nOpenNodeBlock < 0)
            {
                throw lang::IllegalArgumentException();
            }
            ++aCellIndex;
        }
        if (nOpenNodeBlock != 0)
        {
            throw lang::IllegalArgumentException();
        }
    }

    /** The vector<vector> NodeRanges has to contain consecutive nodes.
        In rTableRanges the ranges don't need to be full paragraphs but
        they have to follow each other. To process the ranges they
        have to be aligned on paragraph borders by inserting paragraph
        breaks. Non-consecutive ranges must initiate an exception.
     */
    if (!pLastCell) // first cell?
    {
        // align the beginning - if necessary
        if (aStartCellPam.Start()->nContent.GetIndex())
        {
            m_pDoc->getIDocumentContentOperations().SplitNode(*aStartCellPam.Start(), false);
        }
    }
    else
    {
        // check the predecessor
        const sal_uLong nStartCellNodeIndex =
            aStartCellPam.Start()->nNode.GetIndex();
        const sal_uLong nLastNodeEndIndex = pLastCell->aEnd.GetIndex();
        if (nLastNodeEndIndex == nStartCellNodeIndex)
        {
            // same node as predecessor then equal nContent?
            if (0 != aStartCellPam.Start()->nContent.GetIndex())
            {
                throw lang::IllegalArgumentException();
            }

            m_pDoc->getIDocumentContentOperations().SplitNode(*aStartCellPam.Start(), false);
            sal_uLong const nNewIndex(aStartCellPam.Start()->nNode.GetIndex());
            if (nNewIndex != nStartCellNodeIndex)
            {
                // aStartCellPam now points to the 2nd node
                // the last cell may *also* point to 2nd node now - fix it!
                assert(nNewIndex == nStartCellNodeIndex + 1);
                if (pLastCell->aEnd.GetIndex() == nNewIndex)
                {
                    --pLastCell->aEnd;
                    if (pLastCell->aStart.GetIndex() == nNewIndex)
                    {
                        --pLastCell->aStart;
                    }
                }
            }
        }
        else if (nStartCellNodeIndex == (nLastNodeEndIndex + 1))
        {
            // next paragraph - now the content index of the new should be 0
            // and of the old one should be equal to the text length
            // but if it isn't we don't care - the cell is being inserted on
            // the node border anyway
        }
        else
        {
            throw lang::IllegalArgumentException();
        }
    }
    // now check if there's a need to insert another paragraph break
    if (aEndCellPam.End()->nContent.GetIndex() <
            aEndCellPam.End()->nNode.GetNode().GetTextNode()->Len())
    {
        m_pDoc->getIDocumentContentOperations().SplitNode(*aEndCellPam.End(), false);
        // take care that the new start/endcell is moved to the right position
        // aStartCellPam has to point to the start of the new (previous) node
        // aEndCellPam has to point to the end of the new (previous) node
        aStartCellPam.DeleteMark();
        aStartCellPam.Move(fnMoveBackward, GoInNode);
        aStartCellPam.GetPoint()->nContent = 0;
        aEndCellPam.DeleteMark();
        aEndCellPam.Move(fnMoveBackward, GoInNode);
        aEndCellPam.GetPoint()->nContent =
            aEndCellPam.GetNode().GetTextNode()->Len();
    }

    assert(aStartCellPam.Start()->nContent.GetIndex() == 0);
    assert(aEndCellPam.End()->nContent.GetIndex() == aEndCellPam.End()->nNode.GetNode().GetTextNode()->Len());
    SwNodeRange aCellRange(aStartCellPam.Start()->nNode,
            aEndCellPam.End()->nNode);
    rRowNodes.push_back(aCellRange); // note: invalidates pLastCell!
}

typedef uno::Sequence< text::TableColumnSeparator > TableColumnSeparators;

static void
lcl_ApplyRowProperties(
    uno::Sequence<beans::PropertyValue> const& rRowProperties,
    uno::Any const& rRow,
    TableColumnSeparators & rRowSeparators)
{
    uno::Reference< beans::XPropertySet > xRow;
    rRow >>= xRow;
    for (const beans::PropertyValue& rProperty : rRowProperties)
    {
        if ( rProperty.Name == "TableColumnSeparators" )
        {
            // add the separators to access the cell's positions
            // for vertical merging later
            TableColumnSeparators aSeparators;
            rProperty.Value >>= aSeparators;
            rRowSeparators = aSeparators;
        }
        xRow->setPropertyValue(rProperty.Name, rProperty.Value);
    }
}

static sal_Int32 lcl_GetLeftPos(sal_Int32 nCell, TableColumnSeparators const& rRowSeparators)
{
    if(!nCell)
        return 0;
    if (rRowSeparators.getLength() < nCell)
        return -1;
    return rRowSeparators[nCell - 1].Position;
}

static void
lcl_ApplyCellProperties(
    const sal_Int32 nLeftPos,
    const uno::Sequence< beans::PropertyValue >& rCellProperties,
    const uno::Reference< uno::XInterface >& xCell,
    std::vector<VerticallyMergedCell> & rMergedCells)
{
    const uno::Reference< beans::XPropertySet > xCellPS(xCell, uno::UNO_QUERY);
    for (const auto& rCellProperty : rCellProperties)
    {
        const OUString & rName  = rCellProperty.Name;
        const uno::Any & rValue = rCellProperty.Value;
        if ( rName == "VerticalMerge" )
        {
            // determine left border position
            // add the cell to a queue of merged cells
            bool bMerge = false;<--- Assignment 'bMerge=false', assigned value is 0
            rValue >>= bMerge;
            if (bMerge)<--- Condition 'bMerge' is always false
            {
                // 'close' all the cell with the same left position
                // if separate vertical merges in the same column exist
                for(auto& aMergedCell : rMergedCells)
                {
                    if(lcl_SimilarPosition(aMergedCell.nLeftPosition, nLeftPos))
                    {
                        aMergedCell.bOpen = false;
                    }
                }
                // add the new group of merged cells
                rMergedCells.emplace_back(xCellPS, nLeftPos);
            }
            else
            {
                bool bFound = false;
                SAL_WARN_IF(rMergedCells.empty(), "sw.uno", "the first merged cell is missing");
                for(auto& aMergedCell : rMergedCells)
                {
                    if (aMergedCell.bOpen && lcl_SimilarPosition(aMergedCell.nLeftPosition, nLeftPos))
                    {
                        aMergedCell.aCells.push_back( xCellPS );
                        bFound = true;
                    }
                }
                SAL_WARN_IF(!bFound, "sw.uno", "couldn't find first vertically merged cell" );
            }
        }
        else
        {
            try
            {
                xCellPS->setPropertyValue(rName, rValue);
            }
            catch (const uno::Exception& e)
            {
                SAL_WARN( "sw.uno", "Exception when getting PropertyState: "
                        + rName + ". Message: " + e.Message );
            }
        }
    }
}

static void
lcl_MergeCells(std::vector<VerticallyMergedCell> & rMergedCells)
{
    for(auto& aMergedCell : rMergedCells)
    {
        // the first of the cells gets the number of cells set as RowSpan
        // the others get the inverted number of remaining merged cells
        // (3,-2,-1)
        sal_Int32 nCellCount = static_cast<sal_Int32>(aMergedCell.aCells.size());
        if(nCellCount<2)
        {
            SAL_WARN("sw.uno", "incomplete vertical cell merge");
            continue;
        }
        aMergedCell.aCells.front()->setPropertyValue(UNO_NAME_ROW_SPAN, uno::makeAny(nCellCount--));
        nCellCount*=-1;
        for(auto pxPSet = aMergedCell.aCells.begin()+1; nCellCount<0; ++pxPSet, ++nCellCount)
            (*pxPSet)->setPropertyValue(UNO_NAME_ROW_SPAN, uno::makeAny(nCellCount));
    }
}

uno::Reference< text::XTextTable > SAL_CALL
SwXText::convertToTable(
    const uno::Sequence< uno::Sequence< uno::Sequence<
        uno::Reference< text::XTextRange > > > >& rTableRanges,
    const uno::Sequence< uno::Sequence< uno::Sequence<
        beans::PropertyValue > > >& rCellProperties,
    const uno::Sequence< uno::Sequence< beans::PropertyValue > >&
        rRowProperties,
    const uno::Sequence< beans::PropertyValue >& rTableProperties)
{
    SolarMutexGuard aGuard;

    if(!IsValid())
    {
        throw  uno::RuntimeException();
    }

    IDocumentRedlineAccess & rIDRA(m_pImpl->m_pDoc->getIDocumentRedlineAccess());
    if (!IDocumentRedlineAccess::IsShowChanges(rIDRA.GetRedlineFlags()))
    {
        throw uno::RuntimeException(
            "cannot convertToTable if tracked changes are hidden!");
    }

    //at first collect the text ranges as SwPaMs
    const uno::Sequence< uno::Sequence< uno::Reference< text::XTextRange > > >*
        pTableRanges = rTableRanges.getConstArray();
    std::vector< std::vector<SwNodeRange> > aTableNodes;
    for (sal_Int32 nRow = 0; nRow < rTableRanges.getLength(); ++nRow)
    {
        std::vector<SwNodeRange> aRowNodes;
        const uno::Sequence< uno::Reference< text::XTextRange > >* pRow =
            pTableRanges[nRow].getConstArray();
        const sal_Int32 nCells(pTableRanges[nRow].getLength());

        if (0 == nCells) // this would lead to no pLastCell below
        {                // and make it impossible to detect node gaps
            throw lang::IllegalArgumentException();
        }

        for (sal_Int32 nCell = 0; nCell < nCells; ++nCell)
        {
            SwNodeRange *const pLastCell(
                (nCell == 0)
                    ? ((nRow == 0)
                        ? nullptr
                        : &*aTableNodes.rbegin()->rbegin())
                    : &*aRowNodes.rbegin());
            m_pImpl->ConvertCell(pRow[nCell], aRowNodes, pLastCell);
        }
        assert(!aRowNodes.empty());
        aTableNodes.push_back(aRowNodes);
    }

    std::vector< TableColumnSeparators >
        aRowSeparators(rRowProperties.getLength());
    std::vector<VerticallyMergedCell> aMergedCells;

    SwTable const*const pTable = m_pImpl->m_pDoc->TextToTable( aTableNodes );

    if (!pTable)
        return uno::Reference< text::XTextTable >();

    uno::Reference<text::XTextTable> const xRet =
        SwXTextTable::CreateXTextTable(pTable->GetFrameFormat());
    uno::Reference<beans::XPropertySet> const xPrSet(xRet, uno::UNO_QUERY);
    // set properties to the table
    // catch lang::WrappedTargetException and lang::IndexOutOfBoundsException
    try
    {
        //apply table properties
        for(const auto& rTableProperty : rTableProperties)
        {
            try
            {
                xPrSet->setPropertyValue(rTableProperty.Name, rTableProperty.Value);
            }
            catch (const uno::Exception& e)
            {
                SAL_WARN( "sw.uno", "Exception when setting property: "
                    + rTableProperty.Name + ". Message: " + e.Message );
            }
        }

        //apply row properties
        const auto xRows = xRet->getRows();
        const sal_Int32 nLast = std::min(xRows->getCount(), rRowProperties.getLength());
        SAL_WARN_IF(nLast != rRowProperties.getLength(), "sw.uno", "not enough rows for properties");
        for(sal_Int32 nCnt = 0; nCnt < nLast; ++nCnt)
            lcl_ApplyRowProperties(rRowProperties[nCnt], xRows->getByIndex(nCnt), aRowSeparators[nCnt]);

        uno::Reference<table::XCellRange> const xCR(xRet, uno::UNO_QUERY_THROW);
        //apply cell properties
        sal_Int32 nRow = 0;
        for(const auto& rCellPropertiesForRow : rCellProperties)
        {
            sal_Int32 nCell = 0;
            for(const auto& rCellProps : rCellPropertiesForRow)
            {
                lcl_ApplyCellProperties(lcl_GetLeftPos(nCell, aRowSeparators[nRow]),
                    rCellProps,
                    xCR->getCellByPosition(nCell, nRow),
                    aMergedCells);
                ++nCell;
            }
            ++nRow;
        }

        // now that the cell properties are set the vertical merge values
        // have to be applied
        lcl_MergeCells(aMergedCells);
    }
    catch (const lang::WrappedTargetException&)
    {
    }
    catch (const lang::IndexOutOfBoundsException&)
    {
    }

    assert(SwTable::FindTable(pTable->GetFrameFormat()) == pTable);
    assert(pTable->GetFrameFormat() ==
            dynamic_cast<SwXTextTable&>(*xRet).GetFrameFormat());
    return xRet;
}

void SAL_CALL
SwXText::copyText(
    const uno::Reference< text::XTextCopy >& xSource )
{
    SolarMutexGuard aGuard;

    uno::Reference<lang::XUnoTunnel> const xSourceTunnel(xSource,
        uno::UNO_QUERY);
    SwXText const*const pSource( xSourceTunnel.is()
        ? ::sw::UnoTunnelGetImplementation<SwXText>(xSourceTunnel)
        : nullptr);

    uno::Reference< text::XText > const xText(xSource, uno::UNO_QUERY_THROW);
    uno::Reference< text::XTextCursor > const xCursor =
        xText->createTextCursor();
    xCursor->gotoEnd( true );

    uno::Reference< lang::XUnoTunnel > const xCursorTunnel(xCursor,
        uno::UNO_QUERY_THROW);

    OTextCursorHelper *const pCursor =
        ::sw::UnoTunnelGetImplementation<OTextCursorHelper>(xCursorTunnel);
    if (!pCursor)
    {
        throw uno::RuntimeException();
    }

    SwNodeIndex rNdIndex( *GetStartNode( ), 1 );
    SwPosition rPos( rNdIndex );
    // tdf#112202 need SwXText because cursor cannot select table at the start
    if (pSource)
    {
        SwTextNode * pFirstNode;
        {
            SwPaM temp(*pSource->GetStartNode(), *pSource->GetStartNode()->EndOfSectionNode(), +1, -1);
            pFirstNode = temp.GetMark()->nNode.GetNode().GetTextNode();
            if (pFirstNode)
            {
                pFirstNode->MakeStartIndex(&temp.GetMark()->nContent);
            }
            if (SwTextNode *const pNode = temp.GetPoint()->nNode.GetNode().GetTextNode())
            {
                pNode->MakeEndIndex(&temp.GetPoint()->nContent);
            }
            // Explicitly request copy text mode, so
            // sw::DocumentContentOperationsManager::CopyFlyInFlyImpl() will copy shapes anchored to
            // us, even if we have only a single paragraph.
            m_pImpl->m_pDoc->getIDocumentContentOperations().CopyRange(temp, rPos, SwCopyFlags::CheckPosInFly);
        }
        if (!pFirstNode)
        {   // the node at rPos was split; get rid of the first empty one so
            // that the pasted table is first
            auto pDelCursor(m_pImpl->m_pDoc->CreateUnoCursor(SwPosition(SwNodeIndex(*GetStartNode(), 1))));
            m_pImpl->m_pDoc->getIDocumentContentOperations().DelFullPara(*pDelCursor);
        }
    }
    else
    {
        m_pImpl->m_pDoc->getIDocumentContentOperations().CopyRange(*pCursor->GetPaM(), rPos, SwCopyFlags::CheckPosInFly);
    }

}

SwXBodyText::SwXBodyText(SwDoc *const pDoc)
    : SwXText(pDoc, CursorType::Body)
{
}

SwXBodyText::~SwXBodyText()
{
}

OUString SAL_CALL
SwXBodyText::getImplementationName()
{
    return "SwXBodyText";
}

sal_Bool SAL_CALL SwXBodyText::supportsService(const OUString& rServiceName)
{
    return cppu::supportsService(this, rServiceName);
}

uno::Sequence< OUString > SAL_CALL
SwXBodyText::getSupportedServiceNames()
{
    return { "com.sun.star.text.Text" };
}

uno::Any SAL_CALL
SwXBodyText::queryAggregation(const uno::Type& rType)
{
    uno::Any aRet;
    if (rType == cppu::UnoType<container::XEnumerationAccess>::get())
    {
        aRet <<= uno::Reference< container::XEnumerationAccess >(this);
    }
    else if (rType == cppu::UnoType<container::XElementAccess>::get())
    {
        aRet <<= uno::Reference< container::XElementAccess >(this);
    }
    else if (rType == cppu::UnoType<lang::XServiceInfo>::get())
    {
        aRet <<= uno::Reference< lang::XServiceInfo >(this);
    }
    else
    {
        aRet = SwXText::queryInterface( rType );
    }
    if(aRet.getValueType() == cppu::UnoType<void>::get())
    {
        aRet = OWeakAggObject::queryAggregation( rType );
    }
    return aRet;
}

uno::Sequence< uno::Type > SAL_CALL
SwXBodyText::getTypes()
{
    const uno::Sequence< uno::Type > aTypes = SwXBodyText_Base::getTypes();
    const uno::Sequence< uno::Type > aTextTypes = SwXText::getTypes();
    return ::comphelper::concatSequences(aTypes, aTextTypes);
}

uno::Sequence< sal_Int8 > SAL_CALL
SwXBodyText::getImplementationId()
{
    return css::uno::Sequence<sal_Int8>();
}

uno::Any SAL_CALL
SwXBodyText::queryInterface(const uno::Type& rType)
{
    const uno::Any ret = SwXText::queryInterface(rType);
    return (ret.getValueType() == cppu::UnoType<void>::get())
        ?   SwXBodyText_Base::queryInterface(rType)
        :   ret;
}

SwXTextCursor * SwXBodyText::CreateTextCursor(const bool bIgnoreTables)
{
    if(!IsValid())
    {
        return nullptr;
    }

    // the cursor has to skip tables contained in this text
    SwPaM aPam(GetDoc()->GetNodes().GetEndOfContent());
    aPam.Move( fnMoveBackward, GoInDoc );
    if (!bIgnoreTables)
    {
        SwTableNode * pTableNode = aPam.GetNode().FindTableNode();
        SwContentNode * pCont = nullptr;
        while (pTableNode)
        {
            aPam.GetPoint()->nNode = *pTableNode->EndOfSectionNode();
            pCont = GetDoc()->GetNodes().GoNext(&aPam.GetPoint()->nNode);
            pTableNode = pCont->FindTableNode();
        }
        if (pCont)
        {
            aPam.GetPoint()->nContent.Assign(pCont, 0);
        }
    }
    return new SwXTextCursor(*GetDoc(), this, CursorType::Body, *aPam.GetPoint());
}

uno::Reference< text::XTextCursor > SAL_CALL
SwXBodyText::createTextCursor()
{
    SolarMutexGuard aGuard;

    const uno::Reference< text::XTextCursor > xRef(
            static_cast<text::XWordCursor*>(CreateTextCursor()) );
    if (!xRef.is())
    {
        uno::RuntimeException aRuntime;
        aRuntime.Message = cInvalidObject;
        throw aRuntime;
    }
    return xRef;
}

uno::Reference< text::XTextCursor > SAL_CALL
SwXBodyText::createTextCursorByRange(
    const uno::Reference< text::XTextRange > & xTextPosition)
{
    SolarMutexGuard aGuard;

    if(!IsValid())
    {
        uno::RuntimeException aRuntime;
        aRuntime.Message = cInvalidObject;
        throw aRuntime;
    }

    uno::Reference< text::XTextCursor >  aRef;
    SwUnoInternalPaM aPam(*GetDoc());
    if (::sw::XTextRangeToSwPaM(aPam, xTextPosition))
    {
        if ( !aPam.GetNode().GetTextNode() )
            throw uno::RuntimeException("Invalid text range" );

        SwNode& rNode = GetDoc()->GetNodes().GetEndOfContent();

        SwStartNode* p1 = aPam.GetNode().StartOfSectionNode();
        //document starts with a section?
        while(p1->IsSectionNode())
        {
            p1 = p1->StartOfSectionNode();
        }
        SwStartNode *const p2 = rNode.StartOfSectionNode();

        if(p1 == p2)
        {
            aRef = static_cast<text::XWordCursor*>(
                    new SwXTextCursor(*GetDoc(), this, CursorType::Body,
                        *aPam.GetPoint(), aPam.GetMark()));
        }
    }
    if(!aRef.is())
    {
        throw uno::RuntimeException( "End of content node doesn't have the proper start node",
               uno::Reference< uno::XInterface >( *this ) );
    }
    return aRef;
}

uno::Reference< container::XEnumeration > SAL_CALL
SwXBodyText::createEnumeration()
{
    SolarMutexGuard aGuard;

    if (!IsValid())
    {
        uno::RuntimeException aRuntime;
        aRuntime.Message = cInvalidObject;
        throw aRuntime;
    }

    SwNode& rNode = GetDoc()->GetNodes().GetEndOfContent();
    SwPosition aPos(rNode);
    auto pUnoCursor(GetDoc()->CreateUnoCursor(aPos));
    pUnoCursor->Move(fnMoveBackward, GoInDoc);
    return SwXParagraphEnumeration::Create(this, pUnoCursor, CursorType::Body);
}

uno::Type SAL_CALL
SwXBodyText::getElementType()
{
    return cppu::UnoType<text::XTextRange>::get();
}

sal_Bool SAL_CALL
SwXBodyText::hasElements()
{
    SolarMutexGuard aGuard;

    if (!IsValid())
    {
        uno::RuntimeException aRuntime;
        aRuntime.Message = cInvalidObject;
        throw aRuntime;
    }

    return true;
}

class SwXHeadFootText::Impl
    : public SvtListener
{
    public:
        SwFrameFormat* m_pHeadFootFormat;
        bool m_bIsHeader;

        Impl(SwFrameFormat& rHeadFootFormat, const bool bIsHeader)
            : m_pHeadFootFormat(&rHeadFootFormat)
            , m_bIsHeader(bIsHeader)
        {
            StartListening(m_pHeadFootFormat->GetNotifier());
        }

        SwFrameFormat* GetHeadFootFormat() const {
            return m_pHeadFootFormat;
        }

        SwFrameFormat& GetHeadFootFormatOrThrow() {
            if (!m_pHeadFootFormat) {
                throw uno::RuntimeException("SwXHeadFootText: disposed or invalid", nullptr);
            }
            return *m_pHeadFootFormat;
        }
    protected:
        virtual void Notify(const SfxHint& rHint) override
        {
            if(rHint.GetId() == SfxHintId::Dying)
                m_pHeadFootFormat = nullptr;
        }
};

uno::Reference<text::XText> SwXHeadFootText::CreateXHeadFootText(
        SwFrameFormat& rHeadFootFormat,
        const bool bIsHeader)
{
    // re-use existing SwXHeadFootText
    // #i105557#: do not iterate over the registered clients: race condition
    uno::Reference<text::XText> xText(rHeadFootFormat.GetXObject(), uno::UNO_QUERY);
    if(!xText.is())
    {
        const auto pXHFT(new SwXHeadFootText(rHeadFootFormat, bIsHeader));
        xText.set(pXHFT);
        rHeadFootFormat.SetXObject(xText);
    }
    return xText;
}

SwXHeadFootText::SwXHeadFootText(SwFrameFormat& rHeadFootFormat, const bool bIsHeader)
    : SwXText(
            rHeadFootFormat.GetDoc(),
            bIsHeader ? CursorType::Header : CursorType::Footer)
    , m_pImpl(new SwXHeadFootText::Impl(rHeadFootFormat, bIsHeader))
{
}

SwXHeadFootText::~SwXHeadFootText()
{ }

OUString SAL_CALL
SwXHeadFootText::getImplementationName()
{
  return {"SwXHeadFootText"};
}

sal_Bool SAL_CALL SwXHeadFootText::supportsService(const OUString& rServiceName)
{
    return cppu::supportsService(this, rServiceName);
}

uno::Sequence<OUString> SAL_CALL
SwXHeadFootText::getSupportedServiceNames()
{
    return {"com.sun.star.text.Text"};
}

const SwStartNode* SwXHeadFootText::GetStartNode() const
{
    const SwStartNode* pSttNd = nullptr;
    SwFrameFormat* const pHeadFootFormat = m_pImpl->GetHeadFootFormat();
    if(pHeadFootFormat)
    {
        const SwFormatContent& rFlyContent = pHeadFootFormat->GetContent();
        if(rFlyContent.GetContentIdx())
        {
            pSttNd = rFlyContent.GetContentIdx()->GetNode().GetStartNode();
        }
    }
    return pSttNd;
}

uno::Reference<text::XTextCursor> SwXHeadFootText::CreateCursor()
{
    return createTextCursor();
}

uno::Sequence<uno::Type> SAL_CALL SwXHeadFootText::getTypes()
{
    return ::comphelper::concatSequences(
        SwXHeadFootText_Base::getTypes(),
        SwXText::getTypes());
}

uno::Sequence<sal_Int8> SAL_CALL SwXHeadFootText::getImplementationId()
{
    return css::uno::Sequence<sal_Int8>();
}

uno::Any SAL_CALL SwXHeadFootText::queryInterface(const uno::Type& rType)
{
    const uno::Any ret = SwXHeadFootText_Base::queryInterface(rType);
    return (ret.getValueType() == cppu::UnoType<void>::get())
        ? SwXText::queryInterface(rType)
        : ret;
}

uno::Reference<text::XTextCursor> SAL_CALL
SwXHeadFootText::createTextCursor()
{
    SolarMutexGuard aGuard;

    SwFrameFormat & rHeadFootFormat( m_pImpl->GetHeadFootFormatOrThrow() );

    const SwFormatContent& rFlyContent = rHeadFootFormat.GetContent();
    const SwNode& rNode = rFlyContent.GetContentIdx()->GetNode();
    SwPosition aPos(rNode);
    SwXTextCursor *const pXCursor = new SwXTextCursor(*GetDoc(), this,
            (m_pImpl->m_bIsHeader) ? CursorType::Header : CursorType::Footer, aPos);
    auto& rUnoCursor(pXCursor->GetCursor());
    rUnoCursor.Move(fnMoveForward, GoInNode);

    // save current start node to be able to check if there is content
    // after the table - otherwise the cursor would be in the body text!
    SwStartNode const*const pOwnStartNode = rNode.FindSttNodeByType(
            (m_pImpl->m_bIsHeader) ? SwHeaderStartNode : SwFooterStartNode);
    // is there a table here?
    SwTableNode* pTableNode = rUnoCursor.GetNode().FindTableNode();
    SwContentNode* pCont = nullptr;
    while (pTableNode)
    {
        rUnoCursor.GetPoint()->nNode = *pTableNode->EndOfSectionNode();
        pCont = GetDoc()->GetNodes().GoNext(&rUnoCursor.GetPoint()->nNode);
        pTableNode = pCont->FindTableNode();
    }
    if (pCont)
    {
        rUnoCursor.GetPoint()->nContent.Assign(pCont, 0);
    }
    SwStartNode const*const pNewStartNode = rUnoCursor.GetNode().FindSttNodeByType(
            (m_pImpl->m_bIsHeader) ? SwHeaderStartNode : SwFooterStartNode);
    if (!pNewStartNode || (pNewStartNode != pOwnStartNode))
    {
        uno::RuntimeException aExcept;
        aExcept.Message = "no text available";
        throw aExcept;
    }
    return static_cast<text::XWordCursor*>(pXCursor);
}

uno::Reference<text::XTextCursor> SAL_CALL SwXHeadFootText::createTextCursorByRange(
    const uno::Reference<text::XTextRange>& xTextPosition)
{
    SolarMutexGuard aGuard;
    SwFrameFormat& rHeadFootFormat( m_pImpl->GetHeadFootFormatOrThrow() );

    SwUnoInternalPaM aPam(*GetDoc());
    if (!sw::XTextRangeToSwPaM(aPam, xTextPosition))
    {
        uno::RuntimeException aRuntime;
        aRuntime.Message = cInvalidObject;
        throw aRuntime;
    }

    SwNode& rNode = rHeadFootFormat.GetContent().GetContentIdx()->GetNode();
    SwPosition aPos(rNode);
    SwPaM aHFPam(aPos);
    aHFPam.Move(fnMoveForward, GoInNode);
    SwStartNode* const pOwnStartNode = aHFPam.GetNode().FindSttNodeByType(
            (m_pImpl->m_bIsHeader) ? SwHeaderStartNode : SwFooterStartNode);
    SwStartNode* const p1 = aPam.GetNode().FindSttNodeByType(
            (m_pImpl->m_bIsHeader) ? SwHeaderStartNode : SwFooterStartNode);
    if (p1 == pOwnStartNode)
    {
        return static_cast<text::XWordCursor*>(
                new SwXTextCursor(
                    *GetDoc(),
                    this,
                    (m_pImpl->m_bIsHeader) ? CursorType::Header : CursorType::Footer,
                    *aPam.GetPoint(), aPam.GetMark()));
    }
    return nullptr;
}

uno::Reference<container::XEnumeration> SAL_CALL SwXHeadFootText::createEnumeration()
{
    SolarMutexGuard aGuard;
    SwFrameFormat& rHeadFootFormat(m_pImpl->GetHeadFootFormatOrThrow());

    const SwFormatContent& rFlyContent = rHeadFootFormat.GetContent();
    const SwNode& rNode = rFlyContent.GetContentIdx()->GetNode();
    SwPosition aPos(rNode);
    auto pUnoCursor(GetDoc()->CreateUnoCursor(aPos));
    pUnoCursor->Move(fnMoveForward, GoInNode);
    return SwXParagraphEnumeration::Create(
            this,
            pUnoCursor,
            (m_pImpl->m_bIsHeader)
                ? CursorType::Header
                : CursorType::Footer);
}

uno::Type SAL_CALL SwXHeadFootText::getElementType()
    { return cppu::UnoType<text::XTextRange>::get(); }

sal_Bool SAL_CALL SwXHeadFootText::hasElements()
    { return true; }

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