summaryrefslogtreecommitdiffstats
path: root/xmloff/source/text/txtimp.cxx
blob: d6e132323d3406989c1bca94960bf5fd9b339c25 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
/* -*- 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 <memory>
#include <optional>
#include <tuple>
#include <vector>

#include <com/sun/star/container/XEnumerationAccess.hpp>
#include <com/sun/star/frame/XModel.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/style/XStyleFamiliesSupplier.hpp>
#include <com/sun/star/text/ReferenceFieldSource.hpp>
#include <com/sun/star/text/XChapterNumberingSupplier.hpp>
#include <com/sun/star/text/XTextFrame.hpp>
#include <com/sun/star/text/XTextFieldsSupplier.hpp>
#include <com/sun/star/text/XTextFramesSupplier.hpp>
#include <com/sun/star/text/XTextGraphicObjectsSupplier.hpp>
#include <com/sun/star/text/XTextEmbeddedObjectsSupplier.hpp>
#include <com/sun/star/text/XFormField.hpp>
#include <com/sun/star/ucb/XAnyCompareFactory.hpp>
#include <com/sun/star/container/XNamed.hpp>
#include <com/sun/star/style/XStyle.hpp>
#include <xmloff/xmlnamespace.hxx>
#include <xmloff/txtstyli.hxx>
#include <xmloff/xmlnumi.hxx>
#include <xmloff/maptype.hxx>

#include <sal/log.hxx>
#include "txtparai.hxx"
#include <xmloff/txtprmap.hxx>
#include <xmloff/txtimppr.hxx>
#include <xmloff/xmlimp.hxx>
#include <txtvfldi.hxx>
#include <xmloff/i18nmap.hxx>
#include "XMLTextListItemContext.hxx"
#include "XMLTextListBlockContext.hxx"
#include "XMLTextFrameContext.hxx"
#include "XMLTextFrameHyperlinkContext.hxx"
#include "XMLSectionImportContext.hxx"
#include "XMLIndexTOCContext.hxx"
#include <xmloff/XMLEventsImportContext.hxx>
#include "XMLTrackedChangesImportContext.hxx"
#include "XMLChangeImportContext.hxx"
#include "XMLAutoMarkFileContext.hxx"
#include <xmloff/ProgressBarHelper.hxx>

#include "XMLCalculationSettingsContext.hxx"
#include <XMLNumberStylesImport.hxx>
#include <PageMasterStyleMap.hxx>
#include <PageMasterPropHdlFactory.hxx>
#include <PageMasterPropMapper.hxx>
// XML import: reconstruction of assignment of paragraph style to outline levels (#i69629#)
#include <com/sun/star/beans/XPropertyState.hpp>
#include <txtlists.hxx>
#include <xmloff/odffields.hxx>
#include <comphelper/attributelist.hxx>

using ::com::sun::star::ucb::XAnyCompare;

using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::text;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::style;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::drawing;
using namespace ::com::sun::star::xml::sax;
using namespace ::com::sun::star::lang;
using namespace ::xmloff::token;
using namespace ::com::sun::star::ucb;


// maximum allowed length of combined characters field
#define MAX_COMBINED_CHARACTERS 6

struct XMLTextImportHelper::Impl
{
    std::optional< std::vector<OUString> > m_xPrevFrmNames;
    std::optional< std::vector<OUString> > m_xNextFrmNames;
    std::unique_ptr<XMLTextListsHelper> m_xTextListsHelper;

    rtl::Reference<SvXMLStylesContext> m_xAutoStyles;

    rtl::Reference< SvXMLImportPropertyMapper > m_xParaImpPrMap;
    rtl::Reference< SvXMLImportPropertyMapper > m_xTextImpPrMap;
    rtl::Reference< SvXMLImportPropertyMapper > m_xFrameImpPrMap;
    rtl::Reference< SvXMLImportPropertyMapper > m_xSectionImpPrMap;
    rtl::Reference< SvXMLImportPropertyMapper > m_xRubyImpPrMap;

    std::unique_ptr<SvI18NMap> m_xRenameMap;

    /* Change and extend data structure:
       - data structure contains candidates of paragraph styles, which
         will be assigned to the outline style
       - data structure contains more than one candidate for each list level
         of the outline style (#i69629#)
    */
    std::unique_ptr< std::vector< OUString > []>
        m_xOutlineStylesCandidates;

    // start range, xml:id, RDFa stuff
    typedef std::tuple<
        uno::Reference<text::XTextRange>, OUString,
        std::shared_ptr< ::xmloff::ParsedRDFaAttributes > >
            BookmarkMapEntry_t;
    /// start ranges for open bookmarks
    std::map< OUString, BookmarkMapEntry_t > m_BookmarkStartRanges;

    std::vector< OUString > m_BookmarkVector;

    /// name of the last 'open' redline that started between paragraphs
    OUString m_sOpenRedlineIdentifier;

    // Used for frame deduplication, the name of the last frame imported directly before the current one
    OUString msLastImportedFrameName;

    std::map< OUString, bool > m_bBookmarkHidden;
    std::map< OUString, OUString > m_sBookmarkCondition;

    uno::Reference<text::XText> m_xText;
    uno::Reference<text::XTextCursor> m_xCursor;
    uno::Reference<text::XTextRange> m_xCursorAsRange;
    uno::Reference<container::XNameContainer> m_xParaStyles;
    uno::Reference<container::XNameContainer> m_xTextStyles;
    uno::Reference<container::XNameContainer> m_xNumStyles;
    uno::Reference<container::XNameContainer> m_xFrameStyles;
    uno::Reference<container::XNameContainer> m_xPageStyles;
    uno::Reference<container::XNameContainer> m_xCellStyles;
    uno::Reference<container::XIndexReplace> m_xChapterNumbering;
    uno::Reference<container::XNameAccess> m_xTextFrames;
    uno::Reference<container::XNameAccess> m_xGraphics;
    uno::Reference<container::XNameAccess> m_xObjects;
    uno::Reference<lang::XMultiServiceFactory> m_xServiceFactory;

    SvXMLImport & m_rSvXMLImport;

    bool m_bInsertMode : 1;
    bool m_bStylesOnlyMode : 1;
    bool m_bBlockMode : 1;
    bool m_bProgress : 1;
    bool m_bOrganizerMode : 1;
    bool m_bBodyContentStarted : 1;

    /// Are we inside a <text:deletion> element (deleted redline section)
    bool m_bInsideDeleteContext : 1;

    typedef ::std::pair< OUString, OUString> field_name_type_t;
    typedef ::std::pair< OUString, OUString > field_param_t;
    typedef ::std::vector< field_param_t > field_params_t;
    typedef ::std::tuple<field_name_type_t, field_params_t, uno::Reference<text::XFormField>, uno::Reference<text::XTextRange>> field_stack_item_t;
    typedef ::std::stack< field_stack_item_t > field_stack_t;

    field_stack_t m_FieldStack;

    OUString m_sCellParaStyleDefault;

    std::optional<std::map<OUString, OUString>> m_xCrossRefHeadingBookmarkMap;

    Impl(       uno::Reference<frame::XModel> const& rModel,
                SvXMLImport & rImport,
                bool const bInsertMode, bool const bStylesOnlyMode,
                bool const bProgress, bool const bBlockMode,
                bool const bOrganizerMode)
        :   m_xTextListsHelper( new XMLTextListsHelper() )
        // XML import: reconstruction of assignment of paragraph style to outline levels (#i69629#)
        ,   m_xServiceFactory( rModel, UNO_QUERY )
        ,   m_rSvXMLImport( rImport )
        ,   m_bInsertMode( bInsertMode )
        ,   m_bStylesOnlyMode( bStylesOnlyMode )
        ,   m_bBlockMode( bBlockMode )
        ,   m_bProgress( bProgress )
        ,   m_bOrganizerMode( bOrganizerMode )
        ,   m_bBodyContentStarted( true )
        ,   m_bInsideDeleteContext( false )
    {
    }
    Impl(const Impl&) = delete;
    Impl& operator=(const Impl&) = delete;

    void InitOutlineStylesCandidates()
    {
        if (!m_xOutlineStylesCandidates)
        {
            size_t const size(m_xChapterNumbering->getCount());
            m_xOutlineStylesCandidates.reset(
                new ::std::vector< OUString >[size] );
        }
    }

};


uno::Reference< text::XText > & XMLTextImportHelper::GetText()
{
    return m_xImpl->m_xText;
}

uno::Reference< text::XTextCursor > & XMLTextImportHelper::GetCursor()
{
    return m_xImpl->m_xCursor;
}

uno::Reference< text::XTextRange > & XMLTextImportHelper::GetCursorAsRange()
{
    return m_xImpl->m_xCursorAsRange;
}

bool XMLTextImportHelper::IsInsertMode() const
{
    return m_xImpl->m_bInsertMode;
}

bool XMLTextImportHelper::IsStylesOnlyMode() const
{
    return m_xImpl->m_bStylesOnlyMode;
}

bool XMLTextImportHelper::IsBlockMode() const
{
    return m_xImpl->m_bBlockMode;
}

bool XMLTextImportHelper::IsOrganizerMode() const
{
    return m_xImpl->m_bOrganizerMode;
}

bool XMLTextImportHelper::IsProgress() const
{
    return m_xImpl->m_bProgress;
}

uno::Reference<container::XNameContainer> const&
XMLTextImportHelper::GetParaStyles() const
{
    return m_xImpl->m_xParaStyles;
}

uno::Reference<container::XNameContainer> const&
XMLTextImportHelper::GetTextStyles() const
{
    return m_xImpl->m_xTextStyles;
}

uno::Reference<container::XNameContainer> const&
XMLTextImportHelper::GetNumberingStyles() const
{
    return m_xImpl->m_xNumStyles;
}

uno::Reference<container::XNameContainer> const&
XMLTextImportHelper::GetFrameStyles() const
{
    return m_xImpl->m_xFrameStyles;
}

uno::Reference<container::XNameContainer> const&
XMLTextImportHelper::GetPageStyles() const
{
    return m_xImpl->m_xPageStyles;
}

uno::Reference<container::XNameContainer> const&
XMLTextImportHelper::GetCellStyles() const
{
    return m_xImpl->m_xCellStyles;
}

uno::Reference<container::XIndexReplace> const&
XMLTextImportHelper::GetChapterNumbering() const
{
    return m_xImpl->m_xChapterNumbering;
}

rtl::Reference< SvXMLImportPropertyMapper > const&
XMLTextImportHelper::GetParaImportPropertySetMapper() const
{
    return m_xImpl->m_xParaImpPrMap;
}

rtl::Reference< SvXMLImportPropertyMapper > const&
XMLTextImportHelper::GetTextImportPropertySetMapper() const
{
    return m_xImpl->m_xTextImpPrMap;
}

rtl::Reference< SvXMLImportPropertyMapper > const&
XMLTextImportHelper::GetSectionImportPropertySetMapper() const
{
    return m_xImpl->m_xSectionImpPrMap;
}

rtl::Reference< SvXMLImportPropertyMapper > const&
XMLTextImportHelper::GetRubyImportPropertySetMapper() const
{
    return m_xImpl->m_xRubyImpPrMap;
}

void XMLTextImportHelper::SetInsideDeleteContext(bool const bNew)
{
    m_xImpl->m_bInsideDeleteContext = bNew;
}

bool XMLTextImportHelper::IsInsideDeleteContext() const
{
    return m_xImpl->m_bInsideDeleteContext;
}

SvXMLImport & XMLTextImportHelper::GetXMLImport()
{
    return m_xImpl->m_rSvXMLImport;
}

XMLTextListsHelper & XMLTextImportHelper::GetTextListHelper()
{
    return *m_xImpl->m_xTextListsHelper;
}

namespace
{
    class FieldParamImporter
    {
        public:
            typedef std::pair<OUString,OUString> field_param_t;
            typedef std::vector<field_param_t> field_params_t;
            FieldParamImporter(const field_params_t* const pInParams, Reference<XNameContainer> const & xOutParams)
                : m_pInParams(pInParams)
                , m_xOutParams(xOutParams)
            { };
            void Import();

        private:
            const field_params_t* const m_pInParams;
            Reference<XNameContainer> m_xOutParams;
    };

    void FieldParamImporter::Import()
    {
        ::std::vector<OUString> vListEntries;
        ::std::map<OUString, Any> vOutParams;
        for(const auto& rCurrent : *m_pInParams)
        {
            if(rCurrent.first == ODF_FORMDROPDOWN_RESULT)
            {
                // sal_Int32
                vOutParams[rCurrent.first] <<= rCurrent.second.toInt32();
            }
            else if(rCurrent.first == ODF_FORMCHECKBOX_RESULT)
            {
                // bool
                vOutParams[rCurrent.first] <<= rCurrent.second.toBoolean();
            }
            else if(rCurrent.first == ODF_FORMDROPDOWN_LISTENTRY)
            {
                // sequence
                vListEntries.push_back(rCurrent.second);
            }
            else
                vOutParams[rCurrent.first] <<= rCurrent.second;
        }
        if(!vListEntries.empty())
        {
            Sequence<OUString> vListEntriesSeq(vListEntries.size());
            copy(vListEntries.begin(), vListEntries.end(), vListEntriesSeq.getArray());
            vOutParams[ODF_FORMDROPDOWN_LISTENTRY] <<= vListEntriesSeq;
        }
        for(const auto& rCurrent : vOutParams)
        {
            try
            {
                m_xOutParams->insertByName(rCurrent.first, rCurrent.second);
            }
            catch(const ElementExistException&)
            {
                SAL_INFO("xmloff.text", "duplicate fieldmark param");
            }
        }
    }
}

XMLTextImportHelper::XMLTextImportHelper(
        uno::Reference<frame::XModel> const& rModel,
        SvXMLImport& rImport,
        bool const bInsertMode, bool const bStylesOnlyMode,
        bool const bProgress, bool const bBlockMode,
        bool const bOrganizerMode)
    : m_xImpl( new Impl(rModel, rImport, bInsertMode, bStylesOnlyMode,
                    bProgress, bBlockMode, bOrganizerMode) )
    , m_xBackpatcherImpl( MakeBackpatcherImpl() )
{
    static constexpr OUString s_PropNameDefaultListId = u"DefaultListId"_ustr;

    Reference< XChapterNumberingSupplier > xCNSupplier( rModel, UNO_QUERY );

    if (xCNSupplier.is())
    {
        // note: m_xChapterNumbering is accessed to import some fields
        m_xImpl->m_xChapterNumbering = xCNSupplier->getChapterNumberingRules();
        // the AutoCorrect document doesn't have a proper outline numbering
        if (!IsBlockMode() && m_xImpl->m_xChapterNumbering.is())
        {
            Reference< XPropertySet > const xNumRuleProps(
                m_xImpl->m_xChapterNumbering, UNO_QUERY);
            if ( xNumRuleProps.is() )
            {
                Reference< XPropertySetInfo > xNumRulePropSetInfo(
                                            xNumRuleProps->getPropertySetInfo());
                if (xNumRulePropSetInfo.is() &&
                    xNumRulePropSetInfo->hasPropertyByName(
                         s_PropNameDefaultListId))
                {
                    OUString sListId;
                    xNumRuleProps->getPropertyValue(s_PropNameDefaultListId)
                        >>= sListId;
                    assert( !sListId.isEmpty() &&
                                "no default list id found at chapter numbering rules instance. Serious defect." );
                    if ( !sListId.isEmpty() )
                    {
                        Reference< XNamed > const xChapterNumNamed(
                            m_xImpl->m_xChapterNumbering, UNO_QUERY);
                        if ( xChapterNumNamed.is() )
                        {
                            m_xImpl->m_xTextListsHelper->KeepListAsProcessed(
                                                    sListId,
                                                    xChapterNumNamed->getName(),
                                                    OUString() );
                        }
                    }
                }
            }
        }
    }

    Reference< XStyleFamiliesSupplier > xFamiliesSupp( rModel, UNO_QUERY );
//  SAL_WARN_IF( !xFamiliesSupp.is(), "xmloff", "no chapter numbering supplier" ); for clipboard there may be documents without styles

    if( xFamiliesSupp.is() )
    {
        Reference< XNameAccess > xFamilies(xFamiliesSupp->getStyleFamilies());

        static constexpr OUString aParaStyles(u"ParagraphStyles"_ustr);
        if( xFamilies->hasByName( aParaStyles ) )
        {
            m_xImpl->m_xParaStyles.set(xFamilies->getByName(aParaStyles),
                UNO_QUERY);
        }

        static constexpr OUString aCharStyles(u"CharacterStyles"_ustr);
        if( xFamilies->hasByName( aCharStyles ) )
        {
            m_xImpl->m_xTextStyles.set(xFamilies->getByName(aCharStyles),
                UNO_QUERY);
        }

        static constexpr OUString aNumStyles(u"NumberingStyles"_ustr);
        if( xFamilies->hasByName( aNumStyles ) )
        {
            m_xImpl->m_xNumStyles.set(xFamilies->getByName(aNumStyles),
                UNO_QUERY);
        }

        static constexpr OUString aFrameStyles(u"FrameStyles"_ustr);
        if( xFamilies->hasByName( aFrameStyles ) )
        {
            m_xImpl->m_xFrameStyles.set(xFamilies->getByName(aFrameStyles),
                UNO_QUERY);
        }

        static constexpr OUString aPageStyles(u"PageStyles"_ustr);
        if( xFamilies->hasByName( aPageStyles ) )
        {
            m_xImpl->m_xPageStyles.set(xFamilies->getByName(aPageStyles),
                UNO_QUERY);
        }

        static constexpr OUString aCellStyles(u"CellStyles"_ustr);
        if( xFamilies->hasByName( aCellStyles ) )
        {
            m_xImpl->m_xCellStyles.set(xFamilies->getByName(aCellStyles),
                UNO_QUERY);
        }
    }

    Reference < XTextFramesSupplier > xTFS( rModel, UNO_QUERY );
    if( xTFS.is() )
    {
        m_xImpl->m_xTextFrames.set(xTFS->getTextFrames());
    }

    Reference < XTextGraphicObjectsSupplier > xTGOS( rModel, UNO_QUERY );
    if( xTGOS.is() )
    {
        m_xImpl->m_xGraphics.set(xTGOS->getGraphicObjects());
    }

    Reference < XTextEmbeddedObjectsSupplier > xTEOS( rModel, UNO_QUERY );
    if( xTEOS.is() )
    {
        m_xImpl->m_xObjects.set(xTEOS->getEmbeddedObjects());
    }

    XMLPropertySetMapper *pPropMapper =
            new XMLTextPropertySetMapper( TextPropMap::PARA, false );
    m_xImpl->m_xParaImpPrMap =
        new XMLTextImportPropertyMapper( pPropMapper, rImport );

    pPropMapper = new XMLTextPropertySetMapper( TextPropMap::TEXT, false );
    m_xImpl->m_xTextImpPrMap =
        new XMLTextImportPropertyMapper( pPropMapper, rImport );

    pPropMapper = new XMLTextPropertySetMapper( TextPropMap::FRAME, false );
    m_xImpl->m_xFrameImpPrMap =
        new XMLTextImportPropertyMapper( pPropMapper, rImport );

    pPropMapper = new XMLTextPropertySetMapper( TextPropMap::SECTION, false );
    m_xImpl->m_xSectionImpPrMap =
        new XMLTextImportPropertyMapper( pPropMapper, rImport );

    pPropMapper = new XMLTextPropertySetMapper( TextPropMap::RUBY, false );
    m_xImpl->m_xRubyImpPrMap =
        new SvXMLImportPropertyMapper( pPropMapper, rImport );
}

XMLTextImportHelper::~XMLTextImportHelper()
{
}

void XMLTextImportHelper::dispose()
{
    if (m_xImpl->m_xAutoStyles)
        m_xImpl->m_xAutoStyles->dispose();
}

SvXMLImportPropertyMapper *XMLTextImportHelper::CreateShapeExtPropMapper(SvXMLImport& rImport)
{
    XMLPropertySetMapper *pPropMapper =
        new XMLTextPropertySetMapper( TextPropMap::FRAME, false );
    return new XMLTextImportPropertyMapper( pPropMapper, rImport );
}

SvXMLImportPropertyMapper *XMLTextImportHelper::CreateParaExtPropMapper(SvXMLImport& rImport)
{
    XMLPropertySetMapper *pPropMapper =
        new XMLTextPropertySetMapper( TextPropMap::SHAPE_PARA, false );
    return new XMLTextImportPropertyMapper( pPropMapper, rImport );
}

SvXMLImportPropertyMapper *XMLTextImportHelper::CreateParaDefaultExtPropMapper(SvXMLImport& rImport)
{
    XMLPropertySetMapper* pPropMapper =
        new XMLTextPropertySetMapper( TextPropMap::SHAPE_PARA, false );
    SvXMLImportPropertyMapper* pImportMapper = new XMLTextImportPropertyMapper( pPropMapper, rImport );

    pPropMapper =
        new XMLTextPropertySetMapper( TextPropMap::TEXT_ADDITIONAL_DEFAULTS, false );
    pImportMapper->ChainImportMapper( new XMLTextImportPropertyMapper( pPropMapper, rImport ) );

    return pImportMapper;
}

SvXMLImportPropertyMapper*
    XMLTextImportHelper::CreateTableDefaultExtPropMapper(
        SvXMLImport& rImport )
{
    XMLPropertySetMapper *pPropMapper =
        new XMLTextPropertySetMapper( TextPropMap::TABLE_DEFAULTS, false );
    return new SvXMLImportPropertyMapper( pPropMapper, rImport );
}

SvXMLImportPropertyMapper*
    XMLTextImportHelper::CreateTableRowDefaultExtPropMapper(
        SvXMLImport& rImport )
{
    XMLPropertySetMapper *pPropMapper =
        new XMLTextPropertySetMapper( TextPropMap::TABLE_ROW_DEFAULTS, false );
    return new SvXMLImportPropertyMapper( pPropMapper, rImport );
}

SvXMLImportPropertyMapper*
    XMLTextImportHelper::CreateTableCellExtPropMapper(
        SvXMLImport& rImport )
{
    XMLPropertySetMapper *pPropMapper =
        new XMLTextPropertySetMapper( TextPropMap::CELL, false );
    return new XMLTextImportPropertyMapper( pPropMapper, rImport );
}

SvXMLImportPropertyMapper*
XMLTextImportHelper::CreateDrawingPageExtPropMapper(SvXMLImport& rImport)
{
    rtl::Reference<XMLPropertyHandlerFactory> const pFactory(new XMLPageMasterPropHdlFactory);
    XMLPropertySetMapper *const pPropMapper(
        new XMLPropertySetMapper(g_XMLPageMasterDrawingPageStyleMap, pFactory, false));
    return new SvXMLImportPropertyMapper(pPropMapper, rImport);
}

void XMLTextImportHelper::SetCursor( const Reference < XTextCursor > & rCursor )
{
    m_xImpl->m_xCursor.set(rCursor);
    m_xImpl->m_xText.set(rCursor->getText());
    m_xImpl->m_xCursorAsRange = rCursor;
}

void XMLTextImportHelper::ResetCursor()
{
    m_xImpl->m_xCursor.clear();
    m_xImpl->m_xText.clear();
    m_xImpl->m_xCursorAsRange.clear();
}


bool XMLTextImportHelper::HasFrameByName( const OUString& rName ) const
{
    return (m_xImpl->m_xTextFrames.is() &&
            m_xImpl->m_xTextFrames->hasByName(rName))
        || (m_xImpl->m_xGraphics.is() &&
            m_xImpl->m_xGraphics->hasByName(rName))
        || (m_xImpl->m_xObjects.is() &&
            m_xImpl->m_xObjects->hasByName(rName));
}

bool XMLTextImportHelper::IsDuplicateFrame(const OUString& sName, sal_Int32 nX, sal_Int32 nY, sal_Int32 nWidth, sal_Int32 nHeight) const
{
    if (HasFrameByName(sName))
    {
        uno::Reference<beans::XPropertySet> xOtherFrame;
        if(m_xImpl->m_xTextFrames.is() && m_xImpl->m_xTextFrames->hasByName(sName))
            xOtherFrame.set(m_xImpl->m_xTextFrames->getByName(sName), uno::UNO_QUERY);
        else if(m_xImpl->m_xGraphics.is() && m_xImpl->m_xGraphics->hasByName(sName))
            xOtherFrame.set(m_xImpl->m_xGraphics->getByName(sName), uno::UNO_QUERY);
        else if (m_xImpl->m_xObjects.is() && m_xImpl->m_xObjects->hasByName(sName))
            xOtherFrame.set(m_xImpl->m_xObjects->getByName(sName), uno::UNO_QUERY);

        Reference< XPropertySetInfo > xPropSetInfo = xOtherFrame->getPropertySetInfo();
        if(xPropSetInfo->hasPropertyByName("Width"))
        {
            sal_Int32 nOtherWidth = 0;
            xOtherFrame->getPropertyValue("Width") >>= nOtherWidth;
            if(nWidth != nOtherWidth)
                return false;
        }

        if (xPropSetInfo->hasPropertyByName("Height"))
        {
            sal_Int32 nOtherHeight = 0;
            xOtherFrame->getPropertyValue("Height") >>= nOtherHeight;
            if (nHeight != nOtherHeight)
                return false;
        }

        if (xPropSetInfo->hasPropertyByName("HoriOrientPosition"))
        {
            sal_Int32 nOtherX = 0;
            xOtherFrame->getPropertyValue("HoriOrientPosition") >>= nOtherX;
            if (nX != nOtherX)
                return false;
        }

        if (xPropSetInfo->hasPropertyByName("VertOrientPosition"))
        {
            sal_Int32 nOtherY = 0;
            xOtherFrame->getPropertyValue("VertOrientPosition") >>= nOtherY;
            if (nY != nOtherY)
                return false;
        }

        // In some case, position is not defined for frames, so check whether the two frames follow each other (are anchored to the same position)
        return m_xImpl->msLastImportedFrameName == sName;
    }
    return false;
}

void XMLTextImportHelper::StoreLastImportedFrameName(const OUString& rName)
{
    m_xImpl->msLastImportedFrameName = rName;
}

void XMLTextImportHelper::ClearLastImportedTextFrameName()
{
    m_xImpl->msLastImportedFrameName.clear();
}

void XMLTextImportHelper::InsertString( const OUString& rChars )
{
    assert(m_xImpl->m_xText.is());
    assert(m_xImpl->m_xCursorAsRange.is());
    if (m_xImpl->m_xText.is())
    {
        m_xImpl->m_xText->insertString(m_xImpl->m_xCursorAsRange,
            rChars, false);
    }
}

void XMLTextImportHelper::InsertString( std::u16string_view rChars,
                                        bool& rIgnoreLeadingSpace )
{
    assert(m_xImpl->m_xText.is());
    assert(m_xImpl->m_xCursorAsRange.is());
    if (!m_xImpl->m_xText.is())
        return;

    sal_Int32 nLen = rChars.size();
    OUStringBuffer sChars( nLen );

    for( sal_Int32 i=0; i < nLen; i++ )
    {
        sal_Unicode c = rChars[i];
        switch( c )
        {
            case 0x20:
            case 0x09:
            case 0x0a:
            case 0x0d:
                if( !rIgnoreLeadingSpace )
                    sChars.append( u' ' );
                rIgnoreLeadingSpace = true;
                break;
            default:
                rIgnoreLeadingSpace = false;
                sChars.append( c );
                break;
        }
    }
    m_xImpl->m_xText->insertString(m_xImpl->m_xCursorAsRange,
                                   sChars.makeStringAndClear(), false);
}

void XMLTextImportHelper::InsertControlCharacter( sal_Int16 nControl )
{
    assert(m_xImpl->m_xText.is());
    assert(m_xImpl->m_xCursorAsRange.is());
    if (m_xImpl->m_xText.is())
    {
        m_xImpl->m_xText->insertControlCharacter(
            m_xImpl->m_xCursorAsRange, nControl, false);
    }
}

void XMLTextImportHelper::InsertTextContent(
    Reference < XTextContent > const & xContent )
{
    assert(m_xImpl->m_xText.is());
    assert(m_xImpl->m_xCursorAsRange.is());
    if (m_xImpl->m_xText.is())
    {
        // note: this may throw IllegalArgumentException and callers handle it
        m_xImpl->m_xText->insertTextContent( m_xImpl->m_xCursorAsRange, xContent, false);
    }
}

void XMLTextImportHelper::DeleteParagraph()
{
    assert(m_xImpl->m_xText.is());
    assert(m_xImpl->m_xCursor.is());
    assert(m_xImpl->m_xCursorAsRange.is());

    bool bDelete = true;
    Reference < XEnumerationAccess > const xEnumAccess(
        m_xImpl->m_xCursor, UNO_QUERY);
    if( xEnumAccess.is() )
    {
        Reference < XEnumeration > xEnum(xEnumAccess->createEnumeration());
        SAL_WARN_IF(!xEnum->hasMoreElements(), "xmloff.text",
                "empty text enumeration");
        if( xEnum->hasMoreElements() )
        {
            Reference < XComponent > xComp( xEnum->nextElement(), UNO_QUERY );
            assert(xComp.is());
            if( xComp.is() )
            {
                xComp->dispose();
                bDelete = false;
            }
        }
    }
    if( bDelete )
    {
        if (m_xImpl->m_xCursor->goLeft( 1, true ))
        {
            m_xImpl->m_xText->insertString(m_xImpl->m_xCursorAsRange,
                                           "", true);
        }
    }
}

OUString XMLTextImportHelper::ConvertStarFonts( const OUString& rChars,
                                                const OUString& rStyleName,
                                                sal_uInt8& rFlags,
                                                bool bPara,
                                                SvXMLImport& rImport ) const
{
    OUStringBuffer sChars( rChars );
    bool bConverted = false;
    for( sal_Int32 j=0; j<rChars.getLength(); j++ )
    {
        sal_Unicode c = rChars[j];
        if( c >= 0xf000 && c <= 0xf0ff )
        {
            if( (rFlags & CONV_STAR_FONT_FLAGS_VALID) == 0 )
            {
                XMLTextStyleContext *pStyle = nullptr;
                XmlStyleFamily nFamily = bPara ? XmlStyleFamily::TEXT_PARAGRAPH
                                               : XmlStyleFamily::TEXT_TEXT;
                if (!rStyleName.isEmpty() && m_xImpl->m_xAutoStyles.is())
                {
                    const SvXMLStyleContext* pTempStyle =
                        m_xImpl->m_xAutoStyles->
                                FindStyleChildContext( nFamily, rStyleName,
                                                       true );
                    pStyle = const_cast<XMLTextStyleContext*>( dynamic_cast< const XMLTextStyleContext* >(pTempStyle));
                }

                if( pStyle )
                {
                    sal_Int32 nCount = pStyle->GetProperties_().size();
                    if( nCount )
                    {
                        rtl::Reference < SvXMLImportPropertyMapper > xImpPrMap =
                            m_xImpl->m_xAutoStyles->GetImportPropertyMapper(nFamily);
                        if( xImpPrMap.is() )
                        {
                            rtl::Reference<XMLPropertySetMapper> rPropMapper =
                                xImpPrMap->getPropertySetMapper();
                            for( sal_Int32 i=0; i < nCount; i++ )
                            {
                                const XMLPropertyState& rProp = pStyle->GetProperties_()[i];
                                sal_Int32 nIdx = rProp.mnIndex;
                                sal_uInt32 nContextId = rPropMapper->GetEntryContextId(nIdx);
                                if( CTF_FONTFAMILYNAME == nContextId )
                                {
                                    rFlags &= ~(CONV_FROM_STAR_BATS|CONV_FROM_STAR_MATH);
                                    OUString sFontName;
                                    rProp.maValue >>= sFontName;
                                    if( sFontName.equalsIgnoreAsciiCase( "StarBats"  ) )
                                        rFlags |= CONV_FROM_STAR_BATS;
                                    else if( sFontName.equalsIgnoreAsciiCase( "StarMath" ) )
                                        rFlags |= CONV_FROM_STAR_MATH;
                                    break;
                                }
                            }
                        }
                    }

                }

                rFlags |= CONV_STAR_FONT_FLAGS_VALID;
            }
            if( (rFlags & CONV_FROM_STAR_BATS ) != 0 )
            {
                sChars[j] = rImport.ConvStarBatsCharToStarSymbol( c );
                bConverted = true;
            }
            else if( (rFlags & CONV_FROM_STAR_MATH ) != 0 )
            {
                sChars[j] = rImport.ConvStarMathCharToStarSymbol( c );
                bConverted = true;
            }
        }
    }

    return bConverted ? sChars.makeStringAndClear() : rChars;
}

/* Helper method to determine, if a paragraph style has a list style (inclusive
   an empty one) inherits a list style (inclusive an empty one) from one of its parents (#i69629#)
*/
/* Apply special case, that found list style equals the chapter numbering, also
   to the found list styles of the parent styles. (#i73973#)
*/
static bool lcl_HasListStyle( const OUString& sStyleName,
                              const Reference < XNameContainer >& xParaStyles,
                              SvXMLImport const & rImport,
                              const OUString& sNumberingStyleName,
                              std::u16string_view sOutlineStyleName )
{
    bool bRet( false );

    if ( !xParaStyles->hasByName( sStyleName ) )
    {
        // error case
        return true;
    }

    Reference< XPropertyState > xPropState( xParaStyles->getByName( sStyleName ),
                                            UNO_QUERY );
    if ( !xPropState.is() )
    {
        // error case
        return false;
    }

    if ( xPropState->getPropertyState( sNumberingStyleName ) == PropertyState_DIRECT_VALUE )
    {
        // list style found
        bRet = true;
        // special case: the set list style equals the chapter numbering
        Reference< XPropertySet > xPropSet( xPropState, UNO_QUERY );
        if ( xPropSet.is() )
        {
            OUString sListStyle;
            xPropSet->getPropertyValue( sNumberingStyleName ) >>= sListStyle;
            if ( !sListStyle.isEmpty() &&
                 sListStyle == sOutlineStyleName )
            {
                bRet = false;
            }
        }
    }
    else
    {
        // Tools.Outline settings lost on Save (#i77708#)
        sal_Int32 nUPD( 0 );
        sal_Int32 nBuild( 0 );
        // Don't use UPD for versioning: xmloff/source/text/txtstyli.cxx and txtimp.cxx (#i86058#)
        const bool bBuildIdFound = rImport.getBuildIds( nUPD, nBuild );
        // search list style at parent
        Reference<XStyle> xStyle( xPropState, UNO_QUERY );
        while ( xStyle.is() )
        {
            OUString aParentStyle( xStyle->getParentStyle() );
            if ( !aParentStyle.isEmpty() )
            {
                aParentStyle =
                    rImport.GetStyleDisplayName( XmlStyleFamily::TEXT_PARAGRAPH,
                                                 aParentStyle );
            }
            if ( aParentStyle.isEmpty() || !xParaStyles->hasByName( aParentStyle ) )
            {
                // no list style found
                break;
            }
            else
            {
                xPropState.set( xParaStyles->getByName( aParentStyle ),
                                UNO_QUERY );
                if ( !xPropState.is() )
                {
                    // error case
                    return true;
                }
                if ( xPropState->getPropertyState( sNumberingStyleName ) == PropertyState_DIRECT_VALUE )
                {
                    // list style found
                    bRet = true;
                    // Special case: the found list style equals the chapter numbering (#i73973#)
                    Reference< XPropertySet > xPropSet( xPropState, UNO_QUERY );
                    if ( xPropSet.is() )
                    {
                        OUString sListStyle;
                        xPropSet->getPropertyValue( sNumberingStyleName ) >>= sListStyle;
                        if ( !sListStyle.isEmpty() &&
                             sListStyle == sOutlineStyleName )
                        {
                            bRet = false;
                        }
                        // Special handling for text documents from OOo version prior OOo 2.4 (#i77708#)
                        /* Check explicitly on certain versions and on import of
                           text documents in OpenOffice.org file format (#i86058#)
                        */
                        else if ( sListStyle.isEmpty() &&
                                  ( rImport.IsTextDocInOOoFileFormat() ||
                                    ( bBuildIdFound &&
                                      ( ( nUPD == 641 ) || ( nUPD == 645 ) || // prior OOo 2.0
                                        ( nUPD == 680 && nBuild <= 9238 ) ) ) ) ) // OOo 2.0 - OOo 2.3.1
                        {
                            bRet = false;
                        }
                    }
                    break;
                }
                else
                {
                    // search list style at parent
                    Reference<XStyle> xParentStyle(xPropState, UNO_QUERY);
                    if (xStyle == xParentStyle)
                    {
                        // error case
                        return true;
                    }
                    xStyle = xParentStyle;
                }
            }
        }
    }

    return bRet;
}

namespace {

auto IsPropertySet(uno::Reference<container::XNameContainer> const& rxParaStyles,
        uno::Reference<beans::XPropertySet> const& rxPropSet,
        OUString const& rProperty)
{
    uno::Reference<beans::XPropertyState> const xPropState(rxPropSet, uno::UNO_QUERY);
    // note: this is true only if it is set in automatic style
    if (xPropState->getPropertyState(rProperty) == beans::PropertyState_DIRECT_VALUE)
    {
        return true;
    }
    if (xPropState->getPropertyState("NumberingStyleName") == beans::PropertyState_DIRECT_VALUE)
    {
        return false; // tdf#159903 this overrides value in the parent style
    }
    // check if it is set by any parent common style
    OUString style;
    rxPropSet->getPropertyValue("ParaStyleName") >>= style;
    while (!style.isEmpty() && rxParaStyles.is() && rxParaStyles->hasByName(style))
    {
        uno::Reference<style::XStyle> const xStyle(rxParaStyles->getByName(style), uno::UNO_QUERY);
        assert(xStyle.is());
        uno::Reference<beans::XPropertyState> const xStyleProps(xStyle, uno::UNO_QUERY);
        if (xStyleProps->getPropertyState(rProperty) == beans::PropertyState_DIRECT_VALUE)
        {
            return true;
        }
        if (xStyleProps->getPropertyState("NumberingStyleName") == beans::PropertyState_DIRECT_VALUE)
        {
            return false; // tdf#159903 this overrides value in the parent style
        }
        style = xStyle->getParentStyle();
    }
    return false;
};

} // namespace

OUString XMLTextImportHelper::SetStyleAndAttrs(
        SvXMLImport & rImport,
        const Reference < XTextCursor >& rCursor,
        const OUString& rStyleName,
        bool bPara,
        bool bOutlineLevelAttrFound,
        sal_Int8 nOutlineLevel,
        // Numberings/Bullets in table not visible after save/reload (#i80724#)
        bool bSetListAttrs,
        bool bOutlineContentVisible)
{
    static constexpr OUString s_NumberingRules = u"NumberingRules"_ustr;
    static constexpr OUString s_NumberingIsNumber = u"NumberingIsNumber"_ustr;
    static constexpr OUString s_NumberingLevel = u"NumberingLevel"_ustr;
    static constexpr OUString s_ParaIsNumberingRestart = u"ParaIsNumberingRestart"_ustr;
    static constexpr OUString s_NumberingStartValue = u"NumberingStartValue"_ustr;
    static constexpr OUString s_PropNameListId = u"ListId"_ustr;
    static constexpr OUString s_PageDescName = u"PageDescName"_ustr;
    static constexpr OUString s_OutlineLevel = u"OutlineLevel"_ustr;

    const XmlStyleFamily nFamily = bPara ? XmlStyleFamily::TEXT_PARAGRAPH
                                         : XmlStyleFamily::TEXT_TEXT;
    XMLTextStyleContext *pStyle = nullptr;
    OUString sStyleName( rStyleName );
    if (!sStyleName.isEmpty() && m_xImpl->m_xAutoStyles.is())
    {
        const SvXMLStyleContext* pTempStyle =
            m_xImpl->m_xAutoStyles->FindStyleChildContext( nFamily, sStyleName, true );
        pStyle = const_cast<XMLTextStyleContext*>(dynamic_cast< const XMLTextStyleContext* >(pTempStyle));
    }
    if( pStyle )
        sStyleName = pStyle->GetParentName();

    Reference < XPropertySet > xPropSet( rCursor, UNO_QUERY );
    Reference< XPropertySetInfo > xPropSetInfo(
        xPropSet->getPropertySetInfo());

    // style
    if( !sStyleName.isEmpty() )
    {
        sStyleName = rImport.GetStyleDisplayName( nFamily, sStyleName );
        const OUString rPropName = bPara ? OUString("ParaStyleName") : OUString("CharStyleName");
        const Reference < XNameContainer > & rStyles = bPara
            ? m_xImpl->m_xParaStyles
            : m_xImpl->m_xTextStyles;
        if( rStyles.is() &&
            xPropSetInfo->hasPropertyByName( rPropName ) &&
            rStyles->hasByName( sStyleName ) )
        {
            xPropSet->setPropertyValue( rPropName, Any(sStyleName) );
        }
        else
            sStyleName.clear();
    }

    /* The outline level needs to be only applied as list level, if the heading
       is not inside a list and if it by default applies the outline style. (#i70748#)
    */
    bool bApplyOutlineLevelAsListLevel( false );
    // Numberings/Bullets in table not visible after save/reload (#i80724#)
    if (bSetListAttrs && bPara
        && xPropSetInfo->hasPropertyByName( s_NumberingRules))
    {
        // Set numbering rules
        Reference< XIndexReplace > const xNumRules(
                xPropSet->getPropertyValue(s_NumberingRules), UNO_QUERY);

        XMLTextListBlockContext * pListBlock(nullptr);
        XMLTextListItemContext  * pListItem(nullptr);
        XMLNumberedParaContext  * pNumberedParagraph(nullptr);
        GetTextListHelper().ListContextTop(
            pListBlock, pListItem, pNumberedParagraph);

        assert(!(pListBlock && pNumberedParagraph) && "XMLTextImportHelper::"
            "SetStyleAndAttrs: both list and numbered-paragraph???");

        Reference < XIndexReplace > xNewNumRules;
        sal_Int8 nLevel(-1);
        OUString sListId;
        sal_Int16 nStartValue(-1);
        bool bNumberingIsNumber(true);
        // Assure that list style of automatic paragraph style is applied at paragraph. (#i101349#)
        bool bApplyNumRules(pStyle && pStyle->IsListStyleSet());
        bool bApplyNumRulesFix(false);

        if (pListBlock) {
            // the xNumRules is always created, even without a list-style-name
            if (!bApplyNumRules
                && (pListBlock->HasListStyleName()
                    || (pListItem != nullptr && pListItem->HasNumRulesOverride())))
            {
                bApplyNumRules = true; // tdf#114287
                bApplyNumRulesFix = rImport.isGeneratorVersionOlderThan(SvXMLImport::AOO_4x, SvXMLImport::LO_76);
            }

            if (!pListItem) {
                bNumberingIsNumber = false; // list-header
            }

            // consider text:style-override property of <text:list-item>
            xNewNumRules.set(
                (pListItem != nullptr && pListItem->HasNumRulesOverride())
                    ? pListItem->GetNumRulesOverride()
                    : pListBlock->GetNumRules() );
            nLevel = static_cast<sal_Int8>(pListBlock->GetLevel());

            if ( pListItem && pListItem->HasStartValue() ) {
               nStartValue = pListItem->GetStartValue();
            }

            // Inconsistent behavior regarding lists (#i92811#)
            sListId = m_xImpl->m_xTextListsHelper->GetListIdForListBlock(
                            *pListBlock);
        }
        else if (pNumberedParagraph)
        {
            xNewNumRules.set(pNumberedParagraph->GetNumRules());
            nLevel = static_cast<sal_Int8>(pNumberedParagraph->GetLevel());
            sListId = pNumberedParagraph->GetListId();
            nStartValue = pNumberedParagraph->GetStartValue();
        }


        if (pListBlock || pNumberedParagraph)
        {
            if (!bApplyNumRules || bApplyNumRulesFix)
            {
                bool bSameNumRules = xNewNumRules == xNumRules;
                if( !bSameNumRules && xNewNumRules.is() && xNumRules.is() )
                {
                    // If the interface pointers are different, then this does
                    // not mean that the num rules are different. Further tests
                    // are required then. However, if only one num rule is
                    // set, no tests are required of course.
                    Reference< XNamed > xNewNamed( xNewNumRules, UNO_QUERY );
                    Reference< XNamed > xNamed( xNumRules, UNO_QUERY );
                    if( xNewNamed.is() && xNamed.is() )
                    {
                        bSameNumRules = xNewNamed->getName() == xNamed->getName();
                    }
                    else
                    {
                        Reference< XAnyCompare > xNumRuleCompare( xNumRules, UNO_QUERY );
                        if( xNumRuleCompare.is() )
                        {
                            bSameNumRules = (xNumRuleCompare->compare( Any(xNumRules), Any(xNewNumRules) ) == 0);
                        }
                    }
                }
                if (!bApplyNumRules)
                {
                    bApplyNumRules = !bSameNumRules;
                }
                if (!bSameNumRules)
                {
                    bApplyNumRulesFix = false;
                }
            }

            if ( bApplyNumRules )
            {
                // #102607# This may except when xNewNumRules contains
                // a Writer-NumRule-Implementation bug gets applied to
                // a shape. Since this may occur inside a document
                // (e.g. when edited), this must be handled
                // gracefully.
                try
                {
                    xPropSet->setPropertyValue(
                        s_NumberingRules, Any(xNewNumRules) );
                    if (bApplyNumRulesFix)
                    {   // tdf#156146 override list margins for bug compatibility
                        if (IsPropertySet(m_xImpl->m_xParaStyles, xPropSet, "ParaLeftMargin"))
                        {
                            uno::Any const left(xPropSet->getPropertyValue("ParaLeftMargin"));
                            xPropSet->setPropertyValue("ParaLeftMargin", left);
                        }
                        if (IsPropertySet(m_xImpl->m_xParaStyles, xPropSet, "ParaFirstLineIndent"))
                        {
                            uno::Any const first(xPropSet->getPropertyValue("ParaFirstLineIndent"));
                            xPropSet->setPropertyValue("ParaFirstLineIndent", first);
                        }
                    }
                }
                catch(const Exception&)
                {
                    ; // I would really like to use a warning here,
                      // but I can't access the XMLErrorHandler from
                      // here.
                }
            }

            if (!bNumberingIsNumber &&
                xPropSetInfo->hasPropertyByName(s_NumberingIsNumber))
            {
                xPropSet->setPropertyValue(s_NumberingIsNumber, Any(false));
            }

            xPropSet->setPropertyValue( s_NumberingLevel, Any(nLevel) );

            if( pListBlock && pListBlock->IsRestartNumbering() )
            {
                // TODO: property missing
                if (xPropSetInfo->hasPropertyByName(s_ParaIsNumberingRestart))
                {
                    xPropSet->setPropertyValue(s_ParaIsNumberingRestart,
                                               Any(true) );
                }
                pListBlock->ResetRestartNumbering();
            }

            if ( 0 <= nStartValue &&
                xPropSetInfo->hasPropertyByName(s_NumberingStartValue))
            {
                xPropSet->setPropertyValue(s_NumberingStartValue,
                                           Any(nStartValue));
            }

            if (xPropSetInfo->hasPropertyByName(s_PropNameListId))
            {
                if (!sListId.isEmpty()) {
                    xPropSet->setPropertyValue(s_PropNameListId,
                        Any(sListId) );
                }
            }

            GetTextListHelper().SetListItem( nullptr );
        }
        else
        {
            /* If the paragraph is not in a list but its style, remove it from
               the list. Do not remove it, if the list of the style is
               the chapter numbering rule.
            */
            if( xNumRules.is() )
            {
                bool bRemove( true );
                // Special handling for document from OOo 2.x (#i70748#)
                sal_Int32 nUPD( 0 );
                sal_Int32 nBuild( 0 );
                const bool bBuildIdFound = rImport.getBuildIds( nUPD, nBuild );
                if ( ( bBuildIdFound && nUPD == 680 ) ||
                     !pStyle || !pStyle->IsListStyleSet() )
                {
                    if (m_xImpl->m_xChapterNumbering.is())
                    {
                        Reference< XNamed > xNumNamed( xNumRules, UNO_QUERY );
                        Reference< XNamed > const xChapterNumNamed (
                            m_xImpl->m_xChapterNumbering, UNO_QUERY);
                        if ( xNumNamed.is() && xChapterNumNamed.is() &&
                             xNumNamed->getName() == xChapterNumNamed->getName() )
                        {
                            bRemove = false;
                            // RFE: inserting headings into text documents (#i70748#)
                            bApplyOutlineLevelAsListLevel = true;
                        }
                    }
                }
                else
                {
                    SAL_INFO_IF(!pStyle->GetListStyle().isEmpty(),
                        "xmloff.text",
                        "automatic paragraph style with list style name, but paragraph not in list???");
                }
                if ( bRemove )
                {
                    xPropSet->setPropertyValue( s_NumberingRules, Any() );
                }
            }
        }
    }

    // hard paragraph properties
    if( pStyle )
    {
        pStyle->FillPropertySet( xPropSet );
        if( bPara && pStyle->HasMasterPageName() &&
            xPropSetInfo->hasPropertyByName(s_PageDescName))
        {
            OUString sDisplayName(
                rImport.GetStyleDisplayName(
                                XmlStyleFamily::MASTER_PAGE,
                                pStyle->GetMasterPageName()) );
            if( sDisplayName.isEmpty() ||
                (m_xImpl->m_xPageStyles.is() &&
                 m_xImpl->m_xPageStyles->hasByName( sDisplayName)))
            {
                xPropSet->setPropertyValue(s_PageDescName,
                        Any(sDisplayName));
            }
        }
        if( bPara && !pStyle->GetDropCapStyleName().isEmpty() &&
            m_xImpl->m_xTextStyles.is())
        {
            OUString sDisplayName(
                rImport.GetStyleDisplayName(
                                XmlStyleFamily::TEXT_TEXT,
                                pStyle->GetDropCapStyleName()) );
            if (m_xImpl->m_xTextStyles->hasByName(sDisplayName) &&
                xPropSetInfo->hasPropertyByName("DropCapCharStyleName"))
            {
                xPropSet->setPropertyValue("DropCapCharStyleName", Any(sDisplayName));
            }
        }

        // combined characters special treatment
        if (!bPara && pStyle->HasCombinedCharactersLetter())
        {
            // insert combined characters text field
            if (m_xImpl->m_xServiceFactory.is())
            {
                uno::Reference<beans::XPropertySet> const xTmp(
                    m_xImpl->m_xServiceFactory->createInstance(
                        "com.sun.star.text.TextField.CombinedCharacters"), UNO_QUERY);
                if( xTmp.is() )
                {
                    // fix cursor if larger than possible for
                    // combined characters field
                    if (rCursor->getString().getLength() >
                            MAX_COMBINED_CHARACTERS)
                    {
                        rCursor->gotoRange(rCursor->getStart(), false);
                        rCursor->goRight(MAX_COMBINED_CHARACTERS, true);
                    }

                    // set field value (the combined character string)
                    xTmp->setPropertyValue("Content",
                        Any(rCursor->getString()));

                    // insert the field over it's original text
                    Reference<XTextContent> xTextContent(xTmp, UNO_QUERY);
                    if (m_xImpl->m_xText.is() && rCursor.is())
                    {
                        // #i107225# the combined characters need to be inserted first
                        // the selected text has to be removed afterwards
                        m_xImpl->m_xText->insertTextContent( rCursor->getStart(), xTextContent, true );

                        if( !rCursor->getString().isEmpty() )
                        {
                            try
                            {
                                uno::Reference< text::XTextCursor > xCrsr = rCursor->getText()->createTextCursorByRange( rCursor->getStart() );
                                xCrsr->goLeft( 1, true );
                                uno::Reference< beans::XPropertySet> xCrsrProperties( xCrsr, uno::UNO_QUERY_THROW );
                                //the hard properties of the removed text need to be applied to the combined characters field
                                pStyle->FillPropertySet( xCrsrProperties );
                                xCrsr->collapseToEnd();
                                xCrsr->gotoRange( rCursor->getEnd(), true );
                                xCrsr->setString( OUString() );
                            }
                            catch(const uno::Exception&)
                            {
                            }
                        }
                    }
                }
            }
        }
    }

    // outline level; set after list style has been set
    // Complete re-worked and corrected: (#i53198#)
    // - set outline level at paragraph
    // - set numbering level at paragraph, if none is already set
    // - assure that style is marked as an outline style for the corresponding
    //   outline level.
    // - DO NOT set type of numbering rule to outline.
    // - DO NOT set numbering rule directly at the paragraph.

    // Some minor rework and adjust access to paragraph styles (#i70748#)
    if ( bPara )
    {
        // Headings not numbered anymore in 3.1 (#i103817#)
        sal_Int16 nCurrentOutlineLevelInheritedFromParagraphStyle = 0;
        const bool bHasOutlineLevelProp(
            xPropSetInfo->hasPropertyByName(s_OutlineLevel));
        if ( bHasOutlineLevelProp )
        {
            xPropSet->getPropertyValue(s_OutlineLevel)
                >>= nCurrentOutlineLevelInheritedFromParagraphStyle;
        }
        if ( nOutlineLevel > 0 )
        {
            if ( bHasOutlineLevelProp )
            {
                // In case that the value equals the value of its paragraph style
                // attribute outline level, the paragraph attribute value is left unset
                if ( nCurrentOutlineLevelInheritedFromParagraphStyle != nOutlineLevel )
                {
                    xPropSet->setPropertyValue( s_OutlineLevel,
                        Any( static_cast<sal_Int16>(nOutlineLevel) ) );
                }
            }
            if (!bOutlineContentVisible)
            {
                uno::Sequence<beans::PropertyValue> aGrabBag;
                xPropSet->getPropertyValue("ParaInteropGrabBag") >>= aGrabBag;
                sal_Int32 length = aGrabBag.getLength();
                aGrabBag.realloc(length + 1);
                auto pGrabBag = aGrabBag.getArray();
                pGrabBag[length].Name = "OutlineContentVisibleAttr";
                pGrabBag[length].Value <<= bool(bOutlineContentVisible);
                xPropSet->setPropertyValue("ParaInteropGrabBag", uno::Any(aGrabBag));
            }
            // RFE: inserting headings into text documents (#i70748#)
            if ( bApplyOutlineLevelAsListLevel )
            {
                sal_Int16 nNumLevel = -1;
                xPropSet->getPropertyValue( s_NumberingLevel ) >>= nNumLevel;
                if ( nNumLevel == -1 ||
                     nNumLevel != (nOutlineLevel - 1) )
                {
                    xPropSet->setPropertyValue( s_NumberingLevel,
                            Any( static_cast<sal_Int8>(nOutlineLevel - 1) ) );
                }
            }
            /* Correction: (#i69629#)
               - for text document from version OOo 2.0.4/SO 8 PU4 and earlier
                 the paragraph style of a heading should be assigned to the
                 corresponding list level of the outline style.
               - for other text documents the paragraph style of a heading is only
                 a candidate for an assignment to the list level of the outline
                 style, if it has no direct list style property and (if exists) the
                 automatic paragraph style has also no direct list style set.
            */
            if (m_xImpl->m_xParaStyles.is() && m_xImpl->m_xParaStyles->hasByName(sStyleName))
            {
                bool bOutlineStyleCandidate( false );

                sal_Int32 nUPD( 0 );
                sal_Int32 nBuild( 0 );
                const bool bBuildIdFound = rImport.getBuildIds( nUPD, nBuild );
                // Lost outline numbering in master document (#i73509#)
                // Check explicitly on certain versions (#i86058#)
                if ( rImport.IsTextDocInOOoFileFormat() ||
                     ( bBuildIdFound &&
                       ( nUPD == 645 || nUPD == 641 ) ) )
                {
                    bOutlineStyleCandidate = true;
                }
                else if ( nUPD == 680 && nBuild <= 9073 ) /* BuildId of OOo 2.0.4/SO8 PU4 */
                {
                    bOutlineStyleCandidate = bOutlineLevelAttrFound;
                }
                if ( bOutlineStyleCandidate )
                {
                    AddOutlineStyleCandidate( nOutlineLevel, sStyleName );
                }
                // Assure that heading applies the outline style (#i103817#)
                if ( ( !pStyle || !pStyle->IsListStyleSet() ) &&
                     !bOutlineStyleCandidate &&
                     m_xImpl->m_xChapterNumbering.is())
                {
                    if ( !lcl_HasListStyle( sStyleName,
                                    m_xImpl->m_xParaStyles, GetXMLImport(),
                                    u"NumberingStyleName"_ustr,
                                    u"" ) )
                    {
                        // heading not in a list --> apply outline style
                        xPropSet->setPropertyValue( s_NumberingRules,
                            Any(m_xImpl->m_xChapterNumbering) );
                        xPropSet->setPropertyValue( s_NumberingLevel,
                            Any(static_cast<sal_Int8>(nOutlineLevel - 1)));
                    }
                }
            }
        }
        //handle for text:p,if the paragraphstyle outlinelevel is set to[1~10]
        else if( bHasOutlineLevelProp )
        {
            if ( nCurrentOutlineLevelInheritedFromParagraphStyle != 0 )
            {
                xPropSet->setPropertyValue(s_OutlineLevel,
                    Any( sal_Int16(0) ));
            }
        }
    }

    return sStyleName;
}

void XMLTextImportHelper::FindOutlineStyleName( OUString& rStyleName,
                                                sal_Int8 nOutlineLevel )
{
    // style name empty?
    if( !rStyleName.isEmpty() )
        return;

    // Empty? Then we need o do stuff. Let's do error checking first.
    if (m_xImpl->m_xChapterNumbering.is() &&
        ( nOutlineLevel > 0 ) &&
        (nOutlineLevel <= m_xImpl->m_xChapterNumbering->getCount()))
    {
        nOutlineLevel--;   // for the remainder, the level's are 0-based

        // empty style name: look-up previously used name

        // if we don't have a previously used name, we'll use the default
        m_xImpl->InitOutlineStylesCandidates();
        if (m_xImpl->m_xOutlineStylesCandidates[nOutlineLevel].empty())
        {
            // no other name used previously? Then use default

            // iterate over property value sequence to find the style name
            Sequence<PropertyValue> aProperties;
            m_xImpl->m_xChapterNumbering->getByIndex( nOutlineLevel )
                >>= aProperties;
            auto pProp = std::find_if(std::cbegin(aProperties), std::cend(aProperties),
                [](const PropertyValue& rProp) { return rProp.Name == "HeadingStyleName"; });
            if (pProp != std::cend(aProperties))
            {
                OUString aOutlineStyle;
                pProp->Value >>= aOutlineStyle;
                m_xImpl->m_xOutlineStylesCandidates[nOutlineLevel]
                    .push_back( aOutlineStyle );
            }
        }

        // finally, we'll use the previously used style name for this
        // format (or the default we've just put into that style)
        // take last added one (#i71249#)
        rStyleName =
            m_xImpl->m_xOutlineStylesCandidates[nOutlineLevel].back();
    }
    // else: nothing we can do, so we'll leave it empty
    // else: we already had a style name, so we let it pass.
}

void XMLTextImportHelper::AddOutlineStyleCandidate( const sal_Int8 nOutlineLevel,
                                                    const OUString& rStyleName )
{
    if (!rStyleName.isEmpty()
        && m_xImpl->m_xChapterNumbering.is()
        && (nOutlineLevel > 0)
        && (nOutlineLevel <= m_xImpl->m_xChapterNumbering->getCount()))
    {
        m_xImpl->InitOutlineStylesCandidates();
        m_xImpl->m_xOutlineStylesCandidates[nOutlineLevel-1].push_back(
            rStyleName);
    }
}

void XMLTextImportHelper::SetOutlineStyles( bool bSetEmptyLevels )
{
    if (!(m_xImpl->m_xOutlineStylesCandidates != nullptr || bSetEmptyLevels) ||
        !m_xImpl->m_xChapterNumbering.is() ||
        IsInsertMode())
        return;

    bool bChooseLastOne( false );
    {
        if ( GetXMLImport().IsTextDocInOOoFileFormat() )
        {
            bChooseLastOne = true;
        }
        else
        {
            sal_Int32 nUPD( 0 );
            sal_Int32 nBuild( 0 );
            if ( GetXMLImport().getBuildIds( nUPD, nBuild ) )
            {
                // check explicitly on certain versions
                bChooseLastOne = ( nUPD == 641 ) || ( nUPD == 645 ) ||  // prior OOo 2.0
                                 ( nUPD == 680 && nBuild <= 9073 ); // OOo 2.0 - OOo 2.0.4
            }
        }
    }

    OUString sOutlineStyleName;
    {
        Reference<XPropertySet> xChapterNumRule(
            m_xImpl->m_xChapterNumbering, UNO_QUERY);
        xChapterNumRule->getPropertyValue("Name") >>= sOutlineStyleName;
    }

    const sal_Int32 nCount = m_xImpl->m_xChapterNumbering->getCount();
    /* First collect all paragraph styles chosen for assignment to each
       list level of the outline style, then perform the intrinsic assignment.
       Reason: The assignment of a certain paragraph style to a list level
               of the outline style causes side effects on the children
               paragraph styles in Writer. (#i106218#)
    */
    ::std::vector<OUString> sChosenStyles(nCount);
    for( sal_Int32 i=0; i < nCount; ++i )
    {
        if ( bSetEmptyLevels ||
             (m_xImpl->m_xOutlineStylesCandidates &&
              !m_xImpl->m_xOutlineStylesCandidates[i].empty()))
        {
            // determine, which candidate is one to be assigned to the list
            // level of the outline style
            if (m_xImpl->m_xOutlineStylesCandidates &&
                !m_xImpl->m_xOutlineStylesCandidates[i].empty())
            {
                if ( bChooseLastOne )
                {
                    sChosenStyles[i] =
                    m_xImpl->m_xOutlineStylesCandidates[i].back();
                }
                else
                {
                    for (size_t j = 0;
                        j < m_xImpl->m_xOutlineStylesCandidates[i].size();
                        ++j)
                    {
                        if (!lcl_HasListStyle(
                                m_xImpl->m_xOutlineStylesCandidates[i][j],
                                m_xImpl->m_xParaStyles,
                                GetXMLImport(),
                                "NumberingStyleName",
                                sOutlineStyleName))
                        {
                            sChosenStyles[i] =
                                m_xImpl->m_xOutlineStylesCandidates[i][j];
                            break;
                        }
                    }
                }
            }
        }
    }
    // Trashed outline numbering in ODF 1.1 text document created by OOo 3.x (#i106218#)
    Sequence < PropertyValue > aProps( 1 );
    PropertyValue *pProps = aProps.getArray();
    pProps->Name = "HeadingStyleName";
    for ( sal_Int32 i = 0; i < nCount; ++i )
    {
        // Paragraph style assignments in Outline of template lost from second level on (#i107610#)
        if ( bSetEmptyLevels || !sChosenStyles[i].isEmpty() )
        {
            pProps->Value <<= sChosenStyles[i];
            m_xImpl->m_xChapterNumbering->replaceByIndex(i,
                    Any( aProps ));
        }
    }

}

void XMLTextImportHelper::SetHyperlink(
    SvXMLImport const & rImport,
    const Reference < XTextCursor >& rCursor,
    const OUString& rHRef,
    const OUString& rName,
    const OUString& rTargetFrameName,
    const OUString& rStyleName,
    const OUString& rVisitedStyleName,
    XMLEventsImportContext* pEvents)
{
    static constexpr OUString s_HyperLinkURL = u"HyperLinkURL"_ustr;
    static constexpr OUString s_HyperLinkName = u"HyperLinkName"_ustr;
    static constexpr OUString s_HyperLinkTarget = u"HyperLinkTarget"_ustr;
    static constexpr OUString s_UnvisitedCharStyleName = u"UnvisitedCharStyleName"_ustr;
    static constexpr OUString s_VisitedCharStyleName = u"VisitedCharStyleName"_ustr;
    static constexpr OUString s_HyperLinkEvents = u"HyperLinkEvents"_ustr;

    Reference < XPropertySet > xPropSet( rCursor, UNO_QUERY );
    Reference < XPropertySetInfo > xPropSetInfo(
        xPropSet->getPropertySetInfo());
    if (!xPropSetInfo.is() || !xPropSetInfo->hasPropertyByName(s_HyperLinkURL))
        return;

    xPropSet->setPropertyValue(s_HyperLinkURL, Any(rHRef));

    if (xPropSetInfo->hasPropertyByName(s_HyperLinkName))
    {
        xPropSet->setPropertyValue(s_HyperLinkName, Any(rName));
    }

    if (xPropSetInfo->hasPropertyByName(s_HyperLinkTarget))
    {
        xPropSet->setPropertyValue(s_HyperLinkTarget,
            Any(rTargetFrameName));
    }

    if ( (pEvents != nullptr) &&
        xPropSetInfo->hasPropertyByName(s_HyperLinkEvents))
    {
        // The API treats events at hyperlinks differently from most
        // other properties: You have to set a name replace with the
        // events in it. The easiest way to do this is to 1) get
        // events, 2) set new ones, and 3) then put events back.
        uno::Reference<XNameReplace> const xReplace(
            xPropSet->getPropertyValue(s_HyperLinkEvents), UNO_QUERY);
        if (xReplace.is())
        {
            // set events
            pEvents->SetEvents(xReplace);

            // put events
            xPropSet->setPropertyValue(s_HyperLinkEvents, Any(xReplace));
        }
    }

    if (!m_xImpl->m_xTextStyles.is())
        return;

    OUString sDisplayName(
        rImport.GetStyleDisplayName(
                        XmlStyleFamily::TEXT_TEXT, rStyleName ) );
    if( !sDisplayName.isEmpty() &&
        xPropSetInfo->hasPropertyByName(s_UnvisitedCharStyleName) &&
        m_xImpl->m_xTextStyles->hasByName(sDisplayName))
    {
        xPropSet->setPropertyValue(s_UnvisitedCharStyleName,
            Any(sDisplayName));
    }

    sDisplayName =
        rImport.GetStyleDisplayName(
                        XmlStyleFamily::TEXT_TEXT, rVisitedStyleName );
    if( !sDisplayName.isEmpty() &&
        xPropSetInfo->hasPropertyByName(s_VisitedCharStyleName) &&
        m_xImpl->m_xTextStyles->hasByName(sDisplayName))
    {
        xPropSet->setPropertyValue(s_VisitedCharStyleName,
            Any(sDisplayName));
    }
}

void XMLTextImportHelper::SetRuby(
    SvXMLImport const & rImport,
    const Reference < XTextCursor >& rCursor,
    const OUString& rStyleName,
    const OUString& rTextStyleName,
    const OUString& rText )
{
    Reference<XPropertySet> xPropSet(rCursor, UNO_QUERY);

    OUString sRubyText("RubyText");

    // if we have one Ruby property, we assume all of them are present
    if (!xPropSet.is() ||
        !xPropSet->getPropertySetInfo()->hasPropertyByName( sRubyText ))
        return;

    // the ruby text
    xPropSet->setPropertyValue(sRubyText, Any(rText));

    // the ruby style (ruby-adjust)
    if (!rStyleName.isEmpty() && m_xImpl->m_xAutoStyles.is())
    {
        const SvXMLStyleContext* pTempStyle =
            m_xImpl->m_xAutoStyles->FindStyleChildContext( XmlStyleFamily::TEXT_RUBY,
                                   rStyleName, true );
        XMLPropStyleContext *pStyle = const_cast<XMLPropStyleContext*>(dynamic_cast< const XMLPropStyleContext* >(pTempStyle));

        if (nullptr != pStyle)
            pStyle->FillPropertySet( xPropSet );
    }

    // the ruby text character style
    if (m_xImpl->m_xTextStyles.is())
    {
        OUString sDisplayName(
            rImport.GetStyleDisplayName(
                        XmlStyleFamily::TEXT_TEXT, rTextStyleName ) );
        if( (!sDisplayName.isEmpty()) &&
            m_xImpl->m_xTextStyles->hasByName( sDisplayName ))
        {
            xPropSet->setPropertyValue("RubyCharStyleName", Any(sDisplayName));
        }
    }
}

void XMLTextImportHelper::SetAutoStyles( SvXMLStylesContext *pStyles )
{
    m_xImpl->m_xAutoStyles = pStyles;
}

SvXMLImportContext *XMLTextImportHelper::CreateTextChildContext(
        SvXMLImport& rImport,
        sal_Int32 nElement,
        const Reference< XFastAttributeList > & xAttrList,
        XMLTextType eType )
{
    SvXMLImportContext *pContext = nullptr;

    bool bContent = true;
    switch( nElement )
    {
    case XML_ELEMENT(TEXT, XML_H):
    case XML_ELEMENT(TEXT, XML_P):
    case XML_ELEMENT(LO_EXT, XML_P):
        pContext = new XMLParaContext( rImport,
                                       nElement,
                                       xAttrList );
        if (m_xImpl->m_bProgress && XMLTextType::Shape != eType)
        {
            rImport.GetProgressBarHelper()->Increment();
        }
        break;
    // #i52127#
    case XML_ELEMENT(TEXT, XML_NUMBERED_PARAGRAPH):
        pContext = new XMLNumberedParaContext(
                        rImport, nElement, xAttrList );
        break;
    case XML_ELEMENT(TEXT, XML_LIST):
        pContext = new XMLTextListBlockContext( rImport, *this,
                                                xAttrList );
        break;
    case XML_ELEMENT(TABLE,XML_TABLE):
    case XML_ELEMENT(LO_EXT, XML_TABLE):
        if( XMLTextType::Body == eType ||
            XMLTextType::TextBox == eType ||
             XMLTextType::Section == eType ||
            XMLTextType::HeaderFooter == eType ||
            XMLTextType::ChangedRegion == eType ||
            XMLTextType::Cell == eType )
            pContext = CreateTableChildContext( rImport, nElement, xAttrList );
        break;
    case XML_ELEMENT(TEXT, XML_SEQUENCE_DECLS):
        if ((XMLTextType::Body == eType && m_xImpl->m_bBodyContentStarted) ||
            XMLTextType::HeaderFooter == eType )
        {
            pContext = new XMLVariableDeclsImportContext(
                rImport, *this, VarTypeSequence);
            bContent = false;
        }
        break;
    case XML_ELEMENT(TEXT, XML_VARIABLE_DECLS):
        if ((XMLTextType::Body == eType && m_xImpl->m_bBodyContentStarted) ||
            XMLTextType::HeaderFooter == eType )
        {
            pContext = new XMLVariableDeclsImportContext(
                rImport, *this, VarTypeSimple);
            bContent = false;
        }
        break;
    case XML_ELEMENT(TEXT, XML_USER_FIELD_DECLS):
        if ((XMLTextType::Body == eType && m_xImpl->m_bBodyContentStarted)||
            XMLTextType::HeaderFooter == eType )
        {
            pContext = new XMLVariableDeclsImportContext(
                rImport, *this, VarTypeUserField);
            bContent = false;
        }
        break;
    case XML_ELEMENT(TEXT, XML_DDE_CONNECTION_DECLS):
        if ((XMLTextType::Body == eType && m_xImpl->m_bBodyContentStarted) ||
            XMLTextType::HeaderFooter == eType )
        {
            pContext = new XMLDdeFieldDeclsImportContext(rImport);
            bContent = false;
        }
        break;
    case XML_ELEMENT(DRAW, XML_FRAME):
        if ((XMLTextType::Body == eType && m_xImpl->m_bBodyContentStarted) ||
            XMLTextType::TextBox == eType ||
            XMLTextType::ChangedRegion == eType )
        {
            TextContentAnchorType eAnchorType =
                XMLTextType::TextBox == eType ? TextContentAnchorType_AT_FRAME
                                               : TextContentAnchorType_AT_PAGE;
            pContext = new XMLTextFrameContext( rImport, xAttrList,
                                                eAnchorType );
            bContent = false;
        }
        break;
    case XML_ELEMENT(DRAW, XML_A):
        if ((XMLTextType::Body == eType && m_xImpl->m_bBodyContentStarted) ||
            XMLTextType::TextBox == eType ||
             XMLTextType::ChangedRegion == eType)
        {
            TextContentAnchorType eAnchorType =
                XMLTextType::TextBox == eType ? TextContentAnchorType_AT_FRAME
                                               : TextContentAnchorType_AT_PAGE;
            pContext = new XMLTextFrameHyperlinkContext( rImport, nElement,
                                                xAttrList,
                                                eAnchorType );
            bContent = false;
        }
        break;
    case XML_ELEMENT(TEXT, XML_INDEX_TITLE):
    case XML_ELEMENT(TEXT, XML_SECTION):
        pContext = new XMLSectionImportContext( rImport );
        break;
    case XML_ELEMENT(TEXT, XML_TABLE_OF_CONTENT):
    case XML_ELEMENT(TEXT, XML_OBJECT_INDEX):
    case XML_ELEMENT(TEXT, XML_TABLE_INDEX):
    case XML_ELEMENT(TEXT, XML_ILLUSTRATION_INDEX):
    case XML_ELEMENT(TEXT, XML_USER_INDEX):
    case XML_ELEMENT(TEXT, XML_ALPHABETICAL_INDEX):
    case XML_ELEMENT(TEXT, XML_BIBLIOGRAPHY):
        if( XMLTextType::Shape != eType )
            pContext = new XMLIndexTOCContext( rImport, nElement );
        break;
    case XML_ELEMENT(TEXT, XML_TRACKED_CHANGES):
        pContext = new XMLTrackedChangesImportContext( rImport );
        bContent = false;
        break;
    case XML_ELEMENT(TEXT, XML_CHANGE):
    case XML_ELEMENT(TEXT, XML_CHANGE_START):
    case XML_ELEMENT(TEXT, XML_CHANGE_END):
        pContext = new XMLChangeImportContext(
            rImport,
            ((nElement == XML_ELEMENT(TEXT, XML_CHANGE_END))
                ? XMLChangeImportContext::Element::END
                : (nElement == XML_ELEMENT(TEXT, XML_CHANGE_START))
                    ? XMLChangeImportContext::Element::START
                    : XMLChangeImportContext::Element::POINT),
            true);
        break;
    case XML_ELEMENT(OFFICE, XML_FORMS):
        pContext = xmloff::OFormLayerXMLImport::createOfficeFormsContext(rImport);
        bContent = false;
        break;
    case XML_ELEMENT(TEXT, XML_ALPHABETICAL_INDEX_AUTO_MARK_FILE):
        if( XMLTextType::Body == eType )
        {
            pContext = new XMLAutoMarkFileContext(rImport);
        }
        bContent = false;
        break;
    case XML_ELEMENT(TABLE, XML_CALCULATION_SETTINGS):
        pContext = new XMLCalculationSettingsContext ( rImport, nElement, xAttrList);
        bContent = false;
        break;

    default:
        if ((XMLTextType::Body == eType && m_xImpl->m_bBodyContentStarted) ||
            XMLTextType::TextBox == eType ||
             XMLTextType::ChangedRegion == eType )
        {
            Reference < XShapes > xShapes;
            pContext = XMLShapeImportHelper::CreateGroupChildContext(
                    rImport, nElement, xAttrList, xShapes );
            bContent = false;
        }
    }

    // handle open redlines
    if ( (XML_ELEMENT(TEXT, XML_CHANGE) != nElement) &&
         (XML_ELEMENT(TEXT, XML_CHANGE_END) != nElement) &&
         (XML_ELEMENT(TEXT, XML_CHANGE_START) != nElement) )
    {
//      ResetOpenRedlineId();
    }

    if( XMLTextType::Body == eType && bContent )
    {
        m_xImpl->m_bBodyContentStarted = false;
    }

    if( nElement != XML_ELEMENT(DRAW, XML_FRAME) )
        ClearLastImportedTextFrameName();

    if (!pContext)
        XMLOFF_WARN_UNKNOWN_ELEMENT("xmloff", nElement);

    return pContext;
}

SvXMLImportContext *XMLTextImportHelper::CreateTableChildContext(
        SvXMLImport&,
        sal_Int32 /*nElement*/,
        const Reference< XFastAttributeList > & )
{
    return nullptr;
}

/// get data style key for use with NumberFormat property
sal_Int32 XMLTextImportHelper::GetDataStyleKey(const OUString& sStyleName,
                                               bool* pIsSystemLanguage )
{
    if (!m_xImpl->m_xAutoStyles.is())
        return -1;

    const SvXMLStyleContext* pStyle =
        m_xImpl->m_xAutoStyles->FindStyleChildContext( XmlStyleFamily::DATA_STYLE,
                                              sStyleName, true );

    // get appropriate context


    // first check if it's an Impress and draw only number format
    // this is needed since it's also a SvXMLNumFormatContext,
    // that was needed to support them for controls in impress/draw also
    const SdXMLNumberFormatImportContext* pSdNumStyle = dynamic_cast<const SdXMLNumberFormatImportContext*>( pStyle  );
    if( pSdNumStyle )
    {
        return pSdNumStyle->GetDrawKey();
    }
    else
    {
        SvXMLNumFormatContext* pNumStyle = const_cast<SvXMLNumFormatContext*>(dynamic_cast<const SvXMLNumFormatContext*>( pStyle ) );
        if( pNumStyle )
        {
            if( pIsSystemLanguage != nullptr )
                *pIsSystemLanguage = pNumStyle->IsSystemLanguage();

            // return key
            return pNumStyle->GetKey();
        }
    }
    return -1;
}

const SvxXMLListStyleContext *XMLTextImportHelper::FindAutoListStyle( const OUString& rName ) const
{
    const SvxXMLListStyleContext *pStyle = nullptr;
    if (m_xImpl->m_xAutoStyles.is())
    {
        const SvXMLStyleContext* pTempStyle =
            m_xImpl->m_xAutoStyles->FindStyleChildContext( XmlStyleFamily::TEXT_LIST, rName,
                                           true );
        pStyle = dynamic_cast< const SvxXMLListStyleContext* >(pTempStyle);
    }

    return pStyle;
}

XMLPropStyleContext *XMLTextImportHelper::FindAutoFrameStyle( const OUString& rName ) const
{
    XMLPropStyleContext *pStyle = nullptr;
    if (m_xImpl->m_xAutoStyles.is())
    {
        const SvXMLStyleContext* pTempStyle =
            m_xImpl->m_xAutoStyles->FindStyleChildContext( XmlStyleFamily::SD_GRAPHICS_ID, rName,
                                           true );
        pStyle = const_cast<XMLPropStyleContext*>(dynamic_cast< const XMLPropStyleContext* >(pTempStyle));
    }

    return pStyle;
}

XMLPropStyleContext* XMLTextImportHelper::FindSectionStyle(
    const OUString& rName ) const
{
    XMLPropStyleContext* pStyle = nullptr;
    if (m_xImpl->m_xAutoStyles.is())
    {
        const SvXMLStyleContext* pTempStyle =
            m_xImpl->m_xAutoStyles->FindStyleChildContext(
                               XmlStyleFamily::TEXT_SECTION,
                               rName, true );
        pStyle = const_cast<XMLPropStyleContext*>(dynamic_cast< const XMLPropStyleContext* >(pTempStyle));
    }

    return pStyle;
}

XMLPropStyleContext* XMLTextImportHelper::FindPageMaster(
    const OUString& rName ) const
{
    XMLPropStyleContext* pStyle = nullptr;
    if (m_xImpl->m_xAutoStyles.is())
    {
        const SvXMLStyleContext* pTempStyle =
            m_xImpl->m_xAutoStyles->FindStyleChildContext(
                               XmlStyleFamily::PAGE_MASTER,
                               rName, true );
        pStyle = const_cast<XMLPropStyleContext*>(dynamic_cast< const XMLPropStyleContext* >(pTempStyle));
    }

    return pStyle;
}

XMLPropStyleContext* XMLTextImportHelper::FindAutoCharStyle(const OUString& rName) const
{
    if (!m_xImpl->m_xAutoStyles)
        return nullptr;
    auto pStyle
        = m_xImpl->m_xAutoStyles->FindStyleChildContext(XmlStyleFamily::TEXT_TEXT, rName, true);
    return dynamic_cast<XMLPropStyleContext*>(const_cast<SvXMLStyleContext*>(pStyle));
}

XMLPropStyleContext * XMLTextImportHelper::FindDrawingPage(OUString const& rName) const
{
    if (!m_xImpl->m_xAutoStyles.is())
    {
        return nullptr;
    }
    SvXMLStyleContext const* pStyle(
        m_xImpl->m_xAutoStyles->FindStyleChildContext(
               XmlStyleFamily::SD_DRAWINGPAGE_ID, rName, true));
    assert(pStyle == nullptr || dynamic_cast<XMLPropStyleContext const*>(pStyle) != nullptr);
    return const_cast<XMLPropStyleContext*>(static_cast<XMLPropStyleContext const*>(pStyle));
}

void XMLTextImportHelper::PushListContext()
{
    GetTextListHelper().PushListContext(static_cast<XMLTextListBlockContext*>(nullptr));
}

void XMLTextImportHelper::PopListContext()
{
    GetTextListHelper().PopListContext();
}


SvI18NMap& XMLTextImportHelper::GetRenameMap()
{
    if (!m_xImpl->m_xRenameMap)
    {
        m_xImpl->m_xRenameMap.reset( new SvI18NMap );
    }
    return *m_xImpl->m_xRenameMap;
}

void XMLTextImportHelper::InsertBookmarkStartRange(
    const OUString & sName,
    const Reference<XTextRange> & rRange,
    OUString const& i_rXmlId,
    std::shared_ptr< ::xmloff::ParsedRDFaAttributes > & i_rpRDFaAttributes)
{
    m_xImpl->m_BookmarkStartRanges[sName] =
        std::make_tuple(rRange, i_rXmlId, i_rpRDFaAttributes);
    m_xImpl->m_BookmarkVector.push_back(sName);
}

bool XMLTextImportHelper::FindAndRemoveBookmarkStartRange(
    const OUString & sName,
    Reference<XTextRange> & o_rRange,
    OUString & o_rXmlId,
    std::shared_ptr< ::xmloff::ParsedRDFaAttributes > & o_rpRDFaAttributes)
{
    if (m_xImpl->m_BookmarkStartRanges.count(sName))
    {
        Impl::BookmarkMapEntry_t & rEntry =
            (*m_xImpl->m_BookmarkStartRanges.find(sName)).second;
        o_rRange.set(std::get<0>(rEntry));
        o_rXmlId = std::get<1>(rEntry);
        o_rpRDFaAttributes = std::get<2>(rEntry);
        m_xImpl->m_BookmarkStartRanges.erase(sName);
        auto it = std::find(m_xImpl->m_BookmarkVector.begin(), m_xImpl->m_BookmarkVector.end(), sName);
        if (it!=m_xImpl->m_BookmarkVector.end())
        {
            m_xImpl->m_BookmarkVector.erase(it);
        }
        return true;
    }
    else
    {
        return false;
    }
}

void XMLTextImportHelper::pushFieldCtx( const OUString& name, const OUString& type )
{
    m_xImpl->m_FieldStack.push(Impl::field_stack_item_t(
        Impl::field_name_type_t(name, type), Impl::field_params_t(), uno::Reference<text::XFormField>{}, GetCursor()->getStart()));
}

uno::Reference<text::XFormField>
XMLTextImportHelper::popFieldCtx()
{
    uno::Reference<text::XFormField> xRet;
    if ( !m_xImpl->m_FieldStack.empty() )
    {
        xRet = std::get<2>(m_xImpl->m_FieldStack.top());
        m_xImpl->m_FieldStack.pop();
    }
    else
    {
        SAL_INFO("xmloff.text", "unexpected fieldmark end");
    }
    return xRet;
}

void XMLTextImportHelper::addFieldParam( const OUString& name, const OUString& value )
{
    assert(!m_xImpl->m_FieldStack.empty());
    Impl::field_stack_item_t & FieldStackItem(m_xImpl->m_FieldStack.top());
    std::get<1>(FieldStackItem).emplace_back( name, value );
}

::std::pair<OUString, OUString> XMLTextImportHelper::getCurrentFieldType() const
{
    assert(!m_xImpl->m_FieldStack.empty());
    return std::get<0>(m_xImpl->m_FieldStack.top());
}

uno::Reference<text::XTextRange> XMLTextImportHelper::getCurrentFieldStart() const
{
    assert(!m_xImpl->m_FieldStack.empty());
    return std::get<3>(m_xImpl->m_FieldStack.top());
}

bool XMLTextImportHelper::hasCurrentFieldSeparator() const
{
    assert(!m_xImpl->m_FieldStack.empty());
    return std::get<2>(m_xImpl->m_FieldStack.top()).is();
}

bool XMLTextImportHelper::hasCurrentFieldCtx() const
{
    return !m_xImpl->m_FieldStack.empty();
}

void XMLTextImportHelper::setCurrentFieldParamsTo(css::uno::Reference< css::text::XFormField> const &xFormField)
{
    assert(!m_xImpl->m_FieldStack.empty());
    if (xFormField.is())
    {
        FieldParamImporter(&std::get<1>(m_xImpl->m_FieldStack.top()),
            xFormField->getParameters()).Import();
        std::get<2>(m_xImpl->m_FieldStack.top()) = xFormField;
    }
}


void XMLTextImportHelper::ConnectFrameChains(
        const OUString& rFrmName,
        const OUString& rNextFrmName,
        const Reference < XPropertySet >& rFrmPropSet )
{
    if( rFrmName.isEmpty() )
        return;

    if( !rNextFrmName.isEmpty() )
    {
        OUString sNextFrmName(GetRenameMap().Get( XML_TEXT_RENAME_TYPE_FRAME,
                                                    rNextFrmName ));
        if (m_xImpl->m_xTextFrames.is()
            && m_xImpl->m_xTextFrames->hasByName(sNextFrmName))
        {
            rFrmPropSet->setPropertyValue("ChainNextName",
                Any(sNextFrmName));
        }
        else
        {
            if (!m_xImpl->m_xPrevFrmNames)
            {
                m_xImpl->m_xPrevFrmNames.emplace();
                m_xImpl->m_xNextFrmNames.emplace();
            }
            m_xImpl->m_xPrevFrmNames->push_back(rFrmName);
            m_xImpl->m_xNextFrmNames->push_back(sNextFrmName);
        }
    }
    if (!m_xImpl->m_xPrevFrmNames || m_xImpl->m_xPrevFrmNames->empty())
        return;

    for(std::vector<OUString>::iterator i = m_xImpl->m_xPrevFrmNames->begin(), j = m_xImpl->m_xNextFrmNames->begin(); i != m_xImpl->m_xPrevFrmNames->end() && j != m_xImpl->m_xNextFrmNames->end(); ++i, ++j)
    {
        if((*j) == rFrmName)
        {
            // The previous frame must exist, because it existing than
            // inserting the entry
            rFrmPropSet->setPropertyValue("ChainPrevName", Any(*i));

            i = m_xImpl->m_xPrevFrmNames->erase(i);
            j = m_xImpl->m_xNextFrmNames->erase(j);

            // There cannot be more than one previous frames
            break;
        }
    }
}

bool XMLTextImportHelper::IsInFrame() const
{
    static constexpr OUString s_TextFrame = u"TextFrame"_ustr;

    bool bIsInFrame = false;

    // are we currently in a text frame? yes, if the cursor has a
    // TextFrame property and it's non-NULL
    Reference<XPropertySet> xPropSet(const_cast<XMLTextImportHelper*>(this)->GetCursor(), UNO_QUERY);
    if (xPropSet.is())
    {
        if (xPropSet->getPropertySetInfo()->hasPropertyByName(s_TextFrame))
        {
            uno::Reference<XTextFrame> const xFrame(
                xPropSet->getPropertyValue(s_TextFrame), UNO_QUERY);

            if (xFrame.is())
            {
                bIsInFrame = true;
            }
        }
    }

    return bIsInFrame;
}

bool XMLTextImportHelper::IsInHeaderFooter() const
{
    return false;
}

Reference< XPropertySet> XMLTextImportHelper::createAndInsertOLEObject(
                                        SvXMLImport&,
                                        const OUString& /*rHRef*/,
                                        const OUString& /*rStyleName*/,
                                        const OUString& /*rTblName*/,
                                        sal_Int32 /*nWidth*/, sal_Int32 /*nHeight*/ )
{
    Reference< XPropertySet> xPropSet;
    return xPropSet;
}

Reference< XPropertySet> XMLTextImportHelper::createAndInsertOOoLink(
                                        SvXMLImport&,
                                        const OUString& /*rHRef*/,
                                        const OUString& /*rStyleName*/,
                                        const OUString& /*rTblName*/,
                                        sal_Int32 /*nWidth*/, sal_Int32 /*nHeight*/ )
{
    Reference< XPropertySet> xPropSet;
    return xPropSet;
}

Reference< XPropertySet> XMLTextImportHelper::createAndInsertApplet(
                                        const OUString& /*rCode*/,
                                        const OUString& /*rName*/,
                                        bool /*bMayScript*/,
                                        const OUString& /*rHRef*/,
                                        sal_Int32 /*nWidth*/, sal_Int32 /*nHeight*/ )
{
    Reference< XPropertySet> xPropSet;
    return xPropSet;
}
Reference< XPropertySet> XMLTextImportHelper::createAndInsertPlugin(
                                        const OUString& /*rMimeType*/,
                                        const OUString& /*rHRef*/,
                                        sal_Int32 /*nWidth*/, sal_Int32 /*nHeight*/ )
{
    Reference< XPropertySet> xPropSet;
    return xPropSet;
}
Reference< XPropertySet> XMLTextImportHelper::createAndInsertFloatingFrame(
                                        const OUString& /*rName*/,
                                        const OUString& /*rHRef*/,
                                        const OUString& /*rStyleName*/,
                                        sal_Int32 /*nWidth*/, sal_Int32 /*nHeight*/ )
{
    Reference< XPropertySet> xPropSet;
    return xPropSet;
}

void XMLTextImportHelper::endAppletOrPlugin(
        const Reference < XPropertySet> &,
        std::map < const OUString, OUString > &)
{
}
// redline helper: dummy implementation to be overridden in sw/filter/xml
void XMLTextImportHelper::RedlineAdd( const OUString& /*rType*/,
                                      const OUString& /*rId*/,
                                      const OUString& /*rAuthor*/,
                                      const OUString& /*rComment*/,
                                      const util::DateTime& /*rDateTime*/,
                                      const OUString& /*rMovedID*/,
                                      bool /*bMergeLastPara*/)
{
    // dummy implementation: do nothing
}

Reference<XTextCursor> XMLTextImportHelper::RedlineCreateText(
    Reference<XTextCursor> & /*rOldCursor*/,
    const OUString& /*rId*/)
{
    // dummy implementation: do nothing
    Reference<XTextCursor> xRet;
    return xRet;
}

void XMLTextImportHelper::RedlineSetCursor(
    const OUString& /*rId*/,
    bool /*bStart*/,
    bool /*bIsOutsideOfParagraph*/)
{
    // dummy implementation: do nothing
}

void XMLTextImportHelper::RedlineAdjustStartNodeCursor()
{
    // dummy implementation: do nothing
}

void XMLTextImportHelper::SetShowChanges( bool )
{
    // dummy implementation: do nothing
}

void XMLTextImportHelper::SetRecordChanges( bool )
{
    // dummy implementation: do nothing
}
void XMLTextImportHelper::SetChangesProtectionKey(const Sequence<sal_Int8> &)
{
    // dummy implementation: do nothing
}


OUString const & XMLTextImportHelper::GetOpenRedlineId() const
{
    return m_xImpl->m_sOpenRedlineIdentifier;
}

void XMLTextImportHelper::SetOpenRedlineId( OUString const & rId)
{
    m_xImpl->m_sOpenRedlineIdentifier = rId;
}

void XMLTextImportHelper::ResetOpenRedlineId()
{
    SetOpenRedlineId("");
}

void
XMLTextImportHelper::SetCellParaStyleDefault(OUString const& rNewValue)
{
    m_xImpl->m_sCellParaStyleDefault = rNewValue;
}

OUString const& XMLTextImportHelper::GetCellParaStyleDefault() const
{
    return m_xImpl->m_sCellParaStyleDefault;
}

void XMLTextImportHelper::AddCrossRefHeadingMapping(OUString const& rFrom, OUString const& rTo)
{
    if (!m_xImpl->m_xCrossRefHeadingBookmarkMap)
    {
        m_xImpl->m_xCrossRefHeadingBookmarkMap.emplace();
    }
    m_xImpl->m_xCrossRefHeadingBookmarkMap->insert(std::make_pair(rFrom, rTo));
}

// tdf#94804: hack to map cross reference fields that reference duplicate marks
// note that we can't really check meta:generator for this since the file might
// be round-tripped by different versions preserving duplicates => always map
void XMLTextImportHelper::MapCrossRefHeadingFieldsHorribly()
{
    if (!m_xImpl->m_xCrossRefHeadingBookmarkMap)
    {
        return;
    }

    uno::Reference<text::XTextFieldsSupplier> const xFieldsSupplier(
            m_xImpl->m_rSvXMLImport.GetModel(), uno::UNO_QUERY);
    if (!xFieldsSupplier.is())
    {
        return;
    }
    uno::Reference<container::XEnumerationAccess> const xFieldsEA(
            xFieldsSupplier->getTextFields());
    uno::Reference<container::XEnumeration> const xFields(
            xFieldsEA->createEnumeration());
    while (xFields->hasMoreElements())
    {
        uno::Reference<lang::XServiceInfo> const xFieldInfo(
                xFields->nextElement(), uno::UNO_QUERY);
        if (!xFieldInfo->supportsService("com.sun.star.text.textfield.GetReference"))
        {
            continue;
        }
        uno::Reference<beans::XPropertySet> const xField(
                xFieldInfo, uno::UNO_QUERY);
        sal_uInt16 nType(0);
        xField->getPropertyValue("ReferenceFieldSource") >>= nType;
        if (text::ReferenceFieldSource::BOOKMARK != nType)
        {
            continue;
        }
        OUString name;
        xField->getPropertyValue("SourceName") >>= name;
        auto const iter(m_xImpl->m_xCrossRefHeadingBookmarkMap->find(name));
        if (iter == m_xImpl->m_xCrossRefHeadingBookmarkMap->end())
        {
            continue;
        }
        xField->setPropertyValue("SourceName", uno::Any(iter->second));
    }
}

void XMLTextImportHelper::setBookmarkAttributes(OUString const& bookmark, bool hidden, OUString const& condition)
{
    m_xImpl->m_bBookmarkHidden[bookmark] = hidden;
    m_xImpl->m_sBookmarkCondition[bookmark] = condition;
}

bool XMLTextImportHelper::getBookmarkHidden(OUString const& bookmark) const
{
    return m_xImpl->m_bBookmarkHidden[bookmark];
}

const OUString& XMLTextImportHelper::getBookmarkCondition(OUString const& bookmark) const
{
    return m_xImpl->m_sBookmarkCondition[bookmark];
}

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