summaryrefslogtreecommitdiff
path: root/sc/source/ui/app/inputhdl.cxx
blob: b8d126c936b7836123983ea40d608cb64bd00d36 (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
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include <iterator>
#include <memory>
#include <inputhdl.hxx>
#include <scitems.hxx>
#include <editeng/eeitem.hxx>

#include <sfx2/app.hxx>
#include <sfx2/lokhelper.hxx>
#include <editeng/acorrcfg.hxx>
#include <formula/errorcodes.hxx>
#include <svx/algitem.hxx>
#include <editeng/adjustitem.hxx>
#include <editeng/brushitem.hxx>
#include <svtools/colorcfg.hxx>
#include <editeng/colritem.hxx>
#include <editeng/editobj.hxx>
#include <editeng/editstat.hxx>
#include <editeng/editview.hxx>
#include <editeng/escapementitem.hxx>
#include <editeng/forbiddencharacterstable.hxx>
#include <editeng/langitem.hxx>
#include <editeng/svxacorr.hxx>
#include <editeng/unolingu.hxx>
#include <editeng/wghtitem.hxx>
#include <editeng/justifyitem.hxx>
#include <editeng/misspellrange.hxx>
#include <sfx2/bindings.hxx>
#include <sfx2/viewfrm.hxx>
#include <sfx2/dispatch.hxx>
#include <sfx2/docfile.hxx>
#include <sfx2/printer.hxx>
#include <svl/zforlist.hxx>
#include <unotools/localedatawrapper.hxx>
#include <unotools/charclass.hxx>
#include <vcl/help.hxx>
#include <vcl/cursor.hxx>
#include <vcl/settings.hxx>
#include <tools/urlobj.hxx>
#include <formula/formulahelper.hxx>
#include <formula/funcvarargs.h>
#include <LibreOfficeKit/LibreOfficeKitEnums.h>
#include <comphelper/lok.hxx>
#include <o3tl/make_unique.hxx>

#include <inputwin.hxx>
#include <tabvwsh.hxx>
#include <docsh.hxx>
#include <scmod.hxx>
#include <uiitems.hxx>
#include <global.hxx>
#include <sc.hrc>
#include <globstr.hrc>
#include <scresid.hxx>
#include <patattr.hxx>
#include <viewdata.hxx>
#include <document.hxx>
#include <docpool.hxx>
#include <editutil.hxx>
#include <appoptio.hxx>
#include <docoptio.hxx>
#include <validat.hxx>
#include <userlist.hxx>
#include <rfindlst.hxx>
#include <inputopt.hxx>
#include <simpleformulacalc.hxx>
#include <compiler.hxx>
#include <editable.hxx>
#include <funcdesc.hxx>
#include <markdata.hxx>
#include <tokenarray.hxx>
#include <gridwin.hxx>
#include <output.hxx>
#include <fillinfo.hxx>

// Maximum Ranges in RangeFinder
#define RANGEFIND_MAX   64

using namespace formula;

bool ScInputHandler::bOptLoaded = false;            // Evaluate App options
bool ScInputHandler::bAutoComplete = false;         // Is set in KeyInput

namespace {

// Formula data replacement character for a pair of parentheses at end of
// function name, to force sorting parentheses before all other characters.
// Collation may treat parentheses differently.
const sal_Unicode cParenthesesReplacement = 0x0001;

sal_Unicode lcl_getSheetSeparator(ScDocument* pDoc)
{
    ScCompiler aComp(pDoc, ScAddress(), pDoc->GetGrammar());
    return aComp.GetNativeAddressSymbol(ScCompiler::Convention::SHEET_SEPARATOR);
}

ScTypedCaseStrSet::const_iterator findText(
    const ScTypedCaseStrSet& rDataSet, ScTypedCaseStrSet::const_iterator const & itPos,
    const OUString& rStart, OUString& rResult, bool bBack)
{
    if (bBack) // Backwards
    {
        ScTypedCaseStrSet::const_reverse_iterator it = rDataSet.rbegin(), itEnd = rDataSet.rend();
        if (itPos != rDataSet.end())
        {
            size_t nPos = std::distance(rDataSet.begin(), itPos);
            size_t nRPos = rDataSet.size() - 1 - nPos;
            std::advance(it, nRPos);
            ++it;
        }

        for (; it != itEnd; ++it)
        {
            const ScTypedStrData& rData = *it;
            if (rData.GetStringType() == ScTypedStrData::Value)
                // skip values
                continue;

            if (!ScGlobal::GetpTransliteration()->isMatch(rStart, rData.GetString()))
                // not a match
                continue;

            rResult = rData.GetString();
            return (++it).base(); // convert the reverse iterator back to iterator.
        }
    }
    else // Forwards
    {
        ScTypedCaseStrSet::const_iterator it = rDataSet.begin(), itEnd = rDataSet.end();
        if (itPos != rDataSet.end())
        {
            it = itPos;
            ++it;
        }

        for (; it != itEnd; ++it)
        {
            const ScTypedStrData& rData = *it;
            if (rData.GetStringType() == ScTypedStrData::Value)
                // skip values
                continue;

            if (!ScGlobal::GetpTransliteration()->isMatch(rStart, rData.GetString()))
                // not a match
                continue;

            rResult = rData.GetString();
            return it;
        }
    }

    return rDataSet.end(); // no matching text found
}

OUString getExactMatch(const ScTypedCaseStrSet& rDataSet, const OUString& rString)
{
    ScTypedCaseStrSet::const_iterator it = rDataSet.begin(), itEnd = rDataSet.end();
    for (; it != itEnd; ++it)
    {
        const ScTypedStrData& rData = *it;
        if (rData.GetStringType() == ScTypedStrData::Value)
            continue;

        if (!ScGlobal::GetpTransliteration()->isEqual(rData.GetString(), rString))
            continue;

        return rData.GetString();
    }
    return rString;
}

ScTypedCaseStrSet::const_iterator findTextAll(
    const ScTypedCaseStrSet& rDataSet, ScTypedCaseStrSet::const_iterator const & itPos,
    const OUString& rStart, ::std::vector< OUString > &rResultVec, bool bBack)
{
    rResultVec.clear(); // clear contents

    size_t nCount = 0;
    ScTypedCaseStrSet::const_iterator retit;
    if ( bBack ) // Backwards
    {
        ScTypedCaseStrSet::const_reverse_iterator it, itEnd;
        if ( itPos == rDataSet.end() )
        {
            it = rDataSet.rend();
            --it;
            itEnd = it;
        }
        else
        {
            it = rDataSet.rbegin();
            size_t nPos = std::distance(rDataSet.begin(), itPos);
            size_t nRPos = rDataSet.size() - 1 - nPos; // if itPos == rDataSet.end(), then nRPos = -1
            std::advance(it, nRPos);
            if ( it == rDataSet.rend() )
                it = rDataSet.rbegin();
            itEnd = it;
        }
        bool bFirstTime = true;

        while ( it != itEnd || bFirstTime )
        {
            ++it;
            if ( it == rDataSet.rend() ) // go to the first if reach the end
                it = rDataSet.rbegin();

            if ( bFirstTime )
                bFirstTime = false;
            const ScTypedStrData& rData = *it;
            if ( rData.GetStringType() == ScTypedStrData::Value )
                // skip values
                continue;

            if ( !ScGlobal::GetpTransliteration()->isMatch(rStart, rData.GetString()) )
                // not a match
                continue;

            rResultVec.push_back(rData.GetString()); // set the match data
            if ( nCount == 0 ) // convert the reverse iterator back to iterator.
            {
                // actually we want to do "retit = it;".
                retit = rDataSet.begin();
                size_t nRPos = std::distance(rDataSet.rbegin(), it);
                size_t nPos = rDataSet.size() - 1 - nRPos;
                std::advance(retit, nPos);
            }
            ++nCount;
        }
    }
    else // Forwards
    {
        ScTypedCaseStrSet::const_iterator it, itEnd;
        it = itPos;
        if ( it == rDataSet.end() )
            it = rDataSet.begin();
        itEnd = it;
        bool bFirstTime = true;

        while ( it != itEnd || bFirstTime )
        {
            ++it;
            if ( it == rDataSet.end() ) // go to the first if reach the end
                it = rDataSet.begin();

            if ( bFirstTime )
                bFirstTime = false;
            const ScTypedStrData& rData = *it;
            if ( rData.GetStringType() == ScTypedStrData::Value )
                // skip values
                continue;

            if ( !ScGlobal::GetpTransliteration()->isMatch(rStart, rData.GetString()) )
                // not a match
                continue;

            rResultVec.push_back(rData.GetString()); // set the match data
            if ( nCount == 0 )
                retit = it; // remember first match iterator
            ++nCount;
        }
    }

    if ( nCount > 0 ) // at least one function has matched
        return retit;
    return rDataSet.end(); // no matching text found
}

}

void ScInputHandler::SendReferenceMarks( const SfxViewShell* pViewShell,
                            const std::vector<ReferenceMark>& rReferenceMarks )
{
    if ( !pViewShell )
        return;

    bool bSend = false;

    std::stringstream ss;

    ss << "{ \"marks\": [ ";

    for ( size_t i = 0; i < rReferenceMarks.size(); i++ )
    {
        if ( rReferenceMarks[i].Is() )
        {
            if ( bSend )
                ss << ", ";

            ss << "{ \"rectangle\": \""
               << rReferenceMarks[i].nX << ", "
               << rReferenceMarks[i].nY << ", "
               << rReferenceMarks[i].nWidth << ", "
               << rReferenceMarks[i].nHeight << "\", "
                  "\"color\": \"" << rReferenceMarks[i].aColor.AsRGBHexString() << "\", "
                  "\"part\": \"" << rReferenceMarks[i].nTab << "\" } ";

            bSend = true;
        }
    }

    ss <<  " ] }";

    OString aPayload = ss.str().c_str();
    pViewShell->libreOfficeKitViewCallback(
                LOK_CALLBACK_REFERENCE_MARKS, aPayload.getStr() );
}

void ScInputHandler::InitRangeFinder( const OUString& rFormula )
{
    DeleteRangeFinder();
    if ( !pActiveViewSh || !SC_MOD()->GetInputOptions().GetRangeFinder() )
        return;
    ScDocShell* pDocSh = pActiveViewSh->GetViewData().GetDocShell();
    ScDocument& rDoc = pDocSh->GetDocument();
    const sal_Unicode cSheetSep = lcl_getSheetSeparator(&rDoc);

    OUString aDelimiters = ScEditUtil::ModifyDelimiters(" !~\"");
        // delimiters (in addition to ScEditUtil): only characters that are
        // allowed in formulas next to references and the quotation mark (so
        // string constants can be skipped)

    sal_Int32 nColon = aDelimiters.indexOf( ':' );
    if ( nColon != -1 )
        aDelimiters = aDelimiters.replaceAt( nColon, 1, ""); // Delimiter without colon
    sal_Int32 nDot = aDelimiters.indexOf(cSheetSep);
    if ( nDot != -1 )
        aDelimiters = aDelimiters.replaceAt( nDot, 1 , ""); // Delimiter without dot

    const sal_Unicode* pChar = rFormula.getStr();
    sal_Int32 nLen = rFormula.getLength();
    sal_Int32 nPos = 0;
    sal_Int32 nStart = 0;
    sal_uInt16 nCount = 0;
    ScRange aRange;
    while ( nPos < nLen && nCount < RANGEFIND_MAX )
    {
        // Skip separator
        while ( nPos<nLen && ScGlobal::UnicodeStrChr( aDelimiters.getStr(), pChar[nPos] ) )
        {
            if ( pChar[nPos] == '"' )                       // String
            {
                ++nPos;
                while (nPos<nLen && pChar[nPos] != '"')     // Skip until end
                    ++nPos;
            }
            ++nPos; // Separator or closing quote
        }

        //  Text zwischen Trennern
        nStart = nPos;
handle_r1c1:
        while ( nPos<nLen && !ScGlobal::UnicodeStrChr( aDelimiters.getStr(), pChar[nPos] ) )
            ++nPos;

        // for R1C1 '-' in R[-]... or C[-]... are not delimiters
        // Nothing heroic here to ensure that there are '[]' around a negative
        // integer.  we need to clean up this code.
        if( nPos < nLen && nPos > 0 &&
            '-' == pChar[nPos] && '[' == pChar[nPos-1] &&
            formula::FormulaGrammar::CONV_XL_R1C1 == rDoc.GetAddressConvention() )
        {
            nPos++;
            goto handle_r1c1;
        }

        if ( nPos > nStart )
        {
            OUString aTest = rFormula.copy( nStart, nPos-nStart );
            const ScAddress::Details aAddrDetails( &rDoc, aCursorPos );
            ScRefFlags nFlags = aRange.ParseAny( aTest, &rDoc, aAddrDetails );
            if ( nFlags & ScRefFlags::VALID )
            {
                //  Set tables if not specified
                if ( (nFlags & ScRefFlags::TAB_3D) == ScRefFlags::ZERO)
                    aRange.aStart.SetTab( pActiveViewSh->GetViewData().GetTabNo() );
                if ( (nFlags & ScRefFlags::TAB2_3D) == ScRefFlags::ZERO)
                    aRange.aEnd.SetTab( aRange.aStart.Tab() );

                if ( ( nFlags & (ScRefFlags::COL2_VALID|ScRefFlags::ROW2_VALID|ScRefFlags::TAB2_VALID) ) ==
                                 ScRefFlags::ZERO )
                {
                    // #i73766# if a single ref was parsed, set the same "abs" flags for ref2,
                    // so Format doesn't output a double ref because of different flags.
                    ScRefFlags nAbsFlags = nFlags & (ScRefFlags::COL_ABS|ScRefFlags::ROW_ABS|ScRefFlags::TAB_ABS);
                    applyStartToEndFlags(nFlags, nAbsFlags);
                }

                if (!nCount)
                {
                    mpEditEngine->SetUpdateMode( false );
                    pRangeFindList.reset(new ScRangeFindList( pDocSh->GetTitle() ));
                }

                Color nColor = pRangeFindList->Insert( ScRangeFindData( aRange, nFlags, nStart, nPos ) );

                ESelection aSel( 0, nStart, 0, nPos );
                SfxItemSet aSet( mpEditEngine->GetEmptyItemSet() );
                aSet.Put( SvxColorItem( nColor, EE_CHAR_COLOR ) );
                mpEditEngine->QuickSetAttribs( aSet, aSel );
                ++nCount;
            }
        }

        // Do not skip last separator; could be a quote (?)
    }

    UpdateLokReferenceMarks();

    if (nCount)
    {
        mpEditEngine->SetUpdateMode( true );

        pDocSh->Broadcast( SfxHint( SfxHintId::ScShowRangeFinder ) );
    }
}

ReferenceMark ScInputHandler::GetReferenceMark( ScViewData& rViewData, ScDocShell* pDocSh,
                                    long nX1, long nX2, long nY1, long nY2,
                                    long nTab, const Color& rColor )
{
    ScSplitPos eWhich = rViewData.GetActivePart();

    Point aScrPos = rViewData.GetScrPos( nX1, nY1, eWhich );
    long nScrX = aScrPos.X();
    long nScrY = aScrPos.Y();

    double nPPTX = rViewData.GetPPTX();
    double nPPTY = rViewData.GetPPTY();

    Fraction aZoomX = rViewData.GetZoomX();
    Fraction aZoomY = rViewData.GetZoomY();

    ScTableInfo aTabInfo;
    pDocSh->GetDocument().FillInfo( aTabInfo, nX1, nY1, nX2, nY2,
                                    nTab, nPPTX, nPPTY, false, false );

    ScOutputData aOutputData( nullptr, OUTTYPE_WINDOW, aTabInfo,
                              &( pDocSh->GetDocument() ), nTab,
                              nScrX, nScrY,
                              nX1, nY1, nX2, nY2,
                              nPPTX, nPPTY,
                              &aZoomX, &aZoomY );

    return aOutputData.FillReferenceMark( nX1, nY1, nX2, nY2,
                                          rColor );
}

void ScInputHandler::UpdateLokReferenceMarks()
{
    if ( !comphelper::LibreOfficeKit::isActive())
        return;

    ScTabViewShell* pShell = pActiveViewSh ? pActiveViewSh
                                : dynamic_cast<ScTabViewShell*>(SfxViewShell::Current());

    if (!pShell)
        return;

    ScViewData& rViewData = pShell->GetViewData();
    ScDocShell* pDocSh = rViewData.GetDocShell();
    ScRangeFindList* pRangeFinder = GetRangeFindList();

    if ( !pRangeFinder && !rViewData.IsRefMode() )
        return;

    sal_uInt16 nAdditionalMarks = 0;
    std::vector<ReferenceMark> aReferenceMarks( 1 );

    if ( rViewData.IsRefMode() )
    {
        nAdditionalMarks = 1;

        const svtools::ColorConfig& rColorCfg = SC_MOD()->GetColorConfig();
        Color aRefColor( rColorCfg.GetColorValue( svtools::CALCREFERENCE ).nColor );
        long nX1 = rViewData.GetRefStartX();
        long nX2 = rViewData.GetRefEndX();
        long nY1 = rViewData.GetRefStartY();
        long nY2 = rViewData.GetRefEndY();
        long nTab = rViewData.GetRefTabNo();

        PutInOrder(nX1, nX2);
        PutInOrder(nY1, nY2);

        aReferenceMarks[0] = ScInputHandler::GetReferenceMark( rViewData, pDocSh,
                                                   nX1, nX2, nY1, nY2,
                                                   nTab, aRefColor );
    }

    sal_uInt16 nCount = pRangeFinder ?
        ( static_cast<sal_uInt16>( pRangeFinder->Count() ) + nAdditionalMarks ) : nAdditionalMarks;
    aReferenceMarks.resize( nCount );

    if ( nCount && pRangeFinder && !pRangeFinder->IsHidden() &&
         pRangeFinder->GetDocName() == pDocSh->GetTitle() )
    {
        for (sal_uInt16 i = 0; i < nCount - nAdditionalMarks; i++)
        {
            ScRangeFindData& rData = pRangeFinder->GetObject( i );
            ScRange aRef = rData.aRef;
            aRef.PutInOrder();

            long nX1 = aRef.aStart.Col();
            long nX2 = aRef.aEnd.Col();
            long nY1 = aRef.aStart.Row();
            long nY2 = aRef.aEnd.Row();
            long nTab = aRef.aStart.Tab();

            aReferenceMarks[i + nAdditionalMarks] = ScInputHandler::GetReferenceMark( rViewData, pDocSh,
                                                                          nX1, nX2, nY1, nY2,
                                                                          nTab, Color( rData.nColor ) );

            ScInputHandler::SendReferenceMarks( pShell, aReferenceMarks );
        }
    }
    else if ( nCount )
    {
        ScInputHandler::SendReferenceMarks( pShell, aReferenceMarks );
    }
    else
    {
        // Clear
        aReferenceMarks.clear();
        ScInputHandler::SendReferenceMarks( pShell, aReferenceMarks );
    }
}

void ScInputHandler::SetDocumentDisposing( bool b )
{
    mbDocumentDisposing = b;
}

static void lcl_Replace( EditView* pView, const OUString& rNewStr, const ESelection& rOldSel )
{
    if ( pView )
    {
        ESelection aOldSel = pView->GetSelection();
        if (aOldSel.HasRange())
            pView->SetSelection( ESelection( aOldSel.nEndPara, aOldSel.nEndPos,
                                             aOldSel.nEndPara, aOldSel.nEndPos ) );

        EditEngine* pEngine = pView->GetEditEngine();
        pEngine->QuickInsertText( rNewStr, rOldSel );

        // Dummy InsertText for Update and Paint
        // To do that we need to cancel the selection from above (before QuickInsertText)
        pView->InsertText( EMPTY_OUSTRING );

        sal_Int32 nLen = pEngine->GetTextLen(0);
        ESelection aSel( 0, nLen, 0, nLen );
        pView->SetSelection( aSel ); // Set cursor to the end
    }
}

void ScInputHandler::UpdateRange( sal_uInt16 nIndex, const ScRange& rNew )
{
    ScTabViewShell* pDocView = pRefViewSh ? pRefViewSh : pActiveViewSh;
    if ( pDocView && pRangeFindList && nIndex < pRangeFindList->Count() )
    {
        ScRangeFindData& rData = pRangeFindList->GetObject( nIndex );
        sal_Int32 nOldStart = rData.nSelStart;
        sal_Int32 nOldEnd = rData.nSelEnd;
        Color nNewColor = pRangeFindList->FindColor( rNew, nIndex );

        ScRange aJustified = rNew;
        aJustified.PutInOrder(); // Always display Ref in the Formula the right way
        ScDocument* pDoc = pDocView->GetViewData().GetDocument();
        const ScAddress::Details aAddrDetails( pDoc, aCursorPos );
        OUString aNewStr(aJustified.Format(rData.nFlags, pDoc, aAddrDetails));
        ESelection aOldSel( 0, nOldStart, 0, nOldEnd );
        SfxItemSet aSet( mpEditEngine->GetEmptyItemSet() );

        DataChanging();

        lcl_Replace( pTopView, aNewStr, aOldSel );
        lcl_Replace( pTableView, aNewStr, aOldSel );
        aSet.Put( SvxColorItem( nNewColor, EE_CHAR_COLOR ) );
        mpEditEngine->QuickSetAttribs( aSet, aOldSel );

        bInRangeUpdate = true;
        DataChanged();
        bInRangeUpdate = false;

        long nDiff = aNewStr.getLength() - static_cast<long>(nOldEnd-nOldStart);

        rData.aRef = rNew;
        rData.nSelEnd = rData.nSelEnd + nDiff;
        rData.nColor = nNewColor;

        sal_uInt16 nCount = static_cast<sal_uInt16>(pRangeFindList->Count());
        for (sal_uInt16 i=nIndex+1; i<nCount; i++)
        {
            ScRangeFindData& rNext = pRangeFindList->GetObject( i );
            rNext.nSelStart = rNext.nSelStart + nDiff;
            rNext.nSelEnd   = rNext.nSelEnd   + nDiff;
        }

        EditView* pActiveView = pTopView ? pTopView : pTableView;
        pActiveView->ShowCursor( false );
    }
    else
    {
        OSL_FAIL("UpdateRange: we're missing something");
    }
}

void ScInputHandler::DeleteRangeFinder()
{
    ScTabViewShell* pPaintView = pRefViewSh ? pRefViewSh : pActiveViewSh;
    if ( pRangeFindList && pPaintView )
    {
        ScDocShell* pDocSh = pActiveViewSh->GetViewData().GetDocShell();
        pRangeFindList->SetHidden(true);
        pDocSh->Broadcast( SfxHint( SfxHintId::ScShowRangeFinder ) );  // Steal
        pRangeFindList.reset();
    }
}

static OUString GetEditText(const EditEngine* pEng)
{
    return ScEditUtil::GetSpaceDelimitedString(*pEng);
}

static void lcl_RemoveTabs(OUString& rStr)
{
    rStr = rStr.replace('\t', ' ');
}

static void lcl_RemoveLineEnd(OUString& rStr)
{
    rStr = convertLineEnd(rStr, LINEEND_LF);
    rStr = rStr.replace('\n', ' ');
}

static sal_Int32 lcl_MatchParenthesis( const OUString& rStr, sal_Int32 nPos )
{
    int nDir;
    sal_Unicode c1, c2 = 0;
    c1 = rStr[nPos];
    switch ( c1 )
    {
    case '(' :
        c2 = ')';
        nDir = 1;
        break;
    case ')' :
        c2 = '(';
        nDir = -1;
        break;
    case '<' :
        c2 = '>';
        nDir = 1;
        break;
    case '>' :
        c2 = '<';
        nDir = -1;
        break;
    case '{' :
        c2 = '}';
        nDir = 1;
        break;
    case '}' :
        c2 = '{';
        nDir = -1;
        break;
    case '[' :
        c2 = ']';
        nDir = 1;
        break;
    case ']' :
        c2 = '[';
        nDir = -1;
        break;
    default:
        nDir = 0;
    }
    if ( !nDir )
        return -1;
    sal_Int32 nLen = rStr.getLength();
    const sal_Unicode* p0 = rStr.getStr();
    const sal_Unicode* p;
    const sal_Unicode* p1;
    sal_uInt16 nQuotes = 0;
    if ( nPos < nLen / 2 )
    {
        p = p0;
        p1 = p0 + nPos;
    }
    else
    {
        p = p0 + nPos;
        p1 = p0 + nLen;
    }
    while ( p < p1 )
    {
        if ( *p++ == '\"' )
            nQuotes++;
    }
    // Odd number of quotes that we find ourselves in a string
    bool bLookInString = ((nQuotes % 2) != 0);
    bool bInString = bLookInString;
    p = p0 + nPos;
    p1 = (nDir < 0 ? p0 : p0 + nLen) ;
    sal_uInt16 nLevel = 1;
    while ( p != p1 && nLevel )
    {
        p += nDir;
        if ( *p == '\"' )
        {
            bInString = !bInString;
            if ( bLookInString && !bInString )
                p = p1; // That's it then
        }
        else if ( bInString == bLookInString )
        {
            if ( *p == c1 )
                nLevel++;
            else if ( *p == c2 )
                nLevel--;
        }
    }
    if ( nLevel )
        return -1;
    return static_cast<sal_Int32>(p - p0);
}

ScInputHandler::ScInputHandler()
    :   pInputWin( nullptr ),
        pTableView( nullptr ),
        pTopView( nullptr ),
        pTipVisibleParent( nullptr ),
        nTipVisible( nullptr ),
        pTipVisibleSecParent( nullptr ),
        nTipVisibleSec( nullptr ),
        nFormSelStart( 0 ),
        nFormSelEnd( 0 ),
        nAutoPar( 0 ),
        eMode( SC_INPUT_NONE ),
        bUseTab( false ),
        bTextValid( true ),
        bModified( false ),
        bSelIsRef( false ),
        bFormulaMode( false ),
        bInRangeUpdate( false ),
        bParenthesisShown( false ),
        bCreatingFuncView( false ),
        bInEnterHandler( false ),
        bCommandErrorShown( false ),
        bInOwnChange( false ),
        bProtected( false ),
        bCellHasPercentFormat( false ),
        bLastIsSymbol( false ),
        mbDocumentDisposing(false),
        nValidation( 0 ),
        eAttrAdjust( SvxCellHorJustify::Standard ),
        aScaleX( 1,1 ),
        aScaleY( 1,1 ),
        pRefViewSh( nullptr ),
        pLastPattern( nullptr ),
        maFormulaChar()
{
    //  The InputHandler is constructed with the view, so SfxViewShell::Current
    //  doesn't have the right view yet. pActiveViewSh is updated in NotifyChange.
    pActiveViewSh = nullptr;

    //  Bindings (only still used for Invalidate) are retrieved if needed on demand

    pDelayTimer.reset( new Timer( "ScInputHandlerDelay timer" ) );
    pDelayTimer->SetTimeout( 500 ); // 500 ms delay
    pDelayTimer->SetInvokeHandler( LINK( this, ScInputHandler, DelayTimer ) );

    if (comphelper::LibreOfficeKit::isActive())
    {
        ScInputHandler::bOptLoaded = true;            // Evaluate App options
        ScInputHandler::bAutoComplete = true;         // Is set in KeyInput
    }
}

ScInputHandler::~ScInputHandler()
{
    //  If this is the application InputHandler, the dtor is called after SfxApplication::Main,
    //  thus we can't rely on any Sfx functions
    if (!mbDocumentDisposing) // inplace
        EnterHandler(); // Finish input

    if (SC_MOD()->GetRefInputHdl() == this)
        SC_MOD()->SetRefInputHdl(nullptr);

    if ( pInputWin && pInputWin->GetInputHandler() == this )
        pInputWin->SetInputHandler( nullptr );
}

void ScInputHandler::SetRefScale( const Fraction& rX, const Fraction& rY )
{
    if ( rX != aScaleX || rY != aScaleY )
    {
        aScaleX = rX;
        aScaleY = rY;
        if (mpEditEngine)
        {
            MapMode aMode( MapUnit::Map100thMM, Point(), aScaleX, aScaleY );
            mpEditEngine->SetRefMapMode( aMode );
        }
    }
}

void ScInputHandler::UpdateRefDevice()
{
    if (!mpEditEngine)
        return;

    bool bTextWysiwyg = SC_MOD()->GetInputOptions().GetTextWysiwyg();
    bool bInPlace = pActiveViewSh && pActiveViewSh->GetViewFrame()->GetFrame().IsInPlace();
    EEControlBits nCtrl = mpEditEngine->GetControlWord();
    if ( bTextWysiwyg || bInPlace )
        nCtrl |= EEControlBits::FORMAT100;    // EditEngine default: always format for 100%
    else
        nCtrl &= ~EEControlBits::FORMAT100;   // when formatting for screen, use the actual MapMode
    mpEditEngine->SetControlWord( nCtrl );
    if ( bTextWysiwyg && pActiveViewSh )
        mpEditEngine->SetRefDevice( pActiveViewSh->GetViewData().GetDocument()->GetPrinter() );
    else
        mpEditEngine->SetRefDevice( nullptr );

    MapMode aMode( MapUnit::Map100thMM, Point(), aScaleX, aScaleY );
    mpEditEngine->SetRefMapMode( aMode );

    //  SetRefDevice(NULL) uses VirtualDevice, SetRefMapMode forces creation of a local VDev,
    //  so the DigitLanguage can be safely modified (might use an own VDev instead of NULL).
    if ( !( bTextWysiwyg && pActiveViewSh ) )
    {
        mpEditEngine->GetRefDevice()->SetDigitLanguage( SC_MOD()->GetOptDigitLanguage() );
    }
}

void ScInputHandler::ImplCreateEditEngine()
{
    if ( !mpEditEngine )
    {
        if ( pActiveViewSh )
        {
            ScDocument& rDoc = pActiveViewSh->GetViewData().GetDocShell()->GetDocument();
            mpEditEngine = o3tl::make_unique<ScFieldEditEngine>(&rDoc, rDoc.GetEnginePool(), rDoc.GetEditPool());
        }
        else
            mpEditEngine = o3tl::make_unique<ScFieldEditEngine>(nullptr, EditEngine::CreatePool(), nullptr, true);

        mpEditEngine->SetWordDelimiters( ScEditUtil::ModifyDelimiters( mpEditEngine->GetWordDelimiters() ) );
        UpdateRefDevice();      // also sets MapMode
        mpEditEngine->SetPaperSize( Size( 1000000, 1000000 ) );
        pEditDefaults.reset( new SfxItemSet( mpEditEngine->GetEmptyItemSet() ) );

        mpEditEngine->SetControlWord( mpEditEngine->GetControlWord() | EEControlBits::AUTOCORRECT );
        mpEditEngine->SetReplaceLeadingSingleQuotationMark( false );
        mpEditEngine->SetModifyHdl( LINK( this, ScInputHandler, ModifyHdl ) );
    }
}

void ScInputHandler::UpdateAutoCorrFlag()
{
    EEControlBits nCntrl = mpEditEngine->GetControlWord();
    EEControlBits nOld = nCntrl;

    // Don't use pLastPattern here (may be invalid because of AutoStyle)
    bool bDisable = bLastIsSymbol || bFormulaMode;
    if ( bDisable )
        nCntrl &= ~EEControlBits::AUTOCORRECT;
    else
        nCntrl |= EEControlBits::AUTOCORRECT;

    if ( nCntrl != nOld )
        mpEditEngine->SetControlWord(nCntrl);
}

void ScInputHandler::UpdateSpellSettings( bool bFromStartTab )
{
    if ( pActiveViewSh )
    {
        ScViewData& rViewData = pActiveViewSh->GetViewData();
        bool bOnlineSpell = rViewData.GetDocument()->GetDocOptions().IsAutoSpell();

        //  SetDefaultLanguage is independent of the language attributes,
        //  ScGlobal::GetEditDefaultLanguage is always used.
        //  It must be set every time in case the office language was changed.

        mpEditEngine->SetDefaultLanguage( ScGlobal::GetEditDefaultLanguage() );

        //  if called for changed options, update flags only if already editing
        //  if called from StartTable, always update flags

        if ( bFromStartTab || eMode != SC_INPUT_NONE )
        {
            EEControlBits nCntrl = mpEditEngine->GetControlWord();
            EEControlBits nOld = nCntrl;
            if( bOnlineSpell )
                nCntrl |= EEControlBits::ONLINESPELLING;
            else
                nCntrl &= ~EEControlBits::ONLINESPELLING;
            // No AutoCorrect for Symbol Font (EditEngine does no evaluate Default)
            if ( pLastPattern && pLastPattern->IsSymbolFont() )
                nCntrl &= ~EEControlBits::AUTOCORRECT;
            else
                nCntrl |= EEControlBits::AUTOCORRECT;
            if ( nCntrl != nOld )
                mpEditEngine->SetControlWord(nCntrl);

            ScDocument* pDoc = rViewData.GetDocument();
            pDoc->ApplyAsianEditSettings( *mpEditEngine );
            mpEditEngine->SetDefaultHorizontalTextDirection(
                pDoc->GetEditTextDirection( rViewData.GetTabNo() ) );
            mpEditEngine->SetFirstWordCapitalization( false );
        }

        //  Language is set separately, so the speller is needed only if online spelling is active
        if ( bOnlineSpell ) {
            css::uno::Reference<css::linguistic2::XSpellChecker1> xXSpellChecker1( LinguMgr::GetSpellChecker() );
            mpEditEngine->SetSpeller( xXSpellChecker1 );
        }

        bool bHyphen = pLastPattern && pLastPattern->GetItem(ATTR_HYPHENATE).GetValue();
        if ( bHyphen ) {
            css::uno::Reference<css::linguistic2::XHyphenator> xXHyphenator( LinguMgr::GetHyphenator() );
            mpEditEngine->SetHyphenator( xXHyphenator );
        }
    }
}

// Function/Range names etc. as Tip help

//  The other types are defined in ScDocument::GetFormulaEntries
void ScInputHandler::GetFormulaData()
{
    if ( pActiveViewSh )
    {
        ScDocument& rDoc = pActiveViewSh->GetViewData().GetDocShell()->GetDocument();

        if ( pFormulaData )
            pFormulaData->clear();
        else
        {
            pFormulaData.reset( new ScTypedCaseStrSet );
        }

        if( pFormulaDataPara )
            pFormulaDataPara->clear();
        else
            pFormulaDataPara.reset( new ScTypedCaseStrSet );

        const OUString aParenthesesReplacement( cParenthesesReplacement);
        const ScFunctionList* pFuncList = ScGlobal::GetStarCalcFunctionList();
        sal_uInt32 nListCount = pFuncList->GetCount();
        for(sal_uInt32 i=0;i<nListCount;i++)
        {
            const ScFuncDesc* pDesc = pFuncList->GetFunction( i );
            if ( pDesc->mxFuncName )
            {
                const sal_Unicode* pName = pDesc->mxFuncName->getStr();
                const sal_Int32 nLen = pDesc->mxFuncName->getLength();
                // fdo#75264 fill maFormulaChar with all characters used in formula names
                for ( sal_Int32 j = 0; j < nLen; j++ )
                {
                    sal_Unicode c = pName[ j ];
                    maFormulaChar.insert( c );
                }
                OUString aFuncName = *pDesc->mxFuncName + aParenthesesReplacement;
                pFormulaData->insert(ScTypedStrData(aFuncName, 0.0, ScTypedStrData::Standard));
                pDesc->initArgumentInfo();
                OUString aEntry = pDesc->getSignature();
                pFormulaDataPara->insert(ScTypedStrData(aEntry, 0.0, ScTypedStrData::Standard));
            }
        }
        miAutoPosFormula = pFormulaData->end();
        rDoc.GetFormulaEntries( *pFormulaData );
        rDoc.GetFormulaEntries( *pFormulaDataPara );
    }
}

IMPL_LINK( ScInputHandler, ShowHideTipVisibleParentListener, VclWindowEvent&, rEvent, void )
{
    if( rEvent.GetId() == VclEventId::ObjectDying || rEvent.GetId() == VclEventId::WindowHide )
        HideTip();
}

IMPL_LINK( ScInputHandler, ShowHideTipVisibleSecParentListener, VclWindowEvent&, rEvent, void )
{
    if( rEvent.GetId() == VclEventId::ObjectDying || rEvent.GetId() == VclEventId::WindowHide )
        HideTipBelow();
}

void ScInputHandler::HideTip()
{
    if ( nTipVisible )
    {
        pTipVisibleParent->RemoveEventListener( LINK( this, ScInputHandler, ShowHideTipVisibleParentListener ) );
        Help::HidePopover(pTipVisibleParent, nTipVisible );
        nTipVisible = nullptr;
        pTipVisibleParent = nullptr;
    }
    aManualTip.clear();
}
void ScInputHandler::HideTipBelow()
{
    if ( nTipVisibleSec )
    {
        pTipVisibleSecParent->RemoveEventListener( LINK( this, ScInputHandler, ShowHideTipVisibleSecParentListener ) );
        Help::HidePopover(pTipVisibleSecParent, nTipVisibleSec);
        nTipVisibleSec = nullptr;
        pTipVisibleSecParent = nullptr;
    }
    aManualTip.clear();
}

namespace
{

bool lcl_hasSingleToken(const OUString& s, sal_Unicode c)
{
    return !s.isEmpty() && s.indexOf(c)<0;
}

}

void ScInputHandler::ShowArgumentsTip( OUString& rSelText )
{
    if (comphelper::LibreOfficeKit::isActive())
    {
        return;
    }

    ScDocShell* pDocSh = pActiveViewSh->GetViewData().GetDocShell();
    const sal_Unicode cSep = ScCompiler::GetNativeSymbolChar(ocSep);
    const sal_Unicode cSheetSep = lcl_getSheetSeparator(&pDocSh->GetDocument());
    FormulaHelper aHelper(ScGlobal::GetStarCalcFunctionMgr());
    bool bFound = false;
    while( !bFound )
    {
        rSelText += ")";
        sal_Int32 nLeftParentPos = lcl_MatchParenthesis( rSelText, rSelText.getLength()-1 );
        if( nLeftParentPos != -1 )
        {
            sal_Int32 nNextFStart = aHelper.GetFunctionStart( rSelText, nLeftParentPos, true);
            const IFunctionDescription* ppFDesc;
            ::std::vector< OUString> aArgs;
            if( aHelper.GetNextFunc( rSelText, false, nNextFStart, nullptr, &ppFDesc, &aArgs ) )
            {
                if( !ppFDesc->getFunctionName().isEmpty() )
                {
                    sal_Int32 nArgPos = aHelper.GetArgStart( rSelText, nNextFStart, 0 );
                    sal_uInt16 nArgs = static_cast<sal_uInt16>(ppFDesc->getParameterCount());
                    OUString aFuncName( ppFDesc->getFunctionName() + "(");
                    OUString aNew;
                    ScTypedCaseStrSet::const_iterator it =
                        findText(*pFormulaDataPara, pFormulaDataPara->end(), aFuncName, aNew, false);
                    if (it != pFormulaDataPara->end())
                    {
                        bool bFlag = false;
                        sal_uInt16 nActive = 0;
                        for( sal_uInt16 i=0; i < nArgs; i++ )
                        {
                            sal_Int32 nLength = aArgs[i].getLength();
                            if( nArgPos <= rSelText.getLength()-1 )
                            {
                                nActive = i+1;
                                bFlag = true;
                            }
                            nArgPos+=nLength+1;
                        }
                        if( bFlag )
                        {
                            sal_Int32 nStartPosition = 0;
                            sal_Int32 nEndPosition = 0;

                            if( lcl_hasSingleToken(aNew, cSep) )
                            {
                                for (sal_Int32 i = 0; i < aNew.getLength(); ++i)
                                {
                                    sal_Unicode cNext = aNew[i];
                                    if( cNext == '(' )
                                    {
                                        nStartPosition = i+1;
                                    }
                                }
                            }
                            else if( lcl_hasSingleToken(aNew, cSheetSep) )
                            {
                                sal_uInt16 nCount = 0;
                                for (sal_Int32 i = 0; i < aNew.getLength(); ++i)
                                {
                                    sal_Unicode cNext = aNew[i];
                                    if( cNext == '(' )
                                    {
                                        nStartPosition = i+1;
                                    }
                                    else if( cNext == cSep )
                                    {
                                        nCount ++;
                                        nEndPosition = i;
                                        if( nCount == nActive )
                                        {
                                            break;
                                        }
                                        nStartPosition = nEndPosition+1;
                                    }
                                }
                            }
                            else
                            {
                                sal_uInt16 nCount = 0;
                                for (sal_Int32 i = 0; i < aNew.getLength(); ++i)
                                {
                                    sal_Unicode cNext = aNew[i];
                                    if( cNext == '(' )
                                    {
                                        nStartPosition = i+1;
                                    }
                                    else if( cNext == cSep )
                                    {
                                        nCount ++;
                                        nEndPosition = i;
                                        if( nCount == nActive )
                                        {
                                            break;
                                        }
                                        nStartPosition = nEndPosition+1;
                                    }
                                    else if( cNext == cSheetSep )
                                    {
                                        continue;
                                    }
                                }
                            }

                            if (nStartPosition > 0)
                            {
                                OUStringBuffer aBuf;
                                aBuf.appendCopy(aNew, 0, nStartPosition);
                                aBuf.append(u'\x25BA');
                                aBuf.appendCopy(aNew, nStartPosition);
                                nArgs = ppFDesc->getParameterCount();
                                sal_Int16 nVarArgsSet = 0;
                                if ( nArgs >= PAIRED_VAR_ARGS )
                                {
                                    nVarArgsSet = 2;
                                    nArgs -= PAIRED_VAR_ARGS - nVarArgsSet;
                                }
                                else if ( nArgs >= VAR_ARGS )
                                {
                                    nVarArgsSet = 1;
                                    nArgs -= VAR_ARGS - nVarArgsSet;
                                }
                                if ( nVarArgsSet > 0 && nActive > nArgs )
                                    nActive = nArgs - (nActive - nArgs) % nVarArgsSet;
                                aBuf.append( " : " );
                                aBuf.append( ppFDesc->getParameterDescription(nActive-1) );
                                aNew = aBuf.makeStringAndClear();
                                ShowTipBelow( aNew );
                                bFound = true;
                            }
                        }
                        else
                        {
                            ShowTipBelow( aNew );
                            bFound = true;
                        }
                    }
                }
            }
        }
        else
        {
            break;
        }
    }
}

void ScInputHandler::ShowTipCursor()
{
    HideTip();
    HideTipBelow();
    EditView* pActiveView = pTopView ? pTopView : pTableView;

    if ( bFormulaMode && pActiveView && pFormulaDataPara && mpEditEngine->GetParagraphCount() == 1 )
    {
        OUString aParagraph = mpEditEngine->GetText( 0 );
        ESelection aSel = pActiveView->GetSelection();
        aSel.Adjust();

        if ( aParagraph.getLength() < aSel.nEndPos )
            return;

        if ( aSel.nEndPos > 0 )
        {
            OUString aSelText( aParagraph.copy( 0, aSel.nEndPos ));

            ShowArgumentsTip( aSelText );
        }
    }
}

void ScInputHandler::ShowTip( const OUString& rText )
{
    // aManualTip needs to be set afterwards from outside

    HideTip();
    HideTipBelow();

    EditView* pActiveView = pTopView ? pTopView : pTableView;
    if (pActiveView)
    {
        Point aPos;
        pTipVisibleParent = pActiveView->GetWindow();
        vcl::Cursor* pCur = pActiveView->GetCursor();
        if (pCur)
            aPos = pTipVisibleParent->LogicToPixel( pCur->GetPos() );
        aPos = pTipVisibleParent->OutputToScreenPixel( aPos );
        tools::Rectangle aRect( aPos, aPos );

        QuickHelpFlags const nAlign = QuickHelpFlags::Left|QuickHelpFlags::Bottom;
        nTipVisible = Help::ShowPopover(pTipVisibleParent, aRect, rText, nAlign);
        pTipVisibleParent->AddEventListener( LINK( this, ScInputHandler, ShowHideTipVisibleParentListener ) );
    }
}

void ScInputHandler::ShowTipBelow( const OUString& rText )
{
    HideTipBelow();

    EditView* pActiveView = pTopView ? pTopView : pTableView;
    if ( pActiveView )
    {
        Point aPos;
        pTipVisibleSecParent = pActiveView->GetWindow();
        vcl::Cursor* pCur = pActiveView->GetCursor();
        if ( pCur )
        {
            Point aLogicPos = pCur->GetPos();
            aLogicPos.AdjustY(pCur->GetHeight() );
            aPos = pTipVisibleSecParent->LogicToPixel( aLogicPos );
        }
        aPos = pTipVisibleSecParent->OutputToScreenPixel( aPos );
        tools::Rectangle aRect( aPos, aPos );
        QuickHelpFlags const nAlign = QuickHelpFlags::Left | QuickHelpFlags::Top | QuickHelpFlags::NoEvadePointer;
        nTipVisibleSec = Help::ShowPopover(pTipVisibleSecParent, aRect, rText, nAlign);
        pTipVisibleSecParent->AddEventListener( LINK( this, ScInputHandler, ShowHideTipVisibleSecParentListener ) );
    }
}

bool ScInputHandler::GetFuncName( OUString& aStart, OUString& aResult )
{
    if ( aStart.isEmpty() )
        return false;

    aStart = ScGlobal::pCharClass->uppercase( aStart );
    sal_Int32 nPos = aStart.getLength() - 1;
    sal_Unicode c = aStart[ nPos ];
    // fdo#75264 use maFormulaChar to check if characters are used in function names
    ::std::set< sal_Unicode >::const_iterator p = maFormulaChar.find( c );
    if ( p == maFormulaChar.end() )
        return false; // last character is not part of any function name, quit

    ::std::vector<sal_Unicode> aTemp;
    aTemp.push_back( c );
    for(sal_Int32 i = nPos - 1; i >= 0; --i)
    {
        c = aStart[ i ];
        p = maFormulaChar.find( c );

        if (p == maFormulaChar.end())
            break;

        aTemp.push_back( c );
    }

    ::std::vector<sal_Unicode>::reverse_iterator rIt = aTemp.rbegin();
    aResult = OUString( *rIt++ );
    while ( rIt != aTemp.rend() )
        aResult += OUStringLiteral1( *rIt++ );

    return true;
}

namespace {
    /// Rid ourselves of unwanted " quoted json characters.
    OString escapeJSON(const OUString &aStr)
    {
        OUString aEscaped = aStr;
        aEscaped = aEscaped.replaceAll("\n", " ");
        aEscaped = aEscaped.replaceAll("\"", "'");
        return OUStringToOString(aEscaped, RTL_TEXTENCODING_UTF8);
    }
}

void ScInputHandler::ShowFuncList( const ::std::vector< OUString > & rFuncStrVec )
{
    const SfxViewShell* pViewShell = SfxViewShell::Current();
    if (comphelper::LibreOfficeKit::isActive() &&
            pViewShell && pViewShell->isLOKMobilePhone())
    {
        if (rFuncStrVec.size())
        {
            auto aPos = pFormulaData->begin();
            sal_uInt32 nCurIndex = std::distance(aPos, miAutoPosFormula);
            const sal_uInt32 nSize = pFormulaData->size();

            OUString aFuncNameStr;
            OUString aDescFuncNameStr;
            OStringBuffer aPayload;
            aPayload.append("[ ");
            for (const OUString& rFunc : rFuncStrVec)
            {
                if ( rFunc[rFunc.getLength()-1] == cParenthesesReplacement )
                {
                    aFuncNameStr = rFunc.copy(0, rFunc.getLength()-1);
                }
                else
                {
                    aFuncNameStr = rFunc;
                }

                FormulaHelper aHelper(ScGlobal::GetStarCalcFunctionMgr());
                aDescFuncNameStr = aFuncNameStr + "()";
                sal_Int32 nNextFStart = 0;
                const IFunctionDescription* ppFDesc;
                ::std::vector< OUString > aArgs;
                OUString eqPlusFuncName = "=" + aDescFuncNameStr;
                if ( aHelper.GetNextFunc( eqPlusFuncName, false, nNextFStart, nullptr, &ppFDesc, &aArgs ) )
                {
                    if ( !ppFDesc->getFunctionName().isEmpty() )
                    {
                        aPayload.append("{");
                        aPayload.append("\"index\": ");
                        aPayload.append(OString::number(nCurIndex));
                        aPayload.append(", ");
                        aPayload.append("\"signature\": \"");
                        aPayload.append(escapeJSON(ppFDesc->getSignature()));
                        aPayload.append("\", ");
                        aPayload.append("\"description\": \"");
                        aPayload.append(escapeJSON(ppFDesc->getDescription()));
                        aPayload.append("\"}, ");
                    }
                }
                ++nCurIndex;
                if (nCurIndex == nSize)
                    nCurIndex = 0;
            }
            sal_Int32 nLen = aPayload.getLength();
            aPayload[nLen - 2] = ' ';
            aPayload[nLen - 1] = ']';

            OString s = aPayload.makeStringAndClear();
            pViewShell->libreOfficeKitViewCallback(LOK_CALLBACK_CALC_FUNCTION_LIST, s.getStr());
        }
        return;
    }

    OUStringBuffer aTipStr;
    OUString aFuncNameStr;
    OUString aDescFuncNameStr;
    ::std::vector<OUString>::const_iterator itStr = rFuncStrVec.begin();
    sal_Int32 nMaxFindNumber = 3;
    sal_Int32 nRemainFindNumber = nMaxFindNumber;
    for ( ; itStr != rFuncStrVec.end(); ++itStr )
    {
        const OUString& rFunc = *itStr;
        if ( rFunc[rFunc.getLength()-1] == cParenthesesReplacement )
        {
            aFuncNameStr = rFunc.copy(0, rFunc.getLength()-1);
        }
        else
        {
            aFuncNameStr = rFunc;
        }
        if ( itStr == rFuncStrVec.begin() )
        {
            aTipStr = "[";
            aDescFuncNameStr = aFuncNameStr + "()";
        }
        else
        {
            aTipStr.append(", ");
        }
        aTipStr.append(aFuncNameStr);
        if ( itStr == rFuncStrVec.begin() )
            aTipStr.append("]");
        if ( --nRemainFindNumber <= 0 )
            break;
    }
    sal_Int32 nRemainNumber = rFuncStrVec.size() - nMaxFindNumber;
    if ( nRemainFindNumber == 0 && nRemainNumber > 0 )
    {
        OUString aMessage( ScResId( STR_FUNCTIONS_FOUND ) );
        aMessage = aMessage.replaceFirst("%2", OUString::number(nRemainNumber));
        aMessage = aMessage.replaceFirst("%1", aTipStr.makeStringAndClear());
        aTipStr = aMessage;
    }
    FormulaHelper aHelper(ScGlobal::GetStarCalcFunctionMgr());
    sal_Int32 nNextFStart = 0;
    const IFunctionDescription* ppFDesc;
    ::std::vector< OUString > aArgs;
    OUString eqPlusFuncName = "=" + aDescFuncNameStr;
    if ( aHelper.GetNextFunc( eqPlusFuncName, false, nNextFStart, nullptr, &ppFDesc, &aArgs ) )
    {
        if ( !ppFDesc->getFunctionName().isEmpty() )
        {
            aTipStr.append(" : ").append(ppFDesc->getDescription());
        }
    }
    ShowTip( aTipStr.makeStringAndClear() );
}

void ScInputHandler::UseFormulaData()
{
    EditView* pActiveView = pTopView ? pTopView : pTableView;

    // Formulas may only have 1 paragraph
    if ( pActiveView && pFormulaData && mpEditEngine->GetParagraphCount() == 1 )
    {
        OUString aParagraph = mpEditEngine->GetText( 0 );
        ESelection aSel = pActiveView->GetSelection();
        aSel.Adjust();

        // Due to differences between table and input cell (e.g clipboard with line breaks),
        // the selection may not be in line with the EditEngine anymore.
        // Just return without any indication as to why.
        if ( aSel.nEndPos > aParagraph.getLength() )
            return;

        if ( aParagraph.getLength() > aSel.nEndPos &&
             ( ScGlobal::pCharClass->isLetterNumeric( aParagraph, aSel.nEndPos ) ||
               aParagraph[ aSel.nEndPos ] == '_' ||
               aParagraph[ aSel.nEndPos ] == '.' ||
               aParagraph[ aSel.nEndPos ] == '$'   ) )
            return;

        //  Is the cursor at the end of a word?
        if ( aSel.nEndPos > 0 )
        {
            OUString aSelText( aParagraph.copy( 0, aSel.nEndPos ));

            OUString aText;
            if ( GetFuncName( aSelText, aText ) )
            {
                // function name is incomplete:
                // show matching functions name as tip above cell
                ::std::vector<OUString> aNewVec;
                miAutoPosFormula = pFormulaData->end();
                miAutoPosFormula = findTextAll(*pFormulaData, miAutoPosFormula, aText, aNewVec, false);
                if (miAutoPosFormula != pFormulaData->end())
                {
                    // check if partial function name is not between quotes
                    sal_Unicode cBetweenQuotes = 0;
                    for ( int n = 0; n < aSelText.getLength(); n++ )
                    {
                        if (cBetweenQuotes)
                        {
                            if (aSelText[n] == cBetweenQuotes)
                                cBetweenQuotes = 0;
                        }
                        else if ( aSelText[ n ] == '"' )
                            cBetweenQuotes = '"';
                        else if ( aSelText[ n ] == '\'' )
                            cBetweenQuotes = '\'';
                    }
                    if ( cBetweenQuotes )
                        return;  // we're between quotes

                    ShowFuncList(aNewVec);
                    aAutoSearch = aText;
                }
                return;
            }

            // function name is complete:
            // show tip below the cell with function name and arguments of function
            ShowArgumentsTip( aSelText );
        }
    }
}

void ScInputHandler::NextFormulaEntry( bool bBack )
{
    EditView* pActiveView = pTopView ? pTopView : pTableView;
    if ( pActiveView && pFormulaData )
    {
        ::std::vector<OUString> aNewVec;
        ScTypedCaseStrSet::const_iterator itNew = findTextAll(*pFormulaData, miAutoPosFormula, aAutoSearch, aNewVec, bBack);
        if (itNew != pFormulaData->end())
        {
            miAutoPosFormula = itNew;
            ShowFuncList( aNewVec );
        }
    }

    // For Tab we always call HideCursor first
    if (pActiveView)
        pActiveView->ShowCursor();
}

namespace {

bool needToExtendSelection(const OUString& rSelectedText, const OUString& rInsertText)
{
    return !ScGlobal::GetpTransliteration()->isMatch( rSelectedText, rInsertText);
}

void completeFunction( EditView* pView, const OUString& rInsert, bool& rParInserted )
{
    if (pView)
    {
        ESelection aSel = pView->GetSelection();
        --aSel.nStartPos;
        --aSel.nEndPos;
        pView->SetSelection(aSel);
        pView->SelectCurrentWord();

        bool bNoInitialLetter = false;
        OUString aSelectedText = pView->GetSelected();
        OUString aOld = pView->GetEditEngine()->GetText(0);
        // in case we want just insert a function and not completing
        if ( comphelper::LibreOfficeKit::isActive() )
        {
            if ( aOld == "=" )
            {
                bNoInitialLetter = true;
                aSel.nStartPos = 1;
                aSel.nEndPos = 1;
                pView->SetSelection(aSel);
            }
            else if ( aSelectedText.startsWith("()") )
            {
                bNoInitialLetter = true;
                ++aSel.nStartPos;
                ++aSel.nEndPos;
                pView->SetSelection(aSel);
            }
        }
        // a dot and underscore are word separators so we need special
        // treatment for any formula containing a dot or underscore
        if(!bNoInitialLetter && (rInsert.indexOf(".") != -1 || rInsert.indexOf("_") != -1))
        {
            // need to make sure that we replace also the part before the dot
            // go through the word to find the match with the insert string
            aSel = pView->GetSelection();
            ESelection aOldSelection = aSel;

            if ( needToExtendSelection( aSelectedText, rInsert ) )
            {
                while(needToExtendSelection(aSelectedText, rInsert))
                {
                    assert(aSel.nStartPos > 0);
                    --aSel.nStartPos;
                    aSel.nEndPos = aSel.nStartPos;
                    pView->SetSelection(aSel);
                    pView->SelectCurrentWord();
                    aSelectedText = pView->GetSelected();
                }
                aSel.nStartPos = aSel.nEndPos - ( aSelectedText.getLength() - 1 );
            }
            else
            {
                aSel.nStartPos = aSel.nEndPos - aSelectedText.getLength();
            }
            aSel.nEndPos = aOldSelection.nEndPos;
            pView->SetSelection(aSel);
        }

        OUString aInsStr = rInsert;
        sal_Int32 nInsLen = aInsStr.getLength();
        bool bDoParen = ( nInsLen > 1 && aInsStr[nInsLen-2] == '('
                                      && aInsStr[nInsLen-1] == ')' );
        if ( bDoParen )
        {
            // Do not insert parentheses after function names if there already are some
            // (e.g. if the function name was edited).
            ESelection aWordSel = pView->GetSelection();

            // aWordSel.EndPos points one behind string if word at end
            if (aWordSel.nEndPos < aOld.getLength())
            {
                sal_Unicode cNext = aOld[aWordSel.nEndPos];
                if ( cNext == '(' )
                {
                    bDoParen = false;
                    aInsStr = aInsStr.copy( 0, nInsLen - 2 ); // Skip parentheses
                }
            }
        }

        pView->InsertText( aInsStr );

        if ( bDoParen ) // Put cursor between parentheses
        {
            aSel = pView->GetSelection();
            --aSel.nStartPos;
            --aSel.nEndPos;
            pView->SetSelection(aSel);

            rParInserted = true;
        }
    }
}

}

void ScInputHandler::PasteFunctionData()
{
    if (pFormulaData && miAutoPosFormula != pFormulaData->end())
    {
        const ScTypedStrData& rData = *miAutoPosFormula;
        OUString aInsert = rData.GetString();
        if (aInsert[aInsert.getLength()-1] == cParenthesesReplacement)
            aInsert = aInsert.copy( 0, aInsert.getLength()-1) + "()";
        bool bParInserted = false;

        DataChanging(); // Cannot be new
        completeFunction( pTopView, aInsert, bParInserted );
        completeFunction( pTableView, aInsert, bParInserted );
        DataChanged();
        ShowTipCursor();

        if (bParInserted)
            AutoParAdded();
    }

    HideTip();

    EditView* pActiveView = pTopView ? pTopView : pTableView;
    if (comphelper::LibreOfficeKit::isActive() && pTopView && pInputWin)
        pInputWin->TextGrabFocus();
    if (pActiveView)
        pActiveView->ShowCursor();
}

void ScInputHandler::LOKPasteFunctionData(const OUString& rFunctionName)
{
    // in case we have no top view try to create it
    if (!pTopView && pInputWin)
    {
        ScInputMode eCurMode = eMode;
        SetMode(SC_INPUT_TOP);
        if (!pTopView)
            SetMode(eCurMode);
    }

    EditView* pEditView = pTopView ? pTopView : pTableView;

    if (pActiveViewSh && pEditView)
    {
        bool bEdit = false;
        OUString aFormula;
        const EditEngine* pEditEngine = pEditView->GetEditEngine();
        if (pEditEngine)
        {
            aFormula = pEditEngine->GetText(0);
            bEdit = aFormula.getLength() > 1 && (aFormula[0] == '=' || aFormula[0] == '+' || aFormula[0] == '-');
        }

        if ( !bEdit )
        {
            OUString aNewFormula('=');
            if ( aFormula.startsWith("=") )
                aNewFormula = aFormula;

            InputReplaceSelection( aNewFormula );
        }

        if (pFormulaData)
        {
            OUString aNew;
            ScTypedCaseStrSet::const_iterator aPos = findText(*pFormulaData, pFormulaData->begin(), rFunctionName, aNew, /* backward = */false);

            if (aPos != pFormulaData->end())
            {
                miAutoPosFormula = aPos;
                PasteFunctionData();
            }
        }
    }
}

// Calculate selection and display as tip help
static OUString lcl_Calculate( const OUString& rFormula, ScDocument* pDoc, const ScAddress &rPos )
{
    //TODO: Merge with ScFormulaDlg::CalcValue and move into Document!
    // Quotation marks for Strings are only inserted here.

    if(rFormula.isEmpty())
        return OUString();

    std::unique_ptr<ScSimpleFormulaCalculator> pCalc( new ScSimpleFormulaCalculator( pDoc, rPos, rFormula, false ) );

    // FIXME: HACK! In order to not get a #REF! for ColRowNames, if a name is actually inserted as a Range
    // into the whole Formula, but is interpreted as a single cell reference when displaying it on its own
    bool bColRowName = pCalc->HasColRowName();
    if ( bColRowName )
    {
        // ColRowName in RPN code?
        if ( pCalc->GetCode()->GetCodeLen() <= 1 )
        {   // ==1: Single one is as a Parameter always a Range
            // ==0: It might be one, if ...
            OUStringBuffer aBraced;
            aBraced.append('(');
            aBraced.append(rFormula);
            aBraced.append(')');
            pCalc.reset( new ScSimpleFormulaCalculator( pDoc, rPos, aBraced.makeStringAndClear(), false ) );
        }
        else
            bColRowName = false;
    }

    FormulaError nErrCode = pCalc->GetErrCode();
    if ( nErrCode != FormulaError::NONE )
        return ScGlobal::GetErrorString(nErrCode);

    SvNumberFormatter& aFormatter = *(pDoc->GetFormatTable());
    OUString aValue;
    if ( pCalc->IsValue() )
    {
        double n = pCalc->GetValue();
        sal_uInt32 nFormat = aFormatter.GetStandardFormat( n, 0,
                pCalc->GetFormatType(), ScGlobal::eLnge );
        aFormatter.GetInputLineString( n, nFormat, aValue );
        //! display OutputString but insert InputLineString
    }
    else
    {
        OUString aStr = pCalc->GetString().getString();
        sal_uInt32 nFormat = aFormatter.GetStandardFormat(
                pCalc->GetFormatType(), ScGlobal::eLnge);
        {
            Color* pColor;
            aFormatter.GetOutputString( aStr, nFormat,
                    aValue, &pColor );
        }

        aValue = "\"" + aValue + "\"";
        //! Escape quotation marks in String??
    }

    ScRange aTestRange;
    if ( bColRowName || (aTestRange.Parse(rFormula) & ScRefFlags::VALID) )
        aValue = aValue + " ...";

    return aValue;
}

void ScInputHandler::FormulaPreview()
{
    OUString aValue;
    EditView* pActiveView = pTopView ? pTopView : pTableView;
    if ( pActiveView && pActiveViewSh )
    {
        OUString aPart = pActiveView->GetSelected();
        if (aPart.isEmpty())
            aPart = mpEditEngine->GetText(0);
        ScDocument& rDoc = pActiveViewSh->GetViewData().GetDocShell()->GetDocument();
        aValue = lcl_Calculate( aPart, &rDoc, aCursorPos );
    }

    if (!aValue.isEmpty())
    {
        ShowTip( aValue );          //  Display as QuickHelp
        aManualTip = aValue;        //  Set after ShowTip
        if (pFormulaData)
            miAutoPosFormula = pFormulaData->end();
        if (pColumnData)
            miAutoPosColumn = pColumnData->end();
    }
}

void ScInputHandler::PasteManualTip()
{
    //  Three dots at the end -> Range reference -> do not insert
    //  FIXME: Once we have matrix constants, we can change this
    sal_Int32 nTipLen = aManualTip.getLength();
    sal_uInt32 const nTipLen2(sal::static_int_cast<sal_uInt32>(nTipLen));
    if ( nTipLen && ( nTipLen < 3 || aManualTip.copy( nTipLen2-3 ) != "..." ) )
    {
        DataChanging(); // Cannot be new

        OUString aInsert = aManualTip;
        EditView* pActiveView = pTopView ? pTopView : pTableView;
        if (!pActiveView->HasSelection())
        {
            // Nothing selected -> select everything
            sal_Int32 nOldLen = mpEditEngine->GetTextLen(0);
            ESelection aAllSel( 0, 0, 0, nOldLen );
            if ( pTopView )
                pTopView->SetSelection( aAllSel );
            if ( pTableView )
                pTableView->SetSelection( aAllSel );
        }

        ESelection aSel = pActiveView->GetSelection();
        aSel.Adjust();
        OSL_ENSURE( !aSel.nStartPara && !aSel.nEndPara, "Too many paragraphs in Formula" );
        if ( !aSel.nStartPos )  // Selection from the start?
        {
            if ( aSel.nEndPos == mpEditEngine->GetTextLen(0) )
            {
                //  Everything selected -> skip quotation marks
                if ( aInsert[0] == '"' )
                    aInsert = aInsert.copy(1);
                sal_Int32 nInsLen = aInsert.getLength();
                if ( aInsert.endsWith("\"") )
                    aInsert = aInsert.copy( 0, nInsLen-1 );
            }
            else if ( aSel.nEndPos )
            {
                //  Not everything selected -> do not overwrite equality sign
                //FIXME: Even double equality signs??
                aSel.nStartPos = 1;
                if ( pTopView )
                    pTopView->SetSelection( aSel );
                if ( pTableView )
                    pTableView->SetSelection( aSel );
            }
        }
        if ( pTopView )
            pTopView->InsertText( aInsert, true );
        if ( pTableView )
            pTableView->InsertText( aInsert, true );

        DataChanged();
    }

    HideTip();
}

void ScInputHandler::ResetAutoPar()
{
    nAutoPar = 0;
}

void ScInputHandler::AutoParAdded()
{
    ++nAutoPar; // Closing parenthesis can be overwritten
}

bool ScInputHandler::CursorAtClosingPar()
{
    // Test if the cursor is before a closing parenthesis
    // Selection from SetReference has been removed before
    EditView* pActiveView = pTopView ? pTopView : pTableView;
    if ( pActiveView && !pActiveView->HasSelection() && bFormulaMode )
    {
        ESelection aSel = pActiveView->GetSelection();
        sal_Int32 nPos = aSel.nStartPos;
        OUString aFormula = mpEditEngine->GetText(0);
        if ( nPos < aFormula.getLength() && aFormula[nPos] == ')' )
            return true;
    }
    return false;
}

void ScInputHandler::SkipClosingPar()
{
    //  this is called when a ')' is typed and the cursor is before a ')'
    //  that can be overwritten -> just set the cursor behind the ')'

    EditView* pActiveView = pTopView ? pTopView : pTableView;
    if (pActiveView)
    {
        ESelection aSel = pActiveView->GetSelection();
        ++aSel.nStartPos;
        ++aSel.nEndPos;

        //  this is in a formula (only one paragraph), so the selection
        //  can be used directly for the TopView

        if ( pTopView )
            pTopView->SetSelection( aSel );
        if ( pTableView )
            pTableView->SetSelection( aSel );
    }

    OSL_ENSURE(nAutoPar, "SkipClosingPar: count is wrong");
    --nAutoPar;
}

// Auto input

void ScInputHandler::GetColData()
{
    if ( pActiveViewSh )
    {
        ScDocument& rDoc = pActiveViewSh->GetViewData().GetDocShell()->GetDocument();

        if ( pColumnData )
            pColumnData->clear();
        else
            pColumnData.reset( new ScTypedCaseStrSet );

        std::vector<ScTypedStrData> aEntries;
        rDoc.GetDataEntries(
            aCursorPos.Col(), aCursorPos.Row(), aCursorPos.Tab(), aEntries, true);
        if (!aEntries.empty())
            pColumnData->insert(aEntries.begin(), aEntries.end());

        miAutoPosColumn = pColumnData->end();
    }
}

void ScInputHandler::UseColData() // When typing
{
    EditView* pActiveView = pTopView ? pTopView : pTableView;
    if ( pActiveView && pColumnData )
    {
        //  Only change when cursor is at the end
        ESelection aSel = pActiveView->GetSelection();
        aSel.Adjust();

        sal_Int32 nParCnt = mpEditEngine->GetParagraphCount();
        if ( aSel.nEndPara+1 == nParCnt )
        {
            sal_Int32 nParLen = mpEditEngine->GetTextLen( aSel.nEndPara );
            if ( aSel.nEndPos == nParLen )
            {
                OUString aText = GetEditText(mpEditEngine.get());
                if (!aText.isEmpty())
                {
                    OUString aNew;
                    miAutoPosColumn = pColumnData->end();
                    miAutoPosColumn = findText(*pColumnData, miAutoPosColumn, aText, aNew, false);
                    if (miAutoPosColumn != pColumnData->end())
                    {
                        // Strings can contain line endings (e.g. due to dBase import),
                        // which would result in multiple paragraphs here, which is not desirable.
                        //! Then GetExactMatch doesn't work either
                        lcl_RemoveLineEnd( aNew );

                        // Keep paragraph, just append the rest
                        //! Exact replacement in EnterHandler !!!
                        // One Space between paragraphs:
                        sal_Int32 nEdLen = mpEditEngine->GetTextLen() + nParCnt - 1;
                        OUString aIns = aNew.copy(nEdLen);

                        // Selection must be "backwards", so the cursor stays behind the last
                        // typed character
                        ESelection aSelection( aSel.nEndPara, aSel.nEndPos + aIns.getLength(),
                                               aSel.nEndPara, aSel.nEndPos );

                        // When editing in input line, apply to both edit views
                        if ( pTableView )
                        {
                            pTableView->InsertText( aIns );
                            pTableView->SetSelection( aSelection );
                        }
                        if ( pTopView )
                        {
                            pTopView->InsertText( aIns );
                            pTopView->SetSelection( aSelection );
                        }

                        aAutoSearch = aText; // To keep searching - nAutoPos is set

                        if (aText.getLength() == aNew.getLength())
                        {
                            // If the inserted text is found, consume TAB only if there's more coming
                            OUString aDummy;
                            ScTypedCaseStrSet::const_iterator itNextPos =
                                findText(*pColumnData, miAutoPosColumn, aText, aDummy, false);
                            bUseTab = itNextPos != pColumnData->end();
                        }
                        else
                            bUseTab = true;
                    }
                }
            }
        }
    }
}

void ScInputHandler::NextAutoEntry( bool bBack )
{
    EditView* pActiveView = pTopView ? pTopView : pTableView;
    if ( pActiveView && pColumnData )
    {
        if (miAutoPosColumn != pColumnData->end() && !aAutoSearch.isEmpty())
        {
            // Is the selection still valid (could be changed via the mouse)?
            ESelection aSel = pActiveView->GetSelection();
            aSel.Adjust();
            sal_Int32 nParCnt = mpEditEngine->GetParagraphCount();
            if ( aSel.nEndPara+1 == nParCnt && aSel.nStartPara == aSel.nEndPara )
            {
                OUString aText = GetEditText(mpEditEngine.get());
                sal_Int32 nSelLen = aSel.nEndPos - aSel.nStartPos;
                sal_Int32 nParLen = mpEditEngine->GetTextLen( aSel.nEndPara );
                if ( aSel.nEndPos == nParLen && aText.getLength() == aAutoSearch.getLength() + nSelLen )
                {
                    OUString aNew;
                    ScTypedCaseStrSet::const_iterator itNew =
                        findText(*pColumnData, miAutoPosColumn, aAutoSearch, aNew, bBack);

                    if (itNew != pColumnData->end())
                    {
                        // match found!
                        miAutoPosColumn = itNew;
                        bInOwnChange = true;        // disable ModifyHdl (reset below)

                        lcl_RemoveLineEnd( aNew );
                        OUString aIns = aNew.copy(aAutoSearch.getLength());

                        //  when editing in input line, apply to both edit views
                        if ( pTableView )
                        {
                            pTableView->DeleteSelected();
                            pTableView->InsertText( aIns );
                            pTableView->SetSelection( ESelection(
                                                        aSel.nEndPara, aSel.nStartPos + aIns.getLength(),
                                                        aSel.nEndPara, aSel.nStartPos ) );
                        }
                        if ( pTopView )
                        {
                            pTopView->DeleteSelected();
                            pTopView->InsertText( aIns );
                            pTopView->SetSelection( ESelection(
                                                        aSel.nEndPara, aSel.nStartPos + aIns.getLength(),
                                                        aSel.nEndPara, aSel.nStartPos ) );
                        }

                        bInOwnChange = false;
                    }
                }
            }
        }
    }

    // For Tab, HideCursor was always called first
    if (pActiveView)
        pActiveView->ShowCursor();
}

// Highlight parentheses
void ScInputHandler::UpdateParenthesis()
{
    // Find parentheses
    //TODO: Can we disable parentheses highlighting per parentheses?
    bool bFound = false;
    if ( bFormulaMode && eMode != SC_INPUT_TOP )
    {
        if ( pTableView && !pTableView->HasSelection() ) // Selection is always at the bottom
        {
            ESelection aSel = pTableView->GetSelection();
            if (aSel.nStartPos)
            {
                // Examine character left to the cursor
                sal_Int32 nPos = aSel.nStartPos - 1;
                OUString aFormula = mpEditEngine->GetText(0);
                sal_Unicode c = aFormula[nPos];
                if ( c == '(' || c == ')' )
                {
                    sal_Int32 nOther = lcl_MatchParenthesis( aFormula, nPos );
                    if ( nOther != -1 )
                    {
                        SfxItemSet aSet( mpEditEngine->GetEmptyItemSet() );
                        aSet.Put( SvxWeightItem( WEIGHT_BOLD, EE_CHAR_WEIGHT ) );

                        //! Distinguish if cell is already highlighted!!!!
                        if (bParenthesisShown)
                        {
                            // Remove old highlighting
                            sal_Int32 nCount = mpEditEngine->GetParagraphCount();
                            for (sal_Int32 i=0; i<nCount; i++)
                                mpEditEngine->RemoveCharAttribs( i, EE_CHAR_WEIGHT );
                        }

                        ESelection aSelThis( 0,nPos, 0,nPos+1 );
                        mpEditEngine->QuickSetAttribs( aSet, aSelThis );
                        ESelection aSelOther( 0,nOther, 0,nOther+1 );
                        mpEditEngine->QuickSetAttribs( aSet, aSelOther );

                        // Dummy InsertText for Update and Paint (selection is empty)
                        pTableView->InsertText( EMPTY_OUSTRING );

                        bFound = true;
                    }
                }
            }

            //  mark parenthesis right of cursor if it will be overwritten (nAutoPar)
            //  with different color (COL_LIGHTBLUE) ??
        }
    }

    // Remove old highlighting, if no new one is set
    if ( bParenthesisShown && !bFound && pTableView )
    {
        sal_Int32 nCount = mpEditEngine->GetParagraphCount();
        for (sal_Int32 i=0; i<nCount; i++)
            pTableView->RemoveCharAttribs( i, EE_CHAR_WEIGHT );
    }

    bParenthesisShown = bFound;
}

void ScInputHandler::ViewShellGone(const ScTabViewShell* pViewSh) // Executed synchronously!
{
    if ( pViewSh == pActiveViewSh )
    {
        pLastState.reset();
        pLastPattern = nullptr;
    }

    if ( pViewSh == pRefViewSh )
    {
        //! The input from the EnterHandler does not arrive anymore
        // We end the EditMode anyways
        EnterHandler();
        bFormulaMode = false;
        pRefViewSh = nullptr;
        SfxGetpApp()->Broadcast( SfxHint( SfxHintId::ScRefModeChanged ) );
        SC_MOD()->SetRefInputHdl(nullptr);
        if (pInputWin)
            pInputWin->SetFormulaMode(false);
        UpdateAutoCorrFlag();
    }

    pActiveViewSh = dynamic_cast<ScTabViewShell*>( SfxViewShell::Current()  );

    if ( pActiveViewSh && pActiveViewSh == pViewSh )
    {
        OSL_FAIL("pActiveViewSh is gone");
        pActiveViewSh = nullptr;
    }

    if ( SC_MOD()->GetInputOptions().GetTextWysiwyg() )
        UpdateRefDevice(); // Don't keep old document's printer as RefDevice
}

void ScInputHandler::UpdateActiveView()
{
    ImplCreateEditEngine();

    // #i20588# Don't rely on focus to find the active edit view. Instead, the
    // active pane at the start of editing is now stored (GetEditActivePart).
    // GetActiveWin (the currently active pane) fails for ref input across the
    // panes of a split view.

    vcl::Window* pShellWin = pActiveViewSh ?
                pActiveViewSh->GetWindowByPos( pActiveViewSh->GetViewData().GetEditActivePart() ) :
                nullptr;

    sal_uInt16 nCount = mpEditEngine->GetViewCount();
    if (nCount > 0)
    {
        pTableView = mpEditEngine->GetView();
        for (sal_uInt16 i=1; i<nCount; i++)
        {
            EditView* pThis = mpEditEngine->GetView(i);
            vcl::Window* pWin = pThis->GetWindow();
            if ( pWin==pShellWin )
                pTableView = pThis;
        }
    }
    else
        pTableView = nullptr;

    // setup the pTableView editeng for tiled rendering to get cursor and selections
    if (pTableView && pActiveViewSh)
    {
        if (comphelper::LibreOfficeKit::isActive())
        {
            pTableView->RegisterViewShell(pActiveViewSh);
        }
    }

    if (pInputWin && (eMode == SC_INPUT_TOP || eMode == SC_INPUT_TABLE))
    {
        // tdf#71409: Always create the edit engine instance for the input
        // window, in order to properly manage accessibility events.
        pTopView = pInputWin->GetEditView();
        if (eMode != SC_INPUT_TOP)
            pTopView = nullptr;
    }
    else
        pTopView = nullptr;
}

void ScInputHandler::SetInputWindow(  ScInputWindow* pNew )
{
    pInputWin = pNew;
}

void ScInputHandler::StopInputWinEngine( bool bAll )
{
    if (pInputWin && !pInputWin->IsDisposed())
        pInputWin->StopEditEngine( bAll );

    pTopView = nullptr; // invalid now
}

EditView* ScInputHandler::GetActiveView()
{
    UpdateActiveView();
    return pTopView ? pTopView : pTableView;
}

void ScInputHandler::ForgetLastPattern()
{
    pLastPattern = nullptr;
    if ( !pLastState && pActiveViewSh )
        pActiveViewSh->UpdateInputHandler( true ); // Get status again
    else
        NotifyChange( pLastState.get(), true );
}

void ScInputHandler::UpdateAdjust( sal_Unicode cTyped )
{
    SvxAdjust eSvxAdjust;
    switch (eAttrAdjust)
    {
        case SvxCellHorJustify::Standard:
            {
                bool bNumber = false;
                if (cTyped)                                     // Restarted
                    bNumber = (cTyped>='0' && cTyped<='9');     // Only ciphers are numbers
                else if ( pActiveViewSh )
                {
                    ScDocument& rDoc = pActiveViewSh->GetViewData().GetDocShell()->GetDocument();
                    bNumber = ( rDoc.GetCellType( aCursorPos ) == CELLTYPE_VALUE );
                }
                eSvxAdjust = bNumber ? SvxAdjust::Right : SvxAdjust::Left;
            }
            break;
        case SvxCellHorJustify::Block:
            eSvxAdjust = SvxAdjust::Block;
            break;
        case SvxCellHorJustify::Center:
            eSvxAdjust = SvxAdjust::Center;
            break;
        case SvxCellHorJustify::Right:
            eSvxAdjust = SvxAdjust::Right;
            break;
        default:    // SvxCellHorJustify::Left
            eSvxAdjust = SvxAdjust::Left;
            break;
    }

    bool bAsianVertical = pLastPattern &&
        pLastPattern->GetItem( ATTR_STACKED ).GetValue() &&
        pLastPattern->GetItem( ATTR_VERTICAL_ASIAN ).GetValue();
    if ( bAsianVertical )
    {
        // Always edit at top of cell -> LEFT when editing vertically
        eSvxAdjust = SvxAdjust::Left;
    }

    pEditDefaults->Put( SvxAdjustItem( eSvxAdjust, EE_PARA_JUST ) );
    mpEditEngine->SetDefaults( *pEditDefaults );

    if ( pActiveViewSh )
    {
        pActiveViewSh->GetViewData().SetEditAdjust( eSvxAdjust );
    }
    mpEditEngine->SetVertical( bAsianVertical );
}

void ScInputHandler::RemoveAdjust()
{
    // Delete hard alignment attributes
    bool bUndo = mpEditEngine->IsUndoEnabled();
    if ( bUndo )
        mpEditEngine->EnableUndo( false );

    // Non-default paragraph attributes (e.g. from clipboard)
    // must be turned into character attributes
    mpEditEngine->RemoveParaAttribs();

    if ( bUndo )
        mpEditEngine->EnableUndo( true );

}

void ScInputHandler::RemoveRangeFinder()
{
    // Delete pRangeFindList and colors
    mpEditEngine->SetUpdateMode(false);
    sal_Int32 nCount = mpEditEngine->GetParagraphCount(); // Could just have been inserted
    for (sal_Int32 i=0; i<nCount; i++)
        mpEditEngine->RemoveCharAttribs( i, EE_CHAR_COLOR );
    mpEditEngine->SetUpdateMode(true);

    EditView* pActiveView = pTopView ? pTopView : pTableView;
    pActiveView->ShowCursor( false );

    DeleteRangeFinder(); // Deletes the list and the labels on the table
}

bool ScInputHandler::StartTable( sal_Unicode cTyped, bool bFromCommand, bool bInputActivated,
        ScEditEngineDefaulter* pTopEngine )
{
    bool bNewTable = false;

    if (bModified || !ValidCol(aCursorPos.Col()))
        return false;

    if (pActiveViewSh)
    {
        ImplCreateEditEngine();
        UpdateActiveView();
        SyncViews();

        ScDocument& rDoc = pActiveViewSh->GetViewData().GetDocShell()->GetDocument();

        const ScMarkData& rMark = pActiveViewSh->GetViewData().GetMarkData();
        ScEditableTester aTester;
        if ( rMark.IsMarked() || rMark.IsMultiMarked() )
            aTester.TestSelection( &rDoc, rMark );
        else
            aTester.TestSelectedBlock(
                &rDoc, aCursorPos.Col(), aCursorPos.Row(), aCursorPos.Col(), aCursorPos.Row(), rMark );

        bool bStartInputMode = true;

        if (!aTester.IsEditable())
        {
            bProtected = true;
            // We allow read-only input mode activation regardless
            // whether it's part of an array or not or whether explicit cell
            // activation is requested (double-click or F2) or a click in input
            // line.
            bool bShowError = (!bInputActivated || !aTester.GetMessageId() || strcmp(aTester.GetMessageId(), STR_PROTECTIONERR) != 0) &&
                !pActiveViewSh->GetViewData().GetDocShell()->IsReadOnly();
            if (bShowError)
            {
                eMode = SC_INPUT_NONE;
                StopInputWinEngine( true );
                UpdateFormulaMode();
                if ( pActiveViewSh && ( !bFromCommand || !bCommandErrorShown ) )
                {
                    //  Prevent repeated error messages for the same cell from command events
                    //  (for keyboard events, multiple messages are wanted).
                    //  Set the flag before showing the error message because the command handler
                    //  for the next IME command may be called when showing the dialog.
                    if ( bFromCommand )
                        bCommandErrorShown = true;

                    pActiveViewSh->GetActiveWin()->GrabFocus();
                    pActiveViewSh->ErrorMessage(aTester.GetMessageId());
                }
                bStartInputMode = false;
            }
        }

        if (bStartInputMode)
        {
            // UpdateMode is enabled again in ScViewData::SetEditEngine (and not needed otherwise)
            mpEditEngine->SetUpdateMode( false );

            // Take over attributes in EditEngine
            const ScPatternAttr* pPattern = rDoc.GetPattern( aCursorPos.Col(),
                                                              aCursorPos.Row(),
                                                              aCursorPos.Tab() );
            if (pPattern != pLastPattern)
            {
                // Percent format?
                const SfxItemSet& rAttrSet = pPattern->GetItemSet();
                const SfxPoolItem* pItem;

                if ( SfxItemState::SET == rAttrSet.GetItemState( ATTR_VALUE_FORMAT, true, &pItem ) )
                {
                    sal_uInt32 nFormat = static_cast<const SfxUInt32Item*>(pItem)->GetValue();
                    bCellHasPercentFormat = ( SvNumFormatType::PERCENT ==
                                              rDoc.GetFormatTable()->GetType( nFormat ) );
                }
                else
                    bCellHasPercentFormat = false; // Default: no percent

                // Validity specified?
                if ( SfxItemState::SET == rAttrSet.GetItemState( ATTR_VALIDDATA, true, &pItem ) )
                    nValidation = static_cast<const SfxUInt32Item*>(pItem)->GetValue();
                else
                    nValidation = 0;

                //  EditEngine Defaults
                //  In no case SetParaAttribs, because the EditEngine might already
                //  be filled (for Edit cells).
                //  SetParaAttribs would change the content.

                //! The SetDefaults is now (since MUST/src602
                //! EditEngine changes) implemented as a SetParaAttribs.
                //! Any problems?

                pPattern->FillEditItemSet( pEditDefaults.get() );
                mpEditEngine->SetDefaults( *pEditDefaults );
                pLastPattern = pPattern;
                bLastIsSymbol = pPattern->IsSymbolFont();

                //  Background color must be known for automatic font color.
                //  For transparent cell background, the document background color must be used.

                Color aBackCol = pPattern->GetItem( ATTR_BACKGROUND ).GetColor();
                ScModule* pScMod = SC_MOD();
                if ( aBackCol.GetTransparency() > 0 ||
                        Application::GetSettings().GetStyleSettings().GetHighContrastMode() )
                    aBackCol = pScMod->GetColorConfig().GetColorValue(svtools::DOCCOLOR).nColor;
                mpEditEngine->SetBackgroundColor( aBackCol );

                // Adjustment
                eAttrAdjust = pPattern->GetItem(ATTR_HOR_JUSTIFY).GetValue();
                if ( eAttrAdjust == SvxCellHorJustify::Repeat &&
                     pPattern->GetItem(ATTR_LINEBREAK).GetValue() )
                {
                    // #i31843# "repeat" with "line breaks" is treated as default alignment
                    eAttrAdjust = SvxCellHorJustify::Standard;
                }
            }

            if (pTopEngine)
            {
                // Necessary to sync SvxAutoCorrect behavior. This has to be
                // done before InitRangeFinder() below.
                MergeLanguageAttributes( *pTopEngine);
            }

            //  UpdateSpellSettings enables online spelling if needed
            //  -> also call if attributes are unchanged
            UpdateSpellSettings( true ); // uses pLastPattern

            // Fill EditEngine
            OUString aStr;
            if (bTextValid)
            {
                mpEditEngine->SetText(aCurrentText);
                aStr = aCurrentText;
                bTextValid = false;
                aCurrentText.clear();
            }
            else
                aStr = GetEditText(mpEditEngine.get());

            if (aStr.startsWith("{=") && aStr.endsWith("}") )  // Matrix formula?
            {
                aStr = aStr.copy(1, aStr.getLength() -2);
                mpEditEngine->SetText(aStr);
                if ( pInputWin )
                    pInputWin->SetTextString(aStr);
            }

            UpdateAdjust( cTyped );

            if ( bAutoComplete )
                GetColData();

            if ( !aStr.isEmpty() && ( aStr[0] == '=' || aStr[0] == '+' || aStr[0] == '-' ) &&
                 !cTyped && !bCreatingFuncView )
                InitRangeFinder(aStr); // Formula is being edited -> RangeFinder

            bNewTable = true; // -> PostEditView Call
        }
    }

    if (!bProtected && pInputWin)
        pInputWin->SetOkCancelMode();

    return bNewTable;
}

void ScInputHandler::MergeLanguageAttributes( ScEditEngineDefaulter& rDestEngine ) const
{
    const SfxItemSet& rSrcSet = mpEditEngine->GetDefaults();
    rDestEngine.SetDefaultItem( rSrcSet.Get( EE_CHAR_LANGUAGE ));
    rDestEngine.SetDefaultItem( rSrcSet.Get( EE_CHAR_LANGUAGE_CJK ));
    rDestEngine.SetDefaultItem( rSrcSet.Get( EE_CHAR_LANGUAGE_CTL ));
}

static void lcl_SetTopSelection( EditView* pEditView, ESelection& rSel )
{
    OSL_ENSURE( rSel.nStartPara==0 && rSel.nEndPara==0, "SetTopSelection: Para != 0" );

    EditEngine* pEngine = pEditView->GetEditEngine();
    sal_Int32 nCount = pEngine->GetParagraphCount();
    if (nCount > 1)
    {
        sal_Int32 nParLen = pEngine->GetTextLen(rSel.nStartPara);
        while (rSel.nStartPos > nParLen && rSel.nStartPara+1 < nCount)
        {
            rSel.nStartPos -= nParLen + 1; // Including space from line break
            nParLen = pEngine->GetTextLen(++rSel.nStartPara);
        }

        nParLen = pEngine->GetTextLen(rSel.nEndPara);
        while (rSel.nEndPos > nParLen && rSel.nEndPara+1 < nCount)
        {
            rSel.nEndPos -= nParLen + 1; // Including space from line break
            nParLen = pEngine->GetTextLen(++rSel.nEndPara);
        }
    }

    ESelection aSel = pEditView->GetSelection();

    if (   rSel.nStartPara != aSel.nStartPara || rSel.nEndPara != aSel.nEndPara
        || rSel.nStartPos  != aSel.nStartPos  || rSel.nEndPos  != aSel.nEndPos )
        pEditView->SetSelection( rSel );
}

void ScInputHandler::SyncViews( const EditView* pSourceView )
{
    if (pSourceView)
    {
        bool bSelectionForTopView = false;
        if (pTopView && pTopView != pSourceView)
            bSelectionForTopView = true;
        bool bSelectionForTableView = false;
        if (pTableView && pTableView != pSourceView)
            bSelectionForTableView = true;
        if (bSelectionForTopView || bSelectionForTableView)
        {
            ESelection aSel(pSourceView->GetSelection());
            if (bSelectionForTopView)
                pTopView->SetSelection(aSel);
            if (bSelectionForTableView)
                lcl_SetTopSelection(pTableView, aSel);
        }
    }
    // Only sync selection from topView if we are actually editing there
    else if (pTopView && pTableView)
    {
        ESelection aSel(pTopView->GetSelection());
        lcl_SetTopSelection( pTableView, aSel );
    }
}

IMPL_LINK_NOARG(ScInputHandler, ModifyHdl, LinkParamNone*, void)
{
    if ( !bInOwnChange && ( eMode==SC_INPUT_TYPE || eMode==SC_INPUT_TABLE ) &&
         mpEditEngine && mpEditEngine->GetUpdateMode() && pInputWin )
    {
        // Update input line from ModifyHdl for changes that are not
        // wrapped by DataChanging/DataChanged calls (like Drag&Drop)
        OUString aText(ScEditUtil::GetMultilineString(*mpEditEngine));
        lcl_RemoveTabs(aText);
        pInputWin->SetTextString(aText);
    }
}

/**
 * @return true means new view created
 */
bool ScInputHandler::DataChanging( sal_Unicode cTyped, bool bFromCommand )
{
    if (pActiveViewSh)
        pActiveViewSh->GetViewData().SetPasteMode( ScPasteFlags::NONE );
    bInOwnChange = true; // disable ModifyHdl (reset in DataChanged)

    if ( eMode == SC_INPUT_NONE )
        return StartTable( cTyped, bFromCommand, false, nullptr );
    else
        return false;
}

void ScInputHandler::DataChanged( bool bFromTopNotify, bool bSetModified )
{
    ImplCreateEditEngine();

    if (eMode==SC_INPUT_NONE)
        eMode = SC_INPUT_TYPE;

    if ( eMode == SC_INPUT_TOP && pTopView && !bFromTopNotify )
    {
        //  table EditEngine is formatted below, input line needs formatting after paste
        //  #i20282# not when called from the input line's modify handler
        pTopView->GetEditEngine()->QuickFormatDoc( true );

        //  #i23720# QuickFormatDoc hides the cursor, but can't show it again because it
        //  can't safely access the EditEngine's current view, so the cursor has to be
        //  shown again here.
        pTopView->ShowCursor();
    }

    if (bSetModified)
        bModified = true;
    bSelIsRef = false;

    if ( pRangeFindList && !bInRangeUpdate )
        RemoveRangeFinder(); // Delete attributes and labels

    UpdateParenthesis(); // Highlight parentheses anew

    if (eMode==SC_INPUT_TYPE || eMode==SC_INPUT_TABLE)
    {
        OUString aText;
        if (pInputWin)
            aText = ScEditUtil::GetMultilineString(*mpEditEngine);
        else
            aText = GetEditText(mpEditEngine.get());
        lcl_RemoveTabs(aText);

        if ( pInputWin )
            pInputWin->SetTextString( aText );

        if (comphelper::LibreOfficeKit::isActive())
        {
            if (pActiveViewSh)
                pActiveViewSh->libreOfficeKitViewCallback(LOK_CALLBACK_CELL_FORMULA, aText.toUtf8().getStr());
        }
    }

    // If the cursor is before the end of a paragraph, parts are being pushed to
    // the right (independently from the eMode) -> Adapt View!
    // If the cursor is at the end, the StatusHandler of the ViewData is sufficient.
    //
    // First make sure the status handler is called now if the cursor
    // is outside the visible area
    mpEditEngine->QuickFormatDoc();

    EditView* pActiveView = pTopView ? pTopView : pTableView;
    if (pActiveView && pActiveViewSh)
    {
        ScViewData& rViewData = pActiveViewSh->GetViewData();

        bool bNeedGrow = ( rViewData.GetEditAdjust() != SvxAdjust::Left ); // Always right-aligned
        if (!bNeedGrow)
        {
            // Cursor before the end?
            ESelection aSel = pActiveView->GetSelection();
            aSel.Adjust();
            bNeedGrow = ( aSel.nEndPos != mpEditEngine->GetTextLen(aSel.nEndPara) );
        }
        if (!bNeedGrow)
        {
            bNeedGrow = rViewData.GetDocument()->IsLayoutRTL( rViewData.GetTabNo() );
        }
        if (bNeedGrow)
        {
            // Adjust inplace view
            rViewData.EditGrowY();
            rViewData.EditGrowX();
        }
    }

    UpdateFormulaMode();
    bTextValid = false; // Changes only in the EditEngine
    bInOwnChange = false;
}

void ScInputHandler::UpdateFormulaMode()
{
    SfxApplication* pSfxApp = SfxGetpApp();

    bool bIsFormula = !bProtected && mpEditEngine->GetParagraphCount() == 1;
    if (bIsFormula)
    {
        const OUString& rText = mpEditEngine->GetText(0);
        bIsFormula = !rText.isEmpty() &&
            (rText[0] == '=' || rText[0] == '+' || rText[0] == '-');
    }

    if ( bIsFormula )
    {
        if (!bFormulaMode)
        {
            bFormulaMode = true;
            pRefViewSh = pActiveViewSh;
            pSfxApp->Broadcast( SfxHint( SfxHintId::ScRefModeChanged ) );
            SC_MOD()->SetRefInputHdl(this);
            if (pInputWin)
                pInputWin->SetFormulaMode(true);

            if ( bAutoComplete )
                GetFormulaData();

            UpdateParenthesis();
            UpdateAutoCorrFlag();
        }
    }
    else // Deactivate
    {
        if (bFormulaMode)
        {
            ShowRefFrame();
            bFormulaMode = false;
            pRefViewSh = nullptr;
            pSfxApp->Broadcast( SfxHint( SfxHintId::ScRefModeChanged ) );
            SC_MOD()->SetRefInputHdl(nullptr);
            if (pInputWin)
                pInputWin->SetFormulaMode(false);
            UpdateAutoCorrFlag();
        }
    }
}

void ScInputHandler::ShowRefFrame()
{
    // Modifying pActiveViewSh here would interfere with the bInEnterHandler / bRepeat
    // checks in NotifyChange, and lead to keeping the wrong value in pActiveViewSh.
    // A local variable is used instead.
    ScTabViewShell* pVisibleSh = dynamic_cast<ScTabViewShell*>( SfxViewShell::Current()  );
    if ( pRefViewSh && pRefViewSh != pVisibleSh )
    {
        bool bFound = false;
        SfxViewFrame* pRefFrame = pRefViewSh->GetViewFrame();
        SfxViewFrame* pOneFrame = SfxViewFrame::GetFirst();
        while ( pOneFrame && !bFound )
        {
            if ( pOneFrame == pRefFrame )
                bFound = true;
            pOneFrame = SfxViewFrame::GetNext( *pOneFrame );
        }

        if (bFound)
        {
            // We count on Activate working synchronously here
            // (pActiveViewSh is set while doing so)
            pRefViewSh->SetActive(); // Appear and SetViewFrame

            //  pLastState is set correctly in the NotifyChange from the Activate
        }
        else
        {
            OSL_FAIL("ViewFrame for reference input is not here anymore");
        }
    }
}

void ScInputHandler::RemoveSelection()
{
    EditView* pActiveView = pTopView ? pTopView : pTableView;
    if (!pActiveView)
        return;

    ESelection aSel = pActiveView->GetSelection();
    aSel.nStartPara = aSel.nEndPara;
    aSel.nStartPos  = aSel.nEndPos;
    if (pTableView)
        pTableView->SetSelection( aSel );
    if (pTopView)
        pTopView->SetSelection( aSel );
}

void ScInputHandler::InvalidateAttribs()
{
    SfxViewFrame* pViewFrm = SfxViewFrame::Current();
    if (pViewFrm)
    {
        SfxBindings& rBindings = pViewFrm->GetBindings();

        rBindings.Invalidate( SID_ATTR_CHAR_FONT );
        rBindings.Invalidate( SID_ATTR_CHAR_FONTHEIGHT );
        rBindings.Invalidate( SID_ATTR_CHAR_COLOR );

        rBindings.Invalidate( SID_ATTR_CHAR_WEIGHT );
        rBindings.Invalidate( SID_ATTR_CHAR_POSTURE );
        rBindings.Invalidate( SID_ATTR_CHAR_UNDERLINE );
        rBindings.Invalidate( SID_ATTR_CHAR_OVERLINE );
        rBindings.Invalidate( SID_ULINE_VAL_NONE );
        rBindings.Invalidate( SID_ULINE_VAL_SINGLE );
        rBindings.Invalidate( SID_ULINE_VAL_DOUBLE );
        rBindings.Invalidate( SID_ULINE_VAL_DOTTED );

        rBindings.Invalidate( SID_HYPERLINK_GETLINK );

        rBindings.Invalidate( SID_ATTR_CHAR_KERNING );
        rBindings.Invalidate( SID_SET_SUPER_SCRIPT );
        rBindings.Invalidate( SID_SET_SUB_SCRIPT );
        rBindings.Invalidate( SID_ATTR_CHAR_STRIKEOUT );
        rBindings.Invalidate( SID_ATTR_CHAR_SHADOWED );
    }
}

// --------------- public methods --------------------------------------------

void ScInputHandler::SetMode( ScInputMode eNewMode, const OUString* pInitText, ScEditEngineDefaulter* pTopEngine )
{
    if ( eMode == eNewMode )
        return;

    ImplCreateEditEngine();

    if (bProtected)
    {
        eMode = SC_INPUT_NONE;
        StopInputWinEngine( true );
        if (pActiveViewSh)
            pActiveViewSh->GetActiveWin()->GrabFocus();
        return;
    }

    if (eNewMode != SC_INPUT_NONE && pActiveViewSh)
        // Disable paste mode when edit mode starts.
        pActiveViewSh->GetViewData().SetPasteMode( ScPasteFlags::NONE );

    bInOwnChange = true; // disable ModifyHdl (reset below)

    ScInputMode eOldMode = eMode;
    eMode = eNewMode;
    if (eOldMode == SC_INPUT_TOP && eNewMode != eOldMode)
        StopInputWinEngine( false );

    if (eMode==SC_INPUT_TOP || eMode==SC_INPUT_TABLE)
    {
        if (eOldMode == SC_INPUT_NONE) // not if switching between modes
        {
            if (StartTable(0, false, eMode == SC_INPUT_TABLE, pTopEngine))
            {
                if (pActiveViewSh)
                    pActiveViewSh->GetViewData().GetDocShell()->PostEditView( mpEditEngine.get(), aCursorPos );
            }
        }

        if (pInitText)
        {
            mpEditEngine->SetText(*pInitText);
            bModified = true;
        }

        sal_Int32 nPara = mpEditEngine->GetParagraphCount()-1;
        sal_Int32 nLen = mpEditEngine->GetText(nPara).getLength();
        sal_uInt16 nCount = mpEditEngine->GetViewCount();

        for (sal_uInt16 i=0; i<nCount; i++)
        {
            if ( eMode == SC_INPUT_TABLE && eOldMode == SC_INPUT_TOP )
            {
                // Keep Selection
            }
            else
            {
                mpEditEngine->GetView(i)->
                    SetSelection( ESelection( nPara, nLen, nPara, nLen ) );
            }
            mpEditEngine->GetView(i)->ShowCursor(false);
        }
    }

    UpdateActiveView();
    if (eMode==SC_INPUT_TABLE || eMode==SC_INPUT_TYPE)
    {
        if (pTableView)
            pTableView->SetEditEngineUpdateMode(true);
    }
    else
    {
        if (pTopView)
            pTopView->SetEditEngineUpdateMode(true);
    }

    if (eNewMode != eOldMode)
        UpdateFormulaMode();

    bInOwnChange = false;
}

/**
 * @return true if rString only contains digits (no autocorrect then)
 */
static bool lcl_IsNumber(const OUString& rString)
{
    sal_Int32 nLen = rString.getLength();
    for (sal_Int32 i=0; i<nLen; i++)
    {
        sal_Unicode c = rString[i];
        if ( c < '0' || c > '9' )
            return false;
    }
    return true;
}

static void lcl_SelectionToEnd( EditView* pView )
{
    if ( pView )
    {
        EditEngine* pEngine = pView->GetEditEngine();
        sal_Int32 nParCnt = pEngine->GetParagraphCount();
        if ( nParCnt == 0 )
            nParCnt = 1;
        ESelection aSel( nParCnt-1, pEngine->GetTextLen(nParCnt-1) ); // empty selection, cursor at the end
        pView->SetSelection( aSel );
    }
}

void ScInputHandler::EnterHandler( ScEnterMode nBlockMode )
{
    if (!mbDocumentDisposing && comphelper::LibreOfficeKit::isActive()
        && pActiveViewSh != SfxViewShell::Current())
        return;

    // Macro calls for validity can cause a lot of problems, so inhibit
    // nested calls of EnterHandler().
    if (bInEnterHandler) return;
    bInEnterHandler = true;
    bInOwnChange = true; // disable ModifyHdl (reset below)

    ImplCreateEditEngine();

    bool bMatrix = ( nBlockMode == ScEnterMode::MATRIX );

    SfxApplication* pSfxApp     = SfxGetpApp();
    std::unique_ptr<EditTextObject> pObject;
    std::unique_ptr<ScPatternAttr> pCellAttrs;
    bool            bForget     = false; // Remove due to validity?

    OUString aString = GetEditText(mpEditEngine.get());
    OUString aPreAutoCorrectString(aString);
    EditView* pActiveView = pTopView ? pTopView : pTableView;
    if (bModified && pActiveView && !aString.isEmpty() && !lcl_IsNumber(aString))
    {
        if (pColumnData && miAutoPosColumn != pColumnData->end())
        {
            // #i47125# If AutoInput appended something, do the final AutoCorrect
            // with the cursor at the end of the input.
            lcl_SelectionToEnd(pTopView);
            lcl_SelectionToEnd(pTableView);
        }

        vcl::Window* pFrameWin = pActiveViewSh ? pActiveViewSh->GetFrameWin() : nullptr;

        if (pTopView)
            pTopView->CompleteAutoCorrect(); // CompleteAutoCorrect for both Views
        if (pTableView)
            pTableView->CompleteAutoCorrect(pFrameWin);
        aString = GetEditText(mpEditEngine.get());
    }
    lcl_RemoveTabs(aString);
    lcl_RemoveTabs(aPreAutoCorrectString);

    // Test if valid (always with simple string)
    if ( bModified && nValidation && pActiveViewSh )
    {
        ScDocument* pDoc = pActiveViewSh->GetViewData().GetDocument();
        const ScValidationData* pData = pDoc->GetValidationEntry( nValidation );
        if (pData && pData->HasErrMsg())
        {
            // #i67990# don't use pLastPattern in EnterHandler
            const ScPatternAttr* pPattern = pDoc->GetPattern( aCursorPos.Col(), aCursorPos.Row(), aCursorPos.Tab() );

            bool bOk;

            if (pData->GetDataMode() == SC_VALID_CUSTOM)
            {
                bOk = pData->IsDataValidCustom( aString, *pPattern, aCursorPos,  ScValidationData::CustomValidationPrivateAccess() );
            }
            else
            {
                bOk = pData->IsDataValid( aString, *pPattern, aCursorPos );
            }

            if (!bOk)
            {
                if ( pActiveViewSh )                // If it came from MouseButtonDown
                    pActiveViewSh->StopMarking();   // (the InfoBox consumes the MouseButtonUp)

                vcl::Window* pParent = nullptr;
                if (pActiveViewSh)
                    pParent = &pActiveViewSh->GetViewFrame()->GetWindow();
                else
                    pParent = Application::GetDefDialogParent();

                if (pData->DoError(pParent ? pParent->GetFrameWeld() : nullptr, aString, aCursorPos))
                    bForget = true;                 // Do not take over input
            }
        }
    }

    // Check for input into DataPilot table
    if ( bModified && pActiveViewSh && !bForget )
    {
        ScDocument* pDoc = pActiveViewSh->GetViewData().GetDocument();
        ScDPObject* pDPObj = pDoc->GetDPAtCursor( aCursorPos.Col(), aCursorPos.Row(), aCursorPos.Tab() );
        if ( pDPObj )
        {
            // Any input within the DataPilot table is either a valid renaming
            // or an invalid action - normal cell input is always aborted
            pActiveViewSh->DataPilotInput( aCursorPos, aString );
            bForget = true;
        }
    }

    std::vector<editeng::MisspellRanges> aMisspellRanges;
    mpEditEngine->CompleteOnlineSpelling();
    bool bSpellErrors = !bFormulaMode && mpEditEngine->HasOnlineSpellErrors();
    if ( bSpellErrors )
    {
        //  #i3820# If the spell checker flags numerical input as error,
        //  it still has to be treated as number, not EditEngine object.
        if ( pActiveViewSh )
        {
            ScDocument* pDoc = pActiveViewSh->GetViewData().GetDocument();
            // #i67990# don't use pLastPattern in EnterHandler
            const ScPatternAttr* pPattern = pDoc->GetPattern( aCursorPos.Col(), aCursorPos.Row(), aCursorPos.Tab() );
            if (pPattern)
            {
                SvNumberFormatter* pFormatter = pDoc->GetFormatTable();
                // without conditional format, as in ScColumn::SetString
                sal_uInt32 nFormat = pPattern->GetNumberFormat( pFormatter );
                double nVal;
                if ( pFormatter->IsNumberFormat( aString, nFormat, nVal ) )
                {
                    bSpellErrors = false;       // ignore the spelling errors
                }
            }
        }
    }

    //  After RemoveAdjust, the EditView must not be repainted (has wrong font size etc).
    //  SetUpdateMode must come after CompleteOnlineSpelling.
    //  The view is hidden in any case below (Broadcast).
    mpEditEngine->SetUpdateMode( false );

    if ( bModified && !bForget ) // What is being entered (text/object)?
    {
        sal_Int32 nParCnt = mpEditEngine->GetParagraphCount();
        if ( nParCnt == 0 )
            nParCnt = 1;

        bool bUniformAttribs = true;
        SfxItemSet aPara1Attribs = mpEditEngine->GetAttribs(0, 0, mpEditEngine->GetTextLen(0));
        for (sal_Int32 nPara = 1; nPara < nParCnt; ++nPara)
        {
            SfxItemSet aPara2Attribs = mpEditEngine->GetAttribs(nPara, 0, mpEditEngine->GetTextLen(nPara));
            if (!(aPara1Attribs == aPara2Attribs))
            {
                // Paragraph format different from that of the 1st paragraph.
                bUniformAttribs = false;
                break;
            }
        }

        ESelection aSel( 0, 0, nParCnt-1, mpEditEngine->GetTextLen(nParCnt-1) );
        SfxItemSet aOldAttribs = mpEditEngine->GetAttribs( aSel );
        const SfxPoolItem* pItem = nullptr;

        // Find common (cell) attributes before RemoveAdjust
        if ( pActiveViewSh && bUniformAttribs )
        {
            SfxItemSet* pCommonAttrs = nullptr;
            for (sal_uInt16 nId = EE_CHAR_START; nId <= EE_CHAR_END; nId++)
            {
                SfxItemState eState = aOldAttribs.GetItemState( nId, false, &pItem );
                if ( eState == SfxItemState::SET &&
                        nId != EE_CHAR_ESCAPEMENT && nId != EE_CHAR_PAIRKERNING &&
                        nId != EE_CHAR_KERNING && nId != EE_CHAR_XMLATTRIBS &&
                            *pItem != pEditDefaults->Get(nId) )
                {
                    if ( !pCommonAttrs )
                        pCommonAttrs = new SfxItemSet( mpEditEngine->GetEmptyItemSet() );
                    pCommonAttrs->Put( *pItem );
                }
            }

            if ( pCommonAttrs )
            {
                ScDocument* pDoc = pActiveViewSh->GetViewData().GetDocument();
                pCellAttrs = o3tl::make_unique<ScPatternAttr>(pDoc->GetPool());
                pCellAttrs->GetFromEditItemSet( pCommonAttrs );
                delete pCommonAttrs;
            }
        }

        // Clear ParaAttribs (including adjustment)
        RemoveAdjust();

        bool bAttrib = false; // Formatting present?

        //  check if EditObject is needed
        if (nParCnt > 1)
            bAttrib = true;
        else
        {
            for (sal_uInt16 nId = EE_CHAR_START; nId <= EE_CHAR_END && !bAttrib; nId++)
            {
                SfxItemState eState = aOldAttribs.GetItemState( nId, false, &pItem );
                if (eState == SfxItemState::DONTCARE)
                    bAttrib = true;
                else if (eState == SfxItemState::SET)
                {
                    // Keep same items in EditEngine as in ScEditAttrTester
                    if ( nId == EE_CHAR_ESCAPEMENT || nId == EE_CHAR_PAIRKERNING ||
                         nId == EE_CHAR_KERNING || nId == EE_CHAR_XMLATTRIBS )
                    {
                        if ( *pItem != pEditDefaults->Get(nId) )
                            bAttrib = true;
                    }
                }
            }

            // Contains fields?
            SfxItemState eFieldState = aOldAttribs.GetItemState( EE_FEATURE_FIELD, false );
            if ( eFieldState == SfxItemState::DONTCARE || eFieldState == SfxItemState::SET )
                bAttrib = true;

            // Not converted characters?
            SfxItemState eConvState = aOldAttribs.GetItemState( EE_FEATURE_NOTCONV, false );
            if ( eConvState == SfxItemState::DONTCARE || eConvState == SfxItemState::SET )
                bAttrib = true;

            // Always recognize formulas as formulas
            // We still need the preceding test due to cell attributes
        }

        if (bSpellErrors)
            mpEditEngine->GetAllMisspellRanges(aMisspellRanges);

        if (bMatrix)
            bAttrib = false;

        if (bAttrib)
        {
            mpEditEngine->ClearSpellErrors();
            pObject = mpEditEngine->CreateTextObject();
        }
        else if (bAutoComplete) // Adjust Upper/Lower case
        {
            // Perform case-matching only when the typed text is partial.
            if (pColumnData && aAutoSearch.getLength() < aString.getLength())
                aString = getExactMatch(*pColumnData, aString);
        }
    }

    // Don't rely on ShowRefFrame switching the active view synchronously
    // execute the function directly on the correct view's bindings instead
    // pRefViewSh is reset in ShowRefFrame - get pointer before ShowRefFrame call
    ScTabViewShell* pExecuteSh = pRefViewSh ? pRefViewSh : pActiveViewSh;

    if (bFormulaMode)
    {
        ShowRefFrame();

        if (pExecuteSh)
        {
            pExecuteSh->SetTabNo(aCursorPos.Tab());
            pExecuteSh->ActiveGrabFocus();
        }

        bFormulaMode = false;
        pSfxApp->Broadcast( SfxHint( SfxHintId::ScRefModeChanged ) );
        SC_MOD()->SetRefInputHdl(nullptr);
        if (pInputWin)
            pInputWin->SetFormulaMode(false);
        UpdateAutoCorrFlag();
    }
    pRefViewSh = nullptr; // Also without FormulaMode due to FunctionsAutoPilot
    DeleteRangeFinder();
    ResetAutoPar();

    bool bOldMod = bModified;

    bModified = false;
    bSelIsRef = false;
    eMode     = SC_INPUT_NONE;
    StopInputWinEngine(true);

    // Text input (through number formats) or ApplySelectionPattern modify
    // the cell's attributes, so pLastPattern is no longer valid
    pLastPattern = nullptr;

    if (bOldMod && !bProtected && !bForget)
    {
        bool bInsertPreCorrectedString = true;
        // No typographic quotes in formulas
        if (aString.startsWith("="))
        {
            SvxAutoCorrect* pAuto = SvxAutoCorrCfg::Get().GetAutoCorrect();
            if ( pAuto )
            {
                bInsertPreCorrectedString = false;
                OUString aReplace(pAuto->GetStartDoubleQuote());
                if( aReplace.isEmpty() )
                    aReplace = ScGlobal::pLocaleData->getDoubleQuotationMarkStart();
                if( aReplace != "\"" )
                    aString = aString.replaceAll( aReplace, "\"" );

                aReplace = OUString(pAuto->GetEndDoubleQuote());
                if( aReplace.isEmpty() )
                    aReplace = ScGlobal::pLocaleData->getDoubleQuotationMarkEnd();
                if( aReplace != "\"" )
                    aString = aString.replaceAll( aReplace, "\"" );

                aReplace = OUString(pAuto->GetStartSingleQuote());
                if( aReplace.isEmpty() )
                    aReplace = ScGlobal::pLocaleData->getQuotationMarkStart();
                if( aReplace != "'" )
                    aString = aString.replaceAll( aReplace, "'" );

                aReplace = OUString(pAuto->GetEndSingleQuote());
                if( aReplace.isEmpty() )
                    aReplace = ScGlobal::pLocaleData->getQuotationMarkEnd();
                if( aReplace != "'" )
                    aString = aString.replaceAll( aReplace, "'");
            }
        }

        pSfxApp->Broadcast( SfxHint( SfxHintId::ScKillEditViewNoPaint ) );

        if ( pExecuteSh )
        {
            SfxBindings& rBindings = pExecuteSh->GetViewFrame()->GetBindings();

            sal_uInt16 nId = FID_INPUTLINE_ENTER;
            if ( nBlockMode == ScEnterMode::BLOCK )
                nId = FID_INPUTLINE_BLOCK;
            else if ( nBlockMode == ScEnterMode::MATRIX )
                nId = FID_INPUTLINE_MATRIX;

            const SfxPoolItem* aArgs[2];
            aArgs[1] = nullptr;

            if ( bInsertPreCorrectedString && aString != aPreAutoCorrectString )
            {
               ScInputStatusItem aItem(FID_INPUTLINE_STATUS,
                                       aCursorPos, aCursorPos, aCursorPos,
                                       aPreAutoCorrectString, pObject.get());
                aArgs[0] = &aItem;
                rBindings.Execute(nId, aArgs);
            }

            ScInputStatusItem aItemCorrected(FID_INPUTLINE_STATUS,
                                             aCursorPos, aCursorPos, aCursorPos,
                                             aString, pObject.get());
            if ( !aMisspellRanges.empty() )
                aItemCorrected.SetMisspellRanges(&aMisspellRanges);

            aArgs[0] = &aItemCorrected;
            rBindings.Execute(nId, aArgs);
        }

        pLastState.reset(); // pLastState still contains the old text
    }
    else
        pSfxApp->Broadcast( SfxHint( SfxHintId::ScKillEditView ) );

    if ( bOldMod && pExecuteSh && pCellAttrs && !bForget )
    {
        // Combine with input?
        pExecuteSh->ApplySelectionPattern( *pCellAttrs, true );
        pExecuteSh->AdjustBlockHeight();
    }

    HideTip();
    HideTipBelow();

    nFormSelStart = nFormSelEnd = 0;
    aFormText.clear();

    bInOwnChange = false;
    bInEnterHandler = false;
}

void ScInputHandler::CancelHandler()
{
    bInOwnChange = true; // Also without FormulaMode due to FunctionsAutoPilot

    ImplCreateEditEngine();

    bModified = false;

    // Don't rely on ShowRefFrame switching the active view synchronously
    // execute the function directly on the correct view's bindings instead
    // pRefViewSh is reset in ShowRefFrame - get pointer before ShowRefFrame call
    ScTabViewShell* pExecuteSh = pRefViewSh ? pRefViewSh : pActiveViewSh;

    if (bFormulaMode)
    {
        ShowRefFrame();
        if (pExecuteSh)
        {
            pExecuteSh->SetTabNo(aCursorPos.Tab());
            pExecuteSh->ActiveGrabFocus();
        }
        bFormulaMode = false;
        SfxGetpApp()->Broadcast( SfxHint( SfxHintId::ScRefModeChanged ) );
        SC_MOD()->SetRefInputHdl(nullptr);
        if (pInputWin)
            pInputWin->SetFormulaMode(false);
        UpdateAutoCorrFlag();
    }
    pRefViewSh = nullptr; // Also without FormulaMode due to FunctionsAutoPilot
    DeleteRangeFinder();
    ResetAutoPar();

    eMode = SC_INPUT_NONE;
    StopInputWinEngine( true );
    if (pExecuteSh)
        pExecuteSh->StopEditShell();

    aCursorPos.Set(MAXCOL+1,0,0); // Invalid flag
    mpEditEngine->SetText(OUString());

    if ( !pLastState && pExecuteSh )
        pExecuteSh->UpdateInputHandler( true );  // Update status again
    else
        NotifyChange( pLastState.get(), true );

    nFormSelStart = nFormSelEnd = 0;
    aFormText.clear();

    bInOwnChange = false;

    if ( comphelper::LibreOfficeKit::isActive() && pExecuteSh )
    {
        // Clear
        std::vector<ReferenceMark> aReferenceMarks;
        ScInputHandler::SendReferenceMarks( pActiveViewSh, aReferenceMarks );
    }
}

bool ScInputHandler::IsModalMode( const SfxObjectShell* pDocSh )
{
    // References to unnamed document; that doesn't work
    return bFormulaMode && pRefViewSh
            && pRefViewSh->GetViewData().GetDocument()->GetDocumentShell() != pDocSh
            && !pDocSh->HasName();
}

void ScInputHandler::AddRefEntry()
{
    const sal_Unicode cSep = ScCompiler::GetNativeSymbolChar(ocSep);
    UpdateActiveView();
    if (!pTableView && !pTopView)
        return;                             // E.g. FillMode

    DataChanging();                         // Cannot be new

    RemoveSelection();
    OUString aText = GetEditText(mpEditEngine.get());
    sal_Unicode cLastChar = 0;
    sal_Int32 nPos = aText.getLength() - 1;
    while (nPos >= 0 && ((cLastChar = aText[nPos]) == ' ')) //checking space
        --nPos;

    bool bAppendSeparator = (cLastChar != '(' && cLastChar != cSep && cLastChar != '=');
    if (bAppendSeparator)
    {
        if (pTableView)
            pTableView->InsertText( OUString(cSep) );
        if (pTopView)
            pTopView->InsertText( OUString(cSep) );
    }

    DataChanged();
}

void ScInputHandler::SetReference( const ScRange& rRef, const ScDocument* pDoc )
{
    HideTip();

    bool bOtherDoc = ( pRefViewSh &&
                        pRefViewSh->GetViewData().GetDocument() != pDoc );
    if (bOtherDoc)
        if (!pDoc->GetDocumentShell()->HasName())
        {
            // References to unnamed document; that doesn't work
            // SetReference should not be called, then
            return;
        }

    UpdateActiveView();
    if (!pTableView && !pTopView)
        return;                             // E.g. FillMode

    // Never overwrite the "="!
    EditView* pActiveView = pTopView ? pTopView : pTableView;
    ESelection aSel = pActiveView->GetSelection();
    aSel.Adjust();
    if ( aSel.nStartPara == 0 && aSel.nStartPos == 0 )
        return;

    DataChanging();                         // Cannot be new

    // Turn around selection if backwards (TODO: Do we really need to do that?)
    if (pTableView)
    {
        ESelection aTabSel = pTableView->GetSelection();
        if (aTabSel.nStartPos > aTabSel.nEndPos && aTabSel.nStartPara == aTabSel.nEndPara)
        {
            aTabSel.Adjust();
            pTableView->SetSelection(aTabSel);
        }
    }
    if (pTopView)
    {
        ESelection aTopSel = pTopView->GetSelection();
        if (aTopSel.nStartPos > aTopSel.nEndPos && aTopSel.nStartPara == aTopSel.nEndPara)
        {
            aTopSel.Adjust();
            pTopView->SetSelection(aTopSel);
        }
    }

    // Create string from reference
    OUString aRefStr;
    const ScAddress::Details aAddrDetails( pDoc, aCursorPos );
    if (bOtherDoc)
    {
        // Reference to other document
        OSL_ENSURE(rRef.aStart.Tab()==rRef.aEnd.Tab(), "nStartTab!=nEndTab");

        // Always 3D and absolute.
        OUString aTmp(rRef.Format( ScRefFlags::VALID | ScRefFlags::TAB_ABS_3D, pDoc, aAddrDetails));

        SfxObjectShell* pObjSh = pDoc->GetDocumentShell();
        // #i75893# convert escaped URL of the document to something user friendly
        OUString aFileName = pObjSh->GetMedium()->GetURLObject().GetMainURL( INetURLObject::DecodeMechanism::Unambiguous );

        switch(aAddrDetails.eConv)
        {
             case formula::FormulaGrammar::CONV_XL_A1 :
             case formula::FormulaGrammar::CONV_XL_OOX :
             case formula::FormulaGrammar::CONV_XL_R1C1 :
                         aRefStr = "[\'" + aFileName + "']";
                         break;
             case formula::FormulaGrammar::CONV_OOO :
             default:
                         aRefStr = "\'" + aFileName + "'#";
                         break;
        }
        aRefStr += aTmp;
    }
    else
    {
        if ( rRef.aStart.Tab() != aCursorPos.Tab() ||
             rRef.aStart.Tab() != rRef.aEnd.Tab() )
            // pointer-selected => absolute sheet reference
            aRefStr = rRef.Format(ScRefFlags::VALID | ScRefFlags::TAB_ABS_3D, pDoc, aAddrDetails);
        else
            aRefStr = rRef.Format(ScRefFlags::VALID, pDoc, aAddrDetails);
    }

    if (pTableView || pTopView)
    {
        if (pTableView)
            pTableView->InsertText( aRefStr, true );
        if (pTopView)
            pTopView->InsertText( aRefStr, true );

        DataChanged();
    }

    bSelIsRef = true;
}

void ScInputHandler::InsertFunction( const OUString& rFuncName, bool bAddPar )
{
    if ( eMode == SC_INPUT_NONE )
    {
        OSL_FAIL("InsertFunction, not during input mode");
        return;
    }

    UpdateActiveView();
    if (!pTableView && !pTopView)
        return;                             // E.g. FillMode

    DataChanging();                         // Cannot be new

    OUString aText = rFuncName;
    if (bAddPar)
        aText += "()";

    if (pTableView)
    {
        pTableView->InsertText( aText );
        if (bAddPar)
        {
            ESelection aSel = pTableView->GetSelection();
            --aSel.nStartPos;
            --aSel.nEndPos;
            pTableView->SetSelection(aSel);
        }
    }
    if (pTopView)
    {
        pTopView->InsertText( aText );
        if (bAddPar)
        {
            ESelection aSel = pTopView->GetSelection();
            --aSel.nStartPos;
            --aSel.nEndPos;
            pTopView->SetSelection(aSel);
        }
    }

    DataChanged();

    if (bAddPar)
        AutoParAdded();
}

void ScInputHandler::ClearText()
{
    if ( eMode == SC_INPUT_NONE )
    {
        OSL_FAIL("ClearText, not during input mode");
        return;
    }

    UpdateActiveView();
    if (!pTableView && !pTopView)
        return;                             // E.g. FillMode

    DataChanging();                         // Cannot be new

    if (pTableView)
    {
        pTableView->GetEditEngine()->SetText( "" );
        pTableView->SetSelection( ESelection(0,0, 0,0) );
    }
    if (pTopView)
    {
        pTopView->GetEditEngine()->SetText( "" );
        pTopView->SetSelection( ESelection(0,0, 0,0) );
    }

    DataChanged();
}

bool ScInputHandler::KeyInput( const KeyEvent& rKEvt, bool bStartEdit /* = false */ )
{
    if (!bOptLoaded)
    {
        bAutoComplete = SC_MOD()->GetAppOptions().GetAutoComplete();
        bOptLoaded = true;
    }

    vcl::KeyCode aCode = rKEvt.GetKeyCode();
    sal_uInt16 nModi  = aCode.GetModifier();
    bool bShift   = aCode.IsShift();
    bool bControl = aCode.IsMod1();
    bool bAlt     = aCode.IsMod2();
    sal_uInt16 nCode  = aCode.GetCode();
    sal_Unicode nChar = rKEvt.GetCharCode();

    if (bAlt && !bControl && nCode != KEY_RETURN)
        // Alt-Return and Alt-Ctrl-* are accepted. Everything else with ALT are not.
        return false;

    if (!bControl && nCode == KEY_TAB)
    {
        // Normal TAB moves the cursor right.
        EnterHandler();

        if (pActiveViewSh)
            pActiveViewSh->FindNextUnprot( bShift, true );
        return true;
    }

    bool bInputLine = ( eMode==SC_INPUT_TOP );

    bool bUsed = false;
    bool bSkip = false;
    bool bDoEnter = false;

    switch ( nCode )
    {
        case KEY_RETURN:
            // New line when in the input line and Shift/Ctrl-Enter is pressed,
            // or when in a cell and Ctrl-Enter is pressed.
            if ((pInputWin && bInputLine && bControl != bShift) || (!bInputLine && bControl && !bShift))
            {
                bDoEnter = true;
            }
            else if (nModi == 0 && nTipVisible && pFormulaData && miAutoPosFormula != pFormulaData->end())
            {
                PasteFunctionData();
                bUsed = true;
            }
            else if ( nModi == 0 && nTipVisible && !aManualTip.isEmpty() )
            {
                PasteManualTip();
                bUsed = true;
            }
            else
            {
                ScEnterMode nMode = ScEnterMode::NORMAL;
                if ( bShift && bControl )
                    nMode = ScEnterMode::MATRIX;
                else if ( bAlt )
                    nMode = ScEnterMode::BLOCK;
                EnterHandler( nMode );

                if (pActiveViewSh)
                    pActiveViewSh->MoveCursorEnter( bShift && !bControl );

                bUsed = true;
            }
            break;
        case KEY_TAB:
            if (bControl && !bAlt)
            {
                if (pFormulaData && nTipVisible && miAutoPosFormula != pFormulaData->end())
                {
                    // Iterate
                    NextFormulaEntry( bShift );
                    bUsed = true;
                }
                else if (pColumnData && bUseTab && miAutoPosColumn != pColumnData->end())
                {
                    // Iterate through AutoInput entries
                    NextAutoEntry( bShift );
                    bUsed = true;
                }
            }
            break;
        case KEY_ESCAPE:
            if ( nTipVisible )
            {
                HideTip();
                bUsed = true;
            }
            else if( nTipVisibleSec )
            {
                HideTipBelow();
                bUsed = true;
            }
            else if (eMode != SC_INPUT_NONE)
            {
                CancelHandler();
                bUsed = true;
            }
            else
                bSkip = true;
            break;
        case KEY_F2:
            if ( !bShift && !bControl && !bAlt && eMode == SC_INPUT_TABLE )
            {
                eMode = SC_INPUT_TYPE;
                bUsed = true;
            }
            break;
    }

    // Only execute cursor keys if already in EditMode
    // E.g. due to Shift-Ctrl-PageDn (not defined as an accelerator)
    bool bCursorKey = EditEngine::DoesKeyMoveCursor(rKEvt);
    bool bInsKey = ( nCode == KEY_INSERT && !nModi ); // Treat Insert like Cursorkeys
    if ( !bUsed && !bSkip && ( bDoEnter || EditEngine::DoesKeyChangeText(rKEvt) ||
                    ( eMode != SC_INPUT_NONE && ( bCursorKey || bInsKey ) ) ) )
    {
        HideTip();
        HideTipBelow();

        if (bSelIsRef)
        {
            RemoveSelection();
            bSelIsRef = false;
        }

        UpdateActiveView();
        bool bNewView = DataChanging( nChar );

        if (bProtected)                             // Protected cell?
            bUsed = true;                           // Don't forward KeyEvent
        else                                        // Changes allowed
        {
            if (bNewView )                          // Create anew
            {
                if (pActiveViewSh)
                    pActiveViewSh->GetViewData().GetDocShell()->PostEditView( mpEditEngine.get(), aCursorPos );
                UpdateActiveView();
                if (eMode==SC_INPUT_NONE)
                    if (pTableView || pTopView)
                    {
                        OUString aStrLoP;

                        if ( bStartEdit && bCellHasPercentFormat && ((nChar >= '0' && nChar <= '9') || nChar == '-') )
                            aStrLoP = "%";

                        if (pTableView)
                        {
                            pTableView->GetEditEngine()->SetText( aStrLoP );
                            if ( !aStrLoP.isEmpty() )
                                pTableView->SetSelection( ESelection(0,0, 0,0) );   // before the '%'

                            // Don't call SetSelection if the string is empty anyway,
                            // to avoid breaking the bInitial handling in ScViewData::EditGrowY
                        }
                        if (pTopView)
                        {
                            pTopView->GetEditEngine()->SetText( aStrLoP );
                            if ( !aStrLoP.isEmpty() )
                                pTopView->SetSelection( ESelection(0,0, 0,0) );     // before the '%'
                        }
                    }
                SyncViews();
            }

            if (pTableView || pTopView)
            {
                if (bDoEnter)
                {
                    if (pTableView)
                        if( pTableView->PostKeyEvent( KeyEvent( '\r', vcl::KeyCode(KEY_RETURN) ) ) )
                            bUsed = true;
                    if (pTopView)
                        if( pTopView->PostKeyEvent( KeyEvent( '\r', vcl::KeyCode(KEY_RETURN) ) ) )
                            bUsed = true;
                }
                else if ( nAutoPar && nChar == ')' && CursorAtClosingPar() )
                {
                    SkipClosingPar();
                    bUsed = true;
                }
                else
                {
                    if (pTableView)
                    {
                        if (pTopView)
                            pTableView->SetControlWord(pTableView->GetControlWord() | EVControlBits::SINGLELINEPASTE);

                        vcl::Window* pFrameWin = pActiveViewSh ? pActiveViewSh->GetFrameWin() : nullptr;
                        if ( pTableView->PostKeyEvent( rKEvt, pFrameWin ) )
                            bUsed = true;

                        pTableView->SetControlWord(pTableView->GetControlWord() & ~EVControlBits::SINGLELINEPASTE);
                    }
                    if (pTopView)
                    {
                        if ( bUsed && rKEvt.GetKeyCode().GetFunction() == KeyFuncType::CUT )
                            pTopView->DeleteSelected();
                        else if ( pTopView->PostKeyEvent( rKEvt ) )
                            bUsed = true;
                    }
                }

                // AutoInput:
                if ( bUsed && bAutoComplete )
                {
                    bUseTab = false;
                    if (pFormulaData)
                        miAutoPosFormula = pFormulaData->end();     // do not search further
                    if (pColumnData)
                        miAutoPosColumn = pColumnData->end();

                    KeyFuncType eFunc = rKEvt.GetKeyCode().GetFunction();
                    if ( nChar && nChar != 8 && nChar != 127 &&     // no 'backspace', no 'delete'
                         KeyFuncType::CUT != eFunc)                      // and no 'CTRL-X'
                    {
                        if (bFormulaMode)
                            UseFormulaData();
                        else
                            UseColData();
                    }
                }

                // When the selection is changed manually or an opening parenthesis
                // is typed, stop overwriting parentheses
                if ( bUsed && nChar == '(' )
                    ResetAutoPar();

                if ( KEY_INSERT == nCode )
                {
                    SfxViewFrame* pViewFrm = SfxViewFrame::Current();
                    if (pViewFrm)
                        pViewFrm->GetBindings().Invalidate( SID_ATTR_INSERT );
                }
                if( bUsed && bFormulaMode && ( bCursorKey || bInsKey || nCode == KEY_DELETE || nCode == KEY_BACKSPACE ) )
                {
                    ShowTipCursor();
                }
                if( bUsed && bFormulaMode && nCode == KEY_BACKSPACE )
                {
                    UseFormulaData();
                }

            }

            // #i114511# don't count cursor keys as modification
            bool bSetModified = !bCursorKey;
            DataChanged(false, bSetModified); // also calls UpdateParenthesis()
            InvalidateAttribs();        //! in DataChanged?
        }
    }

    if (pTopView && eMode != SC_INPUT_NONE)
        SyncViews();

    return bUsed;
}

void ScInputHandler::InputCommand( const CommandEvent& rCEvt )
{
    if ( rCEvt.GetCommand() == CommandEventId::CursorPos )
    {
        // For CommandEventId::CursorPos, do as little as possible, because
        // with remote VCL, even a ShowCursor will generate another event.
        if ( eMode != SC_INPUT_NONE )
        {
            UpdateActiveView();
            if (pTableView || pTopView)
            {
                if (pTableView)
                    pTableView->Command( rCEvt );
                else if (pTopView)                      // call only once
                    pTopView->Command( rCEvt );
            }
        }
    }
    else if ( rCEvt.GetCommand() == CommandEventId::QueryCharPosition )
    {
        if ( eMode != SC_INPUT_NONE )
        {
            UpdateActiveView();
            if (pTableView || pTopView)
            {
                if (pTableView)
                    pTableView->Command( rCEvt );
                else if (pTopView)                      // call only once
                    pTopView->Command( rCEvt );
            }
        }
    }
    else
    {
        if (!bOptLoaded)
        {
            bAutoComplete = SC_MOD()->GetAppOptions().GetAutoComplete();
            bOptLoaded = true;
        }

        HideTip();
        HideTipBelow();

        if ( bSelIsRef )
        {
            RemoveSelection();
            bSelIsRef = false;
        }

        UpdateActiveView();
        bool bNewView = DataChanging( 0, true );

        if (!bProtected)                            // changes allowed
        {
            if (bNewView)                           // create new edit view
            {
                if (pActiveViewSh)
                    pActiveViewSh->GetViewData().GetDocShell()->PostEditView( mpEditEngine.get(), aCursorPos );
                UpdateActiveView();
                if (eMode==SC_INPUT_NONE)
                    if (pTableView || pTopView)
                    {
                        OUString aStrLoP;
                        if (pTableView)
                        {
                            pTableView->GetEditEngine()->SetText( aStrLoP );
                            pTableView->SetSelection( ESelection(0,0, 0,0) );
                        }
                        if (pTopView)
                        {
                            pTopView->GetEditEngine()->SetText( aStrLoP );
                            pTopView->SetSelection( ESelection(0,0, 0,0) );
                        }
                    }
                SyncViews();
            }

            if (pTableView || pTopView)
            {
                if (pTableView)
                    pTableView->Command( rCEvt );
                if (pTopView && !comphelper::LibreOfficeKit::isActive())
                    pTopView->Command( rCEvt );

                if ( rCEvt.GetCommand() == CommandEventId::EndExtTextInput )
                {
                    //  AutoInput after ext text input

                    if (pFormulaData)
                        miAutoPosFormula = pFormulaData->end();
                    if (pColumnData)
                        miAutoPosColumn = pColumnData->end();

                    if (bFormulaMode)
                        UseFormulaData();
                    else
                        UseColData();
                }
            }

            DataChanged();              //  calls UpdateParenthesis()
            InvalidateAttribs();        //! in DataChanged ?
        }

        if (pTopView && eMode != SC_INPUT_NONE)
            SyncViews();
    }
}

void ScInputHandler::NotifyChange( const ScInputHdlState* pState,
                                   bool bForce, ScTabViewShell* pSourceSh,
                                   bool bStopEditing)
{
    // If the call originates from a macro call in the EnterHandler,
    // return immediately and don't mess up the status
    if (bInEnterHandler)
        return;

    bool bRepeat = (pState == pLastState.get());
    if (!bRepeat && pState && pLastState)
        bRepeat = (*pState == *pLastState);
    if (bRepeat && !bForce)
        return;

    bInOwnChange = true;                // disable ModifyHdl (reset below)

    if ( pState && !pLastState )        // Enable again
        bForce = true;

    bool bHadObject = pLastState && pLastState->GetEditData();

    //! Before EditEngine gets eventually created (so it gets the right pools)
    if ( pSourceSh )
        pActiveViewSh = pSourceSh;
    else
        pActiveViewSh = dynamic_cast<ScTabViewShell*>( SfxViewShell::Current() );

    ImplCreateEditEngine();

    if ( pState != pLastState.get() )
    {
        pLastState.reset( pState ? new ScInputHdlState( *pState ) : nullptr);
    }

    if ( pState && pActiveViewSh )
    {
        ScModule* pScMod = SC_MOD();

        ScTabViewShell* pScTabViewShell = pScMod ? dynamic_cast<ScTabViewShell*>(pScMod->GetViewShell()) : nullptr;

        // Also take foreign reference input into account here (e.g. FunctionsAutoPilot),
        // FormEditData, if we're switching from Help to Calc:
        if ( !bFormulaMode && !pScMod->IsFormulaMode() &&
             ( !pScTabViewShell || !pScTabViewShell->GetFormEditData() ) )
        {
            bool bIgnore = false;
            if ( bModified )
            {
                if (pState->GetPos() != aCursorPos)
                {
                    if (!bProtected)
                        EnterHandler();
                }
                else
                    bIgnore = true;
            }

            if ( !bIgnore )
            {
                const ScAddress&        rSPos   = pState->GetStartPos();
                const ScAddress&        rEPos   = pState->GetEndPos();
                const EditTextObject*   pData   = pState->GetEditData();
                OUString aString = pState->GetString();
                bool bTxtMod = false;
                ScDocShell* pDocSh = pActiveViewSh->GetViewData().GetDocShell();
                ScDocument& rDoc = pDocSh->GetDocument();

                aCursorPos  = pState->GetPos();

                if ( pData )
                    bTxtMod = true;
                else if ( bHadObject )
                    bTxtMod = true;
                else if ( bTextValid )
                    bTxtMod = ( aString != aCurrentText );
                else
                    bTxtMod = ( aString != GetEditText(mpEditEngine.get()) );

                if ( bTxtMod || bForce )
                {
                    if (pData)
                    {
                        mpEditEngine->SetText( *pData );
                        if (pInputWin)
                            aString = ScEditUtil::GetMultilineString(*mpEditEngine);
                        else
                            aString = GetEditText(mpEditEngine.get());
                        lcl_RemoveTabs(aString);
                        bTextValid = false;
                        aCurrentText.clear();
                    }
                    else
                    {
                        aCurrentText = aString;
                        bTextValid = true;              //! To begin with remember as a string
                    }

                    if ( pInputWin )
                        pInputWin->SetTextString(aString);

                    if (comphelper::LibreOfficeKit::isActive() && pActiveViewSh)
                        pActiveViewSh->libreOfficeKitViewCallback(LOK_CALLBACK_CELL_FORMULA, aString.toUtf8().getStr());
                }

                if ( pInputWin || comphelper::LibreOfficeKit::isActive())                        // Named range input
                {
                    OUString aPosStr;
                    const ScAddress::Details aAddrDetails( &rDoc, aCursorPos );

                    // Is the range a name?
                    //! Find by Timer?
                    if ( pActiveViewSh )
                        pActiveViewSh->GetViewData().GetDocument()->
                            GetRangeAtBlock( ScRange( rSPos, rEPos ), &aPosStr );

                    if ( aPosStr.isEmpty() )           // Not a name -> format
                    {
                        ScRefFlags nFlags = ScRefFlags::ZERO;
                        if( aAddrDetails.eConv == formula::FormulaGrammar::CONV_XL_R1C1 )
                            nFlags |= ScRefFlags::COL_ABS | ScRefFlags::ROW_ABS;
                        if ( rSPos != rEPos )
                        {
                            ScRange r(rSPos, rEPos);
                            applyStartToEndFlags(nFlags);
                            aPosStr = r.Format(ScRefFlags::VALID | nFlags, &rDoc, aAddrDetails);
                        }
                        else
                            aPosStr = aCursorPos.Format(ScRefFlags::VALID | nFlags, &rDoc, aAddrDetails);
                    }

                    if (pInputWin)
                    {
                        // Disable the accessible VALUE_CHANGE event
                        bool bIsSuppressed = pInputWin->IsAccessibilityEventsSuppressed(false);
                        pInputWin->SetAccessibilityEventsSuppressed(true);
                        pInputWin->SetPosString(aPosStr);
                        pInputWin->SetAccessibilityEventsSuppressed(bIsSuppressed);
                        pInputWin->SetSumAssignMode();
                    }

                    if (comphelper::LibreOfficeKit::isActive() && pActiveViewSh)
                        pActiveViewSh->libreOfficeKitViewCallback(LOK_CALLBACK_CELL_ADDRESS, aPosStr.toUtf8().getStr());
                }

                if (bStopEditing)
                    SfxGetpApp()->Broadcast( SfxHint( SfxHintId::ScKillEditView ) );

                //  As long as the content is not edited, turn off online spelling.
                //  Online spelling is turned back on in StartTable, after setting
                //  the right language from cell attributes.

                EEControlBits nCntrl = mpEditEngine->GetControlWord();
                if ( nCntrl & EEControlBits::ONLINESPELLING )
                    mpEditEngine->SetControlWord( nCntrl & ~EEControlBits::ONLINESPELLING );

                bModified = false;
                bSelIsRef = false;
                bProtected = false;
                bCommandErrorShown = false;
            }
        }

        if ( pInputWin)
        {
            // Do not enable if RefDialog is open
            if(!pScMod->IsFormulaMode()&& !pScMod->IsRefDialogOpen())
            {
                if ( !pInputWin->IsEnabled())
                {
                    pDelayTimer->Stop();
                    pInputWin->Enable();
                }
            }
            else if(pScMod->IsRefDialogOpen())
            {   // Because every document has its own InputWin,
                // we should start Timer again, because the input line may
                // still be active
                if ( !pDelayTimer->IsActive() )
                    pDelayTimer->Start();
            }
        }
    }
    else // !pState || !pActiveViewSh
    {
        if ( !pDelayTimer->IsActive() )
            pDelayTimer->Start();
    }

    HideTip();
    HideTipBelow();
    bInOwnChange = false;
}

void ScInputHandler::UpdateCellAdjust( SvxCellHorJustify eJust )
{
    eAttrAdjust = eJust;
    UpdateAdjust( 0 );
}

void ScInputHandler::ResetDelayTimer()
{
    if( pDelayTimer->IsActive() )
    {
        pDelayTimer->Stop();
        if ( pInputWin )
            pInputWin->Enable();
    }
}

IMPL_LINK_NOARG( ScInputHandler, DelayTimer, Timer*, void )
{
    if ( nullptr == pLastState || SC_MOD()->IsFormulaMode() || SC_MOD()->IsRefDialogOpen())
    {
        //! New method at ScModule to query if function autopilot is open
        SfxViewFrame* pViewFrm = SfxViewFrame::Current();
        if ( pViewFrm && pViewFrm->GetChildWindow( SID_OPENDLG_FUNCTION ) )
        {
            if ( pInputWin)
            {
                pInputWin->EnableButtons( false );
                pInputWin->Disable();
            }
        }
        else if ( !bFormulaMode ) // Keep formula e.g. for help
        {
            bInOwnChange = true; // disable ModifyHdl (reset below)

            pActiveViewSh = nullptr;
            mpEditEngine->SetText( EMPTY_OUSTRING );
            if ( pInputWin )
            {
                pInputWin->SetPosString( EMPTY_OUSTRING );
                pInputWin->SetTextString( EMPTY_OUSTRING );
                pInputWin->Disable();
            }

            bInOwnChange = false;
        }
    }
}

void ScInputHandler::InputSelection( const EditView* pView )
{
    SyncViews( pView );
    ShowTipCursor();
    UpdateParenthesis(); // Selection changed -> update parentheses highlighting

    // When the selection is changed manually, stop overwriting parentheses
    ResetAutoPar();
}

void ScInputHandler::InputChanged( const EditView* pView, bool bFromNotify )
{
    UpdateActiveView();

    // #i20282# DataChanged needs to know if this is from the input line's modify handler
    bool bFromTopNotify = ( bFromNotify && pView == pTopView );

    bool bNewView = DataChanging();                     //FIXME: Is this at all possible?
    aCurrentText = pView->GetEditEngine()->GetText();   // Also remember the string
    mpEditEngine->SetText( aCurrentText );
    DataChanged( bFromTopNotify );
    bTextValid = true; // Is set to false in DataChanged

    if ( pActiveViewSh )
    {
        ScViewData& rViewData = pActiveViewSh->GetViewData();
        if ( bNewView )
            rViewData.GetDocShell()->PostEditView( mpEditEngine.get(), aCursorPos );

        rViewData.EditGrowY();
        rViewData.EditGrowX();
    }

    SyncViews( pView );
}

const OUString& ScInputHandler::GetEditString()
{
    if (mpEditEngine)
    {
        aCurrentText = mpEditEngine->GetText(); // Always new from Engine
        bTextValid = true;
    }

    return aCurrentText;
}

Size ScInputHandler::GetTextSize()
{
    Size aSize;
    if ( mpEditEngine )
        aSize = Size( mpEditEngine->CalcTextWidth(), mpEditEngine->GetTextHeight() );

    return aSize;
}

bool ScInputHandler::GetTextAndFields( ScEditEngineDefaulter& rDestEngine )
{
    bool bRet = false;
    if (mpEditEngine)
    {
        // Contains field?
        sal_Int32 nParCnt = mpEditEngine->GetParagraphCount();
        SfxItemSet aSet = mpEditEngine->GetAttribs( ESelection(0,0,nParCnt,0) );
        SfxItemState eFieldState = aSet.GetItemState( EE_FEATURE_FIELD, false );
        if ( eFieldState == SfxItemState::DONTCARE || eFieldState == SfxItemState::SET )
        {
            // Copy content
            std::unique_ptr<EditTextObject> pObj = mpEditEngine->CreateTextObject();
            rDestEngine.SetText(*pObj);
            pObj.reset();

            // Delete attributes
            for (sal_Int32 i=0; i<nParCnt; i++)
                rDestEngine.RemoveCharAttribs( i );

            // Combine paragraphs
            while ( nParCnt > 1 )
            {
                sal_Int32 nLen = rDestEngine.GetTextLen( 0 );
                ESelection aSel( 0,nLen, 1,0 );
                rDestEngine.QuickInsertText( OUString(' '), aSel ); // Replace line break with space
                --nParCnt;
            }

            bRet = true;
        }
    }
    return bRet;
}

/**
 * Methods for FunctionAutoPilot:
 * InputGetSelection, InputSetSelection, InputReplaceSelection, InputGetFormulaStr
 */
void ScInputHandler::InputGetSelection( sal_Int32& rStart, sal_Int32& rEnd )
{
    rStart = nFormSelStart;
    rEnd = nFormSelEnd;
}

EditView* ScInputHandler::GetFuncEditView()
{
    UpdateActiveView(); // Due to pTableView

    EditView* pView = nullptr;
    if ( pInputWin )
    {
        pInputWin->MakeDialogEditView();
        pView = pInputWin->GetEditView();
    }
    else
    {
        if ( eMode != SC_INPUT_TABLE )
        {
            bCreatingFuncView = true; // Don't display RangeFinder
            SetMode( SC_INPUT_TABLE );
            bCreatingFuncView = false;
            if ( pTableView )
                pTableView->GetEditEngine()->SetText( EMPTY_OUSTRING );
        }
        pView = pTableView;
    }

    return pView;
}

void ScInputHandler::InputSetSelection( sal_Int32 nStart, sal_Int32 nEnd )
{
    if ( nStart <= nEnd )
    {
        nFormSelStart = nStart;
        nFormSelEnd = nEnd;
    }
    else
    {
        nFormSelEnd = nStart;
        nFormSelStart = nEnd;
    }

    EditView* pView = GetFuncEditView();
    if (pView)
        pView->SetSelection( ESelection(0,nStart, 0,nEnd) );

    bModified = true;
}

void ScInputHandler::InputReplaceSelection( const OUString& rStr )
{
    if (!pRefViewSh)
        pRefViewSh = pActiveViewSh;

    OSL_ENSURE(nFormSelEnd>=nFormSelStart,"Selection broken...");

    sal_Int32 nOldLen = nFormSelEnd - nFormSelStart;
    sal_Int32 nNewLen = rStr.getLength();

    OUStringBuffer aBuf(aFormText);
    if (nOldLen)
        aBuf.remove(nFormSelStart, nOldLen);
    if (nNewLen)
        aBuf.insert(nFormSelStart, rStr);

    aFormText = aBuf.makeStringAndClear();

    nFormSelEnd = nFormSelStart + nNewLen;

    EditView* pView = GetFuncEditView();
    if (pView)
    {
        pView->SetEditEngineUpdateMode( false );
        pView->GetEditEngine()->SetText( aFormText );
        pView->SetSelection( ESelection(0,nFormSelStart, 0,nFormSelEnd) );
        pView->SetEditEngineUpdateMode( true );
    }
    bModified = true;
}

void ScInputHandler::InputTurnOffWinEngine()
{
    bInOwnChange = true;                // disable ModifyHdl (reset below)

    eMode = SC_INPUT_NONE;
    /* TODO: it would be better if there was some way to reset the input bar
     * engine instead of deleting and having it recreate through
     * GetFuncEditView(), but first least invasively let this fix fdo#71667 and
     * fdo#72278 without reintroducing fdo#69971. */
    StopInputWinEngine(true);

    bInOwnChange = false;
}

/**
 * ScInputHdlState
 */
ScInputHdlState::ScInputHdlState( const ScAddress& rCurPos,
                                  const ScAddress& rStartPos,
                                  const ScAddress& rEndPos,
                                  const OUString& rString,
                                  const EditTextObject* pData )
    :   aCursorPos  ( rCurPos ),
        aStartPos   ( rStartPos ),
        aEndPos     ( rEndPos ),
        aString     ( rString ),
        pEditData   ( pData ? pData->Clone() : nullptr )
{
}

ScInputHdlState::ScInputHdlState( const ScInputHdlState& rCpy )
{
    *this = rCpy;
}

ScInputHdlState::~ScInputHdlState()
{
}

bool ScInputHdlState::operator==( const ScInputHdlState& r ) const
{
    return (    (aStartPos  == r.aStartPos)
             && (aEndPos    == r.aEndPos)
             && (aCursorPos == r.aCursorPos)
             && (aString    == r.aString)
             && ScGlobal::EETextObjEqual( pEditData.get(), r.pEditData.get() ) );
}

ScInputHdlState& ScInputHdlState::operator=( const ScInputHdlState& r )
{
    if (this != &r)
    {
        aCursorPos  = r.aCursorPos;
        aStartPos   = r.aStartPos;
        aEndPos     = r.aEndPos;
        aString     = r.aString;
        pEditData.reset();
        if (r.pEditData)
            pEditData = r.pEditData->Clone();
    }
    return *this;
}

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