summaryrefslogtreecommitdiff
path: root/sw/source/filter/ww8/ww8atr.cxx
blob: 3361e58c5bbca87307a6cf97dfbd0eddfec3ab21 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
/* -*- 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 .
 */

/*
 * This file contains methods for the WW8 output
 * (nodes, attributes, formats and chars).
 */


#include <algorithm>
#include <hintids.hxx>

#include <o3tl/safeint.hxx>
#include <vcl/svapp.hxx>
#include <vcl/settings.hxx>
#include <sal/log.hxx>

#include <svl/zformat.hxx>
#include <svl/itemiter.hxx>
#include <svl/whiter.hxx>
#include <svl/grabbagitem.hxx>
#include <editeng/fontitem.hxx>
#include <editeng/tstpitem.hxx>
#include <editeng/adjustitem.hxx>
#include <editeng/spltitem.hxx>
#include <editeng/widwitem.hxx>
#include <editeng/lspcitem.hxx>
#include <editeng/keepitem.hxx>
#include <editeng/shaditem.hxx>
#include <editeng/brushitem.hxx>
#include <editeng/postitem.hxx>
#include <editeng/wghtitem.hxx>
#include <editeng/kernitem.hxx>
#include <editeng/crossedoutitem.hxx>
#include <editeng/cmapitem.hxx>
#include <editeng/wrlmitem.hxx>
#include <editeng/udlnitem.hxx>
#include <editeng/langitem.hxx>
#include <editeng/escapementitem.hxx>
#include <editeng/fhgtitem.hxx>
#include <editeng/colritem.hxx>
#include <editeng/hyphenzoneitem.hxx>
#include <editeng/formatbreakitem.hxx>
#include <editeng/lrspitem.hxx>
#include <editeng/ulspitem.hxx>
#include <editeng/boxitem.hxx>
#include <editeng/contouritem.hxx>
#include <editeng/shdditem.hxx>
#include <editeng/autokernitem.hxx>
#include <editeng/pbinitem.hxx>
#include <editeng/emphasismarkitem.hxx>
#include <editeng/twolinesitem.hxx>
#include <editeng/charscaleitem.hxx>
#include <editeng/charrotateitem.hxx>
#include <editeng/charreliefitem.hxx>
#include <editeng/paravertalignitem.hxx>
#include <editeng/pgrditem.hxx>
#include <editeng/frmdiritem.hxx>
#include <editeng/blinkitem.hxx>
#include <editeng/charhiddenitem.hxx>
#include <editeng/paperinf.hxx>
#include <svx/xfillit0.hxx>
#include <svx/xflgrit.hxx>
#include <fmtfld.hxx>
#include <fchrfmt.hxx>
#include <fmtfsize.hxx>
#include <fmtpdsc.hxx>
#include <fmtornt.hxx>
#include <fmtanchr.hxx>
#include <fmtclds.hxx>
#include <fmtsrnd.hxx>
#include <fmtftn.hxx>
#include <fmtflcnt.hxx>
#include <frmatr.hxx>
#include <swtable.hxx>
#include <fmtinfmt.hxx>
#include <txtftn.hxx>
#include <poolfmt.hxx>
#include <doc.hxx>
#include <IDocumentSettingAccess.hxx>
#include <IDocumentFieldsAccess.hxx>
#include <IDocumentStylePoolAccess.hxx>
#include <IDocumentListsAccess.hxx>
#include <list.hxx>
#include <docary.hxx>
#include <pam.hxx>
#include <paratr.hxx>
#include <fldbas.hxx>
#include <docufld.hxx>
#include <expfld.hxx>
#include <pagedesc.hxx>
#include <ndtxt.hxx>
#include <swrect.hxx>
#include <redline.hxx>
#include <reffld.hxx>
#include <ftninfo.hxx>
#include <charfmt.hxx>
#include <section.hxx>
#include <fmtline.hxx>
#include <tox.hxx>
#include <fmtftntx.hxx>
#include <breakit.hxx>
#include <com/sun/star/i18n/ScriptType.hpp>
#include <com/sun/star/i18n/XBreakIterator.hpp>
#include <unotools/localedatawrapper.hxx>
#include <svx/unobrushitemhelper.hxx>
#include <tgrditem.hxx>
#include <flddropdown.hxx>
#include <chpfld.hxx>
#include <fmthdft.hxx>
#include <authfld.hxx>
#include <dbfld.hxx>

#include "sprmids.hxx"

#include <fmtcntnt.hxx>
#include "writerhelper.hxx"
#include "writerwordglue.hxx"
#include "wrtww8.hxx"
#include "ww8par.hxx"
#include "ww8attributeoutput.hxx"
#include "fields.hxx"
#include <i18nlangtag/languagetag.hxx>
#include <unotools/fltrcfg.hxx>


using ::editeng::SvxBorderLine;
using namespace ::com::sun::star;
using namespace nsSwDocInfoSubType;
using namespace sw::util;
using namespace sw::types;

bool WW8Export::CollapseScriptsforWordOk( sal_uInt16 nScript, sal_uInt16 nWhich )
{
    bool bRet = true;
    if ( nScript == i18n::ScriptType::ASIAN )
    {
        //for asian in ww8, there is only one fontsize
        //and one fontstyle (posture/weight) for ww6
        //there is the additional problem that there
        //is only one font setting for all three scripts
        switch ( nWhich )
        {
            case RES_CHRATR_FONTSIZE:
            case RES_CHRATR_POSTURE:
            case RES_CHRATR_WEIGHT:
                bRet = false;
                break;
            case RES_CHRATR_LANGUAGE:
            case RES_CHRATR_CTL_FONT:
            case RES_CHRATR_CTL_FONTSIZE:
            case RES_CHRATR_CTL_LANGUAGE:
            case RES_CHRATR_CTL_POSTURE:
            case RES_CHRATR_CTL_WEIGHT:
            default:
                break;
        }
    }
    else if ( nScript == i18n::ScriptType::COMPLEX )
    {
        //Complex is ok in ww8, but for ww6 there is only
        //one font, one fontsize, one fontsize (weight/posture)
        //and only one language
    }
    else
    {
        //for western in ww8, there is only one fontsize
        //and one fontstyle (posture/weight) for ww6
        //there is the additional problem that there
        //is only one font setting for all three scripts
        switch ( nWhich )
        {
            case RES_CHRATR_CJK_FONTSIZE:
            case RES_CHRATR_CJK_POSTURE:
            case RES_CHRATR_CJK_WEIGHT:
                bRet = false;
                break;
            case RES_CHRATR_CJK_LANGUAGE:
            case RES_CHRATR_CTL_FONT:
            case RES_CHRATR_CTL_FONTSIZE:
            case RES_CHRATR_CTL_LANGUAGE:
            case RES_CHRATR_CTL_POSTURE:
            case RES_CHRATR_CTL_WEIGHT:
            default:
                break;
        }
    }
    return bRet;
}


void MSWordExportBase::ExportPoolItemsToCHP( ww8::PoolItems &rItems, sal_uInt16 nScript, const SvxFontItem *pFont, bool bWriteCombChars )
{
    for ( const auto& rItem : rItems )
    {
        const SfxPoolItem *pItem = rItem.second;
        sal_uInt16 nWhich = pItem->Which();
        if ( ( isCHRATR( nWhich ) || isTXTATR( nWhich ) ) && CollapseScriptsforWordOk( nScript, nWhich ) )
        {
             //In the id definition, RES_TXTATR_INETFMT must precede RES_TXTATR_CHARFMT, so that link style can overwrite char style.
             //and in #i24291# it describes "All we want to do is ensure for now is that if a charfmt exist in the character
             //properties that it rises to the top and is exported first."
             //In bug 119649, it is in such situation, so we need to ignore the link style when doing ms word filter exports and
             //add the second judgement for #i24291# definition.
             if (nWhich == RES_TXTATR_CHARFMT)
             {
                 const SfxPoolItem* pINetItem = SearchPoolItems(rItems, RES_TXTATR_INETFMT);

                 if (pINetItem)
                 {
                     const SwFormatINetFormat& rINet = pINetItem->StaticWhichCast(RES_TXTATR_INETFMT);
                     const SwCharFormat* pINetFormat = GetSwCharFormat(rINet, m_rDoc);
                     if (!pINetFormat)
                         continue;

                     const SwCharFormat* pFormat = pItem->StaticWhichCast(RES_TXTATR_CHARFMT).GetCharFormat();
                     ww8::PoolItems aCharItems, aINetItems;
                     GetPoolItems(pFormat->GetAttrSet(), aCharItems, false);
                     GetPoolItems(pINetFormat->GetAttrSet(), aINetItems, false);
                     for (const auto& rCharItem : aCharItems)
                     {
                         const SfxPoolItem* pCharItem = rCharItem.second;
                         sal_uInt16 nCharWhich = pCharItem->Which();
                         if (!SearchPoolItems(aINetItems, nCharWhich) && !SearchPoolItems(rItems, nCharWhich))
                             AttrOutput().OutputItem(*pCharItem);
                     }
                     continue;
                 }
             }

             // tdf#38778 Fix output of the font in DOC run for fields
             if (pFont &&
                 nWhich == RES_TXTATR_FIELD)
             {
                 AttrOutput().OutputItem( *pFont );
             }

             // tdf#66401 For Combined Characters in docx, MS Word uses half the normal font-size for the field's
             // font-size, but only for <w:sz>. Therefore, we check if we are currently writing a field of type
             // Combined Characters and if so, we half the font size.
             if (bWriteCombChars &&
                 nWhich == RES_CHRATR_FONTSIZE)
             {
                SvxFontHeightItem fontHeight(item_cast<SvxFontHeightItem>( *pItem ));
                fontHeight.SetHeight( fontHeight.GetHeight() / 2 );

                AttrOutput().OutputItem( fontHeight );
             }
             else if (nWhich == RES_CHRATR_COLOR)
             {
                const SvxColorItem& rColor = pItem->StaticWhichCast(RES_CHRATR_COLOR);
                const SfxPoolItem* pBackgroundItem = SearchPoolItems(rItems, RES_CHRATR_BACKGROUND);
                if (rColor.GetValue() == COL_AUTO && pBackgroundItem)
                {
                    const SvxBrushItem& rBrushBackground = pBackgroundItem->StaticWhichCast(RES_CHRATR_BACKGROUND);
                    SvxColorItem aForeground(rBrushBackground.GetColor().IsDark() ? COL_WHITE : COL_BLACK, RES_CHRATR_COLOR);
                    AttrOutput().OutputItem(aForeground);
                }
                else
                {
                    // default
                    AttrOutput().OutputItem( *pItem );
                }
             }
             else if (nWhich == RES_CHRATR_HIGHLIGHT)
             {
                const SvxBrushItem& rBrush = pItem->StaticWhichCast(RES_CHRATR_HIGHLIGHT);
                // The UI easily adds unnecessary highlights, so identify and avoid exporting those.
                // Highlight is not valid in character styles, so must not check there.
                // Check the (para) style hierarchy to find the nearest defined highlight.
                const SfxPoolItem* pInherited = nullptr;
                if ( auto pNd = dynamic_cast< const SwContentNode *>( m_pOutFormatNode ) ) //paragraph
                    pInherited = static_cast<SwTextFormatColl&>( pNd->GetAnyFormatColl() ).GetAttrSet().GetItem(nWhich);
                else if ( m_bStyDef && m_pCurrentStyle && m_pCurrentStyle->DerivedFrom() ) //style
                    pInherited = &m_pCurrentStyle->DerivedFrom()->GetFormatAttr(nWhich);

                // Ignore highlight if style already sets the same one.
                // Also ignore a transparent highlight if there is no inherited highlight to cancel
                if ( (pInherited && *pInherited != *pItem) || (!pInherited && rBrush.GetColor() != COL_TRANSPARENT) )
                     AttrOutput().OutputItem( *pItem );
             }
             else
             {
                AttrOutput().OutputItem( *pItem );
             }
        }
    }
}

/*
 * Output format as follows:
 *      - output the attributes; without parents!
 */

void MSWordExportBase::OutputItemSet( const SfxItemSet& rSet, bool bPapFormat, bool bChpFormat, sal_uInt16 nScript,
                                      bool bExportParentItemSet )
{
    if( !(bExportParentItemSet || rSet.Count()) )
        return;

    const SfxPoolItem* pItem;
    m_pISet = &rSet;                  // for double attributes

    // If frame dir is set, but not adjust, then force adjust as well
    if ( bPapFormat && SfxItemState::SET == rSet.GetItemState( RES_FRAMEDIR, bExportParentItemSet ) )
    {
        // No explicit adjust set ?
        if ( SfxItemState::SET != rSet.GetItemState( RES_PARATR_ADJUST, bExportParentItemSet ) )
        {
            pItem = rSet.GetItem( RES_PARATR_ADJUST, bExportParentItemSet );
            if ( nullptr != pItem )
            {
                // then set the adjust used by the parent format
                AttrOutput().OutputItem( *pItem );
            }
        }
    }

    if ( bPapFormat && SfxItemState::SET == rSet.GetItemState( RES_PARATR_NUMRULE, bExportParentItemSet, &pItem ) )
    {
        AttrOutput().OutputItem( *pItem );

        // switch off the numbering?
        if ( pItem->StaticWhichCast(RES_PARATR_NUMRULE).GetValue().isEmpty() &&
             SfxItemState::SET != rSet.GetItemState( RES_LR_SPACE, false) &&
             SfxItemState::SET == rSet.GetItemState( RES_LR_SPACE, true, &pItem ) )
        {
            // the set the LR-Space of the parentformat!
            AttrOutput().OutputItem( *pItem );
        }
    }

    ww8::PoolItems aItems;
    GetPoolItems( rSet, aItems, bExportParentItemSet );
    if ( bChpFormat )
        ExportPoolItemsToCHP(aItems, nScript, nullptr);
    if ( bPapFormat )
    {
        const bool bAlreadyOutputBrushItem = AttrOutput().MaybeOutputBrushItem(rSet);

        for ( const auto& rItem : aItems )
        {
            pItem = rItem.second;
            sal_uInt16 nWhich = pItem->Which();
            // Handle fill attributes just like frame attributes for now.
            if ( (nWhich >= RES_PARATR_BEGIN && nWhich < RES_FRMATR_END && nWhich != RES_PARATR_NUMRULE ) ||
                 (nWhich >= XATTR_FILL_FIRST && nWhich < XATTR_FILL_LAST))
                AttrOutput().OutputItem( *pItem );
        }

        // Has to be called after RES_PARATR_GRABBAG is processed.
        const XFillStyleItem* pFill(rSet.GetItem<XFillStyleItem>(XATTR_FILLSTYLE, false));
        if (!bAlreadyOutputBrushItem && pFill
            && (pFill->GetValue() == drawing::FillStyle_SOLID || pFill->GetValue() == drawing::FillStyle_NONE)
            && !rSet.GetItem(RES_BACKGROUND, false))
        {
            const bool bFillStyleNone = pFill->GetValue() == drawing::FillStyle_NONE;
            // No need to write out a NONE background if it can't inherit something else, or if it already inherits a NONE.
            std::unique_ptr<SvxBrushItem> pInherited;
            if (bFillStyleNone)
            {
                if ( auto pNd = dynamic_cast<const SwContentNode*>(m_pOutFormatNode)) //paragraph
                    pInherited = getSvxBrushItemFromSourceSet(static_cast<SwTextFormatColl&>(pNd->GetAnyFormatColl()).GetAttrSet(), RES_BACKGROUND);
                else if (m_bStyDef && m_pCurrentStyle && m_pCurrentStyle->DerivedFrom()) //style
                    pInherited = getSvxBrushItemFromSourceSet(m_pCurrentStyle->DerivedFrom()->GetAttrSet(), RES_BACKGROUND);
            }
            // Construct an SvxBrushItem, as expected by the exporters.
            std::unique_ptr<SvxBrushItem> aBrush(getSvxBrushItemFromSourceSet(rSet, RES_BACKGROUND));
            if (!bFillStyleNone || (pInherited && *pInherited != *aBrush))
                AttrOutput().OutputItem(*aBrush);
        }
#if 0
        else
        {
            // note: *does not work* due to undocumented Word behavior: must be before a:ln element at least
            AttrOutput().MaybeOutputBrushItem(rSet);
        }
#endif
    }
    m_pISet = nullptr;                      // for double attributes
}

void MSWordExportBase::GatherChapterFields()
{
    //If the header/footer contains a chapter field
    SwFieldType* pType = m_rDoc.getIDocumentFieldsAccess().GetSysFieldType( SwFieldIds::Chapter );
    pType->GatherNodeIndex(m_aChapterFieldLocs);
}

bool MSWordExportBase::ContentContainsChapterField(const SwFormatContent &rContent) const
{
    bool bRet = false;
    if ( const SwNodeIndex* pSttIdx = rContent.GetContentIdx() )
    {
        SwNodeIndex aIdx( *pSttIdx, 1 );
        SwNodeIndex aEnd( *pSttIdx->GetNode().EndOfSectionNode() );
        sal_uLong nStart = aIdx.GetIndex();
        sal_uLong nEnd = aEnd.GetIndex();
        //If the header/footer contains a chapter field
        bRet = std::any_of(m_aChapterFieldLocs.cbegin(), m_aChapterFieldLocs.cend(),
            [nStart, nEnd](sal_uLong i) { return ( nStart <= i ) && ( i <= nEnd ); });
    }
    return bRet;
}

bool MSWordExportBase::FormatHdFtContainsChapterField(const SwFrameFormat &rFormat) const
{
    if ( m_aChapterFieldLocs.empty() )
        return false;

    const SwFrameFormat *pFormat = nullptr;

    pFormat = rFormat.GetHeader().GetHeaderFormat();
    if ( pFormat && ContentContainsChapterField( pFormat->GetContent() ) )
        return true;

    pFormat = rFormat.GetFooter().GetFooterFormat();
    return pFormat && ContentContainsChapterField( pFormat->GetContent() );
}

bool MSWordExportBase::SetCurrentPageDescFromNode(const SwNode &rNd)
{
    bool bNewPageDesc = false;
    const SwPageDesc* pCurrent = SwPageDesc::GetPageDescOfNode(rNd);
    OSL_ENSURE(pCurrent && m_pCurrentPageDesc, "Not possible surely");
    if (m_pCurrentPageDesc && pCurrent)
    {
        if (pCurrent != m_pCurrentPageDesc)
        {
            if (m_pCurrentPageDesc->GetFollow() != pCurrent)
                bNewPageDesc = true;
            else
            {
                const SwFrameFormat& rTitleFormat = m_pCurrentPageDesc->GetFirstMaster();
                const SwFrameFormat& rFollowFormat = pCurrent->GetMaster();

                bNewPageDesc = !IsPlausableSingleWordSection(rTitleFormat,
                    rFollowFormat);
            }
            m_pCurrentPageDesc = pCurrent;
        }
        else
        {
            const SwFrameFormat &rFormat = pCurrent->GetMaster();
            bNewPageDesc = FormatHdFtContainsChapterField(rFormat);
        }
    }
    return bNewPageDesc;
}

/**
 * WW only knows Break-After (page break and section breaks),
 * whereas in SW page breaks exist both "before" and "after" and PageDesc exists
 * only "before". Therefore the breaks are iterated two times, namely before
 * and after every line.
 * Depending on the break type they're set before or after the line.
 * Only functions can be called, which do not write in output area pO,
 * because that one only exits once for CHP and PAP and therefore end up in
 * the wrong one.
 */
void MSWordExportBase::OutputSectionBreaks( const SfxItemSet *pSet, const SwNode& rNd, bool isCellOpen )
{
    if ( m_bStyDef || m_bOutKF || m_bInWriteEscher || m_bOutPageDescs )
        return;

    m_bBreakBefore = true;
    bool bNewPageDesc = false;
    const SfxPoolItem* pItem=nullptr;
    const SwFormatPageDesc *pPgDesc=nullptr;
    bool bExtraPageBreakBeforeSectionBreak = false;

    //Output a sectionbreak if there's a new pagedescriptor. Otherwise output a
    //pagebreak if there is a pagebreak here, unless the new page (follow
    //style) is different to the current one, in which case plump for a
    //section.
    bool bBreakSet = false;

    const SwPageDesc * pPageDesc = rNd.FindPageDesc();

    // Even if m_pCurrentPageDesc != pPageDesc ,it might be because of the different header & footer types.
    if (m_pCurrentPageDesc != pPageDesc)
    {
        if (isCellOpen && ( m_pCurrentPageDesc->GetName() != pPageDesc->GetName() ))
        {
            /*
             * If Table cell is open and page header types are different
             * set pSet to NULL as we don't want to add any section breaks inside a table.
             */
            pSet = nullptr;
        }
        else if (!sw::util::IsPlausableSingleWordSection(m_pCurrentPageDesc->GetFirstMaster(), pPageDesc->GetMaster()))
        {
            bBreakSet = true;
            bNewPageDesc = true;
            m_pCurrentPageDesc = pPageDesc;
        }
    }

    if ( pSet && pSet->Count() )
    {
        if ( SfxItemState::SET == pSet->GetItemState( RES_PAGEDESC, false, &pItem ) &&
             pItem->StaticWhichCast(RES_PAGEDESC).GetRegisteredIn() != nullptr)
        {
            bBreakSet = true;
            bNewPageDesc = true;
            pPgDesc = static_cast<const SwFormatPageDesc*>(pItem);
            m_pCurrentPageDesc = pPgDesc->GetPageDesc();

            // tdf#121666: nodes that have pagebreak + sectionbreak may need to export both breaks
            // tested / implemented with docx format only.
            // If other formats (rtf /doc) need similar fix, then that may can be done similar way.
            if (SfxItemState::SET == pSet->GetItemState(RES_BREAK, false, &pItem))
            {
                bExtraPageBreakBeforeSectionBreak = true;
            }
        }
        else if ( SfxItemState::SET == pSet->GetItemState( RES_BREAK, false, &pItem ) )
        {
            // Word does not like hard break attributes in some table cells
            bool bRemoveHardBreakInsideTable = false;
            if ( m_bOutTable )
            {
                const SwTableNode* pTableNode = rNd.FindTableNode();
                if ( pTableNode )
                {
                    const SwTableBox* pBox = rNd.GetTableBox();
                    const SwTableLine* pLine = pBox ? pBox->GetUpper() : nullptr;
                    // but only for non-complex tables
                    if ( pLine && !pLine->GetUpper() )
                    {
                        // check if box is not first in that line:
                        if ( 0 < pLine->GetBoxPos( pBox ) && pBox->GetSttNd() )
                        {
                            bRemoveHardBreakInsideTable = true;
                        }
                    }
                }
            }
            bBreakSet = true;

            if ( !bRemoveHardBreakInsideTable )
            {
                OSL_ENSURE(m_pCurrentPageDesc, "should not be possible");
                /*
                 If because of this pagebreak the page desc following the page
                 break is the follow style of the current page desc then output a
                 section break using that style instead.  At least in those cases
                 we end up with the same style in word and writer, nothing can be
                 done when it happens when we get a new pagedesc because we
                 overflow from the first page style.
                */
                if ( m_pCurrentPageDesc )
                {
                    // #i76301# - assure that there is a page break before set at the node.
                    const SvxFormatBreakItem* pBreak = dynamic_cast<const SvxFormatBreakItem*>(pItem);
                    if ( pBreak &&
                         pBreak->GetBreak() == SvxBreak::PageBefore )
                    {
                        bNewPageDesc |= SetCurrentPageDescFromNode( rNd );
                    }
                }
                if ( !bNewPageDesc )
                    AttrOutput().OutputItem( *pItem );
            }
        }
    }

    /*
    #i9301#
    No explicit page break, lets see if the style had one and we've moved to a
    new page style because of it, if we have to then we take the opportunity to
    set the equivalent word section here. We *could* do it for every paragraph
    that moves onto a new page because of layout, but that would be insane.
    */
    bool bHackInBreak = false;
    if ( !bBreakSet )
    {
        if ( const SwContentNode *pNd = rNd.GetContentNode() )
        {
            const SvxFormatBreakItem &rBreak =
                ItemGet<SvxFormatBreakItem>( *pNd, RES_BREAK );
            if ( rBreak.GetBreak() == SvxBreak::PageBefore )
                bHackInBreak = true;
            else
            {   // Even a pagedesc item is set, the break item can be set 'NONE',
                // but a pagedesc item is an implicit page break before...
                const SwFormatPageDesc &rPageDesc =
                    ItemGet<SwFormatPageDesc>( *pNd, RES_PAGEDESC );
                if ( rPageDesc.KnowsPageDesc() )
                    bHackInBreak = true;
            }
        }
    }

    if ( bHackInBreak )
    {
        OSL_ENSURE( m_pCurrentPageDesc, "should not be possible" );
        if ( m_pCurrentPageDesc )
            bNewPageDesc = SetCurrentPageDescFromNode( rNd );
    }

    if ( bNewPageDesc && m_pCurrentPageDesc )
    {
        PrepareNewPageDesc( pSet, rNd, pPgDesc, m_pCurrentPageDesc, bExtraPageBreakBeforeSectionBreak );
    }
    m_bBreakBefore = false;
}

// #i76300#
bool MSWordExportBase::OutputFollowPageDesc( const SfxItemSet* pSet, const SwTextNode* pNd )
{
    bool bRet = false;

    if ( pNd &&
         m_pCurrentPageDesc &&
         m_pCurrentPageDesc != m_pCurrentPageDesc->GetFollow() )
    {
        PrepareNewPageDesc( pSet, *pNd, nullptr, m_pCurrentPageDesc->GetFollow() );
        bRet = true;
    }

    return bRet;
}

const SwSectionFormat* MSWordExportBase::GetSectionFormat( const SwNode& rNd )
{
    const SwSectionFormat* pFormat = nullptr;
    const SwSectionNode* pSect = rNd.FindSectionNode();
    if ( pSect &&
         SectionType::Content == pSect->GetSection().GetType() )
    {
        pFormat = pSect->GetSection().GetFormat();
    }

    return pFormat;
}

sal_uLong MSWordExportBase::GetSectionLineNo( const SfxItemSet* pSet, const SwNode& rNd )
{
    const SwFormatLineNumber* pNItem = nullptr;
    if ( pSet )
    {
        pNItem = &( ItemGet<SwFormatLineNumber>( *pSet, RES_LINENUMBER ) );
    }
    else if ( const SwContentNode *pNd = rNd.GetContentNode() )
    {
        pNItem = &( ItemGet<SwFormatLineNumber>( *pNd, RES_LINENUMBER ) );
    }

    return pNItem? pNItem->GetStartValue() : 0;
}

void WW8Export::PrepareNewPageDesc( const SfxItemSet*pSet,
                                      const SwNode& rNd,
                                      const SwFormatPageDesc* pNewPgDescFormat,
                                      const SwPageDesc* pNewPgDesc,
                                      bool /*bExtraPageBreak*/ )
{
    // The PageDescs will only be inserted in WW8Writer::pSepx with the corresponding
    // position by the occurrences of PageDesc attributes. The construction and
    // output of the attributes and header/footer of the PageDesc are done
    // after the main text and its attributes.

    sal_uLong nFcPos = ReplaceCr( msword::PageBreak ); // Page/Section-Break

    // actually nothing is outputted here, rather the arrays aCps, aSects
    // accordingly completed
    if ( !nFcPos )
        return;

    const SwSectionFormat* pFormat = GetSectionFormat( rNd );
    const sal_uLong nLnNm = GetSectionLineNo( pSet, rNd );

    OSL_ENSURE( pNewPgDescFormat || pNewPgDesc, "Neither page desc format nor page desc provided." );

    if ( pNewPgDescFormat )
    {
        pSepx->AppendSep( Fc2Cp( nFcPos ), *pNewPgDescFormat, rNd, pFormat, nLnNm );
    }
    else if ( pNewPgDesc )
    {
        pSepx->AppendSep( Fc2Cp( nFcPos ), pNewPgDesc, rNd, pFormat, nLnNm );
    }
}

void MSWordExportBase::CorrectTabStopInSet( SfxItemSet& rSet, sal_Int32 nAbsLeft )
{
    const SvxTabStopItem *pItem = rSet.GetItem<SvxTabStopItem>(RES_PARATR_TABSTOP);
    if (!pItem)
        return;

    // then it must be corrected for the output
    SvxTabStopItem aTStop(*pItem);
    for ( sal_uInt16 nCnt = 0; nCnt < aTStop.Count(); ++nCnt )
    {
        SvxTabStop& rTab = const_cast<SvxTabStop&>(aTStop[ nCnt ]);
        if ( SvxTabAdjust::Default != rTab.GetAdjustment() &&
            rTab.GetTabPos() >= nAbsLeft )
        {
            rTab.GetTabPos() -= nAbsLeft;
        }
        else
        {
            aTStop.Remove( nCnt );
            --nCnt;
        }
    }
    rSet.Put( aTStop );
}

sal_uInt8 WW8Export::GetNumId( sal_uInt16 eNumType )
{
    sal_uInt8 nRet = 0;
    switch( eNumType )
    {
    case SVX_NUM_CHARS_UPPER_LETTER:
    case SVX_NUM_CHARS_UPPER_LETTER_N:  nRet = 3;       break;
    case SVX_NUM_CHARS_LOWER_LETTER:
    case SVX_NUM_CHARS_LOWER_LETTER_N:  nRet = 4;       break;
    case SVX_NUM_ROMAN_UPPER:           nRet = 1;       break;
    case SVX_NUM_ROMAN_LOWER:           nRet = 2;       break;

    case SVX_NUM_BITMAP:
    case SVX_NUM_CHAR_SPECIAL:          nRet = 23;      break;

    // nothing, WW does the same (undocumented)
    case SVX_NUM_NUMBER_NONE:           nRet = 0xff;    break;
    case SVX_NUM_SYMBOL_CHICAGO:
        // 0x09, msonfcChiManSty
        nRet = 9;
        break;
    case SVX_NUM_ARABIC_ZERO:
        // 0x16, msonfcArabicLZ
        nRet = 22;
        break;
    }
    return nRet;
}

void WW8AttributeOutput::OutlineNumbering(sal_uInt8 nLvl)
{
    if ( nLvl >= WW8ListManager::nMaxLevel )
        nLvl = WW8ListManager::nMaxLevel-1;

    // write sprmPIlvl and sprmPIlfo
    // (sprmPOutLvl now handled by ParaOutlineLevel)
    SwWW8Writer::InsUInt16( *m_rWW8Export.pO, NS_sprm::PIlvl::val );
    m_rWW8Export.pO->push_back( nLvl );
    SwWW8Writer::InsUInt16( *m_rWW8Export.pO, NS_sprm::PIlfo::val );
    SwWW8Writer::InsUInt16( *m_rWW8Export.pO,
        1 + m_rWW8Export.GetNumberingId(*m_rWW8Export.m_rDoc.GetOutlineNumRule()) );
}

// #i77805#
bool WW8Export::DisallowInheritingOutlineNumbering(const SwFormat &rFormat)
{
    bool bRet( false );

    //If there is no numbering on this fmt, but its parent was outline
    //numbered, then in writer this is no inheritied, but in word it would
    //be, so we must export "no numbering" and "body level" to make word
    //behave like writer (see #i25755)
    if (SfxItemState::SET != rFormat.GetItemState(RES_PARATR_NUMRULE, false))
    {
        if (const SwFormat *pParent = rFormat.DerivedFrom())
        {
            if (static_cast<const SwTextFormatColl*>(pParent)->IsAssignedToListLevelOfOutlineStyle())
            {
                SwWW8Writer::InsUInt16(*pO, NS_sprm::POutLvl::val);
                pO->push_back(sal_uInt8(9));
                SwWW8Writer::InsUInt16(*pO, NS_sprm::PIlfo::val);
                SwWW8Writer::InsUInt16(*pO, 0);

                bRet = true;
            }
        }
    }

    return bRet;
}

void MSWordExportBase::OutputFormat( const SwFormat& rFormat, bool bPapFormat, bool bChpFormat, bool bFlyFormat )
{
    bool bCallOutSet = true;
    const sw::BroadcastingModify* pOldMod = m_pOutFormatNode;
    m_pOutFormatNode = &rFormat;

    switch( rFormat.Which() )
    {
    case RES_CONDTXTFMTCOLL:
    case RES_TXTFMTCOLL:
        if( bPapFormat )
        {
            int nLvl = MAXLEVEL;

            if (static_cast<const SwTextFormatColl&>(rFormat).IsAssignedToListLevelOfOutlineStyle())
                nLvl = static_cast<const SwTextFormatColl&>(rFormat).GetAssignedOutlineStyleLevel();

            if (nLvl >= 0 && nLvl < MAXLEVEL)
            {
                //if outline numbered
                // if Write StyleDefinition then write the OutlineRule
                const SwNumFormat& rNFormat = m_rDoc.GetOutlineNumRule()->Get( o3tl::narrowing<sal_uInt16>( nLvl ) );
                if ( m_bStyDef )
                    AttrOutput().OutlineNumbering(static_cast<sal_uInt8>(nLvl));

                if ( rNFormat.GetPositionAndSpaceMode() ==
                                           SvxNumberFormat::LABEL_WIDTH_AND_POSITION  &&
                     rNFormat.GetAbsLSpace() )
                {
                    SfxItemSet aSet( rFormat.GetAttrSet() );
                    SvxLRSpaceItem aLR(
                        ItemGet<SvxLRSpaceItem>(aSet, RES_LR_SPACE));

                    aLR.SetTextLeft( aLR.GetTextLeft() + rNFormat.GetAbsLSpace() );
                    aLR.SetTextFirstLineOffset( GetWordFirstLineOffset(rNFormat));

                    aSet.Put( aLR );
                    CorrectTabStopInSet( aSet, rNFormat.GetAbsLSpace() );
                    OutputItemSet( aSet, bPapFormat, bChpFormat,
                        i18n::ScriptType::LATIN, m_bExportModeRTF);
                    bCallOutSet = false;
                }
            }
            else
            {
                //otherwise we might have to remove outline numbering from
                //what gets exported if the parent style was outline numbered
                // #i77805#
                // If inherited outline numbering is suppress, the left/right
                // margins has to be exported explicitly.
                if ( m_bStyDef && DisallowInheritingOutlineNumbering(rFormat) )
                {
                    SfxItemSet aSet( rFormat.GetAttrSet() );
                    const SvxLRSpaceItem& aLR(
                        ItemGet<SvxLRSpaceItem>(aSet, RES_LR_SPACE));
                    aSet.Put( aLR );
                    OutputItemSet( aSet, bPapFormat, bChpFormat,
                        css::i18n::ScriptType::LATIN, m_bExportModeRTF);
                    bCallOutSet = false;
                }
            }
        }
        break;

    case RES_CHRFMT:
        break;
    case RES_FLYFRMFMT:
        if (bFlyFormat)
        {
            OSL_ENSURE(m_pParentFrame, "No parent frame, all broken");

            if (m_pParentFrame)
            {
                const SwFrameFormat &rFrameFormat = m_pParentFrame->GetFrameFormat();

                SfxItemSet aSet(m_rDoc.GetAttrPool(), svl::Items<RES_FRMATR_BEGIN,
                    RES_FRMATR_END-1,
                    XATTR_FILL_FIRST, XATTR_FILL_LAST>{});
                aSet.Set(rFrameFormat.GetAttrSet());

                // Fly as character becomes a paragraph bound
                // now set the distance to paragraph margin
                if (m_pFlyOffset)
                {
                    aSet.Put(SwFormatHoriOrient(m_pFlyOffset->X()));
                    aSet.Put(SwFormatVertOrient(m_pFlyOffset->Y()));
                    SwFormatAnchor aAnchor(rFrameFormat.GetAnchor());
                    aAnchor.SetType(m_eNewAnchorType);
                    aSet.Put(aAnchor);
                }

                if (SfxItemState::SET != aSet.GetItemState(RES_SURROUND))
                    aSet.Put(SwFormatSurround(css::text::WrapTextMode_NONE));

                const XFillStyleItem* pXFillStyleItem(rFrameFormat.GetAttrSet().GetItem<XFillStyleItem>(XATTR_FILLSTYLE));
                if (pXFillStyleItem)
                {
                    switch (pXFillStyleItem->GetValue())
                    {
                    case drawing::FillStyle_NONE:
                        break;
                    case drawing::FillStyle_SOLID:
                    {
                        // Construct an SvxBrushItem, as expected by the exporters.
                        std::unique_ptr<SvxBrushItem> aBrush(getSvxBrushItemFromSourceSet(rFrameFormat.GetAttrSet(), RES_BACKGROUND));
                        aSet.Put(*aBrush);
                        break;
                    }
                    default:
                        break;
                    }
                }

                m_bOutFlyFrameAttrs = true;
                //script doesn't matter if not exporting chp
                OutputItemSet(aSet, true, false,
                    i18n::ScriptType::LATIN, m_bExportModeRTF);
                m_bOutFlyFrameAttrs = false;

                bCallOutSet = false;
            }
        }
        break;
    case RES_FRMFMT:
        break;
    default:
        OSL_ENSURE( false, "Which format is exported here?" );
        break;
    }

    if( bCallOutSet )
        OutputItemSet( rFormat.GetAttrSet(), bPapFormat, bChpFormat,
            i18n::ScriptType::LATIN, m_bExportModeRTF);
    m_pOutFormatNode = pOldMod;
}

bool MSWordExportBase::HasRefToAttr(const OUString& rName)
{
    SwFieldType* pType = m_rDoc.getIDocumentFieldsAccess().GetSysFieldType(SwFieldIds::GetRef);
    std::vector<SwGetRefField*> vpRFields;
    pType->GatherRefFields(vpRFields, REF_SETREFATTR);
    return std::any_of(vpRFields.begin(), vpRFields.end(),
            [rName](SwGetRefField* pF) { return rName == pF->GetSetRefName(); });
}

bool MSWordExportBase::HasRefToFootOrEndnote(const bool isEndNote, const sal_uInt16 nSeqNo)
{
    SwFieldType* pType = m_rDoc.getIDocumentFieldsAccess().GetSysFieldType(SwFieldIds::GetRef);
    std::vector<SwGetRefField*> vpRFields;
    pType->GatherRefFields(vpRFields, isEndNote ? REF_ENDNOTE : REF_FOOTNOTE);
    return std::any_of(vpRFields.begin(), vpRFields.end(),
            [nSeqNo](SwGetRefField* pF) { return nSeqNo == pF->GetSeqNo(); });
}

OUString MSWordExportBase::GetBookmarkName( sal_uInt16 nTyp, const OUString* pName, sal_uInt16 nSeqNo )
{
    OUString sRet;
    switch ( nTyp )
    {
        case REF_SETREFATTR:
            if ( pName )
            {
                sRet = "Ref_" + *pName;
            }
            break;
        case REF_SEQUENCEFLD:
        {
            assert(pName);
            sRet = "Ref_" + *pName;
            break;
        }
        case REF_BOOKMARK:
            if ( pName )
                sRet = *pName;
            break;
        case REF_OUTLINE:
            break;      // ???
        case REF_FOOTNOTE:
            sRet = "_RefF" + OUString::number( nSeqNo );
            break;
        case REF_ENDNOTE:
            sRet = "_RefE" + OUString::number( nSeqNo );
            break;
    }
    return BookmarkToWord( sRet ); // #i43956# - encode bookmark accordingly
}

/* File CHRATR.HXX: */
void WW8AttributeOutput::RTLAndCJKState( bool bIsRTL, sal_uInt16 nScript )
{
    if (bIsRTL)
    {
        if( m_rWW8Export.m_rDoc.GetDocumentType() != SwDoc::DOCTYPE_MSWORD )
        {
            m_rWW8Export.InsUInt16( NS_sprm::CFBiDi::val );
            m_rWW8Export.pO->push_back( sal_uInt8(1) );
        }
    }

    // #i46087# patch from james_clark; complex texts needs the undocumented SPRM CComplexScript with param 0x81.
    if (nScript == i18n::ScriptType::COMPLEX && !bIsRTL)
    {
        m_rWW8Export.InsUInt16( NS_sprm::CFComplexScripts::val );
        m_rWW8Export.pO->push_back( sal_uInt8(0x81) );
        m_rWW8Export.pDop->bUseThaiLineBreakingRules = true;
    }
}

void WW8AttributeOutput::EndParagraph( ww8::WW8TableNodeInfoInner::Pointer_t pTextNodeInfoInner )
{
    m_rWW8Export.m_pPapPlc->AppendFkpEntry( m_rWW8Export.Strm().Tell() - (mbOnTOXEnding?2:0), m_rWW8Export.pO->size(), m_rWW8Export.pO->data() );
    mbOnTOXEnding = false;
    m_rWW8Export.pO->clear();

    if ( pTextNodeInfoInner )
    {
        if ( pTextNodeInfoInner->isEndOfLine() )
        {
            TableRowEnd( pTextNodeInfoInner->getDepth() );

            SVBT16 nSty;
            ShortToSVBT16( 0, nSty );
            m_rWW8Export.pO->insert( m_rWW8Export.pO->end(), nSty, nSty+2 );     // Style #
            TableInfoRow( pTextNodeInfoInner );
            m_rWW8Export.m_pPapPlc->AppendFkpEntry( m_rWW8Export.Strm().Tell(), m_rWW8Export.pO->size(), m_rWW8Export.pO->data());
            m_rWW8Export.pO->clear();
        }
    }

    // Clear bookmarks of the current paragraph
    m_aBookmarksOfParagraphStart.clear();
    m_aBookmarksOfParagraphEnd.clear();
}

void WW8AttributeOutput::StartRunProperties()
{
    WW8_WrPlcField* pCurrentFields = m_rWW8Export.CurrentFieldPlc();
    m_nFieldResults = pCurrentFields ? pCurrentFields->ResultCount() : 0;
}

void WW8AttributeOutput::StartRun( const SwRedlineData* pRedlineData, sal_Int32 nPos, bool /*bSingleEmptyRun*/ )
{
    if (pRedlineData)
    {
        const OUString &rComment = pRedlineData->GetComment();
        //Only possible to export to main text
        if (!rComment.isEmpty() && (m_rWW8Export.m_nTextTyp == TXT_MAINTEXT))
        {
            if (m_rWW8Export.m_pAtn->IsNewRedlineComment(pRedlineData))
            {
                m_rWW8Export.m_pAtn->Append( m_rWW8Export.Fc2Cp( m_rWW8Export.Strm().Tell() ), pRedlineData );
                m_rWW8Export.WritePostItBegin( m_rWW8Export.pO.get() );
            }
        }
    }

    /// Insert bookmarks started at this run
    auto aRange = m_aBookmarksOfParagraphStart.equal_range(nPos);
    for( auto aIter = aRange.first; aIter != aRange.second; ++aIter)
    {
        GetExport().AppendBookmark(BookmarkToWord(aIter->second));
    }
}

void WW8AttributeOutput::OnTOXEnding()
{
    mbOnTOXEnding = true;
}

void WW8AttributeOutput::EndRun( const SwTextNode* /*pNode*/, sal_Int32 nPos, bool bLastRun )
{
    /// Insert bookmarks ended after this run
    auto aRange = m_aBookmarksOfParagraphEnd.equal_range(nPos);
    for( auto aIter = aRange.first; aIter != aRange.second; ++aIter)
    {
        if(bLastRun)
            GetExport().AppendBookmarkEndWithCorrection(BookmarkToWord(aIter->second));
        else
            GetExport().AppendBookmark(BookmarkToWord(aIter->second));
    }
}

void WW8AttributeOutput::EndRunProperties( const SwRedlineData* pRedlineData )
{
    Redline( pRedlineData );

    WW8_WrPlcField* pCurrentFields = m_rWW8Export.CurrentFieldPlc();
    sal_uInt16 nNewFieldResults = pCurrentFields ? pCurrentFields->ResultCount() : 0;

    bool bExportedFieldResult = ( m_nFieldResults != nNewFieldResults );

    // If we have exported a field result, then we will have been forced to
    // split up the text into a 0x13, 0x14, <result> 0x15 sequence with the
    // properties forced out at the end of the result, so the 0x15 itself
    // should remain clean of all other attributes to avoid #iXXXXX#
    if ( !bExportedFieldResult )
    {
        m_rWW8Export.m_pChpPlc->AppendFkpEntry( m_rWW8Export.Strm().Tell(),
                m_rWW8Export.pO->size(), m_rWW8Export.pO->data() );
    }
    m_rWW8Export.pO->clear();
}

void WW8AttributeOutput::RunText( const OUString& rText, rtl_TextEncoding eCharSet )
{
    RawText(rText, eCharSet);
}

void WW8AttributeOutput::RawText(const OUString& rText, rtl_TextEncoding)
{
    m_rWW8Export.OutSwString(rText, 0, rText.getLength());
}

void WW8AttributeOutput::OutputFKP(bool bForce)
{
    if (!m_rWW8Export.pO->empty() || bForce)
    {
        m_rWW8Export.m_pChpPlc->AppendFkpEntry( m_rWW8Export.Strm().Tell(),
                m_rWW8Export.pO->size(), m_rWW8Export.pO->data() );
        m_rWW8Export.pO->clear();
    }
}

void WW8AttributeOutput::ParagraphStyle( sal_uInt16 nStyle )
{
    OSL_ENSURE( m_rWW8Export.pO->empty(), " pO is not empty at line end" );

    SVBT16 nSty;
    ShortToSVBT16( nStyle, nSty );
    m_rWW8Export.pO->insert( m_rWW8Export.pO->end(), nSty, nSty+2 );     // style #
}

void WW8AttributeOutput::OutputWW8Attribute( sal_uInt8 nId, bool bVal )
{
    m_rWW8Export.InsUInt16( 8 == nId ? NS_sprm::CFDStrike::val : NS_sprm::CFBold::val + nId );

    m_rWW8Export.pO->push_back( bVal ? 1 : 0 );
}

void WW8AttributeOutput::OutputWW8AttributeCTL( sal_uInt8 nId, bool bVal )
{
    OSL_ENSURE( nId <= 1, "out of range" );
    if (nId > 1)
        return;

    m_rWW8Export.InsUInt16( NS_sprm::CFBoldBi::val + nId );
    m_rWW8Export.pO->push_back( bVal ? 1 : 0 );
}

void WW8AttributeOutput::CharFont( const SvxFontItem& rFont )
{
    sal_uInt16 nFontID = m_rWW8Export.GetId( rFont );

    m_rWW8Export.InsUInt16( NS_sprm::CRgFtc0::val );
    m_rWW8Export.InsUInt16( nFontID );
    m_rWW8Export.InsUInt16( NS_sprm::CRgFtc2::val );

    m_rWW8Export.InsUInt16( nFontID );
}

void WW8AttributeOutput::CharFontCTL( const SvxFontItem& rFont )
{
    sal_uInt16 nFontID = m_rWW8Export.GetId( rFont );
    m_rWW8Export.InsUInt16( NS_sprm::CFtcBi::val );
    m_rWW8Export.InsUInt16( nFontID );
}

void WW8AttributeOutput::CharFontCJK( const SvxFontItem& rFont )
{
    sal_uInt16 nFontID = m_rWW8Export.GetId( rFont );
    m_rWW8Export.InsUInt16( NS_sprm::CRgFtc1::val );
    m_rWW8Export.InsUInt16( nFontID );
}

void WW8AttributeOutput::CharWeightCTL( const SvxWeightItem& rWeight )
{
    OutputWW8AttributeCTL( 0, WEIGHT_BOLD == rWeight.GetWeight());
}

void WW8AttributeOutput::CharPostureCTL( const SvxPostureItem& rPosture )
{
    OutputWW8AttributeCTL( 1, ITALIC_NONE != rPosture.GetPosture() );
}

void WW8AttributeOutput::CharPosture( const SvxPostureItem& rPosture )
{
    OutputWW8Attribute( 1, ITALIC_NONE != rPosture.GetPosture() );
}

void WW8AttributeOutput::CharWeight( const SvxWeightItem& rWeight )
{
    OutputWW8Attribute( 0, WEIGHT_BOLD == rWeight.GetWeight() );
}

// Shadowed and Contour are not in WW-UI. JP: ??
void WW8AttributeOutput::CharContour( const SvxContourItem& rContour )
{
    OutputWW8Attribute( 3, rContour.GetValue() );
}

void WW8AttributeOutput::CharShadow( const SvxShadowedItem& rShadow )
{
    OutputWW8Attribute( 4, rShadow.GetValue() );
}

void WW8AttributeOutput::CharKerning( const SvxKerningItem& rKerning )
{
    m_rWW8Export.InsUInt16( NS_sprm::CDxaSpace::val );

    m_rWW8Export.InsUInt16( rKerning.GetValue() );
}

void WW8AttributeOutput::CharAutoKern( const SvxAutoKernItem& rAutoKern )
{
    m_rWW8Export.InsUInt16( NS_sprm::CHpsKern::val );

    m_rWW8Export.InsUInt16( rAutoKern.GetValue() ? 2 : 0 );
}

void WW8AttributeOutput::CharAnimatedText( const SvxBlinkItem& rBlink )
{
    m_rWW8Export.InsUInt16( NS_sprm::CSfxText::val );
    // At the moment the only animated text effect we support is blinking
    m_rWW8Export.pO->push_back( rBlink.GetValue() ? 2 : 0 );
}

void WW8AttributeOutput::CharCrossedOut( const SvxCrossedOutItem& rCrossed )
{
    FontStrikeout eSt = rCrossed.GetStrikeout();
    if ( STRIKEOUT_DOUBLE == eSt )
    {
        OutputWW8Attribute( 8, true );
        return;
    }
    if ( STRIKEOUT_NONE != eSt )
    {
        OutputWW8Attribute( 2, true );
        return;
    }

    // otherwise both off
    OutputWW8Attribute( 8, false );
    OutputWW8Attribute( 2, false );
}

void WW8AttributeOutput::CharCaseMap( const SvxCaseMapItem& rCaseMap )
{
    SvxCaseMap eSt = rCaseMap.GetValue();
    switch ( eSt )
    {
        case SvxCaseMap::SmallCaps:
            OutputWW8Attribute( 5, true );
            return;
        case SvxCaseMap::Uppercase:
            OutputWW8Attribute( 6, true );
            return;
        case SvxCaseMap::Capitalize:
            // no such feature in word
            break;
        default:
            // otherwise both off
            OutputWW8Attribute( 5, false );
            OutputWW8Attribute( 6, false );
            return;
    }
}

void WW8AttributeOutput::CharHidden( const SvxCharHiddenItem& rHidden )
{
    OutputWW8Attribute( 7, rHidden.GetValue() );
}

void WW8AttributeOutput::CharBorder( const SvxBorderLine* pAllBorder, const sal_uInt16 /*nDist*/, const bool bShadow )
{
    WW8Export::Out_BorderLine( *m_rWW8Export.pO, pAllBorder, 0, NS_sprm::CBrc80::val, NS_sprm::CBrc::val, bShadow );
}

void WW8AttributeOutput::CharHighlight( const SvxBrushItem& rBrush )
{
    sal_uInt8 nColor = msfilter::util::TransColToIco( rBrush.GetColor() );
    m_rWW8Export.InsUInt16( NS_sprm::CHighlight::val );
    m_rWW8Export.pO->push_back( nColor );
}

void WW8AttributeOutput::CharUnderline( const SvxUnderlineItem& rUnderline )
{
    m_rWW8Export.InsUInt16( NS_sprm::CKul::val );

    // FIXME: this should likely be a StaticWhichCast(), but some we put something dirty in RES_CHRATR_WORDLINEMODE apparently
    const auto pItem = m_rWW8Export.HasItem(RES_CHRATR_WORDLINEMODE);
    bool bWord = false;
    if(pItem)
    {
        const auto pWordline = pItem->DynamicWhichCast(RES_CHRATR_WORDLINEMODE);
        if(pWordline)
            bWord = pWordline->GetValue();
        else
            SAL_WARN("sw.ww8", "m_rWW8Export has an RES_CHRATR_WORDLINEMODE item, but its of the wrong type.");
    }

    // WW95 - parameters:   0 = none,   1 = single, 2 = by Word,
    //                      3 = double, 4 = dotted, 5 = hidden
    // WW97 - additional parameters:
    //                      6 = thick,   7 = dash,       8 = dot(not used)
    //                      9 = dotdash 10 = dotdotdash, 11 = wave
    sal_uInt8 b = 0;
    switch ( rUnderline.GetLineStyle() )
    {
        case LINESTYLE_SINGLE:
            b = bWord ? 2 : 1;
            break;
        case LINESTYLE_BOLD:
            b = 6;
            break;
        case LINESTYLE_DOUBLE:
            b = 3;
            break;
        case LINESTYLE_DOTTED:
            b = 4;
            break;
        case LINESTYLE_DASH:
            b = 7;
            break;
        case LINESTYLE_DASHDOT:
            b = 9;
            break;
        case LINESTYLE_DASHDOTDOT:
            b = 10;
            break;
        case LINESTYLE_WAVE:
            b = 11;
            break;
        // new in WW2000
        case LINESTYLE_BOLDDOTTED:
            b = 20;
            break;
        case LINESTYLE_BOLDDASH:
            b = 23;
            break;
        case LINESTYLE_LONGDASH:
            b = 39;
            break;
        case LINESTYLE_BOLDLONGDASH:
            b = 55;
            break;
        case LINESTYLE_BOLDDASHDOT:
            b = 25;
            break;
        case LINESTYLE_BOLDDASHDOTDOT:
            b = 26;
            break;
        case LINESTYLE_BOLDWAVE:
            b = 27;
            break;
        case LINESTYLE_DOUBLEWAVE:
            b = 43;
            break;
        case LINESTYLE_NONE:
            b = 0;
            break;
        default:
            OSL_ENSURE( rUnderline.GetLineStyle() == LINESTYLE_NONE, "Unhandled underline type" );
            break;
    }

    m_rWW8Export.pO->push_back( b );
    Color aColor = rUnderline.GetColor();
    if( aColor != COL_TRANSPARENT )
    {
        m_rWW8Export.InsUInt16( NS_sprm::CCvUl::val );

        m_rWW8Export.InsUInt32( wwUtility::RGBToBGR( aColor ) );
    }
}

void WW8AttributeOutput::CharLanguage( const SvxLanguageItem& rLanguage )
{
    sal_uInt16 nId = 0;
    switch ( rLanguage.Which() )
    {
        case RES_CHRATR_LANGUAGE:
            nId = NS_sprm::CRgLid0_80::val;
            break;
        case RES_CHRATR_CJK_LANGUAGE:
            nId = NS_sprm::CRgLid1_80::val;
            break;
        case RES_CHRATR_CTL_LANGUAGE:
            nId = NS_sprm::CLidBi::val;
            break;
    }

    if ( !nId )
        return;

    // use sprmCRgLid0_80 rather than sprmCLid
    m_rWW8Export.InsUInt16( nId );
    m_rWW8Export.InsUInt16( static_cast<sal_uInt16>(rLanguage.GetLanguage()) );

    // Word 2000 and above apparently require both old and new versions of
    // these sprms to be set, without it spellchecking doesn't work
    if ( nId == NS_sprm::CRgLid0_80::val )
    {
        m_rWW8Export.InsUInt16( NS_sprm::CRgLid0::val );
        m_rWW8Export.InsUInt16( static_cast<sal_uInt16>(rLanguage.GetLanguage()) );
    }
    else if ( nId == NS_sprm::CRgLid1_80::val )
    {
        m_rWW8Export.InsUInt16( NS_sprm::CRgLid1::val );
        m_rWW8Export.InsUInt16( static_cast<sal_uInt16>(rLanguage.GetLanguage()) );
    }
}

void WW8AttributeOutput::CharEscapement( const SvxEscapementItem& rEscapement )
{
    sal_uInt8 b = 0xFF;
    short nEsc = rEscapement.GetEsc(), nProp = rEscapement.GetProportionalHeight();
    if ( !nEsc )
    {
        b = 0;
        nEsc = 0;
        nProp = 100;
    }
    else if ( DFLT_ESC_PROP == nProp || nProp < 1 || nProp > 100 )
    {
        if ( DFLT_ESC_SUB == nEsc || DFLT_ESC_AUTO_SUB == nEsc )
            b = 2;
        else if ( DFLT_ESC_SUPER == nEsc || DFLT_ESC_AUTO_SUPER == nEsc )
            b = 1;
    }
    else if ( DFLT_ESC_AUTO_SUPER == nEsc )
    {
        // Raised by the differences between the ascenders (ascent = baseline to top of highest letter).
        // The ascent is generally about 80% of the total font height.
        // That is why DFLT_ESC_PROP (58) leads to 33% (DFLT_ESC_SUPER)
        nEsc = .8 * (100 - nProp);
    }
    else if ( DFLT_ESC_AUTO_SUB == nEsc )
    {
        // Lowered by the differences between the descenders (descent = baseline to bottom of lowest letter).
        // The descent is generally about 20% of the total font height.
        // That is why DFLT_ESC_PROP (58) leads to 8% (DFLT_ESC_SUB)
        nEsc = .2 * -(100 - nProp);
    }

    if ( 0xFF != b )
    {
        m_rWW8Export.InsUInt16( NS_sprm::CIss::val );

        m_rWW8Export.pO->push_back( b );
    }

    if ( 0 != b && 0xFF != b )
        return;

    double fHeight = m_rWW8Export.GetItem( RES_CHRATR_FONTSIZE ).GetHeight();
    m_rWW8Export.InsUInt16( NS_sprm::CHpsPos::val );

    m_rWW8Export.InsUInt16(static_cast<short>( round(fHeight * nEsc / 1000) ));

    if( 100 != nProp || !b )
    {
        m_rWW8Export.InsUInt16( NS_sprm::CHps::val );
        m_rWW8Export.InsUInt16(msword_cast<sal_uInt16>( round(fHeight * nProp / 1000) ));
    }
}

void WW8AttributeOutput::CharFontSize( const SvxFontHeightItem& rHeight )
{
    sal_uInt16 nId = 0;
    switch ( rHeight.Which() )
    {
        case RES_CHRATR_FONTSIZE:
        case RES_CHRATR_CJK_FONTSIZE:
            nId = NS_sprm::CHps::val;
            break;
        case RES_CHRATR_CTL_FONTSIZE:
            nId = NS_sprm::CHpsBi::val;
            break;
    }

    if ( nId )
    {
        m_rWW8Export.InsUInt16( nId );

        m_rWW8Export.InsUInt16( o3tl::narrowing<sal_uInt16>(( rHeight.GetHeight() + 5 ) / 10 ) );
    }
}

void WW8AttributeOutput::CharScaleWidth( const SvxCharScaleWidthItem& rScaleWidth )
{
    m_rWW8Export.InsUInt16( NS_sprm::CCharScale::val );
    m_rWW8Export.InsUInt16( rScaleWidth.GetValue() );
}

void WW8AttributeOutput::CharRelief( const SvxCharReliefItem& rRelief )
{
    sal_uInt16 nId;
    switch ( rRelief.GetValue() )
    {
        case FontRelief::Embossed:   nId = NS_sprm::CFEmboss::val;     break;
        case FontRelief::Engraved:   nId = NS_sprm::CFImprint::val;    break;
        default:                nId = 0;                        break;
    }

    if( nId )
    {
        m_rWW8Export.InsUInt16( nId );
        m_rWW8Export.pO->push_back( sal_uInt8(0x81) );
    }
    else
    {
        // switch both flags off
        m_rWW8Export.InsUInt16( NS_sprm::CFEmboss::val );
        m_rWW8Export.pO->push_back( sal_uInt8(0x0) );
        m_rWW8Export.InsUInt16( NS_sprm::CFImprint::val );
        m_rWW8Export.pO->push_back( sal_uInt8(0x0) );
    }
}

void WW8AttributeOutput::CharBidiRTL( const SfxPoolItem& rHt )
{
    const SfxInt16Item& rAttr = static_cast<const SfxInt16Item&>(rHt);
    if( rAttr.GetValue() == 1 )
    {
        m_rWW8Export.InsUInt16(0x85a);
        m_rWW8Export.pO->push_back(sal_uInt8(1));
    }
}

void WW8AttributeOutput::CharIdctHint( const SfxPoolItem& rHt )
{
    const SfxInt16Item& rAttr = static_cast<const SfxInt16Item&>(rHt);
    m_rWW8Export.InsUInt16(0x286F);
    m_rWW8Export.pO->push_back(static_cast<sal_uInt8>(rAttr.GetValue()));
}

void WW8AttributeOutput::CharRotate( const SvxCharRotateItem& rRotate )
{
    // #i28331# - check that a Value is set
    if ( !rRotate.GetValue() )
        return;

    if (m_rWW8Export.IsInTable())
        return;

    // #i36867 In word the text in a table is rotated via the TC or NS_sprm::TTextFlow::val
    // This means you can only rotate all or none of the text adding NS_sprm::CFELayout::val
    // here corrupts the table, hence !m_rWW8Export.bIsInTable

    m_rWW8Export.InsUInt16( NS_sprm::CFELayout::val );
    m_rWW8Export.pO->push_back( sal_uInt8(0x06) ); //len 6
    m_rWW8Export.pO->push_back( sal_uInt8(0x01) );

    m_rWW8Export.InsUInt16( rRotate.IsFitToLine() ? 1 : 0 );
    static const sal_uInt8 aZeroArr[ 3 ] = { 0, 0, 0 };
    m_rWW8Export.pO->insert( m_rWW8Export.pO->end(), aZeroArr, aZeroArr+3);
}

void WW8AttributeOutput::CharEmphasisMark( const SvxEmphasisMarkItem& rEmphasisMark )
{
    sal_uInt8 nVal;
    const FontEmphasisMark v = rEmphasisMark.GetEmphasisMark();
    if (v == FontEmphasisMark::NONE)
        nVal = 0;
    else if (v == (FontEmphasisMark::Accent | FontEmphasisMark::PosAbove))
        nVal = 2;
    else if (v == (FontEmphasisMark::Circle | FontEmphasisMark::PosAbove))
        nVal = 3;
    else if (v == (FontEmphasisMark::Dot | FontEmphasisMark::PosBelow))
        nVal = 4;
    else
        // case 1:
        nVal = 1;

    m_rWW8Export.InsUInt16( NS_sprm::CKcd::val );
    m_rWW8Export.pO->push_back( nVal );
}

/**
 * TransBrush converts SW-Brushes to WW. The result is WW8_SHD.
 * Non-standard colours of SW won't be converted now to the mixed values
 * ( 0 .. 95% ) of WW.
 * Also if transparent, e.g. for tables a transparent brush is returned
 *
 * @return real brush ( not transparent )
 */
bool WW8Export::TransBrush(const Color& rCol, WW8_SHD& rShd)
{
    if( rCol.IsTransparent() )
        rShd = WW8_SHD();               // all zeros: transparent
    else
    {
        rShd.SetFore( 0);
        rShd.SetBack( msfilter::util::TransColToIco( rCol ) );
        rShd.SetStyle( 0 );
    }
    return !rCol.IsTransparent();
}

static sal_uInt32 SuitableBGColor(Color nIn)
{
    if (nIn == COL_AUTO)
        return 0xFF000000;
    return wwUtility::RGBToBGR(nIn);
}

void WW8AttributeOutput::CharColor( const SvxColorItem& rColor )
{
    m_rWW8Export.InsUInt16( NS_sprm::CIco::val );

    sal_uInt8 nColor = msfilter::util::TransColToIco( rColor.GetValue() );
    m_rWW8Export.pO->push_back( nColor );

    if (nColor)
    {
        m_rWW8Export.InsUInt16( NS_sprm::CCv::val );
        m_rWW8Export.InsUInt32( wwUtility::RGBToBGR( rColor.GetValue() ) );
    }
}

void WW8AttributeOutput::CharBackground( const SvxBrushItem& rBrush )
{
    WW8_SHD aSHD;

    WW8Export::TransBrush( rBrush.GetColor(), aSHD );
    // sprmCShd80
    m_rWW8Export.InsUInt16( NS_sprm::CShd80::val );
    m_rWW8Export.InsUInt16( aSHD.GetValue() );

    //Quite a few unknowns, some might be transparency or something
    //of that nature...
    m_rWW8Export.InsUInt16( NS_sprm::CShd::val );
    m_rWW8Export.pO->push_back( 10 );
    m_rWW8Export.InsUInt32( 0xFF000000 );
    m_rWW8Export.InsUInt32( SuitableBGColor( rBrush.GetColor() ) );
    m_rWW8Export.InsUInt16( 0x0000);
}

namespace sw { namespace util {

const SwCharFormat* GetSwCharFormat(const SwFormatINetFormat& rINet, SwDoc& rDoc)
{
    if (rINet.GetValue().isEmpty())
        return nullptr;

    const sal_uInt16 nId = rINet.GetINetFormatId();
    const OUString& rStr = rINet.GetINetFormat();
    if (rStr.isEmpty())
    {
        OSL_ENSURE( false, "WW8AttributeOutput::TextINetFormat(..) - missing unvisited character format at hyperlink attribute" );
    }

    return IsPoolUserFormat( nId )
               ? rDoc.FindCharFormatByName( rStr )
               : rDoc.getIDocumentStylePoolAccess().GetCharFormatFromPool( nId );
}

} }

void WW8AttributeOutput::TextINetFormat( const SwFormatINetFormat& rINet )
{
    const SwCharFormat* pFormat = GetSwCharFormat(rINet, m_rWW8Export.m_rDoc);
    if (!pFormat)
        return;

    m_rWW8Export.InsUInt16( NS_sprm::CIstd::val );

    m_rWW8Export.InsUInt16( m_rWW8Export.GetId( pFormat ) );
}

// #i43956# - add optional parameter <pLinkStr>
// It's needed to write the hyperlink data for a certain cross-reference
// - it contains the name of the link target, which is a bookmark.
// add optional parameter <bIncludeEmptyPicLocation>
// It is needed to write an empty picture location for page number field separators
static void InsertSpecialChar( WW8Export& rWrt, sal_uInt8 c,
                               OUString const * pLinkStr,
                               bool bIncludeEmptyPicLocation = false )
{
    ww::bytes aItems;
    rWrt.GetCurrentItems(aItems);

    if (c == 0x13)
        rWrt.m_pChpPlc->AppendFkpEntry(rWrt.Strm().Tell());
    else
        rWrt.m_pChpPlc->AppendFkpEntry(rWrt.Strm().Tell(), aItems.size(), aItems.data());

    rWrt.WriteChar(c);

    // store empty sprmCPicLocation for field separator
    if ( bIncludeEmptyPicLocation &&
         ( c == 0x13 || c == 0x14 || c == 0x15 ) )
    {
        SwWW8Writer::InsUInt16( aItems, NS_sprm::CPicLocation::val );
        SwWW8Writer::InsUInt32( aItems, 0x00000000 );
    }

    // #i43956# - write hyperlink data and attributes
    if ( c == 0x01 && pLinkStr)
    {
        // write hyperlink data to data stream
        SvStream& rStrm = *rWrt.pDataStrm;
        // position of hyperlink data
        const sal_uInt32 nLinkPosInDataStrm = rStrm.Tell();
        // write empty header
        const sal_uInt16 nEmptyHdrLen = 0x44;
        sal_uInt8 aEmptyHeader[ nEmptyHdrLen ] = { 0 };
        aEmptyHeader[ 4 ] = 0x44;
        rStrm.WriteBytes( aEmptyHeader, nEmptyHdrLen );
        // writer fixed header
        const sal_uInt16 nFixHdrLen = 0x19;
        sal_uInt8 const aFixHeader[ nFixHdrLen ] =
        {
            0x08, 0xD0, 0xC9, 0xEA, 0x79, 0xF9, 0xBA, 0xCE,
            0x11, 0x8C, 0x82, 0x00, 0xAA, 0x00, 0x4B, 0xA9,
            0x0B, 0x02, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00,
            0x00,
        };
        rStrm.WriteBytes( aFixHeader, nFixHdrLen );
        // write reference string including length+1
        sal_uInt32 nStrLen( pLinkStr->getLength() + 1 );
        SwWW8Writer::WriteLong( rStrm, nStrLen );
        SwWW8Writer::WriteString16( rStrm, *pLinkStr, false );
        // write additional two NULL Bytes
        SwWW8Writer::WriteLong( rStrm, 0 );
        // write length of hyperlink data
        const sal_uInt32 nCurrPos = rStrm.Tell();
        rStrm.Seek( nLinkPosInDataStrm );
        rStrm.WriteUInt32(nCurrPos - nLinkPosInDataStrm);
        rStrm.Seek( nCurrPos );

        // write attributes of hyperlink character 0x01
        SwWW8Writer::InsUInt16( aItems, NS_sprm::CFFldVanish::val );
        aItems.push_back( sal_uInt8(0x81) );
        SwWW8Writer::InsUInt16( aItems, NS_sprm::CPicLocation::val );
        SwWW8Writer::InsUInt32( aItems, nLinkPosInDataStrm );
        SwWW8Writer::InsUInt16( aItems, NS_sprm::CFData::val );
        aItems.push_back( sal_uInt8(0x01) );
    }

    //Technically we should probably Remove all attribs
    //here for the 0x13, 0x14, 0x15, but our import
    //is slightly lacking
    //aItems.Remove(0, aItems.Count());
    // fSpec-Attribute true
    SwWW8Writer::InsUInt16( aItems, NS_sprm::CFSpec::val );
    aItems.push_back( 1 );

    rWrt.m_pChpPlc->AppendFkpEntry(rWrt.Strm().Tell(), aItems.size(), aItems.data());
}

static OUString lcl_GetExpandedField(const SwField &rField)
{
    //replace LF 0x0A with VT 0x0B
    return rField.ExpandField(true, nullptr).replace(0x0A, 0x0B);
}

WW8_WrPlcField* WW8Export::CurrentFieldPlc() const
{
    WW8_WrPlcField* pFieldP = nullptr;
    switch (m_nTextTyp)
    {
        case TXT_MAINTEXT:
            pFieldP = m_pFieldMain.get();
            break;
        case TXT_HDFT:
            pFieldP = m_pFieldHdFt.get();
            break;
        case TXT_FTN:
            pFieldP = m_pFieldFootnote.get();
            break;
        case TXT_EDN:
            pFieldP = m_pFieldEdn.get();
            break;
        case TXT_ATN:
            pFieldP = m_pFieldAtn.get();
            break;
        case TXT_TXTBOX:
            pFieldP = m_pFieldTextBxs.get();
            break;
        case TXT_HFTXTBOX:
            pFieldP = m_pFieldHFTextBxs.get();
            break;
        default:
            OSL_ENSURE( false, "what type of SubDoc is that?" );
    }
    return pFieldP;
}

void WW8Export::OutputField( const SwField* pField, ww::eField eFieldType,
    const OUString& rFieldCmd, FieldFlags nMode )
{
    OUString sFieldCmd(rFieldCmd);
    switch (eFieldType)
    {
        // map fields that are not supported in WW8 as of Word 2003
        case ww::eBIBLIOGRAPHY:
            eFieldType = ww::eQUOTE;
            assert(rFieldCmd == FieldString(ww::eBIBLIOGRAPHY));
            sFieldCmd = FieldString(ww::eQUOTE);
            break;
        case ww::eCITATION:
            eFieldType = ww::eQUOTE;
            assert(rFieldCmd.trim().startsWith("CITATION"));
            sFieldCmd = rFieldCmd.replaceFirst(FieldString(ww::eCITATION),
                                               FieldString(ww::eQUOTE));
            break;
        default:
            break;
    }

    assert(eFieldType <= 0x5F); // 95 is the highest documented one

    WW8_WrPlcField* pFieldP = CurrentFieldPlc();

    const bool bIncludeEmptyPicLocation = ( eFieldType == ww::ePAGE );
    if (FieldFlags::Start & nMode)
    {
        sal_uInt8 aField13[2] = { 0x13, 0x00 };  // will change
        //#i3958#, Needed to make this field work correctly in Word 2000
        if (eFieldType == ww::eSHAPE)
            aField13[0] |= 0x80;
        aField13[1] = static_cast< sal_uInt8 >(eFieldType);  // add type
        pFieldP->Append( Fc2Cp( Strm().Tell() ), aField13 );
        InsertSpecialChar( *this, 0x13, nullptr, bIncludeEmptyPicLocation );
    }
    if (FieldFlags::CmdStart & nMode)
    {
        SwWW8Writer::WriteString16(Strm(), sFieldCmd, false);
        // #i43956# - write hyperlink character including
        // attributes and corresponding binary data for certain reference fields.
        bool bHandleBookmark = false;

        if (pField)
        {
            if (pField->GetTyp()->Which() == SwFieldIds::GetRef &&
                ( eFieldType == ww::ePAGEREF || eFieldType == ww::eREF ||
                  eFieldType == ww::eNOTEREF || eFieldType == ww::eFOOTREF ))
                bHandleBookmark = true;
        }

        if ( bHandleBookmark )
        {
            // retrieve reference destination - the name of the bookmark
            OUString aLinkStr;
            const sal_uInt16 nSubType = pField->GetSubType();
            const SwGetRefField& rRField = *static_cast<const SwGetRefField*>(pField);
            if ( nSubType == REF_SETREFATTR ||
                 nSubType == REF_BOOKMARK )
            {
                const OUString& aRefName(rRField.GetSetRefName());
                aLinkStr = GetBookmarkName( nSubType, &aRefName, 0 );
            }
            else if ( nSubType == REF_FOOTNOTE ||
                      nSubType == REF_ENDNOTE )
            {
                aLinkStr = GetBookmarkName( nSubType, nullptr, rRField.GetSeqNo() );
            }
            else if ( nSubType == REF_SEQUENCEFLD )
            {
                aLinkStr = pField->GetPar2();
            }
            // insert hyperlink character including attributes and data.
            InsertSpecialChar( *this, 0x01, &aLinkStr );
        }
    }
    if (FieldFlags::CmdEnd & nMode)
    {
        static const sal_uInt8 aField14[2] = { 0x14, 0xff };
        pFieldP->Append( Fc2Cp( Strm().Tell() ), aField14 );
        pFieldP->ResultAdded();
        InsertSpecialChar( *this, 0x14, nullptr, bIncludeEmptyPicLocation );
    }
    if (FieldFlags::End & nMode)
    {
        OUString sOut;
        if( pField )
            sOut = lcl_GetExpandedField(*pField);
        else
            sOut = sFieldCmd;
        if( !sOut.isEmpty() )
        {
            SwWW8Writer::WriteString16(Strm(), sOut, false);

            if (pField)
            {
                if (pField->GetTyp()->Which() == SwFieldIds::Input &&
                    eFieldType == ww::eFORMTEXT)
                {
                    sal_uInt8 aArr[12];
                    sal_uInt8 *pArr = aArr;

                    Set_UInt16( pArr, NS_sprm::CPicLocation::val );
                    Set_UInt32( pArr, 0x0 );

                    Set_UInt16( pArr, NS_sprm::CFSpec::val );
                    Set_UInt8( pArr, 1 );

                    Set_UInt16( pArr, NS_sprm::CFNoProof::val );
                    Set_UInt8( pArr, 1 );

                    m_pChpPlc->AppendFkpEntry( Strm().Tell(), static_cast< short >(pArr - aArr), aArr );
                }
            }
        }
    }
    if (!(FieldFlags::Close & nMode))
        return;

    sal_uInt8 aField15[2] = { 0x15, 0x80 };

    if (pField)
    {
        if (pField->GetTyp()->Which() == SwFieldIds::Input &&
            eFieldType == ww::eFORMTEXT)
        {
            sal_uInt16 nSubType = pField->GetSubType();

            if (nSubType == REF_SEQUENCEFLD)
                aField15[0] |= (0x4 << 5);
        }
        // This ought to apply to any field, but just to be safe, start off with DATE/TIME only.
        if (pField->GetTyp()->Which() == SwFieldIds::DateTime
            && (pField->GetSubType() & FIXEDFLD))
        {
            //bit 5 - Locked: do not recalculate field
            aField15[1] |= 0x10;
        }
    }

    pFieldP->Append( Fc2Cp( Strm().Tell() ), aField15 );
    InsertSpecialChar( *this, 0x15, nullptr, bIncludeEmptyPicLocation );
}

void WW8Export::StartCommentOutput(std::u16string_view rName)
{
    const OUString sStr{ FieldString(ww::eQUOTE) + "[" + rName + "] " };
    OutputField(nullptr, ww::eQUOTE, sStr, FieldFlags::Start | FieldFlags::CmdStart);
}

void WW8Export::EndCommentOutput(std::u16string_view rName)
{
    const OUString sStr{ OUString::Concat(" [") + rName + "] " };
    OutputField(nullptr, ww::eQUOTE, sStr, FieldFlags::CmdEnd | FieldFlags::End |
        FieldFlags::Close);
}

sal_uInt16 MSWordExportBase::GetId( const SwTOXType& rTOXType )
{
    std::vector<const SwTOXType*>::iterator it
        = std::find( m_aTOXArr.begin(), m_aTOXArr.end(), &rTOXType );
    if ( it != m_aTOXArr.end() )
    {
        return it - m_aTOXArr.begin();
    }
    m_aTOXArr.push_back( &rTOXType );
    return m_aTOXArr.size() - 1;
}

// return values:  1 - no PageNum,
//                 2 - TabStop before PageNum,
//                 3 - Text before PageNum - rText hold the text
//                 4 - no Text and no TabStop before PageNum
static int lcl_CheckForm( const SwForm& rForm, sal_uInt8 nLvl, OUString& rText )
{
    int nRet = 4;
    rText.clear();

    // #i21237#
    SwFormTokens aPattern = rForm.GetPattern(nLvl);
    SwFormTokens::iterator aIt = aPattern.begin();
    FormTokenType eTType;

    // #i61362#
    if (! aPattern.empty())
    {
        bool bPgNumFnd = false;

        // #i21237#
        while( ++aIt != aPattern.end() && !bPgNumFnd )
        {
            eTType = aIt->eTokenType;

            switch( eTType )
            {
            case TOKEN_PAGE_NUMS:
                bPgNumFnd = true;
                break;

            case TOKEN_TAB_STOP:
                nRet = 2;
                break;
            case TOKEN_TEXT:
            {
                nRet = 3;
                sal_Int32 nCount = std::min<sal_Int32>(5, aIt->sText.getLength());
                rText = aIt->sText.copy(0, nCount); // #i21237#
                break;
            }
            case TOKEN_LINK_START:
            case TOKEN_LINK_END:
                break;

            default:
                nRet = 4;
                break;
            }
        }

        if( !bPgNumFnd )
            nRet = 1;
    }

    return nRet;
}

static bool lcl_IsHyperlinked(const SwForm& rForm, sal_uInt16 nTOXLvl)
{
    bool bRes = false;
    for (sal_uInt16 nI = 1; nI < nTOXLvl; ++nI)
    {
        // #i21237#
        SwFormTokens aPattern = rForm.GetPattern(nI);

        if ( !aPattern.empty() )
        {
            SwFormTokens::iterator aIt = aPattern.begin();

            FormTokenType eTType;

            // #i21237#
            while ( ++aIt != aPattern.end() )
            {
                eTType = aIt->eTokenType;
                switch (eTType)
                {
                case TOKEN_LINK_START:
                case TOKEN_LINK_END:
                    bRes = true;
                break;
                default:
                    ;
                }
            }
        }
    }
    return bRes;
}

void AttributeOutputBase::GenerateBookmarksForSequenceField(const SwTextNode& rNode, SwWW8AttrIter& rAttrIter)
{
    if(GetExport().GetExportFormat() == MSWordExportBase::ExportFormat::RTF) // Not implemented for RTF
        return;

    const SwpHints* pTextAttrs = rNode.GetpSwpHints();
    if (!pTextAttrs)
        return;

    for( size_t i = 0; i < pTextAttrs->Count(); ++i )
    {
        const SwTextAttr* pHt = pTextAttrs->Get(i);
        if (pHt->GetAttr().Which() == RES_TXTATR_FIELD)
        {
            const SwFormatField& rField = static_cast<const SwFormatField&>(pHt->GetAttr());
            const SwField* pField = rField.GetField();
            // Need to have bookmarks only for sequence fields
            if (pField && pField->GetTyp()->Which() == SwFieldIds::SetExp && pField->GetSubType() == nsSwGetSetExpType::GSE_SEQ)
            {
                const sal_uInt16 nSeqFieldNumber = static_cast<const SwSetExpField*>(pField)->GetSeqNumber();
                const OUString sObjectName = static_cast<const SwSetExpFieldType*>(pField->GetTyp())->GetName();
                const SwFieldTypes* pFieldTypes = GetExport().m_rDoc.getIDocumentFieldsAccess().GetFieldTypes();
                bool bHaveFullBkm = false;
                bool bHaveLabelAndNumberBkm = false;
                bool bHaveCaptionOnlyBkm = false;
                bool bHaveNumberOnlyBkm = false;
                bool bRunSplittedAtSep = false;
                for( auto const & pFieldType : *pFieldTypes )
                {
                    if( SwFieldIds::GetRef == pFieldType->Which() )
                    {
                        SwIterator<SwFormatField,SwFieldType> aIter( *pFieldType );
                        for( SwFormatField* pFormatField = aIter.First(); pFormatField; pFormatField = aIter.Next() )
                        {
                            SwGetRefField* pRefField = static_cast<SwGetRefField*>(pFormatField->GetField());
                            // If we have a reference to the current sequence field
                            if(pRefField->GetSeqNo() == nSeqFieldNumber && pRefField->GetSetRefName() == sObjectName)
                            {
                                // Need to create a separate run for separator character
                                SwWW8AttrIter aLocalAttrIter( GetExport(), rNode ); // We need a local iterator having the right number of runs
                                const OUString& aText = rNode.GetText();
                                const sal_Int32 nCategoryStart = aText.indexOf(pRefField->GetSetRefName());
                                const sal_Int32 nPosBeforeSeparator = std::max(nCategoryStart, pHt->GetStart());
                                bool bCategoryFirst = nCategoryStart < pHt->GetStart();
                                sal_Int32 nSeparatorPos = 0;
                                if (bCategoryFirst)
                                {
                                    nSeparatorPos = aLocalAttrIter.WhereNext();
                                    while (nSeparatorPos <= nPosBeforeSeparator)
                                    {
                                        aLocalAttrIter.NextPos();
                                        nSeparatorPos = aLocalAttrIter.WhereNext();
                                    }
                                }
                                else
                                {
                                    nSeparatorPos = nCategoryStart + pRefField->GetSetRefName().getLength();
                                }
                                sal_Int32 nRefTextPos = 0;
                                if(nSeparatorPos < aText.getLength())
                                {
                                    nRefTextPos = SwGetExpField::GetReferenceTextPos(pHt->GetFormatField(), GetExport().m_rDoc, nSeparatorPos);
                                    if(nRefTextPos != nSeparatorPos)
                                    {
                                        if(!bRunSplittedAtSep)
                                        {
                                            if(!bCategoryFirst)
                                                rAttrIter.SplitRun(nSeparatorPos);
                                            rAttrIter.SplitRun(nRefTextPos);
                                            bRunSplittedAtSep = true;
                                        }
                                        if(!bCategoryFirst)
                                            aLocalAttrIter.SplitRun(nSeparatorPos);
                                        aLocalAttrIter.SplitRun(nRefTextPos);
                                    }
                                    else if (bCategoryFirst)
                                    {
                                        if(!bRunSplittedAtSep)
                                        {
                                            rAttrIter.SplitRun(nSeparatorPos);
                                            bRunSplittedAtSep = true;
                                        }
                                        aLocalAttrIter.SplitRun(nSeparatorPos);
                                    }
                                }
                                // Generate bookmarks on the right position
                                OUString sName("Ref_" + pRefField->GetSetRefName() + OUString::number(pRefField->GetSeqNo()));
                                switch (pRefField->GetFormat())
                                {
                                    case REF_PAGE:
                                    case REF_PAGE_PGDESC:
                                    case REF_CONTENT:
                                    case REF_UPDOWN:
                                        if(!bHaveFullBkm)
                                        {
                                            sal_Int32 nLastAttrStart = 0;
                                            sal_Int32 nActAttr = aLocalAttrIter.WhereNext();
                                            while (nActAttr < rNode.GetText().getLength())
                                            {
                                                nLastAttrStart = nActAttr;
                                                aLocalAttrIter.NextPos();
                                                nActAttr = aLocalAttrIter.WhereNext();
                                            }
                                            WriteBookmarkInActParagraph( sName + "_full", std::min(nCategoryStart, pHt->GetStart()), nLastAttrStart );
                                            bHaveFullBkm = true;
                                        }
                                        break;
                                    case REF_ONLYNUMBER:
                                    {
                                        if(!bHaveLabelAndNumberBkm)
                                        {
                                            sName += "_label_and_number";
                                            if(bCategoryFirst)
                                                WriteBookmarkInActParagraph( sName, std::min(nCategoryStart, pHt->GetStart()), std::max(nCategoryStart, pHt->GetStart()) );
                                            else
                                            {
                                                // Find the last run which contains category text
                                                SwWW8AttrIter aLocalAttrIter2( GetExport(), rNode );
                                                sal_Int32 nCatLastRun = 0;
                                                sal_Int32 nNextAttr = aLocalAttrIter2.WhereNext();
                                                while (nNextAttr < nSeparatorPos)
                                                {
                                                    nCatLastRun = nNextAttr;
                                                    aLocalAttrIter2.NextPos();
                                                    nNextAttr = aLocalAttrIter2.WhereNext();
                                                }
                                                WriteBookmarkInActParagraph( sName, pHt->GetStart(), nCatLastRun );
                                            }
                                            bHaveLabelAndNumberBkm = true;
                                        }
                                        break;
                                    }
                                    case REF_ONLYCAPTION:
                                    {
                                        if(!bHaveCaptionOnlyBkm)
                                        {
                                            // Find last run
                                            sal_Int32 nLastAttrStart = 0;
                                            sal_Int32 nActAttr = aLocalAttrIter.WhereNext();
                                            while (nActAttr < rNode.GetText().getLength())
                                            {
                                                nLastAttrStart = nActAttr;
                                                aLocalAttrIter.NextPos();
                                                nActAttr = aLocalAttrIter.WhereNext();
                                            }
                                            WriteBookmarkInActParagraph( sName + "_caption_only", nRefTextPos, nLastAttrStart );
                                            bHaveCaptionOnlyBkm = true;
                                        }
                                        break;
                                    }
                                    case REF_ONLYSEQNO:
                                    {
                                        if(!bHaveNumberOnlyBkm)
                                        {
                                            WriteBookmarkInActParagraph( sName + "_number_only", pHt->GetStart(), pHt->GetStart() );
                                            bHaveNumberOnlyBkm = true;
                                        }
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
                return;
            }
        }
    }
}

void AttributeOutputBase::StartTOX( const SwSection& rSect )
{
    if ( const SwTOXBase* pTOX = rSect.GetTOXBase() )
    {
        static const char sEntryEnd[] = "\" ";

        ww::eField eCode = ww::eTOC;
        OUString sStr = pTOX ->GetMSTOCExpression();
        if ( sStr.isEmpty() )
        {
            switch (pTOX->GetType())
            {
            case TOX_INDEX:
                eCode = ww::eINDEX;
                sStr = FieldString(eCode);

                {
                    const SwFormatCol& rCol = rSect.GetFormat()->GetFormatAttr( RES_COL );
                    const SwColumns& rColumns = rCol.GetColumns();
                    sal_Int32 nCol = rColumns.size();

                    if ( 0 < nCol )
                    {
                        // Add a continuous section break
                        if( GetExport().AddSectionBreaksForTOX() )
                        {
                            SwSection *pParent = rSect.GetParent();
                            WW8_SepInfo rInfo(&GetExport().m_rDoc.GetPageDesc(0),
                                pParent ? pParent->GetFormat() : nullptr, 0/*nRstLnNum*/);
                            GetExport( ).AttrOutput().SectionBreak( msword::PageBreak, false, &rInfo );
                        }

                        sStr += "\\c \"" + OUString::number( nCol ) + "\"";
                    }
                }

                if (pTOX->GetTOXForm().IsCommaSeparated())
                    sStr += "\\r ";

                if (SwTOIOptions::AlphaDelimiter & pTOX->GetOptions())
                    sStr += "\\h \"A\" ";

                if(SwTOXElement::IndexEntryType & pTOX->GetCreateType())
                {
                    sStr += "\\f ";
                    const OUString& sName = pTOX->GetEntryTypeName();
                    if(!sName.isEmpty())
                    {
                       sStr += sName + sEntryEnd;
                    }
                }

                if (!pTOX->GetTOXForm().IsCommaSeparated())
                {
                    // In case of Run-in style no separators are added.
                    OUString aFillText;
                    for (sal_uInt8 n = 1; n <= 3; ++n)
                    {
                        OUString aText;
                        int nRet = ::lcl_CheckForm(pTOX->GetTOXForm(), n, aText);

                        if( 3 == nRet )
                            aFillText = aText;
                        else if ((4 == nRet) || (2 == nRet))
                            aFillText = "\t";
                        else
                            aFillText.clear();
                    }
                    sStr += "\\e \"" + aFillText + sEntryEnd;
                }
                break;

            case TOX_ILLUSTRATIONS:
            case TOX_OBJECTS:
            case TOX_TABLES:
                if (!pTOX->IsFromObjectNames())
                {
                    sStr = FieldString(eCode) + "\\c ";
                    const OUString& seqName = pTOX->GetSequenceName();
                    if(!seqName.isEmpty())
                    {
                        sStr += "\"" + seqName + sEntryEnd;
                    }
                    OUString aText;
                    int nRet = ::lcl_CheckForm( pTOX->GetTOXForm(), 1, aText );
                    if (1 == nRet)
                        sStr += "\\n ";
                    else if( 3 == nRet || 4 == nRet )
                    {
                        sStr += "\\p \"" + aText + sEntryEnd;
                    }
                }
                break;

            case TOX_AUTHORITIES:
                eCode = ww::eBIBLIOGRAPHY;
                sStr = FieldString(eCode);
                 break;
                //      case TOX_USER:
                //      case TOX_CONTENT:
            default:
                {
                    sStr = FieldString(eCode);

                    OUString sTOption;
                    sal_uInt16 n, nTOXLvl = pTOX->GetLevel();
                    if( !nTOXLvl )
                        ++nTOXLvl;

                    if(SwTOXElement::TableLeader & pTOX->GetCreateType())
                    {
                        sStr +="\\z " ;
                        GetExport( ).m_bHideTabLeaderAndPageNumbers = true ;
                    }
                    if(SwTOXElement::TableInToc & pTOX->GetCreateType())
                    {
                        sStr +="\\w " ;
                        GetExport( ).m_bTabInTOC = true ;
                    }
                    if(SwTOXElement::Newline & pTOX->GetCreateType())
                    {
                        sStr +="\\x " ;
                    }
                    if( SwTOXElement::Mark & pTOX->GetCreateType() )
                    {
                        sStr += "\\f ";

                        if( TOX_USER == pTOX->GetType() )
                        {
                            sStr += "\""
                                + OUStringChar(static_cast<char>( 'A' + GetExport( ).GetId( *pTOX->GetTOXType() ) ))
                                + sEntryEnd;
                        }
                    }
                    if(SwTOXElement::Bookmark & pTOX->GetCreateType())
                    {
                        sStr += "\\b \"" + pTOX->GetBookmarkName() + sEntryEnd;
                    }

                    if( SwTOXElement::OutlineLevel & pTOX->GetCreateType() )
                    {
                        // Take the TOC value of the max level to evaluate to as
                        // the starting point for the \o flag, but reduce it to the
                        // value of the highest outline level filled by a *standard*
                        // Heading 1 - 9 style because \o "Builds a table of
                        // contents from paragraphs formatted with built-in heading
                        // styles". And afterward fill in any outline styles left
                        // uncovered by that range to the \t flag

                        // i.e. for
                        // Heading 1
                        // Heading 2
                        // custom-style
                        // Heading 4
                        // output
                        // \o 1-2 \tcustom-style,3,Heading 3,4

                        // Search over all the outline styles used and figure out
                        // what is the minimum outline level (if any) filled by a
                        // non-standard style for that level, i.e. ignore headline
                        // styles 1-9 and find the lowest valid outline level
                        sal_uInt8 nPosOfLowestNonStandardLvl = MAXLEVEL;
                        const SwTextFormatColls& rColls = *GetExport().m_rDoc.GetTextFormatColls();
                        for( n = rColls.size(); n; )
                        {
                            const SwTextFormatColl* pColl = rColls[ --n ];
                            sal_uInt16 nPoolId = pColl->GetPoolFormatId();
                            if (
                                //Is a Non-Standard Outline Style
                                (RES_POOLCOLL_HEADLINE1 > nPoolId || RES_POOLCOLL_HEADLINE9 < nPoolId) &&
                                //Has a valid outline level
                                (pColl->IsAssignedToListLevelOfOutlineStyle()) &&
                                // Is less than the lowest known non-standard level
                                (pColl->GetAssignedOutlineStyleLevel() < nPosOfLowestNonStandardLvl)
                                )
                            {
                                nPosOfLowestNonStandardLvl = ::sal::static_int_cast<sal_uInt8>(pColl->GetAssignedOutlineStyleLevel());
                            }
                        }

                        sal_uInt8 nMaxMSAutoEvaluate = nPosOfLowestNonStandardLvl < nTOXLvl ? nPosOfLowestNonStandardLvl : static_cast<sal_uInt8>(nTOXLvl);

                        //output \o 1-X where X is the highest normal outline style to be included in the toc
                        if ( nMaxMSAutoEvaluate )
                        {
                            if (nMaxMSAutoEvaluate > WW8ListManager::nMaxLevel)
                                nMaxMSAutoEvaluate = WW8ListManager::nMaxLevel;

                            sStr += "\\o \"1-" + OUString::number(nMaxMSAutoEvaluate) + sEntryEnd;
                        }

                        //collect up any other styles in the writer TOC which will
                        //not already appear in the MS TOC and place then into the
                        //\t option
                        if( nMaxMSAutoEvaluate < nTOXLvl )
                        {
                            // collect this templates into the \t option
                            for( n = rColls.size(); n;)
                            {
                                const SwTextFormatColl* pColl = rColls[ --n ];
                                if (!pColl->IsAssignedToListLevelOfOutlineStyle())
                                    continue;
                                sal_uInt8 nTestLvl =  ::sal::static_int_cast<sal_uInt8>(pColl->GetAssignedOutlineStyleLevel());
                                if (nTestLvl < nTOXLvl && nTestLvl >= nMaxMSAutoEvaluate)
                                {
                                    if (!sTOption.isEmpty())
                                        sTOption += ",";
                                    sTOption += pColl->GetName() + "," + OUString::number( nTestLvl + 1 );
                                }
                            }
                        }
                    }

                    if( SwTOXElement::ParagraphOutlineLevel & pTOX->GetCreateType() )
                    {
                        sStr +="\\u " ;
                    }

                    if( SwTOXElement::Template & pTOX->GetCreateType() )
                    {
                        // #i99641# - Consider additional styles regardless of TOX-outlinelevel
                        for( n = 0; n < MAXLEVEL; ++n )
                        {
                            const OUString& rStyles = pTOX->GetStyleNames( n );
                            if( !rStyles.isEmpty() )
                            {
                                sal_Int32 nPos = 0;
                                const OUString sLvl{ "," + OUString::number( n + 1 ) };
                                do {
                                    const OUString sStyle( rStyles.getToken( 0, TOX_STYLE_DELIMITER, nPos ));
                                    if( !sStyle.isEmpty() )
                                    {
                                        SwTextFormatColl* pColl = GetExport().m_rDoc.FindTextFormatCollByName(sStyle);
                                        if (pColl)
                                        {
                                            if (!pColl->IsAssignedToListLevelOfOutlineStyle() || pColl->GetAssignedOutlineStyleLevel() < nTOXLvl)
                                            {
                                                if( !sTOption.isEmpty() )
                                                    sTOption += ",";
                                                sTOption += sStyle + sLvl;
                                            }
                                        }
                                    }
                                } while( -1 != nPos );
                            }
                        }
                    }

                    // No 'else' branch; why the below snippet is a block I have no idea.
                    {
                        OUString aFillText;
                        sal_uInt8 nNoPgStt = MAXLEVEL, nNoPgEnd = MAXLEVEL;
                        bool bFirstFillText = true, bOnlyText = true;
                        for( n = 0; n < nTOXLvl; ++n )
                        {
                            OUString aText;
                            int nRet = ::lcl_CheckForm( pTOX->GetTOXForm(),
                                static_cast< sal_uInt8 >(n+1), aText );
                            if( 1 == nRet )
                            {
                                bOnlyText = false;
                                if( MAXLEVEL == nNoPgStt )
                                    nNoPgStt = static_cast< sal_uInt8 >(n+1);
                            }
                            else
                            {
                                if( MAXLEVEL != nNoPgStt &&
                                    MAXLEVEL == nNoPgEnd )
                                    nNoPgEnd = sal_uInt8(n);

                                bOnlyText = bOnlyText && 3 == nRet;
                                if( 3 == nRet || 4 == nRet )
                                {
                                    if( bFirstFillText )
                                        aFillText = aText;
                                    else if( aFillText != aText )
                                        aFillText.clear();
                                    bFirstFillText = false;
                                }
                            }
                        }
                        if( MAXLEVEL != nNoPgStt )
                        {
                            if (WW8ListManager::nMaxLevel < nNoPgEnd)
                                nNoPgEnd = WW8ListManager::nMaxLevel;
                            sStr += "\\n "
                                + OUString::number( nNoPgStt )
                                + "-"
                                + OUString::number( nNoPgEnd )
                                + " ";
                        }
                        if( bOnlyText )
                        {
                            sStr += "\\p \"" + aFillText + sEntryEnd;
                        }
                    }

                    if( !sTOption.isEmpty() )
                    {
                        sStr += "\\t \"" + sTOption + sEntryEnd;
                    }

                    if (lcl_IsHyperlinked(pTOX->GetTOXForm(), nTOXLvl))
                        sStr += "\\h";
                    break;
                }
            }
        }

        if (!sStr.isEmpty())
        {
            GetExport( ).m_bInWriteTOX = true;
            if (GetExport().GetExportFormat() == MSWordExportBase::ExportFormat::RTF)
            {   // tdf#129574: required for RTF; doesn't work with DOCX
                StartRun(nullptr, -42, true);
            }
            GetExport( ).OutputField( nullptr, eCode, sStr, FieldFlags::Start | FieldFlags::CmdStart |
                FieldFlags::CmdEnd );
            if (GetExport().GetExportFormat() == MSWordExportBase::ExportFormat::RTF)
            {
                EndRun(nullptr, -42, true);
            }
        }
    }

    GetExport( ).m_bStartTOX = false;
}

void AttributeOutputBase::EndTOX( const SwSection& rSect,bool bCareEnd )
{
    const SwTOXBase* pTOX = rSect.GetTOXBase();
    if ( pTOX )
    {
        ww::eField eCode = TOX_INDEX == pTOX->GetType() ? ww::eINDEX : ww::eTOC;
        GetExport( ).OutputField( nullptr, eCode, OUString(), FieldFlags::Close );

        if ( pTOX->GetType() == TOX_INDEX && GetExport().AddSectionBreaksForTOX() )
        {
            const SwFormatCol& rCol = rSect.GetFormat()->GetFormatAttr( RES_COL );
            const SwColumns& rColumns = rCol.GetColumns();
            sal_Int32 nCol = rColumns.size();

            if ( 0 < nCol )
            {
                WW8_SepInfo rInfo( &GetExport().m_rDoc.GetPageDesc( 0 ), rSect.GetFormat(), 0/*nRstLnNum*/ );
                GetExport( ).AttrOutput().SectionBreak( msword::PageBreak, false, &rInfo );
            }
        }
    }
    GetExport( ).m_bInWriteTOX = false;
    GetExport( ).m_bHideTabLeaderAndPageNumbers = false;
    if (bCareEnd)
        OnTOXEnding();
}

bool MSWordExportBase::GetNumberFormat(const SwField& rField, OUString& rStr)
{
    // Returns a date or time format string by using the US NfKeywordTable
    bool bHasFormat = false;
    SvNumberFormatter* pNFormatr = m_rDoc.GetNumberFormatter();
    sal_uInt32 nFormatIdx = rField.GetFormat();
    const SvNumberformat* pNumFormat = pNFormatr->GetEntry( nFormatIdx );
    if( pNumFormat )
    {
        LanguageType nLng = rField.GetLanguage();
        LocaleDataWrapper aLocDat(pNFormatr->GetComponentContext(),
                                  LanguageTag(nLng));

        OUString sFormat(pNumFormat->GetMappedFormatstring(GetNfKeywordTable(),
            aLocDat));

        if (!sFormat.isEmpty())
        {
            sw::ms::SwapQuotesInField(sFormat);

            rStr = "\\@\"" + sFormat + "\" " ;
            bHasFormat = true;
        }
    }
    return bHasFormat;
}

void AttributeOutputBase::GetNumberPara( OUString& rStr, const SwField& rField )
{
    switch(rField.GetFormat())
    {
        case SVX_NUM_CHARS_UPPER_LETTER:
        case SVX_NUM_CHARS_UPPER_LETTER_N:
            rStr += "\\* ALPHABETIC ";
            break;
        case SVX_NUM_CHARS_LOWER_LETTER:
        case SVX_NUM_CHARS_LOWER_LETTER_N:
            rStr += "\\* alphabetic ";
            break;
        case SVX_NUM_ROMAN_UPPER:
            rStr += "\\* ROMAN ";
            break;
        case SVX_NUM_ROMAN_LOWER:
            rStr += "\\* roman ";
            break;
        default:
            OSL_ENSURE(rField.GetFormat() == SVX_NUM_ARABIC,
                "Unknown numbering type exported as default of Arabic");
            [[fallthrough]];
        case SVX_NUM_ARABIC:
            rStr += "\\* ARABIC ";
            break;
        case SVX_NUM_PAGEDESC:
            //Nothing, use word's default
            break;
    }
}

void WW8Export::WritePostItBegin( ww::bytes* pOut )
{
    sal_uInt8 aArr[ 3 ];
    sal_uInt8* pArr = aArr;

    // sprmCFSpec true
    Set_UInt16( pArr, NS_sprm::CFSpec::val );
    Set_UInt8( pArr, 1 );

    m_pChpPlc->AppendFkpEntry( Strm().Tell() );
    WriteChar( 0x05 );              // Annotation reference

    if( pOut )
        pOut->insert( pOut->end(), aArr, pArr );
    else
        m_pChpPlc->AppendFkpEntry( Strm().Tell(), static_cast< short >(pArr - aArr), aArr );
}

OUString FieldString(ww::eField eIndex)
{
    if (const char *pField = ww::GetEnglishFieldName(eIndex))
        return " " + OUString::createFromAscii(pField) + " ";
    return "  ";
}

void WW8AttributeOutput::HiddenField( const SwField& rField )
{
    //replace LF 0x0A with VT 0x0B
    const OUString sExpand(rField.GetPar2().replace(0x0A, 0x0B));

    m_rWW8Export.m_pChpPlc->AppendFkpEntry(m_rWW8Export.Strm().Tell());
    SwWW8Writer::WriteString16(m_rWW8Export.Strm(), sExpand, false);
    static sal_uInt8 aArr[] =
    {
        0x3C, 0x08, 0x1
    };
    m_rWW8Export.m_pChpPlc->AppendFkpEntry(m_rWW8Export.Strm().Tell(), sizeof(aArr), aArr);
}

void WW8AttributeOutput::SetField( const SwField& rField, ww::eField eType, const OUString& rCmd )
{
    const SwSetExpField* pSet = static_cast<const SwSetExpField*>(&rField);
    const OUString &rVar = pSet->GetPar2();

    sal_uLong nFrom = m_rWW8Export.Fc2Cp(m_rWW8Export.Strm().Tell());

    GetExport().OutputField(&rField, eType, rCmd, FieldFlags::Start |
        FieldFlags::CmdStart | FieldFlags::CmdEnd);

    /*
    Is there a bookmark at the start position of this field, if so
    move it to the 0x14 of the result of the field.  This is what word
    does. MoveFieldMarks moves any bookmarks at this position to
    the beginning of the field result, and marks the bookmark as a
    fieldbookmark which is to be ended before the field end mark
    instead of after it like a normal bookmark.
    */
    m_rWW8Export.MoveFieldMarks(nFrom,m_rWW8Export.Fc2Cp(m_rWW8Export.Strm().Tell()));

    if (!rVar.isEmpty())
    {
        SwWW8Writer::WriteString16(m_rWW8Export.Strm(), rVar, false);
    }
    GetExport().OutputField(&rField, eType, rCmd, FieldFlags::Close);
}

void WW8AttributeOutput::PostitField( const SwField* pField )
{
    const SwPostItField *pPField = static_cast<const SwPostItField*>(pField);
    m_rWW8Export.m_pAtn->Append( m_rWW8Export.Fc2Cp( m_rWW8Export.Strm().Tell() ), pPField );
    m_rWW8Export.WritePostItBegin( m_rWW8Export.pO.get() );
}

bool WW8AttributeOutput::DropdownField( const SwField* pField )
{
    const SwDropDownField& rField2 = *static_cast<const SwDropDownField*>(pField);
    uno::Sequence<OUString> aItems =
        rField2.GetItemSequence();
    GetExport().DoComboBox(rField2.GetName(),
                       rField2.GetHelp(),
                       rField2.GetToolTip(),
                       rField2.GetSelectedItem(), aItems);
    return false;
}

bool WW8AttributeOutput::PlaceholderField( const SwField* )
{
    return true; // expand to text?
}

void WW8AttributeOutput::RefField( const SwField &rField, const OUString &rRef)
{
    const OUString sStr{ FieldString( ww::eREF ) + "\"" + rRef + "\" " };
    m_rWW8Export.OutputField( &rField, ww::eREF, sStr, FieldFlags::Start |
        FieldFlags::CmdStart | FieldFlags::CmdEnd );
    const OUString sVar = lcl_GetExpandedField( rField );
    if ( !sVar.isEmpty() )
    {
        SwWW8Writer::WriteString16( m_rWW8Export.Strm(), sVar, false );
    }
    m_rWW8Export.OutputField( &rField, ww::eREF, sStr, FieldFlags::Close );
}

void WW8AttributeOutput::WriteExpand( const SwField* pField )
{
    SwWW8Writer::WriteString16( m_rWW8Export.Strm(), lcl_GetExpandedField( *pField ), false );
}

namespace
{
// Escapes a token string for storing in Word formats. Its import counterpart
// is lcl_ExtractToken in writerfilter/source/dmapper/DomainMapper_Impl.cxx
OUString EscapeToken(const OUString& rCommand)
{
    bool bWasEscaped = false;

    const int nBufferLen = rCommand.getLength()*1.5;
    OUStringBuffer sResult(nBufferLen);
    sResult.append('"'); // opening quote
    for (sal_Int32 i = 0; i < rCommand.getLength(); ++i)
    {
        sal_Unicode ch = rCommand[i];
        switch (ch)
        {
        case '\\':
        case '"':
            // Backslashes and doublequotes must be escaped
            bWasEscaped = true;
            sResult.append('\\');
            break;
        case ' ':
            // Spaces require quotation
            bWasEscaped = true;
            break;
        }
        sResult.append(ch);
    }

    if (bWasEscaped)
    {
        sResult.append('"'); // closing quote
        return sResult.makeStringAndClear();
    }
    // No escapement/quotation was required
    return rCommand;
}
}

void AttributeOutputBase::TextField( const SwFormatField& rField )
{
    const SwField* pField = rField.GetField();
    bool bWriteExpand = false;
    const sal_uInt16 nSubType = pField->GetSubType();

    switch (pField->GetTyp()->Which())
    {
    case SwFieldIds::GetExp:
        if (nSubType == nsSwGetSetExpType::GSE_STRING)
        {
            const SwGetExpField *pGet = static_cast<const SwGetExpField*>(pField);
            RefField( *pGet, pGet->GetFormula() );
        }
        else
            bWriteExpand = true;
        break;
    case SwFieldIds::SetExp:
        if (nsSwGetSetExpType::GSE_SEQ == nSubType)
        {
            OUString sStr;
            if (GetExport().FieldsQuoted())
                sStr = FieldString(ww::eSEQ) + pField->GetTyp()->GetName() + " ";
            else
                sStr = FieldString(ww::eSEQ) + "\"" + pField->GetTyp()->GetName() +"\" ";
            GetNumberPara( sStr, *pField );
            GetExport().OutputField(pField, ww::eSEQ, sStr);
        }
        else if (nSubType & nsSwGetSetExpType::GSE_STRING)
        {
            bool bShowAsWell = false;
            ww::eField eFieldNo;
            const SwSetExpField *pSet = static_cast<const SwSetExpField*>(pField);
            const OUString sVar = pSet->GetPar2();
            OUString sStr;
            if (pSet->GetInputFlag())
            {
                sStr = FieldString(ww::eASK) + "\""
                    + pSet->GetPar1() + "\" "
                    + pSet->GetPromptText() + " \\d "
                    + sVar;
                eFieldNo = ww::eASK;
            }
            else
            {
                sStr = FieldString(ww::eSET)
                    + pSet->GetPar1() + " \""
                    + sVar + "\" ";
                eFieldNo = ww::eSET;
                bShowAsWell = (nSubType & nsSwExtendedSubType::SUB_INVISIBLE) == 0;
            }

            SetField( *pField, eFieldNo, sStr );

            if (bShowAsWell)
                RefField( *pSet, pSet->GetPar1() );
        }
        else
            bWriteExpand = true;
        break;
    case SwFieldIds::PageNumber:
        {
            OUString sStr = FieldString(ww::ePAGE);
            GetNumberPara(sStr, *pField);
            GetExport().OutputField(pField, ww::ePAGE, sStr);
        }
        break;
    case SwFieldIds::Filename:
        {
            OUString sStr = FieldString(ww::eFILENAME);
            if (pField->GetFormat() == FF_PATHNAME)
                sStr += "\\p ";
            GetExport().OutputField(pField, ww::eFILENAME, sStr);
        }
        break;
    case SwFieldIds::Database:
        {
            OUString sStr = FieldString(ww::eMERGEFIELD)
                + EscapeToken(static_cast<SwDBFieldType *>(pField->GetTyp())->GetColumnName()) + " ";
            GetExport().OutputField(pField, ww::eMERGEFIELD, sStr);
        }
        break;
    case SwFieldIds::DatabaseName:
        {
            SwDBData aData = GetExport().m_rDoc.GetDBData();
            const OUString sStr = FieldString(ww::eDATABASE)
                + aData.sDataSource
                + OUStringChar(DB_DELIM)
                + aData.sCommand;
            GetExport().OutputField(pField, ww::eDATABASE, sStr);
        }
        break;
    case SwFieldIds::Author:
        {
            ww::eField eField =
                ((AF_SHORTCUT & pField->GetFormat()) ? ww::eUSERINITIALS : ww::eUSERNAME);
            GetExport().OutputField(pField, eField, FieldString(eField));
        }
        break;
    case SwFieldIds::TemplateName:
        GetExport().OutputField(pField, ww::eTEMPLATE, FieldString(ww::eTEMPLATE));
        break;
    case SwFieldIds::DocInfo:    // Last printed, last edited,...
        if( DI_SUB_FIXED & nSubType )
            bWriteExpand = true;
        else
        {
            OUString sStr;
            ww::eField eField(ww::eNONE);
            switch (0xff & nSubType)
            {
                case DI_TITLE:
                    eField = ww::eTITLE;
                    break;
                case DI_SUBJECT:
                    eField = ww::eSUBJECT;
                    break;
                case DI_KEYS:
                    eField = ww::eKEYWORDS;
                    break;
                case DI_COMMENT:
                    eField = ww::eCOMMENTS;
                    break;
                case DI_DOCNO:
                    eField = ww::eREVNUM;
                    break;
                case DI_CREATE:
                    if (DI_SUB_AUTHOR == (nSubType & DI_SUB_MASK))
                        eField = ww::eAUTHOR;
                    else if (GetExport().GetNumberFormat(*pField, sStr))
                        eField = ww::eCREATEDATE;
                    break;

                case DI_CHANGE:
                    if (DI_SUB_AUTHOR == (nSubType & DI_SUB_MASK))
                        eField = ww::eLASTSAVEDBY;
                    else if (GetExport().GetNumberFormat(*pField, sStr))
                        eField = ww::eSAVEDATE;
                    break;

                case DI_PRINT:
                    if (DI_SUB_AUTHOR != (nSubType & DI_SUB_MASK) &&
                        GetExport().GetNumberFormat(*pField, sStr))
                        eField = ww::ePRINTDATE;
                    break;
                case DI_EDIT:
                    if( DI_SUB_AUTHOR != (nSubType & DI_SUB_MASK ) &&
                        GetExport().GetNumberFormat( *pField, sStr ))
                        eField = ww::eSAVEDATE;
                    else
                        eField = ww::eEDITTIME;
                    break;
                case DI_CUSTOM:
                    eField = ww::eDOCPROPERTY;
                    {
                        const SwDocInfoField * pDocInfoField =
                        dynamic_cast<const SwDocInfoField *> (pField);

                        if (pDocInfoField != nullptr)
                        {
                            OUString sFieldname = pDocInfoField->GetFieldName();

                            const sal_Int32 nIndex = sFieldname.indexOf(':');
                            if (nIndex >= 0)
                                sFieldname = sFieldname.copy(nIndex + 1);

                            sStr = "\"" + sFieldname + "\"";
                        }
                    }
                    break;
                default:
                    break;
            }

            if (eField != ww::eNONE)
            {
                GetExport().OutputField(pField, eField, FieldString(eField) + sStr);
            }
            else
                bWriteExpand = true;
        }
        break;
    case SwFieldIds::DateTime:
        {
            OUString sStr;
            if (!GetExport().GetNumberFormat(*pField, sStr))
                bWriteExpand = true;
            else
            {
                ww::eField eField = (DATEFLD & nSubType) ? ww::eDATE : ww::eTIME;
                GetExport().OutputField(pField, eField, FieldString(eField) + sStr);
            }
        }
        break;
    case SwFieldIds::DocStat:
        {
            ww::eField eField = ww::eNONE;

            switch (nSubType)
            {
                case DS_PAGE:
                    eField = ww::eNUMPAGES;
                    break;
                case DS_WORD:
                    eField = ww::eNUMWORDS;
                    break;
                case DS_CHAR:
                    eField = ww::eNUMCHARS;
                    break;
            }

            if (eField != ww::eNONE)
            {
                OUString sStr = FieldString(eField);
                GetNumberPara(sStr, *pField);
                GetExport().OutputField(pField, eField, sStr);
            }
            else
                bWriteExpand = true;
        }
        break;
    case SwFieldIds::ExtUser:
        {
            ww::eField eField = ww::eNONE;
            switch (0xFF & nSubType)
            {
                case EU_FIRSTNAME:
                case EU_NAME:
                    eField = ww::eUSERNAME;
                    break;
                case EU_SHORTCUT:
                    eField = ww::eUSERINITIALS;
                    break;
                case EU_STREET:
                case EU_COUNTRY:
                case EU_ZIP:
                case EU_CITY:
                    eField = ww::eUSERADDRESS;
                    break;
            }

            if (eField != ww::eNONE)
            {
                GetExport().OutputField(pField, eField, FieldString(eField));
            }
            else
                bWriteExpand = true;
        }
        break;
    case SwFieldIds::TableOfAuthorities:
    {
        OUString sRet(static_cast<SwAuthorityField const*>(pField)
                        ->ExpandCitation(AUTH_FIELD_IDENTIFIER, nullptr));
        // FIXME: DomainMapper_Impl::CloseFieldCommand() stuffs fully formed
        // field instructions in here, but if the field doesn't originate
        // from those filters it won't have that
        if (!sRet.trim().startsWith("CITATION"))
        {
            sRet = FieldString(ww::eCITATION) + " \"" + sRet + "\"";
        }
        GetExport().OutputField( pField, ww::eCITATION, sRet );
    }
    break;
    case SwFieldIds::Postit:
        //Sadly only possible for word in main document text
        if (GetExport().m_nTextTyp == TXT_MAINTEXT)
        {
            PostitField( pField );
        }
        break;
    case SwFieldIds::Input:
        {
            const SwInputField * pInputField = dynamic_cast<const SwInputField *>(pField);

            if (pInputField && pInputField->isFormField())
                GetExport().DoFormText(pInputField);
            else
            {
                const OUString sStr = FieldString(ww::eFILLIN) + "\""
                    + pField->GetPar2() + "\"";

                GetExport().OutputField(pField, ww::eFILLIN, sStr);
            }
        }
        break;
    case SwFieldIds::GetRef:
        {
            ww::eField eField = ww::eNONE;
            OUString sStr;
            const SwGetRefField& rRField = *static_cast<const SwGetRefField*>(pField);
            switch (nSubType)
            {
                case REF_SETREFATTR:
                case REF_BOOKMARK:
                    switch (pField->GetFormat())
                    {
                        case REF_PAGE_PGDESC:
                        case REF_PAGE:
                            eField = ww::ePAGEREF;
                            break;
                        default:
                            eField = ww::eREF;
                            break;
                    }
                    {
                        const OUString& aRefName(rRField.GetSetRefName());
                        sStr = FieldString(eField)
                            + MSWordExportBase::GetBookmarkName(nSubType, &aRefName, 0);
                    }
                    switch (pField->GetFormat())
                    {
                        case REF_NUMBER:
                            sStr += " \\r";
                            break;
                        case REF_NUMBER_NO_CONTEXT:
                            sStr += " \\n";
                            break;
                        case REF_NUMBER_FULL_CONTEXT:
                            sStr += " \\w";
                            break;
                    }
                    break;
                case REF_SEQUENCEFLD:
                {
                    // Not implemented for RTF
                    if(GetExport().GetExportFormat() == MSWordExportBase::ExportFormat::RTF)
                        break;

                    switch (pField->GetFormat())
                    {
                        case REF_PAGE:
                        case REF_PAGE_PGDESC:
                            eField = ww::ePAGEREF;
                            break;
                        default:
                            eField = ww::eREF;
                            break;
                    }
                    // Generate a unique bookmark name
                    {
                        OUString sName{rRField.GetSetRefName() + OUString::number(rRField.GetSeqNo())};
                        switch (pField->GetFormat())
                        {
                            case REF_PAGE:
                            case REF_PAGE_PGDESC:
                            case REF_CONTENT:
                            case REF_UPDOWN:
                                    sName += "_full";
                                    break;
                            case REF_ONLYNUMBER:
                                    sName += "_label_and_number";
                                    break;
                            case REF_ONLYCAPTION:
                                    sName += "_caption_only";
                                    break;
                            case REF_ONLYSEQNO:
                                    sName += "_number_only";
                                    break;
                            default: // Ignore other types of reference fields
                                    eField = ww::eNONE;
                                    break;
                        }
                        sStr = FieldString(eField) + MSWordExportBase::GetBookmarkName(nSubType, &sName, 0);
                    }
                    switch (pField->GetFormat())
                    {
                        case REF_NUMBER:
                            sStr += " \\r";
                            break;
                        case REF_NUMBER_NO_CONTEXT:
                            sStr += " \\n";
                            break;
                        case REF_NUMBER_FULL_CONTEXT:
                            sStr += " \\w";
                            break;
                    }
                    break;
                }
                case REF_FOOTNOTE:
                case REF_ENDNOTE:
                    switch (pField->GetFormat())
                    {
                        case REF_PAGE_PGDESC:
                        case REF_PAGE:
                            eField = ww::ePAGEREF;
                            break;
                        case REF_UPDOWN:
                            eField = ww::eREF;
                            break;
                        default:
                            eField =
                                REF_ENDNOTE == nSubType ? ww::eNOTEREF : ww::eFOOTREF;
                            break;
                    }
                    sStr = FieldString(eField)
                        + MSWordExportBase::GetBookmarkName(nSubType, nullptr, rRField.GetSeqNo());
                    break;
            }

            if (eField != ww::eNONE)
            {
                switch (pField->GetFormat())
                {
                    case REF_UPDOWN:
                        sStr += " \\p \\h ";   // with hyperlink
                        break;
                    case REF_CHAPTER:
                        sStr += " \\n \\h ";   // with hyperlink
                        break;
                    default:
                        sStr += " \\h ";       // insert hyperlink
                        break;
                }
                GetExport().OutputField(pField, eField, sStr);
            }
            else
                bWriteExpand = true;
        }
        break;
    case SwFieldIds::CombinedChars:
        {
        /*
        We need a font size to fill in the defaults, if these are overridden
        (as they generally are) by character properties then those properties
        win.

        The fontsize that is used in MS for determining the defaults is always
        the CJK fontsize even if the text is not in that language, in OOo the
        largest fontsize used in the field is the one we should take, but
        whatever we do, word will actually render using the fontsize set for
        CJK text. Nevertheless we attempt to guess whether the script is in
        asian or western text based up on the first character and use the
        font size of that script as our default.
        */
        assert(g_pBreakIt && g_pBreakIt->GetBreakIter().is());
        sal_uInt16 nScript = g_pBreakIt->GetBreakIter()->getScriptType( pField->GetPar1(), 0);

        tools::Long nHeight = static_cast<const SvxFontHeightItem&>((GetExport().GetItem(
            GetWhichOfScript(RES_CHRATR_FONTSIZE,nScript)))).GetHeight();

        nHeight = (nHeight + 10) / 20; //Font Size in points;

        /*
        Divide the combined char string into its up and down part. Get the
        font size and fill in the defaults as up == half the font size and
        down == a fifth the font size
        */
        const sal_Int32 nAbove = (pField->GetPar1().getLength()+1)/2;
        const OUString sStr = FieldString(ww::eEQ)
            + "\\o (\\s\\up "
            + OUString::number(nHeight/2)
            + "("
            + pField->GetPar1().subView(0, nAbove)
            + "), \\s\\do "
            + OUString::number(nHeight/5)
            + "("
            + pField->GetPar1().subView(nAbove)
            + "))";
        GetExport().OutputField(pField, ww::eEQ, sStr);
        }
        break;
    case SwFieldIds::Dropdown:
        bWriteExpand = DropdownField( pField );
        break;
    case SwFieldIds::Chapter:
        bWriteExpand = true;
        if (GetExport().m_bOutKF && rField.GetTextField())
        {
            const SwTextNode *pTextNd = GetExport().GetHdFtPageRoot();
            if (!pTextNd)
            {
                pTextNd = GetExport().m_pCurPam->GetNode().GetTextNode();
            }

            if (pTextNd)
            {
                SwChapterField aCopy(*static_cast<const SwChapterField*>(pField));
                aCopy.ChangeExpansion(*pTextNd, false);
                const OUString sStr = FieldString(ww::eSTYLEREF)
                    + " "
                    + OUString::number(aCopy.GetLevel() + 1)
                    + " \\* MERGEFORMAT ";
                GetExport().OutputField(pField, ww::eSTYLEREF, sStr);
                bWriteExpand = false;
            }
        }
        break;
    case SwFieldIds::HiddenText:
        {
            OUString sExpand(pField->GetPar2());
            if (!sExpand.isEmpty())
            {
                HiddenField( *pField );
            }
        }
        break;
    case SwFieldIds::JumpEdit:
        bWriteExpand = PlaceholderField( pField );
        break;
    case SwFieldIds::Macro:
        {
            const OUString sStr = " MACROBUTTON"
                + pField->GetPar1().replaceFirst("StarOffice.Standard.Modul1.", " ")
                + " "
                + lcl_GetExpandedField(*pField);
            GetExport().OutputField( pField, ww::eMACROBUTTON, sStr );
        }
        break;
    case SwFieldIds::Table:
        {
            ww::eField eField = ww::eEquals;
            OUString aExpand = " =" + pField->GetFieldName().trim();
            GetExport().OutputField(pField, eField, aExpand);
        }
        break;
    case SwFieldIds::User:
    {
        ww::eField eField = ww::eDOCVARIABLE;
        OUString aExpand = FieldString(eField) + pField->GetPar1() + " ";
        GetExport().OutputField(pField, eField, aExpand);
    }
    break;
    default:
        bWriteExpand = true;
        break;
    }

    if (bWriteExpand)
        WriteExpand( pField );
}

void AttributeOutputBase::TextFlyContent( const SwFormatFlyCnt& rFlyContent )
{
    if ( auto pTextNd = dynamic_cast< const SwContentNode *>( GetExport().m_pOutFormatNode )  )
    {
        Point const origin;
        Point aLayPos = pTextNd->FindLayoutRect( false, &origin ).Pos();

        SwPosition aPos( *pTextNd );
        ww8::Frame aFrame( *rFlyContent.GetFrameFormat(), aPos );

        OutputFlyFrame_Impl( aFrame, aLayPos );
    }
}

// TOXMarks are still missing

// WW allows detailed settings for hyphenation only for the whole document.
// One could implement following mimic: The values of the style "Standard" will
// be set in the Document Properties ( DOP ) if they exist.

// ACK. This suggestion fits exactly to our implementation of the import,
// therefore I'll implement that right now. (KHZ, 07/15/2000)
void WW8AttributeOutput::ParaHyphenZone( const SvxHyphenZoneItem& rHyphenZone )
{
    // sprmPFNoAutoHyph
    m_rWW8Export.InsUInt16( NS_sprm::PFNoAutoHyph::val );

    m_rWW8Export.pO->push_back( rHyphenZone.IsHyphen() ? 0 : 1 );
}

void WW8AttributeOutput::ParaScriptSpace( const SfxBoolItem& rScriptSpace )
{
    m_rWW8Export.InsUInt16( NS_sprm::PFAutoSpaceDE::val );
    m_rWW8Export.pO->push_back( rScriptSpace.GetValue() ? 1 : 0 );
}

void WW8AttributeOutput::ParaHangingPunctuation( const SfxBoolItem& rItem )
{
    m_rWW8Export.InsUInt16( NS_sprm::PFOverflowPunct::val );
    m_rWW8Export.pO->push_back( rItem.GetValue() ? 1 : 0 );
}

void WW8AttributeOutput::ParaForbiddenRules( const SfxBoolItem& rItem )
{
    m_rWW8Export.InsUInt16( NS_sprm::PFKinsoku::val );
    m_rWW8Export.pO->push_back( rItem.GetValue() ? 1 : 0 );
}

void WW8AttributeOutput::ParaSnapToGrid( const SvxParaGridItem& rGrid )
{
    // sprmPFUsePgsuSettings

    m_rWW8Export.InsUInt16( NS_sprm::PFUsePgsuSettings::val );
    m_rWW8Export.pO->push_back( rGrid.GetValue() ? 1 : 0 );
}

void WW8AttributeOutput::ParaVerticalAlign( const SvxParaVertAlignItem& rAlign )
{
    // sprmPWAlignFont

    m_rWW8Export.InsUInt16( NS_sprm::PWAlignFont::val );

    SvxParaVertAlignItem::Align nAlign = rAlign.GetValue();
    sal_uInt16 nVal;
    switch ( nAlign )
    {
        case SvxParaVertAlignItem::Align::Baseline:
            nVal = 2;
            break;
        case SvxParaVertAlignItem::Align::Top:
            nVal = 0;
            break;
        case SvxParaVertAlignItem::Align::Center:
            nVal = 1;
            break;
        case SvxParaVertAlignItem::Align::Bottom:
            nVal = 3;
            break;
        case SvxParaVertAlignItem::Align::Automatic:
            nVal = 4;
            break;
        default:
            nVal = 4;
            OSL_FAIL( "Unknown vert alignment" );
            break;
    }
    m_rWW8Export.InsUInt16( nVal );
}

// NoHyphen: I didn't find an equal in the SW UI and WW UI

// RefMark, NoLineBreakHere are still missing

void WW8Export::WriteFootnoteBegin( const SwFormatFootnote& rFootnote, ww::bytes* pOutArr )
{
    ww::bytes aAttrArr;
    const bool bAutoNum = rFootnote.GetNumStr().isEmpty();
    if( bAutoNum )
    {
        static const sal_uInt8 aSpec[] =
        {
            0x03, 0x6a, 0, 0, 0, 0, // sprmCObjLocation
            0x55, 0x08, 1           // sprmCFSpec
        };

        aAttrArr.insert(aAttrArr.end(), aSpec, aSpec+sizeof(aSpec));
    }

    // sprmCIstd
    const SwEndNoteInfo* pInfo;
    if( rFootnote.IsEndNote() )
        pInfo = &m_rDoc.GetEndNoteInfo();
    else
        pInfo = &m_rDoc.GetFootnoteInfo();
    const SwCharFormat* pCFormat = pOutArr
                                ? pInfo->GetAnchorCharFormat( m_rDoc )
                                : pInfo->GetCharFormat( m_rDoc );
    SwWW8Writer::InsUInt16( aAttrArr, NS_sprm::CIstd::val );
    SwWW8Writer::InsUInt16( aAttrArr, GetId( pCFormat ) );

                                                // fSpec-Attribute true
                            // For Auto-Number a special character must go
                            // into the text and therefore a fSpec attribute
    m_pChpPlc->AppendFkpEntry( Strm().Tell() );
    if( bAutoNum )
        WriteChar( 0x02 );              // auto number character
    else
        // user numbering
        OutSwString(rFootnote.GetNumStr(), 0, rFootnote.GetNumStr().getLength());

    if( pOutArr )
    {
        // insert at start of array, so the "hard" attribute overrule the
        // attributes of the character template
        pOutArr->insert( pOutArr->begin(), aAttrArr.begin(), aAttrArr.end() );
    }
    else
    {
        std::unique_ptr<ww::bytes> pOwnOutArr(new ww::bytes);

        // insert at start of array, so the "hard" attribute overrule the
        // attributes of the character template
        pOwnOutArr->insert(pOwnOutArr->begin(), aAttrArr.begin(), aAttrArr.end());

        // write for the ftn number in the content, the font of the anchor
        const SwTextFootnote* pTextFootnote = rFootnote.GetTextFootnote();
        if( pTextFootnote )
        {
            std::unique_ptr<ww::bytes> pOld = std::move(pO);
            pO = std::move(pOwnOutArr);
            SfxItemSet aSet( m_rDoc.GetAttrPool(), svl::Items<RES_CHRATR_FONT,
                                                  RES_CHRATR_FONT>{} );

            pCFormat = pInfo->GetCharFormat( m_rDoc );

            pTextFootnote->GetTextNode().GetParaAttr(aSet,
                pTextFootnote->GetStart(), pTextFootnote->GetStart() + 1, true);
            if (aSet.Count())
            {
                m_pAttrOutput->OutputItem( aSet.Get( RES_CHRATR_FONT ) );
            }
            else
            {
                m_pAttrOutput->OutputItem( pCFormat->GetAttrSet().Get(RES_CHRATR_FONT) );
            }
            pOwnOutArr = std::move(pO);
            pO = std::move(pOld);
        }
        m_pChpPlc->AppendFkpEntry( Strm().Tell(), pOwnOutArr->size(),
                                                pOwnOutArr->data() );
    }
}

static bool lcl_IsAtTextEnd(const SwFormatFootnote& rFootnote)
{
    bool bRet = true;
    if( rFootnote.GetTextFootnote() )
    {
        sal_uInt16 nWh = rFootnote.IsEndNote() ? sal_uInt16(RES_END_AT_TXTEND)
                                      : sal_uInt16(RES_FTN_AT_TXTEND);
        const SwSectionNode* pSectNd = rFootnote.GetTextFootnote()->GetTextNode().
                                                        FindSectionNode();
        while( pSectNd && FTNEND_ATPGORDOCEND ==
                static_cast<const SwFormatFootnoteEndAtTextEnd&>(pSectNd->GetSection().GetFormat()->
                GetFormatAttr( nWh)).GetValue() )
            pSectNd = pSectNd->StartOfSectionNode()->FindSectionNode();

        if (!pSectNd)
            bRet = false;   // the is ftn/end collected at Page- or Doc-End
    }
    return bRet;
}

void AttributeOutputBase::TextFootnote( const SwFormatFootnote& rFootnote )
{
    sal_uInt16 nTyp;
    if ( rFootnote.IsEndNote() )
    {
        nTyp = REF_ENDNOTE;
        if ( GetExport().m_bEndAtTextEnd )
            GetExport().m_bEndAtTextEnd = lcl_IsAtTextEnd( rFootnote );
    }
    else
    {
        nTyp = REF_FOOTNOTE;
        if ( GetExport().m_bFootnoteAtTextEnd )
            GetExport().m_bFootnoteAtTextEnd = lcl_IsAtTextEnd( rFootnote );
    }

    // if any reference to this footnote/endnote then insert an internal
    // Bookmark.
    OUString sBkmkNm;
    if ( GetExport().HasRefToFootOrEndnote( rFootnote.IsEndNote(), rFootnote.GetTextFootnote()->GetSeqRefNo()))
    {
        sBkmkNm = MSWordExportBase::GetBookmarkName( nTyp, nullptr,
                                    rFootnote.GetTextFootnote()->GetSeqRefNo() );
        GetExport().AppendBookmark( sBkmkNm );
    }

    TextFootnote_Impl( rFootnote );

    if ( !sBkmkNm.isEmpty() )
        GetExport().AppendBookmark( sBkmkNm ); // FIXME: Why is it added twice?  Shouldn't this one go to WW8AttributeOutput::TextFootnote_Impl()?
}

void WW8AttributeOutput::TextFootnote_Impl( const SwFormatFootnote& rFootnote )
{
    WW8_WrPlcFootnoteEdn* pFootnoteEnd;
    if ( rFootnote.IsEndNote() || GetExport().m_rDoc.GetFootnoteInfo().m_ePos == FTNPOS_CHAPTER )
        pFootnoteEnd = m_rWW8Export.pEdn.get();
    else
        pFootnoteEnd = m_rWW8Export.pFootnote.get();

    pFootnoteEnd->Append( m_rWW8Export.Fc2Cp( m_rWW8Export.Strm().Tell() ), rFootnote );
    m_rWW8Export.WriteFootnoteBegin( rFootnote, m_rWW8Export.pO.get() );
}

void WW8AttributeOutput::TextCharFormat( const SwFormatCharFormat& rCharFormat )
{
    if( rCharFormat.GetCharFormat() )
    {
        m_rWW8Export.InsUInt16( NS_sprm::CIstd::val );

        m_rWW8Export.InsUInt16( m_rWW8Export.GetId( rCharFormat.GetCharFormat() ) );
    }
}

/*
 See ww8par6.cxx Read_DoubleLine for some more info
 */
void WW8AttributeOutput::CharTwoLines( const SvxTwoLinesItem& rTwoLines )
{
    // #i28331# - check that bOn is set
    if ( !rTwoLines.GetValue() )
        return;

    m_rWW8Export.InsUInt16( NS_sprm::CFELayout::val );
    m_rWW8Export.pO->push_back( sal_uInt8(0x06) ); //len 6
    m_rWW8Export.pO->push_back( sal_uInt8(0x02) );

    sal_Unicode cStart = rTwoLines.GetStartBracket();
    sal_Unicode cEnd = rTwoLines.GetEndBracket();

    /*
    As per usual we have problems. We can have separate left and right brackets
    in OOo, it doesn't appear that you can in word. Also in word there appear
    to only be a limited number of possibilities, we can use pretty much
    anything.

    So if we have none, we export none, if either bracket is set to a known
    word type we export both as that type (with the bracket winning out in
    the case of a conflict simply being the order of test here.

    Upshot being a documented created in word will be reexported with no
    ill effects.
    */

    sal_uInt16 nType;
    if (!cStart && !cEnd)
        nType = 0;
    else if ((cStart == '{') || (cEnd == '}'))
        nType = 4;
    else if ((cStart == '<') || (cEnd == '>'))
        nType = 3;
    else if ((cStart == '[') || (cEnd == ']'))
        nType = 2;
    else
        nType = 1;
    m_rWW8Export.InsUInt16( nType );
    static const sal_uInt8 aZeroArr[ 3 ] = { 0, 0, 0 };
    m_rWW8Export.pO->insert( m_rWW8Export.pO->end(), aZeroArr, aZeroArr+3);
}

void AttributeOutputBase::ParaOutlineLevelBase( const SfxUInt16Item& rItem )
{
    sal_uInt16 nOutLvl = rItem.GetValue();

    // Do not write out default level (Body Text) if there is no inheritance, or if the level matches the inherited value
    const SfxUInt16Item* pInherited = nullptr;
    if (auto pNd = dynamic_cast<const SwContentNode*>(GetExport().m_pOutFormatNode)) //paragraph
        pInherited = static_cast<SwTextFormatColl&>(pNd->GetAnyFormatColl()).GetAttrSet().GetItem<SfxUInt16Item>(RES_PARATR_OUTLINELEVEL);
    else if (GetExport().m_bStyDef && GetExport().m_pCurrentStyle && GetExport().m_pCurrentStyle->DerivedFrom()) //style
        pInherited = GetExport().m_pCurrentStyle->DerivedFrom()->GetAttrSet().GetItem<SfxUInt16Item>(RES_PARATR_OUTLINELEVEL);
    if ((pInherited && pInherited->GetValue() == nOutLvl)
        || (!pInherited && !nOutLvl))
        return;

    ParaOutlineLevel(rItem);
}

void AttributeOutputBase::ParaNumRule( const SwNumRuleItem& rNumRule )
{
    const SwTextNode* pTextNd = nullptr;
    if (rNumRule.GetValue().isEmpty())
    {
        ParaNumRule_Impl(pTextNd, 0, 0);
        return;
    }
    const SwNumRule* pRule = GetExport().m_rDoc.FindNumRulePtr(
                                    rNumRule.GetValue() );
    if (!pRule)
        return;

    sal_uInt16 nNumId = GetExport().GetNumberingId(*pRule) + 1;
    sal_uInt8 nLvl = 0;

    if (!GetExport().m_pOutFormatNode)
    {
        ParaNumRule_Impl(pTextNd, nLvl, nNumId);
        return;
    }

    if ( dynamic_cast< const SwContentNode *>( GetExport().m_pOutFormatNode ) != nullptr  )
    {
        pTextNd = static_cast<const SwTextNode*>(GetExport().m_pOutFormatNode);

        if( pTextNd->IsCountedInList())
        {
            int nLevel = pTextNd->GetActualListLevel();

            if (nLevel < 0)
                nLevel = 0;

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

            nLvl = static_cast< sal_uInt8 >(nLevel);

            if (GetExport().GetExportFormat() == MSWordExportBase::DOCX) // FIXME
            {
                // tdf#95848 find the abstract list definition
                OUString const listId(pTextNd->GetListId());
                if (!listId.isEmpty()
                    && (listId != pRule->GetDefaultListId() // default list id uses the 1:1 mapping
                        || pTextNd->IsListRestart())    // or restarting previous list
                    )
                {
                    SwList const*const pList(
                        GetExport().m_rDoc.getIDocumentListsAccess().getListByName(listId));
                    if (pList)
                    {
                        SwNumRule const*const pAbstractRule(
                            GetExport().m_rDoc.FindNumRulePtr(
                                pList->GetDefaultListStyleName()));
                        assert(pAbstractRule);
                        if (pAbstractRule == pRule && !pTextNd->IsListRestart())
                        {
                            // different list, but no override
                            nNumId = GetExport().DuplicateAbsNum(listId, *pAbstractRule) + 1;
                        }
                        else
                        {
                            nNumId = GetExport().OverrideNumRule(
                                    *pRule, listId, *pAbstractRule) + 1;

                            if (pTextNd->IsListRestart())
                            {
                                // For restarted lists we should also keep value for
                                // future w:lvlOverride / w:startOverride
                                GetExport().AddListLevelOverride(nNumId-1, pTextNd->GetActualListLevel(),
                                    pTextNd->GetActualListStartValue());
                            }
                        }
                    }
                }
            }
            else if (pTextNd->IsListRestart())
            {
                sal_uInt16 nStartWith = static_cast<sal_uInt16>(pTextNd->GetActualListStartValue());
                nNumId = GetExport().DuplicateNumRule(pRule, nLvl, nStartWith);
                if (USHRT_MAX != nNumId)
                    ++nNumId;
            }
        }
        else
        {
            // #i44815# adjust numbering for numbered paragraphs
            // without number (NO_NUMLEVEL). These paragraphs
            // will receive a list id 0, which WW interprets as
            // 'no number'.
            nNumId = 0;
        }
    }
    else if ( auto pC = dynamic_cast< const SwTextFormatColl *>( GetExport().m_pOutFormatNode ) )
    {
        if ( pC && pC->IsAssignedToListLevelOfOutlineStyle() )
            nLvl = static_cast< sal_uInt8 >( pC->GetAssignedOutlineStyleLevel() );
    }

    if ( nLvl >= WW8ListManager::nMaxLevel )
        nLvl = WW8ListManager::nMaxLevel - 1;

    ParaNumRule_Impl( pTextNd, nLvl, nNumId);
}

void WW8AttributeOutput::ParaNumRule_Impl(const SwTextNode* /*pTextNd*/,
        sal_Int32 const nLvl, sal_Int32 const nNumId)
{
    if (USHRT_MAX == nNumId)
        return;

    // write sprmPIlvl and sprmPIlfo
    SwWW8Writer::InsUInt16( *m_rWW8Export.pO, NS_sprm::PIlvl::val );
    m_rWW8Export.pO->push_back( ::sal::static_int_cast<sal_uInt8>(nLvl) );
    SwWW8Writer::InsUInt16( *m_rWW8Export.pO, NS_sprm::PIlfo::val );
    SwWW8Writer::InsUInt16( *m_rWW8Export.pO, ::sal::static_int_cast<sal_uInt16>(nNumId) );
}

/* File FRMATR.HXX */

void WW8AttributeOutput::FormatFrameSize( const SwFormatFrameSize& rSize )
{
    if( m_rWW8Export.m_bOutFlyFrameAttrs )                   // Flys
    {
        if( m_rWW8Export.m_bOutGrf )
            return;                // Fly around graphic -> Auto-size

        //???? What about percentages ???
        if ( rSize.GetWidth() && rSize.GetWidthSizeType() == SwFrameSize::Fixed)
        {
            //"sprmPDxaWidth"
            m_rWW8Export.InsUInt16( NS_sprm::PDxaWidth::val );
            m_rWW8Export.InsUInt16( o3tl::narrowing<sal_uInt16>(rSize.GetWidth()) );
        }

        if ( rSize.GetHeight() )
        {
            // sprmPWHeightAbs
            m_rWW8Export.InsUInt16( NS_sprm::PWHeightAbs::val );

            sal_uInt16 nH = 0;
            switch ( rSize.GetHeightSizeType() )
            {
                case SwFrameSize::Variable: break;
                case SwFrameSize::Fixed: nH = o3tl::narrowing<sal_uInt16>(rSize.GetHeight()) & 0x7fff; break;
                default:           nH = o3tl::narrowing<sal_uInt16>(rSize.GetHeight()) | 0x8000; break;
            }
            m_rWW8Export.InsUInt16( nH );
        }
    }
    else if( m_rWW8Export.m_bOutPageDescs )            // PageDesc : width + height
    {
        if( m_rWW8Export.m_pCurrentPageDesc->GetLandscape() )
        {
            /*sprmSBOrientation*/
            m_rWW8Export.InsUInt16( NS_sprm::SBOrientation::val );
            m_rWW8Export.pO->push_back( 2 );
        }

        /*sprmSXaPage*/
        m_rWW8Export.InsUInt16( NS_sprm::SXaPage::val );
        m_rWW8Export.InsUInt16(
            msword_cast<sal_uInt16>(SvxPaperInfo::GetSloppyPaperDimension(rSize.GetWidth())));

        /*sprmSYaPage*/
        m_rWW8Export.InsUInt16( NS_sprm::SYaPage::val );
        m_rWW8Export.InsUInt16(
            msword_cast<sal_uInt16>(SvxPaperInfo::GetSloppyPaperDimension(rSize.GetHeight())));
    }
}

// FillOrder is still missing

/**
 * ReplaceCr() is used for Pagebreaks and Pagedescs. An already written CR
 * will be replaced by a break character. Replace must be called right after
 * the writing of CR.
 *
 * @return FilePos + 1 of the replaced CR or 0 if nothing was replaced.
 */
sal_uLong WW8Export::ReplaceCr( sal_uInt8 nChar )
{
    OSL_ENSURE( nChar, "replaced with 0 crashes WW97/95" );

    bool bReplaced = false;
    SvStream& rStrm = Strm();
    sal_uLong nRetPos = 0, nPos = rStrm.Tell();
    //If there is at least two characters already output
    if (nPos - 2 >= o3tl::make_unsigned(pFib->m_fcMin))
    {
        sal_uInt16 nUCode=0;

        rStrm.SeekRel(-2);
        rStrm.ReadUInt16( nUCode );
        //If the last char was a cr
        if (nUCode == 0x0d)             // CR ?
        {
            if ((nChar == 0x0c) &&
                (nPos - 4 >= o3tl::make_unsigned(pFib->m_fcMin)))
            {
                rStrm.SeekRel(-4);
                rStrm.ReadUInt16( nUCode );
            }
            else
            {
                rStrm.SeekRel(-2);
                nUCode = 0x0;
            }
            //And the para is not of len 0, then replace this cr with the mark
            //#120140# If there is a cr before a column break, need replace the cr. So remove the "nChar==0x0e" check.
            if( nUCode == 0x0d )
                bReplaced = false;
            else
            {
                bReplaced = true;
                WriteChar(nChar);
                nRetPos = nPos;
            }
        }
        else if ((nUCode == 0x0c) && (nChar == 0x0e))
        {
            // a column break after a section has no effect in writer
            bReplaced = true;
        }
        rStrm.Seek( nPos );
    }
    else
        bReplaced = true;

    if (!bReplaced)
    {
        // then write as normal char
        WriteChar(nChar);
        m_pPiece->SetParaBreak();
        m_pPapPlc->AppendFkpEntry(rStrm.Tell());
        m_pChpPlc->AppendFkpEntry(rStrm.Tell());
        nRetPos = rStrm.Tell();
    }
    return nRetPos;
}

void WW8AttributeOutput::TableRowEnd(sal_uInt32 nDepth)
{
    if ( nDepth == 1 )
        m_rWW8Export.WriteChar( 0x07 );
    else if ( nDepth > 1 )
        m_rWW8Export.WriteChar( 0x0d );

    //Technically in a word document this is a different value for a row ends
    //that are not row ends directly after a cell with a graphic. But it
    //doesn't seem to make a difference
    //pMagicTable->Append(Fc2Cp(Strm().Tell()),0x1B6);
}

void AttributeOutputBase::FormatPageDescription( const SwFormatPageDesc& rPageDesc )
{
    if ( GetExport().m_bStyDef )
        if (auto pC = dynamic_cast< const SwTextFormatColl *>( GetExport().m_pOutFormatNode ) )
        {
            if ( (SfxItemState::SET != pC->GetItemState( RES_BREAK, false ) ) && rPageDesc.KnowsPageDesc() )
                FormatBreak( SvxFormatBreakItem( SvxBreak::PageBefore, RES_BREAK ) );
        }
}

void WW8AttributeOutput::PageBreakBefore( bool bBreak )
{
    // sprmPPageBreakBefore/sprmPFPageBreakBefore
    m_rWW8Export.InsUInt16( NS_sprm::PFPageBreakBefore::val );

    m_rWW8Export.pO->push_back( bBreak ? 1 : 0 );
}

/**
 * breaks write nothing in the output field rWrt.pO,
 * but only in the text stream (requirement so they can
 * be called from Out_Break...)
 */
void AttributeOutputBase::FormatBreak( const SvxFormatBreakItem& rBreak )
{
    if ( GetExport().m_bStyDef )
    {
        switch ( rBreak.GetBreak() )
        {
            case SvxBreak::NONE:
            case SvxBreak::PageBefore:
            case SvxBreak::PageBoth:
                PageBreakBefore( rBreak.GetValue() != SvxBreak::NONE );
                break;
            default:
                break;
        }
    }
    else if ( !GetExport().m_pParentFrame )
    {
        sal_uInt8 nC = 0;
        bool bBefore = false;
        // #i76300# - Note: Can only be <true>, if <bBefore> equals <false>.
        bool bCheckForFollowPageDesc = false;

        switch ( rBreak.GetBreak() )
        {
            case SvxBreak::NONE:                                // disabled
                if ( !GetExport().m_bBreakBefore )
                    PageBreakBefore( false );
                return;

            case SvxBreak::ColumnBefore:                       // ColumnBreak
                bBefore = true;
                [[fallthrough]];
            case SvxBreak::ColumnAfter:
            case SvxBreak::ColumnBoth:
                if ( GetExport().m_rDoc.getIDocumentSettingAccess().get( DocumentSettingId::TREAT_SINGLE_COLUMN_BREAK_AS_PAGE_BREAK )
                     || GetExport().Sections().CurrentNumberOfColumns( GetExport().m_rDoc ) > 1 )
                {
                    nC = msword::ColumnBreak;
                }
                break;

            case SvxBreak::PageBefore:                         // PageBreak
                // From now on(fix for #i77900#) we prefer to save a page break
                // as paragraph attribute (if the exporter is OK with that),
                // this has to be done after the export of the paragraph ( =>
                // !GetExport().bBreakBefore )
                if (GetExport().PreferPageBreakBefore())
                {
                    if (!GetExport().m_bBreakBefore)
                        PageBreakBefore(true);
                }
                else
                {
                    bBefore = true;
                    nC = msword::PageBreak;
                }
                break;
            case SvxBreak::PageAfter:
            case SvxBreak::PageBoth:
                nC = msword::PageBreak;
                // #i76300# - check for follow page description,
                // if current writing attributes of a paragraph.
                if ( dynamic_cast< const SwTextNode* >( GetExport().m_pOutFormatNode ) &&
                     GetExport().GetCurItemSet() )
                {
                    bCheckForFollowPageDesc = true;
                }
                break;

            default:
                break;
        }

        if ( ( bBefore == GetExport().m_bBreakBefore ) && nC )
        {
            // #i76300#
            bool bFollowPageDescWritten = false;
            if ( bCheckForFollowPageDesc )
            {
                bFollowPageDescWritten =
                    GetExport().OutputFollowPageDesc( GetExport().GetCurItemSet(),
                            dynamic_cast<const SwTextNode*>( GetExport().m_pOutFormatNode ) );
            }
            if ( !bFollowPageDescWritten )
            {
                SectionBreak(nC, !bBefore);
            }
        }
    }
}

void WW8AttributeOutput::SectionBreak( sal_uInt8 nC, bool /*bBreakAfter*/, const WW8_SepInfo* /*pSectionInfo*/, bool /*bExtraPageBreak*/ )
{
    m_rWW8Export.ReplaceCr( nC );
}

sal_uInt32 AttributeOutputBase::GridCharacterPitch( const SwTextGridItem& rGrid ) const
{
    MSWordStyles * pStyles = GetExport().m_pStyles.get();
    const SwFormat * pSwFormat = pStyles->GetSwFormat(0);

    sal_uInt32 nPageCharSize = 0;

    if (pSwFormat != nullptr)
    {
        nPageCharSize = ItemGet<SvxFontHeightItem>
            (*pSwFormat, RES_CHRATR_FONTSIZE).GetHeight();
    }
    sal_uInt16 nPitch = rGrid.IsSquaredMode() ? rGrid.GetBaseHeight() :
        rGrid.GetBaseWidth( );

    sal_Int32 nCharWidth = nPitch - nPageCharSize;
    sal_Int32 nFraction = nCharWidth % 20;
    if ( nCharWidth < 0 )
        nFraction = 20 + nFraction;
    nFraction = ( nFraction * 0xFFF ) / 20;
    nFraction = ( nFraction & 0x00000FFF );

    sal_Int32 nMain = nCharWidth / 20;
    if ( nCharWidth < 0 )
        nMain -= 1;
    nMain = nMain * 0x1000;
    nMain = ( nMain & 0xFFFFF000 );

    return sal_uInt32( nFraction + nMain );
}

void WW8AttributeOutput::FormatTextGrid( const SwTextGridItem& rGrid )
{
    if (!m_rWW8Export.m_bOutPageDescs)
        return;

    sal_uInt16 nGridType = 0;
    switch ( rGrid.GetGridType() )
    {
        default:
            OSL_FAIL("Unknown grid type");
            [[fallthrough]];
        case GRID_NONE:
            nGridType = 0;
            break;
        case GRID_LINES_ONLY:
            nGridType = 2;
            break;
        case GRID_LINES_CHARS:
            if ( rGrid.IsSnapToChars() )
                nGridType = 3;
            else
                nGridType = 1;
            break;
    }
    m_rWW8Export.InsUInt16( NS_sprm::SClm::val );
    m_rWW8Export.InsUInt16( nGridType );

    sal_uInt16 nHeight = rGrid.GetBaseHeight() + rGrid.GetRubyHeight();
    m_rWW8Export.InsUInt16( NS_sprm::SDyaLinePitch::val );
    m_rWW8Export.InsUInt16( nHeight );

    m_rWW8Export.InsUInt16( NS_sprm::SDxtCharSpace::val );
    m_rWW8Export.InsUInt32( GridCharacterPitch( rGrid ) );
}

void WW8AttributeOutput::FormatPaperBin( const SvxPaperBinItem& rPaperBin )
{
    if ( !m_rWW8Export.m_bOutPageDescs )
        return;

    sal_uInt16 nVal;
    switch ( rPaperBin.GetValue() )
    {
        case 0: nVal = 15;  break;      // Automatically select
        case 1: nVal = 1;   break;      // Upper paper tray
        case 2: nVal = 4;   break;      // Manual paper feed
        default: nVal = 0;  break;
    }

    if ( nVal )
    {
        m_rWW8Export.InsUInt16( m_rWW8Export.m_bOutFirstPage
                ? NS_sprm::SDmBinFirst::val : NS_sprm::SDmBinOther::val );

        m_rWW8Export.InsUInt16( nVal );
    }
}

void WW8AttributeOutput::FormatLRSpace( const SvxLRSpaceItem& rLR )
{
    // Flys are still missing ( see RTF )

    if ( m_rWW8Export.m_bOutFlyFrameAttrs )                   // Flys
    {
        // sprmPDxaFromText10
        m_rWW8Export.InsUInt16( NS_sprm::LN_PDxaFromText10 );
        // use average, since WW only knows one value
        m_rWW8Export.InsUInt16( o3tl::narrowing<sal_uInt16>( ( rLR.GetLeft() + rLR.GetRight() ) / 2 ) );
    }
    else if ( m_rWW8Export.m_bOutPageDescs )                // PageDescs
    {
        m_pageMargins.nLeft = 0;
        m_pageMargins.nRight = 0;

        if ( auto pBoxItem = static_cast<const SvxBoxItem*>(m_rWW8Export.HasItem( RES_BOX )) )
        {
            m_pageMargins.nLeft = pBoxItem->CalcLineSpace( SvxBoxItemLine::LEFT, /*bEvenIfNoLine*/true );
            m_pageMargins.nRight = pBoxItem->CalcLineSpace( SvxBoxItemLine::RIGHT, /*bEvenIfNoLine*/true );
        }

        m_pageMargins.nLeft += sal::static_int_cast<sal_uInt16>(rLR.GetLeft());
        m_pageMargins.nRight += sal::static_int_cast<sal_uInt16>(rLR.GetRight());
        sal_uInt16 nGutter = rLR.GetGutterMargin();

        // sprmSDxaLeft
        m_rWW8Export.InsUInt16( NS_sprm::SDxaLeft::val );
        m_rWW8Export.InsUInt16( m_pageMargins.nLeft );

        // sprmSDxaRight
        m_rWW8Export.InsUInt16( NS_sprm::SDxaRight::val );
        m_rWW8Export.InsUInt16( m_pageMargins.nRight );

        if (nGutter)
        {
            // sprmSDzaGutter
            m_rWW8Export.InsUInt16(NS_sprm::SDzaGutter::val);
            m_rWW8Export.InsUInt16(nGutter);
        }
    }
    else
    {                                          // normal paragraphs
        // sprmPDxaLeft
        m_rWW8Export.InsUInt16( 0x845E );        //asian version ?
        m_rWW8Export.InsUInt16( o3tl::narrowing<sal_uInt16>(rLR.GetTextLeft()) );

        // sprmPDxaRight
        m_rWW8Export.InsUInt16( 0x845D );        //asian version ?
        m_rWW8Export.InsUInt16( o3tl::narrowing<sal_uInt16>(rLR.GetRight()) );

        // sprmPDxaLeft1
        m_rWW8Export.InsUInt16( 0x8460 );        //asian version ?
        m_rWW8Export.InsUInt16( rLR.GetTextFirstLineOffset() );
    }
}

void WW8AttributeOutput::SectionRtlGutter(const SfxBoolItem& rRtlGutter)
{
    if (!rRtlGutter.GetValue())
    {
        return;
    }

    // sprmSFRTLGutter
    m_rWW8Export.InsUInt16(NS_sprm::SFRTLGutter::val);
    m_rWW8Export.pO->push_back(1);
}

void WW8AttributeOutput::FormatULSpace( const SvxULSpaceItem& rUL )
{
    // Flys are still missing ( see RTF )

    if ( m_rWW8Export.m_bOutFlyFrameAttrs )                   // Flys
    {
        // sprmPDyaFromText
        m_rWW8Export.InsUInt16( NS_sprm::PDyaFromText::val );
        // use average, since WW only knows one value
        m_rWW8Export.InsUInt16( o3tl::narrowing<sal_uInt16>( ( rUL.GetUpper() + rUL.GetLower() ) / 2 ) );
    }
    else if ( m_rWW8Export.m_bOutPageDescs )            // Page-UL
    {
        OSL_ENSURE( m_rWW8Export.GetCurItemSet(), "Impossible" );
        if ( !m_rWW8Export.GetCurItemSet() )
            return;

        HdFtDistanceGlue aDistances( *m_rWW8Export.GetCurItemSet() );

        if ( aDistances.HasHeader() )
        {
            //sprmSDyaHdrTop
            m_rWW8Export.InsUInt16( NS_sprm::SDyaHdrTop::val );
            m_rWW8Export.InsUInt16( aDistances.dyaHdrTop );
        }

        // sprmSDyaTop
        m_rWW8Export.InsUInt16( NS_sprm::SDyaTop::val );
        m_rWW8Export.InsUInt16( aDistances.dyaTop );
        m_pageMargins.nTop = aDistances.dyaTop;

        if ( aDistances.HasFooter() )
        {
            //sprmSDyaHdrBottom
            m_rWW8Export.InsUInt16( NS_sprm::SDyaHdrBottom::val );
            m_rWW8Export.InsUInt16( aDistances.dyaHdrBottom );
        }

        //sprmSDyaBottom
        m_rWW8Export.InsUInt16( NS_sprm::SDyaBottom::val );
        m_rWW8Export.InsUInt16( aDistances.dyaBottom );
        m_pageMargins.nBottom = aDistances.dyaBottom;
    }
    else
    {
        // sprmPDyaBefore
        m_rWW8Export.InsUInt16( NS_sprm::PDyaBefore::val );
        m_rWW8Export.InsUInt16( rUL.GetUpper() );
        // sprmPDyaAfter
        m_rWW8Export.InsUInt16( NS_sprm::PDyaAfter::val );
        m_rWW8Export.InsUInt16( rUL.GetLower() );
        // sprmPFContextualSpacing

        // Write out Contextual Spacing = false if it would have inherited a true.
        const SvxULSpaceItem* pInherited = nullptr;
        if (!rUL.GetContext())
        {
            if (auto pNd = dynamic_cast<const SwContentNode*>(m_rWW8Export.m_pOutFormatNode)) //paragraph
                pInherited = &static_cast<SwTextFormatColl&>(pNd->GetAnyFormatColl()).GetAttrSet().GetULSpace();
            else if (m_rWW8Export.m_bStyDef && m_rWW8Export.m_pCurrentStyle && m_rWW8Export.m_pCurrentStyle->DerivedFrom()) //style
                pInherited = &m_rWW8Export.m_pCurrentStyle->DerivedFrom()->GetULSpace();
        }
        if (rUL.GetContext() || (pInherited && pInherited->GetContext()))
        {
            m_rWW8Export.InsUInt16(NS_sprm::PFContextualSpacing::val);
            m_rWW8Export.pO->push_back( static_cast<sal_uInt8>(rUL.GetContext()) );
        }
    }
}

// print, opaque, protect are still missing

void WW8AttributeOutput::FormatSurround( const SwFormatSurround& rSurround )
{
    if ( m_rWW8Export.m_bOutFlyFrameAttrs )
    {
        m_rWW8Export.InsUInt16( NS_sprm::PWr::val );

        m_rWW8Export.pO->push_back(
                ( css::text::WrapTextMode_NONE != rSurround.GetSurround() ) ? 2 : 1 );
    }
}

void WW8AttributeOutput::FormatVertOrientation( const SwFormatVertOrient& rFlyVert )
{

    //!!!! anchor type and corresponding borders are still missing
    if ( !m_rWW8Export.m_bOutFlyFrameAttrs )
        return;

    short nPos;
    switch( rFlyVert.GetVertOrient() )
    {
        case text::VertOrientation::NONE:
            nPos = static_cast<short>(rFlyVert.GetPos());
            break;
        case text::VertOrientation::CENTER:
        case text::VertOrientation::LINE_CENTER:
            nPos = -8;
            break;
        case text::VertOrientation::BOTTOM:
        case text::VertOrientation::LINE_BOTTOM:
            nPos = -12;
            break;
        case text::VertOrientation::TOP:
        case text::VertOrientation::LINE_TOP:
        default:
            nPos = -4;
            break;
    }

    // sprmPDyaAbs
    m_rWW8Export.InsUInt16( NS_sprm::PDyaAbs::val );
    m_rWW8Export.InsUInt16( nPos );
}

void WW8AttributeOutput::FormatHorizOrientation( const SwFormatHoriOrient& rFlyHori )
{
    if ( !m_rWW8Export.m_pParentFrame )
    {
        OSL_ENSURE( m_rWW8Export.m_pParentFrame, "HoriOrient without mpParentFrame !!" );
        return;
    }

    //!!!! anchor type and corresponding borders are still missing
    if ( !m_rWW8Export.m_bOutFlyFrameAttrs )
        return;

    short nPos;
    switch( rFlyHori.GetHoriOrient() )
    {
        case text::HoriOrientation::NONE:
            nPos = static_cast<short>(rFlyHori.GetPos());
            if( !nPos )
                nPos = 1;   // WW: 0 is reserved
            break;
        case text::HoriOrientation::LEFT:
            nPos = rFlyHori.IsPosToggle() ? -12 : 0;
            break;
        case text::HoriOrientation::RIGHT:
            nPos = rFlyHori.IsPosToggle() ? -16 : -8;
            break;
        case text::HoriOrientation::CENTER:
        case text::HoriOrientation::FULL: // FULL only for tables
        default:
            nPos = -4;
            break;
    }

    // sprmPDxaAbs
    m_rWW8Export.InsUInt16( NS_sprm::PDxaAbs::val );
    m_rWW8Export.InsUInt16( nPos );
}

void WW8AttributeOutput::FormatAnchor( const SwFormatAnchor& rAnchor )
{
    OSL_ENSURE( m_rWW8Export.m_pParentFrame, "Anchor without mpParentFrame !!" );

    if ( !m_rWW8Export.m_bOutFlyFrameAttrs )
        return;

    sal_uInt8 nP = 0;
    switch ( rAnchor.GetAnchorId() )
    {
        case RndStdIds::FLY_AT_PAGE:
            // vertical: page | horizontal: page
            nP |= (1 << 4) | (2 << 6);
            break;
        // in case of Fly as characters: set paragraph-bound!!!
        case RndStdIds::FLY_AT_FLY:
        case RndStdIds::FLY_AT_CHAR:
        case RndStdIds::FLY_AT_PARA:
        case RndStdIds::FLY_AS_CHAR:
            // vertical: page | horizontal: page
            nP |= (2 << 4) | (0 << 6);
            break;
        default:
            break;
    }

    // sprmPPc
    m_rWW8Export.InsUInt16( NS_sprm::PPc::val );
    m_rWW8Export.pO->push_back( nP );
}

void WW8AttributeOutput::FormatBackground( const SvxBrushItem& rBrush )
{
    // WW cannot have background in a section
    if ( m_rWW8Export.m_bOutPageDescs )
        return;

    WW8_SHD aSHD;
    WW8Export::TransBrush( rBrush.GetColor(), aSHD );

    m_rWW8Export.InsUInt16( NS_sprm::PShd80::val );
    m_rWW8Export.InsUInt16( aSHD.GetValue() );

    m_rWW8Export.InsUInt16( NS_sprm::PShd::val );
    m_rWW8Export.pO->push_back( 10 ); //size of operand: MUST be 10
    m_rWW8Export.InsUInt32( 0xFF000000 ); //cvFore: Foreground BGR = cvAuto
    m_rWW8Export.InsUInt32( SuitableBGColor( rBrush.GetColor() ) ); //cvBack
    m_rWW8Export.InsUInt16( 0x0000 ); //iPat: specifies the pattern used for shading = clear/100% background
}

void WW8AttributeOutput::FormatFillStyle( const XFillStyleItem& rFillStyle )
{
    // WW cannot have background in a section
    if ( m_rWW8Export.m_bOutPageDescs )
        return;

    // see MSWordExportBase::OutputItemSet for how _SOLID is handled
    if ( rFillStyle.GetValue() != drawing::FillStyle_NONE )
        return;

    //Shd80Nil
    m_rWW8Export.InsUInt16( NS_sprm::PShd80::val );
    m_rWW8Export.InsUInt16( 0xffff );

    //cvAuto
    m_rWW8Export.InsUInt16( NS_sprm::PShd::val );
    m_rWW8Export.pO->push_back( 10 );
    m_rWW8Export.InsUInt32( 0xFF000000 );
    m_rWW8Export.InsUInt32( 0xFF000000 );
    m_rWW8Export.InsUInt16( 0x0000 );
}

void WW8AttributeOutput::FormatFillGradient( const XFillGradientItem& /*rFillGradient*/ )
{
}

WW8_BRCVer9 WW8Export::TranslateBorderLine(const SvxBorderLine& rLine,
    sal_uInt16 nDist, bool bShadow)
{
    sal_uInt32 nColBGR = 0;
    sal_uInt16 nWidth = ::editeng::ConvertBorderWidthToWord(
            rLine.GetBorderLineStyle(), rLine.GetWidth());
    sal_uInt8 brcType = 0;

    if( nWidth ) // line ?
    {
        // BRC.brcType
        brcType = 0;
        // All the border types values are available on
        // http://msdn.microsoft.com/en-us/library/dd908142%28v=office.12%29.aspx
        switch (rLine.GetBorderLineStyle())
        {
            case SvxBorderLineStyle::SOLID:
                {
                    if ( rLine.GetWidth( ) == DEF_LINE_WIDTH_0 )
                        brcType = 5;
                    else
                        brcType = 1;
                }
                break;
            case SvxBorderLineStyle::DOTTED:
                brcType = 6;
                break;
            case SvxBorderLineStyle::DASHED:
                brcType = 7;
                break;
            case SvxBorderLineStyle::DOUBLE:
            case SvxBorderLineStyle::DOUBLE_THIN:
                brcType = 3;
                break;
            case SvxBorderLineStyle::THINTHICK_SMALLGAP:
                brcType = 11;
                break;
            case SvxBorderLineStyle::THINTHICK_MEDIUMGAP:
                brcType = 14;
                break;
            case SvxBorderLineStyle::THINTHICK_LARGEGAP:
                brcType = 17;
                break;
            case SvxBorderLineStyle::THICKTHIN_SMALLGAP:
                brcType = 12;
                break;
            case SvxBorderLineStyle::THICKTHIN_MEDIUMGAP:
                brcType = 15;
                break;
            case SvxBorderLineStyle::THICKTHIN_LARGEGAP:
                brcType = 18;
                break;
            case SvxBorderLineStyle::EMBOSSED:
                brcType = 24;
                break;
            case SvxBorderLineStyle::ENGRAVED:
                brcType = 25;
                break;
            case SvxBorderLineStyle::OUTSET:
                brcType = 26;
                break;
            case SvxBorderLineStyle::INSET:
                brcType = 27;
                break;
            case SvxBorderLineStyle::FINE_DASHED:
                brcType = 22;
                break;
            case SvxBorderLineStyle::DASH_DOT:
                brcType = 8;
                break;
            case SvxBorderLineStyle::DASH_DOT_DOT:
                brcType = 9;
                break;
            default:
                break;
        }

        // convert width from twips (1/20 pt) to eighths of a point
        nWidth = (( nWidth * 8 ) + 10 ) / 20;
        if( 0xff < nWidth )
            nWidth = 0xff;

        if( 0 == nWidth )                       // really thin line
            nWidth = 1;                         // don't omit

        // BRC.cv
        nColBGR = wwUtility::RGBToBGR(rLine.GetColor().GetRGBColor());
    }

    // BRC.dptSpace
    sal_uInt16 nLDist = rtl::math::round(nDist / 20.0); // unit of measurement: pt
    if( nLDist > 0x1f )
        nLDist = 0x1f;

    return WW8_BRCVer9(nColBGR, sal_uInt8(nWidth), brcType, sal_uInt8(nLDist),
        bShadow, false);
}

/**
 * Gets passed a WW8Bytes*, so the function also can be used for the table border.
 *
 * @param nSprmNo  If nSprmNo == 0, then the opcode isn't outputted.
 * @param bShadow  SHOULDN'T be set for table cells !
 */
void WW8Export::Out_BorderLine(ww::bytes& rO, const SvxBorderLine* pLine,
    sal_uInt16 nDist, sal_uInt16 nSprmNo, sal_uInt16 nSprmNoVer9, bool bShadow)
{
    OSL_ENSURE( ( nSprmNo == 0 ) ||
            ( nSprmNo >= 38 && nSprmNo <= 41 ) ||
            ( nSprmNo >= NS_sprm::PBrcTop80::val
              && nSprmNo <= NS_sprm::PBrcRight80::val ) ||
            ( nSprmNo >= NS_sprm::SBrcTop80::val
              && nSprmNo <= NS_sprm::SBrcRight80::val ),
            "Sprm for border out is of range" );

    WW8_BRCVer9 aBrcVer9;
    WW8_BRC aBrcVer8;

    if( pLine && pLine->GetBorderLineStyle() != SvxBorderLineStyle::NONE )
    {
        aBrcVer9 = TranslateBorderLine( *pLine, nDist, bShadow );
        sal_uInt8 ico = msfilter::util::TransColToIco( msfilter::util::BGRToRGB(aBrcVer9.cv()) );
        aBrcVer8 = WW8_BRC( aBrcVer9.dptLineWidth(), aBrcVer9.brcType(), ico,
            aBrcVer9.dptSpace(), aBrcVer9.fShadow(), aBrcVer9.fFrame() );
    }

    // WW97-SprmIds
    if ( nSprmNo != 0 )
        SwWW8Writer::InsUInt16( rO, nSprmNo );

    rO.insert( rO.end(), aBrcVer8.aBits1, aBrcVer8.aBits2+2 );

    if ( nSprmNoVer9 != 0 )
    {
        SwWW8Writer::InsUInt16( rO, nSprmNoVer9 );
        rO.push_back(sizeof(WW8_BRCVer9));
        rO.insert( rO.end(), aBrcVer9.aBits1, aBrcVer9.aBits2+4);
    }
}

/**
 * is for all boxes except in tables. pO of the WW8Writer is used
 *
 * @param rBox
 * @param bShadow
 */
void WW8Export::Out_SwFormatBox(const SvxBoxItem& rBox, bool bShadow)
{
    static const SvxBoxItemLine aBorders[] =
    {
        SvxBoxItemLine::TOP, SvxBoxItemLine::LEFT, SvxBoxItemLine::BOTTOM, SvxBoxItemLine::RIGHT
    };
    static const sal_uInt16 aPBrc[] =
    {
        // WW8 SPRMs
        NS_sprm::PBrcTop80::val, NS_sprm::PBrcLeft80::val,
        NS_sprm::PBrcBottom80::val, NS_sprm::PBrcRight80::val,
        // WW9 SPRMs
        NS_sprm::PBrcTop::val, NS_sprm::PBrcLeft::val,
        NS_sprm::PBrcBottom::val, NS_sprm::PBrcRight::val
    };
    static const sal_uInt16 aSBrc[] =
    {
        // WW8 SPRMs
        NS_sprm::SBrcTop80::val, NS_sprm::SBrcLeft80::val,
        NS_sprm::SBrcBottom80::val, NS_sprm::SBrcRight80::val,
        // WW9 SPRMs
        NS_sprm::SBrcTop::val, NS_sprm::SBrcLeft::val,
        NS_sprm::SBrcBottom::val, NS_sprm::SBrcRight::val
    };

    const SvxBoxItemLine* pBrd = aBorders;
    for( sal_uInt16 i = 0; i < 4; ++i, ++pBrd )
    {
        const SvxBorderLine* pLn = rBox.GetLine( *pBrd );

        sal_uInt16 nSprmNo, nSprmNoVer9 = 0;
        if (m_bOutPageDescs)
        {
            nSprmNo = aSBrc[i];
            nSprmNoVer9 = aSBrc[i+4];
        }
        else
        {
            nSprmNo = aPBrc[i];
            nSprmNoVer9 = aPBrc[i+4];
        }

        Out_BorderLine( *pO, pLn, rBox.GetDistance( *pBrd ), nSprmNo,
            nSprmNoVer9, bShadow );
    }
}

/**
 * FormatBox2() is for TC structures in tables. The Sprm opcode isn't written
 * because it is packed into the TC structure without opcode.
 * dxpSpace always becomes 0, because WW requires that in tables
 * ( table borders otherwise will fray )
 *
 * @param rO A WW8Bytes pointer is passed in as output parameter
 */
void WW8Export::Out_SwFormatTableBox( ww::bytes& rO, const SvxBoxItem * pBox )
{
    // possible and maybe better would be 0xffff
    static const SvxBoxItemLine aBorders[] =
    {
        SvxBoxItemLine::TOP, SvxBoxItemLine::LEFT, SvxBoxItemLine::BOTTOM, SvxBoxItemLine::RIGHT
    };
    static const SvxBorderLine aBorderLine;

    for(const SvxBoxItemLine & rBorder : aBorders)
    {
        const SvxBorderLine* pLn;
        if (pBox != nullptr)
            pLn = pBox->GetLine( rBorder );
        else
            pLn = & aBorderLine;

        Out_BorderLine(rO, pLn, 0, 0, 0, false);
    }
}

void WW8Export::Out_CellRangeBorders( const SvxBoxItem * pBox, sal_uInt8 nStart,
       sal_uInt8 nLimit )
{
    if ( !pBox )
        return;

    static const SvxBoxItemLine aBorders[] =
    {
        SvxBoxItemLine::TOP, SvxBoxItemLine::LEFT, SvxBoxItemLine::BOTTOM, SvxBoxItemLine::RIGHT
    };

    for( int i = 0; i < 4; ++i )
    {
        const SvxBorderLine* pLn = pBox->GetLine( aBorders[i] );
        if (!pLn)
            continue;

        InsUInt16( NS_sprm::TSetBrc::val );
        pO->push_back( 11 );
        pO->push_back( nStart );
        pO->push_back( nLimit );
        pO->push_back( 1<<i );
        WW8_BRCVer9 aBrcVer9 = TranslateBorderLine( *pLn, 0, false );
        pO->insert( pO->end(), aBrcVer9.aBits1, aBrcVer9.aBits2+4 );
    }
}

void WW8AttributeOutput::FormatBox( const SvxBoxItem& rBox )
{
    // Fly around graphic -> here no border, because the
    // graphics header already has the border
    if ( m_rWW8Export.m_bOutGrf )
        return;

    bool bShadow = false;
    const SfxPoolItem* pItem = m_rWW8Export.HasItem( RES_SHADOW );
    if ( pItem )
    {
        const SvxShadowItem& rShadow = pItem->StaticWhichCast(RES_SHADOW);
        bShadow = ( rShadow.GetLocation() != SvxShadowLocation::NONE )
                  && ( rShadow.GetWidth() != 0 );
    }

    SvxBoxItem aBox(rBox);
    if (m_rWW8Export.m_bOutPageDescs)
    {
        editeng::WordBorderDistances aDistances;
        editeng::BorderDistancesToWord(aBox, m_pageMargins, aDistances);

        aBox.SetDistance(aDistances.nTop, SvxBoxItemLine::TOP);
        aBox.SetDistance(aDistances.nLeft, SvxBoxItemLine::LEFT);
        aBox.SetDistance(aDistances.nBottom, SvxBoxItemLine::BOTTOM);
        aBox.SetDistance(aDistances.nRight, SvxBoxItemLine::RIGHT);

        m_bFromEdge = aDistances.bFromEdge;
    }

    m_rWW8Export.Out_SwFormatBox( aBox, bShadow );
}

SwTwips WW8Export::CurrentPageWidth(SwTwips &rLeft, SwTwips &rRight) const
{
    const SwFrameFormat* pFormat = m_pCurrentPageDesc ? &m_pCurrentPageDesc->GetMaster()
        : &m_rDoc.GetPageDesc(0).GetMaster();

    const SvxLRSpaceItem& rLR = pFormat->GetLRSpace();
    SwTwips nPageSize = pFormat->GetFrameSize().GetWidth();
    rLeft = rLR.GetLeft();
    rRight = rLR.GetRight();
    return nPageSize;
}

void WW8AttributeOutput::FormatColumns_Impl( sal_uInt16 nCols, const SwFormatCol & rCol, bool bEven, SwTwips nPageSize )
{
    // CColumns
    m_rWW8Export.InsUInt16( NS_sprm::SCcolumns::val );
    m_rWW8Export.InsUInt16( nCols - 1 );

    // DxaColumns
    m_rWW8Export.InsUInt16( NS_sprm::SDxaColumns::val );
    m_rWW8Export.InsUInt16( rCol.GetGutterWidth( true ) );

    // LBetween
    m_rWW8Export.InsUInt16( NS_sprm::SLBetween::val );
    m_rWW8Export.pO->push_back( COLADJ_NONE == rCol.GetLineAdj(  )? 0 : 1 );

    const SwColumns & rColumns = rCol.GetColumns(  );

    // FEvenlySpaced
    m_rWW8Export.InsUInt16( NS_sprm::SFEvenlySpaced::val );
    m_rWW8Export.pO->push_back( bEven ? 1 : 0 );

    if ( bEven )
        return;

    for ( sal_uInt16 n = 0; n < nCols; ++n )
    {
        //sprmSDxaColWidth
        m_rWW8Export.InsUInt16( NS_sprm::SDxaColWidth::val );
        m_rWW8Export.pO->push_back( static_cast<sal_uInt8>(n) );
        m_rWW8Export.InsUInt16( rCol.
                                CalcPrtColWidth( n,
                                                 o3tl::narrowing<sal_uInt16>(nPageSize) ) );

        if ( n + 1 != nCols )
        {
            //sprmSDxaColSpacing
            m_rWW8Export.InsUInt16( NS_sprm::SDxaColSpacing::val );
            m_rWW8Export.pO->push_back( static_cast<sal_uInt8>(n) );
            m_rWW8Export.InsUInt16( rColumns[n].GetRight(  ) +
                                    rColumns[n + 1].GetLeft(  ) );
        }
    }
}

void AttributeOutputBase::FormatColumns( const SwFormatCol& rCol )
{
    const SwColumns& rColumns = rCol.GetColumns();

    sal_uInt16 nCols = rColumns.size();
    if (1 >= nCols || GetExport( ).m_bOutFlyFrameAttrs)
        return;

    // get the page width without borders !!

    const SwFrameFormat* pFormat = GetExport( ).m_pCurrentPageDesc ? &GetExport( ).m_pCurrentPageDesc->GetMaster() : &const_cast<const SwDoc&>(GetExport().m_rDoc).GetPageDesc(0).GetMaster();
    const SvxFrameDirectionItem &frameDirection = pFormat->GetFrameDir();
    SwTwips nPageSize;
    if ( frameDirection.GetValue() == SvxFrameDirection::Vertical_RL_TB || frameDirection.GetValue() == SvxFrameDirection::Vertical_LR_TB )
    {
        const SvxULSpaceItem &rUL = pFormat->GetULSpace();
        nPageSize = pFormat->GetFrameSize().GetHeight();
        nPageSize -= rUL.GetUpper() + rUL.GetLower();

        const SwFormatHeader *header = pFormat->GetAttrSet().GetItem(RES_HEADER);
        if ( header )
        {
            const SwFrameFormat *headerFormat = header->GetHeaderFormat();
            if (headerFormat)
            {
                nPageSize -= headerFormat->GetFrameSize().GetHeight();
            }
        }
        const SwFormatFooter *footer = pFormat->GetAttrSet().GetItem(RES_FOOTER);
        if ( footer )
        {
            const SwFrameFormat *footerFormat = footer->GetFooterFormat();
            if ( footerFormat )
            {
                nPageSize -= footerFormat->GetFrameSize().GetHeight();
            }
        }
    }
    else
    {
        const SvxLRSpaceItem &rLR = pFormat->GetLRSpace();
        nPageSize = pFormat->GetFrameSize().GetWidth();
        nPageSize -= rLR.GetLeft() + rLR.GetRight();
        //i120133: The Section width should consider page indent value.
        nPageSize -= rCol.GetAdjustValue();

    }

    // look if all columns are equal
    bool bEven = rCol.IsOrtho();
    if (!bEven)
    {
        bEven = true;
        sal_uInt16 n;
        sal_uInt16 nColWidth = rCol.CalcPrtColWidth( 0, o3tl::narrowing<sal_uInt16>(nPageSize) );
        for ( n = 1; n < nCols; n++ )
        {
            short nDiff = nColWidth -
                rCol.CalcPrtColWidth( n, o3tl::narrowing<sal_uInt16>(nPageSize) );

            if ( nDiff > 10 || nDiff < -10 )      // Tolerance: 10 tw
            {
                bEven = false;
                break;
            }
        }
    }

    FormatColumns_Impl( nCols, rCol, bEven, nPageSize );
}

// "Paragraphs together"
void WW8AttributeOutput::FormatKeep( const SvxFormatKeepItem& rKeep )
{
    // sprmFKeepFollow
    m_rWW8Export.InsUInt16( NS_sprm::PFKeepFollow::val );

    m_rWW8Export.pO->push_back( rKeep.GetValue() ? 1 : 0 );
}

// exclude a paragraph from Line Numbering
void WW8AttributeOutput::FormatLineNumbering( const SwFormatLineNumber& rNumbering )
{
    // sprmPFNoLineNumb
    m_rWW8Export.InsUInt16( NS_sprm::PFNoLineNumb::val );

    m_rWW8Export.pO->push_back( rNumbering.IsCount() ? 0 : 1 );
}

/* File PARATR.HXX  */

void WW8AttributeOutput::ParaLineSpacing_Impl( short nSpace, short nMulti )
{
    // sprmPDyaLine
    m_rWW8Export.InsUInt16( NS_sprm::PDyaLine::val );

    m_rWW8Export.InsUInt16( nSpace );
    m_rWW8Export.InsUInt16( nMulti );
}

void AttributeOutputBase::ParaLineSpacing( const SvxLineSpacingItem& rSpacing )
{
    short nSpace = 240, nMulti = 0;

    switch ( rSpacing.GetLineSpaceRule() )
    {
        default:
            break;
        case SvxLineSpaceRule::Fix: // Fix
            nSpace = -static_cast<short>(rSpacing.GetLineHeight());
            break;
        case SvxLineSpaceRule::Min: // At least
            nSpace = static_cast<short>(rSpacing.GetLineHeight());
            break;
        case SvxLineSpaceRule::Auto:
        {
            if( rSpacing.GetInterLineSpaceRule() == SvxInterLineSpaceRule::Fix ) // Leading
            {
                // doesn't exist in WW - how do you get the MaxLineHeight?
                nSpace = rSpacing.GetInterLineSpace();
                sal_uInt16 nScript =
                    i18n::ScriptType::LATIN;
                const SwAttrSet *pSet = nullptr;
                if ( auto pFormat = dynamic_cast< const SwFormat *>( GetExport().m_pOutFormatNode ) )
                {
                    pSet = &pFormat->GetAttrSet();
                }
                else if ( auto pNd = dynamic_cast< const SwTextNode *>( GetExport().m_pOutFormatNode )  )
                {
                    pSet = &pNd->GetSwAttrSet();
                    nScript = g_pBreakIt->GetBreakIter()->getScriptType(pNd->GetText(), 0);
                }
                OSL_ENSURE( pSet, "No attrset for lineheight :-(" );
                if ( pSet )
                {
                    nSpace = nSpace + static_cast<short>( AttrSetToLineHeight( GetExport().m_rDoc.getIDocumentSettingAccess(),
                        *pSet, *Application::GetDefaultDevice(), nScript ) );
                }
            }
            else // Proportional
            {
                if ( rSpacing.GetInterLineSpaceRule() != SvxInterLineSpaceRule::Off )
                    nSpace = static_cast<short>( ( 240L * rSpacing.GetPropLineSpace() ) / 100L );
                nMulti = 1;
            }
        }
        break;
    }
    // if nSpace is negative, it is a fixed size in 1/20 of a point
    // if nSpace is positive and nMulti is 1, it is 1/240 of a single line height
    // otherwise, it is a minimum size in 1/20 of a point
    ParaLineSpacing_Impl( nSpace, nMulti );
}

void WW8AttributeOutput::ParaAdjust( const SvxAdjustItem& rAdjust )
{
    // sprmPJc
    sal_uInt8 nAdj;
    sal_uInt8 nAdjBiDi;
    switch ( rAdjust.GetAdjust() )
    {
        case SvxAdjust::Left:
            nAdj = 0;
            nAdjBiDi = 2;
            break;
        case SvxAdjust::Right:
            nAdj = 2;
            nAdjBiDi = 0;
            break;
        case SvxAdjust::BlockLine:
        case SvxAdjust::Block:
            nAdj = nAdjBiDi = 3;
            break;
        case SvxAdjust::Center:
            nAdj = nAdjBiDi = 1;
            break;
        default:
            return;    // not a supported Attribute
    }

    m_rWW8Export.InsUInt16(NS_sprm::PJc80::val);
    m_rWW8Export.pO->push_back(nAdj);

    /*
    Sadly for left to right paragraphs both these values are the same,
    for right to left paragraphs the bidi one is the reverse of the
    normal one.
    */
    m_rWW8Export.InsUInt16(NS_sprm::PJc::val); //bidi version ?
    bool bBiDiSwap = false;
    if (m_rWW8Export.m_pOutFormatNode)
    {
        SvxFrameDirection nDirection = SvxFrameDirection::Horizontal_LR_TB;
        if (auto pTN = dynamic_cast<const SwTextNode*>(m_rWW8Export.m_pOutFormatNode))
        {
            SwPosition aPos(*pTN);
            nDirection = m_rWW8Export.m_rDoc.GetTextDirection(aPos);
        }
        else if (auto pC = dynamic_cast<const SwTextFormatColl*>(m_rWW8Export.m_pOutFormatNode))
        {
            const SvxFrameDirectionItem &rItem =
                ItemGet<SvxFrameDirectionItem>(*pC, RES_FRAMEDIR);
            nDirection = rItem.GetValue();
        }
        if ( ( nDirection == SvxFrameDirection::Horizontal_RL_TB ) ||
             ( nDirection == SvxFrameDirection::Environment && AllSettings::GetLayoutRTL() ) )
        {
            bBiDiSwap = true;
        }
    }

    if (bBiDiSwap)
        m_rWW8Export.pO->push_back(nAdjBiDi);
    else
        m_rWW8Export.pO->push_back(nAdj);
}

void WW8AttributeOutput::FormatFrameDirection( const SvxFrameDirectionItem& rDirection )
{
    sal_uInt16 nTextFlow=0;
    bool bBiDi = false;
    SvxFrameDirection nDir = rDirection.GetValue();

    if ( nDir == SvxFrameDirection::Environment )
        nDir = GetExport( ).GetDefaultFrameDirection( );


    switch ( nDir )
    {
        default:
            //Can't get an unknown type here
            OSL_FAIL("Unknown frame direction");
            [[fallthrough]];
        case SvxFrameDirection::Horizontal_LR_TB:
            nTextFlow = 0;
            break;
        case SvxFrameDirection::Horizontal_RL_TB:
            nTextFlow = 0;
            bBiDi = true;
            break;
        case SvxFrameDirection::Vertical_LR_TB:  //word doesn't have this
        case SvxFrameDirection::Vertical_RL_TB:
            nTextFlow = 1;
            break;
    }

    if ( m_rWW8Export.m_bOutPageDescs )
    {
        m_rWW8Export.InsUInt16( NS_sprm::STextFlow::val );
        m_rWW8Export.InsUInt16( nTextFlow );
        m_rWW8Export.InsUInt16( NS_sprm::SFBiDi::val );
        m_rWW8Export.pO->push_back( bBiDi ? 1 : 0 );
    }
    else if ( !m_rWW8Export.m_bOutFlyFrameAttrs )  //paragraph/style
    {
        m_rWW8Export.InsUInt16( NS_sprm::PFBiDi::val );
        m_rWW8Export.pO->push_back( bBiDi ? 1 : 0 );
    }
}

void WW8AttributeOutput::ParaGrabBag(const SfxGrabBagItem& /*rItem*/)
{
}

void WW8AttributeOutput::CharGrabBag(const SfxGrabBagItem& /*rItem*/)
{
}

void WW8AttributeOutput::ParaOutlineLevel(const SfxUInt16Item& rItem)
{
    sal_uInt16 nOutLvl = std::min(rItem.GetValue(), sal_uInt16(WW8ListManager::nMaxLevel));
    // Outline Level: in LO Body Text = 0, in MS Body Text = 9
    nOutLvl = nOutLvl ? nOutLvl - 1 : 9;
    m_rWW8Export.InsUInt16( NS_sprm::POutLvl::val );
    m_rWW8Export.pO->push_back( nOutLvl );
}

// "Separate paragraphs"
void WW8AttributeOutput::ParaSplit( const SvxFormatSplitItem& rSplit )
{
    // sprmPFKeep
    m_rWW8Export.InsUInt16( NS_sprm::PFKeep::val );
    m_rWW8Export.pO->push_back( rSplit.GetValue() ? 0 : 1 );
}

/**
 * Only convert the item "SvxWidowItem" and not the orphans, because
 * in WW only one attribute "paragraph control" exists for both and
 * in SW probably both or none is set by the user.
 */
void WW8AttributeOutput::ParaWidows( const SvxWidowsItem& rWidows )
{
    // sprmPFWidowControl
    m_rWW8Export.InsUInt16( NS_sprm::PFWidowControl::val );
    m_rWW8Export.pO->push_back( rWidows.GetValue() ? 1 : 0 );
}

namespace {

class SwWW8WrTabu
{
    std::unique_ptr<sal_uInt8[]> pDel;            // DelArray
    std::unique_ptr<sal_uInt8[]> pAddPos;         // AddPos-Array
    std::unique_ptr<sal_uInt8[]> pAddTyp;         // AddTyp-Array
    sal_uInt16 nAdd;            // number of tabs to be added
    sal_uInt16 nDel;            // number of tabs to be deleted

    SwWW8WrTabu(const SwWW8WrTabu&) = delete;
    SwWW8WrTabu& operator=(const SwWW8WrTabu&) = delete;

public:
    SwWW8WrTabu(sal_uInt16 nDelMax, sal_uInt16 nAddMax);

    void Add(const SvxTabStop &rTS, tools::Long nAdjustment);
    void Del(const SvxTabStop &rTS, tools::Long nAdjustment);
    void PutAll(WW8Export& rWW8Wrt);
};

}

SwWW8WrTabu::SwWW8WrTabu(sal_uInt16 nDelMax, sal_uInt16 nAddMax)
    : nAdd(0), nDel(0)
{
    if (nDelMax)
        pDel.reset( new sal_uInt8[nDelMax * 2] );
    pAddPos.reset( new sal_uInt8[nAddMax * 2] );
    pAddTyp.reset( new sal_uInt8[nAddMax] );
}

/**
 * insert a tab in the WW structure
 */
void SwWW8WrTabu::Add(const SvxTabStop & rTS, tools::Long nAdjustment)
{
    // insert tab position
    ShortToSVBT16(msword_cast<sal_Int16>(rTS.GetTabPos() + nAdjustment),
        pAddPos.get() + (nAdd * 2));

    // insert tab type
    sal_uInt8 nPara = 0;
    switch (rTS.GetAdjustment())
    {
        case SvxTabAdjust::Right:
            nPara = 2;
            break;
        case SvxTabAdjust::Center:
            nPara = 1;
            break;
        case SvxTabAdjust::Decimal:
            /*
            There is nothing we can do btw the decimal separator has been
            customized, but if you think different remember that different
            locales have different separators, i.e. german is a , while english
            is a .
            */
            nPara = 3;
            break;
        default:
            break;
    }

    switch( rTS.GetFill() )
    {
        case '.':   // dotted leader
            nPara |= 1 << 3;
            break;
        case '_':   // Single line leader
            nPara |= 3 << 3;
            break;
        case '-':   // hyphenated leader
            nPara |= 2 << 3;
            break;
        case '=':   // heavy line leader
            nPara |= 4 << 3;
            break;
    }

    pAddTyp[nAdd] = nPara;
    ++nAdd;
}

/**
 * Insert a to be deleted tab in the WW structure
 */
void SwWW8WrTabu::Del(const SvxTabStop &rTS, tools::Long nAdjustment)
{
    // insert tab position
    ShortToSVBT16(msword_cast<sal_Int16>(rTS.GetTabPos() + nAdjustment),
        pDel.get() + (nDel * 2));
    ++nDel;
}

/**
 * Writes the attribute to rWrt.pO
 */
void SwWW8WrTabu::PutAll(WW8Export& rWrt)
{
    if (!nAdd && !nDel) //If it's a no-op
        return;
    OSL_ENSURE(nAdd <= 255, "more than 255 added tabstops?");
    OSL_ENSURE(nDel <= 255, "more than 244 removed tabstops?");
    if (nAdd > 255)
        nAdd = 255;
    if (nDel > 255)
        nDel = 255;

    sal_uInt16 nSiz = 2 * nDel + 3 * nAdd + 2;
    if (nSiz > 255)
        nSiz = 255;

    rWrt.InsUInt16(NS_sprm::PChgTabsPapx::val);
    // insert cch
    rWrt.pO->push_back(msword_cast<sal_uInt8>(nSiz));
    // write DelArr
    rWrt.pO->push_back(msword_cast<sal_uInt8>(nDel));
    rWrt.OutSprmBytes(pDel.get(), nDel * 2);
    // write InsArr
    rWrt.pO->push_back(msword_cast<sal_uInt8>(nAdd));
    rWrt.OutSprmBytes(pAddPos.get(), 2 * nAdd);         // AddPosArray
    rWrt.OutSprmBytes(pAddTyp.get(), nAdd);             // AddTypArray
}

static void ParaTabStopAdd( WW8Export& rWrt,
                            const SvxTabStopItem& rTStops,
                            const tools::Long nLParaMgn )
{
    SwWW8WrTabu aTab( 0, rTStops.Count());

    for( sal_uInt16 n = 0; n < rTStops.Count(); n++ )
    {
        const SvxTabStop& rTS = rTStops[n];
        // ignore default tabs
        if (SvxTabAdjust::Default != rTS.GetAdjustment())
            aTab.Add(rTS, nLParaMgn);
    }
    aTab.PutAll( rWrt );
}

static bool lcl_IsEqual(tools::Long nOneLeft, const SvxTabStop &rOne,
    tools::Long nTwoLeft, const SvxTabStop &rTwo)
{
    return(
            nOneLeft == nTwoLeft &&
            rOne.GetAdjustment() == rTwo.GetAdjustment() &&
            rOne.GetDecimal() == rTwo.GetDecimal() &&
            rOne.GetFill() == rTwo.GetFill()
          );
}

static void ParaTabStopDelAdd( WW8Export& rWrt,
                               const SvxTabStopItem& rTStyle,
                               const tools::Long nLStypeMgn,
                               const SvxTabStopItem& rTNew,
                               const tools::Long nLParaMgn )
{
    SwWW8WrTabu aTab(rTStyle.Count(), rTNew.Count());

    sal_uInt16 nO = 0;      // rTStyle Index
    sal_uInt16 nN = 0;      // rTNew Index

    do {
        const SvxTabStop* pTO;
        tools::Long nOP;
        if( nO < rTStyle.Count() )                  // old not yet at the end?
        {
            pTO = &rTStyle[ nO ];
            nOP = pTO->GetTabPos() + nLStypeMgn;
            if( SvxTabAdjust::Default == pTO->GetAdjustment() )
            {
                nO++;                                // ignore default tab
                continue;
            }
        }
        else
        {
            pTO = nullptr;
            nOP = LONG_MAX;
        }

        const SvxTabStop* pTN;
        tools::Long nNP;
        if( nN < rTNew.Count() )                    // new not yet at the end
        {
            pTN = &rTNew[ nN ];
            nNP = pTN->GetTabPos() + nLParaMgn;
            if( SvxTabAdjust::Default == pTN->GetAdjustment() )
            {
                nN++;                               // ignore default tab
                continue;
            }
        }
        else
        {
            pTN = nullptr;
            nNP = LONG_MAX;
        }

        if( nOP == LONG_MAX && nNP == LONG_MAX )
            break;                                  // everything done

        if( nOP < nNP )                             // next tab is old
        {
            assert(pTO);
            aTab.Del(*pTO, nLStypeMgn);             // must be deleted
            nO++;
        }
        else if( nNP < nOP )                        // next tab is new
        {
            assert(pTN);
            aTab.Add(*pTN, nLParaMgn);              // must be inserted
            nN++;
        }
        else if (lcl_IsEqual(nOP, *pTO, nNP, *pTN)) // tabs are equal
        {
            nO++;                                   // nothing to do
            nN++;
        }
        else                                        // tabs same position, different type
        {
            aTab.Del(*pTO, nLStypeMgn);             // delete old one
            aTab.Add(*pTN, nLParaMgn);              // insert new one
            nO++;
            nN++;
        }
    } while( true );

    aTab.PutAll( rWrt );
}

void WW8AttributeOutput::ParaTabStop( const SvxTabStopItem& rTabStops )
{
    const bool bTabsRelativeToIndex = m_rWW8Export.m_pCurPam->GetDoc().getIDocumentSettingAccess().get( DocumentSettingId::TABS_RELATIVE_TO_INDENT );

    tools::Long nCurrentLeft = 0;
    if ( bTabsRelativeToIndex )
    {
        if(const SfxPoolItem* pItem = m_rWW8Export.HasItem( RES_LR_SPACE ))
        {
            if(const auto pLR = pItem->DynamicWhichCast(RES_LR_SPACE))
                nCurrentLeft = pLR->GetTextLeft();
            else
                // FIXME: This fails in sw.ww8export/testCommentExport::Load_Verify_Reload_Verify
                SAL_WARN("sw.ww8", "m_rWW8Export has an RES_LR_SPACE item, but its of the wrong type.");
        }
    }

    // #i100264#
    if ( m_rWW8Export.m_bStyDef &&
         m_rWW8Export.m_pCurrentStyle != nullptr &&
         m_rWW8Export.m_pCurrentStyle->DerivedFrom() != nullptr )
    {
        SvxTabStopItem aParentTabs( 0, 0, SvxTabAdjust::Default, RES_PARATR_TABSTOP );
        const SwFormat *pParentStyle = m_rWW8Export.m_pCurrentStyle->DerivedFrom();
        {
            if (const SvxTabStopItem* pParentTabs = pParentStyle->GetAttrSet().GetItem<SvxTabStopItem>(RES_PARATR_TABSTOP))
            {
                aParentTabs.Insert( pParentTabs );
            }
        }

        // #i120938# - consider left indentation of style and its parent style
        tools::Long nParentLeft = 0;
        if ( bTabsRelativeToIndex )
        {
            const SvxLRSpaceItem &rStyleLR = ItemGet<SvxLRSpaceItem>( pParentStyle->GetAttrSet(), RES_LR_SPACE );
            nParentLeft = rStyleLR.GetTextLeft();
        }

        ParaTabStopDelAdd( m_rWW8Export, aParentTabs, nParentLeft, rTabStops, nCurrentLeft );
        return;
    }

    const SvxTabStopItem* pStyleTabs = nullptr;
    if ( !m_rWW8Export.m_bStyDef && m_rWW8Export.m_pStyAttr )
    {
        pStyleTabs = m_rWW8Export.m_pStyAttr->GetItem<SvxTabStopItem>(RES_PARATR_TABSTOP);
    }

    if ( !pStyleTabs )
    {
        ParaTabStopAdd(m_rWW8Export, rTabStops, nCurrentLeft);
    }
    else
    {
        tools::Long nStyleLeft = 0;
        if ( bTabsRelativeToIndex )
        {
            const SvxLRSpaceItem &rStyleLR = ItemGet<SvxLRSpaceItem>(*m_rWW8Export.m_pStyAttr, RES_LR_SPACE);
            nStyleLeft = rStyleLR.GetTextLeft();
        }

        ParaTabStopDelAdd( m_rWW8Export,
                           *pStyleTabs, nStyleLeft,
                           rTabStops, nCurrentLeft);
    }
}

void AttributeOutputBase::OutputItem( const SfxPoolItem& rHt )
{
    // FIXME maybe use 'item_cast', like 'item_cast<SvxCharHiddenItem>( rHt )'?
    switch ( rHt.Which() )
    {
        case RES_CHRATR_CASEMAP:
            CharCaseMap(rHt.StaticWhichCast(RES_CHRATR_CASEMAP));
            break;
        case RES_CHRATR_COLOR:
            CharColor(rHt.StaticWhichCast(RES_CHRATR_COLOR));
            break;
        case RES_CHRATR_CONTOUR:
            CharContour(rHt.StaticWhichCast(RES_CHRATR_CONTOUR));
            break;
        case RES_CHRATR_CROSSEDOUT:
            CharCrossedOut(rHt.StaticWhichCast(RES_CHRATR_CROSSEDOUT));
            break;
        case RES_CHRATR_ESCAPEMENT:
            CharEscapement( static_cast< const SvxEscapementItem& >( rHt ) );
            break;
        case RES_CHRATR_FONT:
            CharFont( static_cast< const SvxFontItem& >( rHt ) );
            break;
        case RES_CHRATR_FONTSIZE:
            CharFontSize( static_cast< const SvxFontHeightItem& >( rHt ) );
            break;
        case RES_CHRATR_KERNING:
            CharKerning( static_cast< const SvxKerningItem& >( rHt ) );
            break;
        case RES_CHRATR_LANGUAGE:
            CharLanguage( static_cast< const SvxLanguageItem& >( rHt ) );
            break;
        case RES_CHRATR_POSTURE:
            CharPosture( static_cast< const SvxPostureItem& >( rHt ) );
            break;
        case RES_CHRATR_SHADOWED:
            CharShadow( static_cast< const SvxShadowedItem& >( rHt ) );
            break;
        case RES_CHRATR_UNDERLINE:
            CharUnderline( static_cast< const SvxUnderlineItem& >( rHt ) );
            break;
        case RES_CHRATR_WEIGHT:
            CharWeight( static_cast< const SvxWeightItem& >( rHt ) );
            break;
        case RES_CHRATR_AUTOKERN:
            CharAutoKern( static_cast< const SvxAutoKernItem& >( rHt ) );
            break;
        case RES_CHRATR_BLINK:
            CharAnimatedText( static_cast< const SvxBlinkItem& >( rHt ) );
            break;
        case RES_CHRATR_BACKGROUND:
            CharBackgroundBase( static_cast< const SvxBrushItem& >( rHt ) );
            break;

        case RES_CHRATR_CJK_FONT:
            CharFontCJK( static_cast< const SvxFontItem& >( rHt ) );
            break;
        case RES_CHRATR_CJK_FONTSIZE:
            CharFontSizeCJK( static_cast< const SvxFontHeightItem& >( rHt ) );
            break;
        case RES_CHRATR_CJK_LANGUAGE:
            CharLanguageCJK( static_cast< const SvxLanguageItem& >( rHt ) );
            break;
        case RES_CHRATR_CJK_POSTURE:
            CharPostureCJK( static_cast< const SvxPostureItem& >( rHt ) );
            break;
        case RES_CHRATR_CJK_WEIGHT:
            CharWeightCJK( static_cast< const SvxWeightItem& >( rHt ) );
            break;

        case RES_CHRATR_CTL_FONT:
            CharFontCTL( static_cast< const SvxFontItem& >( rHt ) );
            break;
        case RES_CHRATR_CTL_FONTSIZE:
            CharFontSizeCTL( static_cast< const SvxFontHeightItem& >( rHt ) );
            break;
        case RES_CHRATR_CTL_LANGUAGE:
            CharLanguageCTL( static_cast< const SvxLanguageItem& >( rHt ) );
            break;
        case RES_CHRATR_CTL_POSTURE:
            CharPostureCTL( static_cast< const SvxPostureItem& >( rHt ) );
            break;
        case RES_CHRATR_CTL_WEIGHT:
            CharWeightCTL( static_cast< const SvxWeightItem& >( rHt ) );
            break;

        case RES_CHRATR_ROTATE:
            CharRotate( static_cast< const SvxCharRotateItem& >( rHt ) );
            break;
        case RES_CHRATR_EMPHASIS_MARK:
            CharEmphasisMark( static_cast< const SvxEmphasisMarkItem& >( rHt ) );
            break;
        case RES_CHRATR_TWO_LINES:
            CharTwoLines( static_cast< const SvxTwoLinesItem& >( rHt ) );
            break;
        case RES_CHRATR_SCALEW:
            CharScaleWidth( static_cast< const SvxCharScaleWidthItem& >( rHt ) );
            break;
        case RES_CHRATR_RELIEF:
            CharRelief( static_cast< const SvxCharReliefItem& >( rHt ) );
            break;
        case RES_CHRATR_HIDDEN:
            CharHidden( static_cast< const SvxCharHiddenItem& >( rHt ) );
            break;
        case RES_CHRATR_BOX:
            FormatCharBorder( static_cast< const SvxBoxItem& >( rHt ) );
            break;
        case RES_CHRATR_HIGHLIGHT:
            CharHighlight( static_cast< const SvxBrushItem& >( rHt ) );
            break;
        case RES_CHRATR_BIDIRTL:
            CharBidiRTL( rHt );
            break;
        case RES_CHRATR_IDCTHINT:
            CharIdctHint( rHt );
            break;
        case RES_TXTATR_INETFMT:
            TextINetFormat( static_cast< const SwFormatINetFormat& >( rHt ) );
            break;
        case RES_TXTATR_CHARFMT:
            TextCharFormat( static_cast< const SwFormatCharFormat& >( rHt ) );
            break;

        case RES_TXTATR_FIELD:
        case RES_TXTATR_ANNOTATION:
        case RES_TXTATR_INPUTFIELD:
            TextField( static_cast< const SwFormatField& >( rHt ) );
            break;

        case RES_TXTATR_FLYCNT:
            TextFlyContent( static_cast< const SwFormatFlyCnt& >( rHt ) );
            break;
        case RES_TXTATR_FTN:
            TextFootnote( static_cast< const SwFormatFootnote& >( rHt ) );
            break;

        case RES_PARATR_LINESPACING:
            ParaLineSpacing( static_cast< const SvxLineSpacingItem& >( rHt ) );
            break;
        case RES_PARATR_ADJUST:
            ParaAdjust( static_cast< const SvxAdjustItem& >( rHt ) );
            break;
        case RES_PARATR_SPLIT:
            ParaSplit( static_cast< const SvxFormatSplitItem& >( rHt ) );
            break;
        case RES_PARATR_WIDOWS:
            ParaWidows( static_cast< const SvxWidowsItem& >( rHt ) );
            break;
        case RES_PARATR_TABSTOP:
            ParaTabStop( static_cast< const SvxTabStopItem& >( rHt ) );
            break;
        case RES_PARATR_HYPHENZONE:
            ParaHyphenZone( static_cast< const SvxHyphenZoneItem& >( rHt ) );
            break;
        case RES_PARATR_NUMRULE:
            ParaNumRule( static_cast< const SwNumRuleItem& >( rHt ) );
            break;
        case RES_PARATR_SCRIPTSPACE:
            ParaScriptSpace( static_cast< const SfxBoolItem& >( rHt ) );
            break;
        case RES_PARATR_HANGINGPUNCTUATION:
            ParaHangingPunctuation( static_cast< const SfxBoolItem& >( rHt ) );
            break;
        case RES_PARATR_FORBIDDEN_RULES:
            ParaForbiddenRules( static_cast< const SfxBoolItem& >( rHt ) );
            break;
        case RES_PARATR_VERTALIGN:
            ParaVerticalAlign( static_cast< const SvxParaVertAlignItem& >( rHt ) );
            break;
        case RES_PARATR_SNAPTOGRID:
            ParaSnapToGrid( static_cast< const SvxParaGridItem& >( rHt ) );
            break;

        case RES_FRM_SIZE:
            FormatFrameSize( static_cast< const SwFormatFrameSize& >( rHt ) );
            break;
        case RES_PAPER_BIN:
            FormatPaperBin( static_cast< const SvxPaperBinItem& >( rHt ) );
            break;
        case RES_LR_SPACE:
            FormatLRSpace( static_cast< const SvxLRSpaceItem& >( rHt ) );
            break;
        case RES_UL_SPACE:
            FormatULSpace( static_cast< const SvxULSpaceItem& >( rHt ) );
            break;
        case RES_PAGEDESC:
            FormatPageDescription( static_cast< const SwFormatPageDesc& >( rHt ) );
            break;
        case RES_BREAK:
            FormatBreak( static_cast< const SvxFormatBreakItem& >( rHt ) );
            break;
        case RES_SURROUND:
            FormatSurround( static_cast< const SwFormatSurround& >( rHt ) );
            break;
        case RES_VERT_ORIENT:
            FormatVertOrientation( static_cast< const SwFormatVertOrient& >( rHt ) );
            break;
        case RES_HORI_ORIENT:
            FormatHorizOrientation( static_cast< const SwFormatHoriOrient& >( rHt ) );
            break;
        case RES_ANCHOR:
            FormatAnchor( static_cast< const SwFormatAnchor& >( rHt ) );
            break;
        case RES_BACKGROUND:
            FormatBackground( static_cast< const SvxBrushItem& >( rHt ) );
            break;
        case XATTR_FILLSTYLE:
            FormatFillStyle( static_cast< const XFillStyleItem& >( rHt ) );
            break;
        case XATTR_FILLGRADIENT:
            FormatFillGradient( static_cast< const XFillGradientItem& >( rHt ) );
            break;
        case RES_BOX:
            FormatBox( static_cast< const SvxBoxItem& >( rHt ) );
            break;
        case RES_COL:
            FormatColumns( static_cast< const SwFormatCol& >( rHt ) );
            break;
        case RES_KEEP:
            FormatKeep( static_cast< const SvxFormatKeepItem& >( rHt ) );
            break;
        case RES_TEXTGRID:
            FormatTextGrid( static_cast< const SwTextGridItem& >( rHt ) );
            break;
        case RES_LINENUMBER:
            FormatLineNumbering( static_cast< const SwFormatLineNumber& >( rHt ) );
            break;
        case RES_FRAMEDIR:
            FormatFrameDirection( static_cast< const SvxFrameDirectionItem& >( rHt ) );
            break;
        case RES_PARATR_GRABBAG:
            ParaGrabBag(static_cast<const SfxGrabBagItem&>(rHt));
            break;
        case RES_PARATR_OUTLINELEVEL:
            ParaOutlineLevelBase(static_cast<const SfxUInt16Item&>(rHt));
            break;
        case RES_CHRATR_GRABBAG:
            CharGrabBag(static_cast<const SfxGrabBagItem&>(rHt));
            break;
        case RES_RTL_GUTTER:
            SectionRtlGutter(static_cast<const SfxBoolItem&>(rHt));
            break;

        default:
            SAL_INFO("sw.ww8", "Unhandled SfxPoolItem with id " << rHt.Which() );
            break;
    }
}

void AttributeOutputBase::OutputStyleItemSet( const SfxItemSet& rSet, bool bTestForDefault )
{
    // based on OutputItemSet() from wrt_fn.cxx

    const SfxItemPool& rPool = *rSet.GetPool();
    const SfxItemSet* pSet = &rSet;
    if ( !pSet->Count() )
    {
        while ( nullptr != ( pSet = pSet->GetParent() ) && !pSet->Count() )
            ;

        if ( !pSet )
            return;
    }

    const SfxPoolItem* pItem;
    if ( !pSet->GetParent() )
    {
        assert(rSet.Count() && "Was already handled or?");
        SfxItemIter aIter( *pSet );
        pItem = aIter.GetCurItem();
        do {
            OutputItem( *pItem );
        } while ((pItem = aIter.NextItem()));
    }
    else
    {
        SfxWhichIter aIter( *pSet );
        sal_uInt16 nWhich = aIter.FirstWhich();
        while ( nWhich )
        {
            if ( SfxItemState::SET == pSet->GetItemState( nWhich, true/*bDeep*/, &pItem ) &&
                 ( !bTestForDefault ||
                   nWhich == RES_UL_SPACE ||
                   nWhich == RES_LR_SPACE ||
                   *pItem != rPool.GetDefaultItem( nWhich ) ||
                   ( pSet->GetParent() && *pItem != pSet->GetParent()->Get( nWhich ) ) ) )
            {
                OutputItem( *pItem );
            }
            nWhich = aIter.NextWhich();
        }
    }
}

void AttributeOutputBase::FormatCharBorder( const SvxBoxItem& rBox )
{
    // Get one of the borders (if there is any border then in docx also will be)
    const SvxBorderLine* pBorderLine = nullptr;
    sal_uInt16 nDist = 0;
    if( rBox.GetTop() )
    {
       pBorderLine = rBox.GetTop();
       nDist = rBox.GetDistance( SvxBoxItemLine::TOP );
    }
    else if( rBox.GetLeft() )
    {
       pBorderLine = rBox.GetLeft();
       nDist = rBox.GetDistance( SvxBoxItemLine::LEFT );
    }
    else if( rBox.GetBottom() )
    {
       pBorderLine = rBox.GetBottom();
       nDist = rBox.GetDistance( SvxBoxItemLine::BOTTOM );
    }
    else if( rBox.GetRight() )
    {
       pBorderLine = rBox.GetRight();
       nDist = rBox.GetDistance( SvxBoxItemLine::RIGHT );
    }

    // RTF: avoid regressions since RTF doesn't know how to export a border_NONE style-override
    if( pBorderLine || GetExport().GetExportFormat() != MSWordExportBase::ExportFormat::RTF )
    {
        const SfxPoolItem* pItem = GetExport().HasItem( RES_CHRATR_SHADOW );
        const SvxShadowItem* pShadowItem = static_cast<const SvxShadowItem*>(pItem);
        const bool bShadow = pBorderLine &&
            pShadowItem && pShadowItem->GetLocation() != SvxShadowLocation::NONE &&
            pShadowItem->GetWidth() > 0;

        CharBorder( pBorderLine, nDist, bShadow );
    }
}

/*
 * This function is used to check if the current SwTextNode (paragraph) has a redline object
 * that is attached to the paragraph marker.
 * This is done by checking if the range (SwPaM) of the redline is :
 * - Start = the last character of the current paragraph
 * - End = the first character of the next paragraph
 */
const SwRedlineData* AttributeOutputBase::GetParagraphMarkerRedline( const SwTextNode& rNode, RedlineType aRedlineType)
{
    // ToDo : this is not the most ideal ... should start maybe from 'nCurRedlinePos'
    for(SwRangeRedline* pRedl : GetExport().m_rDoc.getIDocumentRedlineAccess().GetRedlineTable())
    {
        // Only check redlines that are of type 'Delete'
        if ( pRedl->GetRedlineData().GetType() != aRedlineType )
            continue;

        sal_uLong uStartNodeIndex = pRedl->Start()->nNode.GetIndex();
        sal_uLong uEndNodeIndex   = pRedl->End()->nNode.GetIndex();
        sal_uLong uNodeIndex = rNode.GetIndex();

        if( uStartNodeIndex <= uNodeIndex && uNodeIndex < uEndNodeIndex )
            return &( pRedl->GetRedlineData() );
    }
    return nullptr;
}

void AttributeOutputBase::CharBackgroundBase( const SvxBrushItem& rBrush )
{
    bool bConvertToShading = SvtFilterOptions::Get().IsCharBackground2Shading();
    bool bHasShadingMarker = false;

    // MS Word doesn't support highlight in character styles. Always export those as shading.
    if ( !bConvertToShading && GetExport().m_bStyDef )
    {
        const SwFormat* pFormat = dynamic_cast<const SwFormat*>( GetExport().m_pOutFormatNode );
        bConvertToShading = pFormat && pFormat->Which() == RES_CHRFMT;
    }

    // Check shading marker
    const SfxPoolItem* pItem = GetExport().HasItem(RES_CHRATR_GRABBAG);
    if( pItem )
    {
        const SfxGrabBagItem aGrabBag = static_cast< const SfxGrabBagItem& >(*pItem);
        const std::map<OUString, css::uno::Any>& rMap = aGrabBag.GetGrabBag();
        auto aIterator = rMap.find("CharShadingMarker");
        if( aIterator != rMap.end() )
        {
            aIterator->second >>= bHasShadingMarker;
        }
    }

    if( bConvertToShading || bHasShadingMarker )
    {
        CharBackground(rBrush);
    }
    else
    {
        // Don't create a duplicate entry when converting to highlight. An existing one has priority.
        // Character runs seem to need a different method to detect duplicates? Just continue to ignore that situation.
        if (GetExport().m_aCurrentCharPropStarts.size() || !GetExport().HasItem(RES_CHRATR_HIGHLIGHT))
            CharHighlight(rBrush);
    }
}

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