File: search.c

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

#ifdef HAVE_CONFIG_H
#include "../config.h"
#endif

#include "search.h"
#include "regularExp.h"
#include "textBuf.h"
#include "text.h"
#include "nedit.h"
#include "server.h"
#include "window.h" 
#include "userCmds.h" 
#include "preferences.h"
#include "file.h"
#include "highlight.h"
#include "selection.h"
#ifdef REPLACE_SCOPE
#include "textDisp.h"
#include "textP.h"
#endif
#include "../util/DialogF.h"
#include "../util/misc.h"

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#ifdef VMS
#include "../util/VMSparam.h"
#else
#ifndef __MVS__
#include <sys/param.h>
#endif
#endif /*VMS*/

#include <Xm/Xm.h>
#include <X11/Shell.h>
#include <Xm/XmP.h>
#include <Xm/Form.h>
#include <Xm/Label.h>
#ifdef REPLACE_SCOPE
#if XmVersion >= 1002
#include <Xm/PrimitiveP.h>
#endif
#endif
#include <Xm/PushB.h>
#include <Xm/RowColumn.h>
#include <Xm/Text.h>
#include <Xm/ToggleB.h>
#include <Xm/List.h>
#include <X11/Xatom.h>		/* for getting selection */
#include <X11/keysym.h>
#include <X11/X.h>		/* " " */

#ifdef HAVE_DEBUG_H
#include "../debug.h"
#endif


int NHist = 0;

typedef struct _SelectionInfo {
    int done;
    WindowInfo* window;
    char* selection;
} SelectionInfo;

typedef struct {
    int direction;
    int searchType;
    int searchWrap;
} SearchSelectedCallData;

/* History mechanism for search and replace strings */
static char *SearchHistory[MAX_SEARCH_HISTORY];
static char *ReplaceHistory[MAX_SEARCH_HISTORY];
static int SearchTypeHistory[MAX_SEARCH_HISTORY];
static int HistStart = 0;

static int textFieldNonEmpty(Widget w);
static void setTextField(WindowInfo* window, Time time, Widget textField);
static void getSelectionCB(Widget w, SelectionInfo *selectionInfo, Atom *selection,
	Atom *type, char *value, int *length, int *format);
static void fFocusCB(Widget w, WindowInfo *window, caddr_t *callData);
static void rFocusCB(Widget w, WindowInfo *window, caddr_t *callData);
static void rKeepCB(Widget w, WindowInfo *window, caddr_t *callData);
static void fKeepCB(Widget w, WindowInfo *window, caddr_t *callData);
static void replaceCB(Widget w, WindowInfo *window,
	XmAnyCallbackStruct *callData); 
static void replaceAllCB(Widget w, WindowInfo *window,
	XmAnyCallbackStruct *callData);
static void rInSelCB(Widget w, WindowInfo *window,
	XmAnyCallbackStruct *callData); 
static void rCancelCB(Widget w, WindowInfo *window, caddr_t callData);
static void fCancelCB(Widget w, WindowInfo *window, caddr_t callData);
static void rFindCB(Widget w,WindowInfo *window,XmAnyCallbackStruct *callData);
static void rFindTextValueChangedCB(Widget w, WindowInfo *window, XKeyEvent *event);
static void rFindArrowKeyCB(Widget w, WindowInfo *window, XKeyEvent *event);

static void rSetActionButtons(WindowInfo* window,
                              int replaceBtn,
                              int replaceFindBtn,
                              int replaceAndFindBtn,
#ifndef REPLACE_SCOPE
                              int replaceInWinBtn,
                              int replaceInSelBtn,
#endif      
                              int replaceAllBtn);
#ifdef REPLACE_SCOPE
static void rScopeWinCB(Widget w, WindowInfo *window, 
	XmAnyCallbackStruct *callData);
static void rScopeSelCB(Widget w, WindowInfo *window, 
	XmAnyCallbackStruct *callData);
static void rScopeMultiCB(Widget w, WindowInfo *window, 
	XmAnyCallbackStruct *callData);
static void replaceAllScopeCB(Widget w, WindowInfo *window, 
	XmAnyCallbackStruct *callData);
#endif

static void replaceArrowKeyCB(Widget w, WindowInfo *window, XKeyEvent *event);
static void fUpdateActionButtons(WindowInfo *window);
static void findTextValueChangedCB(Widget w, WindowInfo *window, XKeyEvent *event);
static void findArrowKeyCB(Widget w, WindowInfo *window, XKeyEvent *event);
static void replaceFindCB(Widget w, WindowInfo *window, XmAnyCallbackStruct *callData);
static void findCB(Widget w, WindowInfo *window,XmAnyCallbackStruct *callData); 
static void replaceMultiFileCB(Widget w, WindowInfo *window,
	XmAnyCallbackStruct *callData);
static void rMultiFileReplaceCB(Widget w, WindowInfo *window,  
       XmAnyCallbackStruct * callData);
static void rMultiFileCancelCB(Widget w, WindowInfo *window, caddr_t callData);
static void rMultiFileSelectAllCB(Widget w, WindowInfo *window, 
       XmAnyCallbackStruct *callData);
static void rMultiFileDeselectAllCB(Widget w, WindowInfo *window, 
       XmAnyCallbackStruct * callData);
static void rMultiFilePathCB(Widget w, WindowInfo *window,  
	XmAnyCallbackStruct *callData);
static void uploadFileListItems(WindowInfo* window, Bool replace);
static int countWindows(void);
static int countWritableWindows(void);
static void collectWritableWindows(WindowInfo* window);
static void freeWritableWindowsCB(Widget w, WindowInfo* window,
                                  XmAnyCallbackStruct *callData);
static void checkMultiReplaceListForDoomedW(WindowInfo* window, 
                                                     WindowInfo* doomedWindow);
static void removeDoomedWindowFromList(WindowInfo* window, int index);
static void unmanageReplaceDialogs(WindowInfo *window);
static void flashTimeoutProc(XtPointer clientData, XtIntervalId *id);
static void eraseFlash(WindowInfo *window);
static int getReplaceDlogInfo(WindowInfo *window, int *direction,
	char *searchString, char *replaceString, int *searchType);
static int getFindDlogInfo(WindowInfo *window, int *direction,
	char *searchString, int *searchType);
static void selectedSearchCB(Widget w, XtPointer callData, Atom *selection,
	Atom *type, char *value, int *length, int *format);
static void iSearchTextClearAndPasteAP(Widget w, XEvent *event, String *args,
        Cardinal *nArg);
static void iSearchTextClearCB(Widget w, WindowInfo *window,
	XmAnyCallbackStruct *callData);
static void iSearchTextActivateCB(Widget w, WindowInfo *window,
	XmAnyCallbackStruct *callData);
static void iSearchTextValueChangedCB(Widget w, WindowInfo *window,
	XmAnyCallbackStruct *callData);
static void iSearchTextKeyEH(Widget w, WindowInfo *window,
	XKeyEvent *event, Boolean *continueDispatch);
static int searchLiteral(const char *string, const char *searchString, int caseSense, 
	int direction, int wrap, int beginPos, int *startPos, int *endPos,
	int *searchExtentBW, int *searchExtentFW);
static int searchLiteralWord(const char *string, const char *searchString, int caseSense,
 	int direction, int wrap, int beginPos, int *startPos, int *endPos, 
        const char * delimiters);
static int searchRegex(const char *string, const char *searchString, int direction,
	int wrap, int beginPos, int *startPos, int *endPos, int *searchExtentBW,
	int *searchExtentFW, const char *delimiters, int defaultFlags);
static int forwardRegexSearch(const char *string, const char *searchString, int wrap,
	int beginPos, int *startPos, int *endPos, int *searchExtentBW,
        int *searchExtentFW, const char *delimiters, int defaultFlags);
static int backwardRegexSearch(const char *string, const char *searchString, int wrap,
	int beginPos, int *startPos, int *endPos, int *searchExtentBW,
        int *searchExtentFW, const char *delimiters, int defaultFlags);
static void upCaseString(char *outString, const char *inString);
static void downCaseString(char *outString, const char *inString);
static void resetFindTabGroup(WindowInfo *window);
static void resetReplaceTabGroup(WindowInfo *window);
static int searchMatchesSelection(WindowInfo *window, const char *searchString,
	int searchType, int *left, int *right, int *searchExtentBW, 
	int *searchExtentFW);
static int findMatchingChar(WindowInfo *window, char toMatch,
	void *toMatchStyle, int charPos, int startLimit, int endLimit, 
	int *matchPos);
static void replaceUsingRE(const char *searchStr, const char *replaceStr,
	const char *sourceStr, int beginPos, char *destStr, 
        int maxDestLen, int prevChar, const char *delimiters, int defaultFlags);
static void saveSearchHistory(const char *searchString,
        const char *replaceString, int searchType, int isIncremental);
static int historyIndex(int nCycles);
static char *searchTypeArg(int searchType);
static char *searchWrapArg(int searchWrap);
static char *directionArg(int direction);
static int isRegexType(int searchType);
static int defaultRegexFlags(int searchType);
static void findRegExpToggleCB(Widget w, XtPointer clientData, 
	XtPointer callData);
static void replaceRegExpToggleCB(Widget w, XtPointer clientData, 
	XtPointer callData);
static void iSearchRegExpToggleCB(Widget w, XtPointer clientData, 
	XtPointer callData);
static void findCaseToggleCB(Widget w, XtPointer clientData, 
	XtPointer callData);
static void replaceCaseToggleCB(Widget w, XtPointer clientData, 
	XtPointer callData);
static void iSearchCaseToggleCB(Widget w, XtPointer clientData, 
	XtPointer callData);
static void iSearchTryBeepOnWrap(WindowInfo *window, int direction, 
      	int beginPos, int startPos); 
static void iSearchRecordLastBeginPos(WindowInfo *window, int direction, 
	int initPos); 

typedef struct _charMatchTable {
    char c;
    char match;
    char direction;
} charMatchTable;

#define N_MATCH_CHARS 13
#define N_FLASH_CHARS 6
static charMatchTable MatchingChars[N_MATCH_CHARS] = {
    {'{', '}', SEARCH_FORWARD},
    {'}', '{', SEARCH_BACKWARD},
    {'(', ')', SEARCH_FORWARD},
    {')', '(', SEARCH_BACKWARD},
    {'[', ']', SEARCH_FORWARD},
    {']', '[', SEARCH_BACKWARD},
    {'<', '>', SEARCH_FORWARD},
    {'>', '<', SEARCH_BACKWARD},
    {'/', '/', SEARCH_FORWARD},
    {'"', '"', SEARCH_FORWARD},
    {'\'', '\'', SEARCH_FORWARD},
    {'`', '`', SEARCH_FORWARD},
    {'\\', '\\', SEARCH_FORWARD},
};

/*
** Definitions for the search method strings, used as arguments for 
** macro search subroutines and search action routines
*/
static char *searchTypeStrings[] = {
    "literal",          /* SEARCH_LITERAL         */
    "case",             /* SEARCH_CASE_SENSE      */
    "regex",            /* SEARCH_REGEX           */
    "word",             /* SEARCH_LITERAL_WORD    */
    "caseWord",         /* SEARCH_CASE_SENSE_WORD */
    "regexNoCase",      /* SEARCH_REGEX_NOCASE    */
    NULL
};

/*
** Shared routine for replace and find dialogs and i-search bar to initialize
** the state of the regex/case/word toggle buttons, and the sticky case 
** sensitivity states.
*/    
static void initToggleButtons(int searchType, Widget regexToggle,
                              Widget caseToggle, Widget* wordToggle,
                              Bool* lastLiteralCase,
                              Bool* lastRegexCase)
{
    /* Set the initial search type and remember the corresponding case
       sensitivity states in case sticky case sensitivity is required. */
    switch (searchType) {
      case SEARCH_LITERAL:
              *lastLiteralCase = False;
              *lastRegexCase   = True;
	      XmToggleButtonSetState(regexToggle, False, False);
	      XmToggleButtonSetState(caseToggle,  False, False);
	      if (wordToggle) {
		  XmToggleButtonSetState(*wordToggle, False, False);
                  XtSetSensitive(*wordToggle, True);
              }
      break;
      case SEARCH_CASE_SENSE:
              *lastLiteralCase = True;
              *lastRegexCase   = True;
	      XmToggleButtonSetState(regexToggle, False, False);
	      XmToggleButtonSetState(caseToggle,  True,  False);
	      if (wordToggle) {
                  XmToggleButtonSetState(*wordToggle, False, False);
                  XtSetSensitive(*wordToggle, True);
              }
      break;
      case SEARCH_LITERAL_WORD:
              *lastLiteralCase = False;
              *lastRegexCase   = True;
	      XmToggleButtonSetState(regexToggle, False, False);
	      XmToggleButtonSetState(caseToggle, False, False);
	      if (wordToggle) {
                  XmToggleButtonSetState(*wordToggle,  True,  False);
                  XtSetSensitive(*wordToggle, True);
              }
      break;
      case SEARCH_CASE_SENSE_WORD:
              *lastLiteralCase = True;
              *lastRegexCase   = True;
	      XmToggleButtonSetState(regexToggle, False, False);
	      XmToggleButtonSetState(caseToggle,  True,  False);
	      if (wordToggle) {
                  XmToggleButtonSetState(*wordToggle,  True,  False);
                  XtSetSensitive(*wordToggle, True);
              }
      break;
      case SEARCH_REGEX:
              *lastLiteralCase = False;
              *lastRegexCase   = True;
	      XmToggleButtonSetState(regexToggle, True,  False);
	      XmToggleButtonSetState(caseToggle,  True,  False);
	      if (wordToggle) {
                  XmToggleButtonSetState(*wordToggle,  False, False);
                  XtSetSensitive(*wordToggle, False);
              }
      break;
      case SEARCH_REGEX_NOCASE:
              *lastLiteralCase = False;
              *lastRegexCase   = False;
	      XmToggleButtonSetState(regexToggle, True,  False);
	      XmToggleButtonSetState(caseToggle,  False, False);
	      if (wordToggle) {
                  XmToggleButtonSetState(*wordToggle,  False, False);
                  XtSetSensitive(*wordToggle, False);
              }
      break;
    }
}

#ifdef REPLACE_SCOPE
/*
** Checks whether a selection spans multiple lines. Used to decide on the
** default scope for replace dialogs. 
** This routine introduces a dependency on textDisp.h, which is not so nice,
** but I currently don't have a cleaner solution.
*/
static int selectionSpansMultipleLines(WindowInfo *window)
{
    int selStart, selEnd, isRect, rectStart, rectEnd, lineStartStart,
        lineStartEnd;
    int lineWidth;
    textDisp *textD;
    
    if (!BufGetSelectionPos(window->buffer, &selStart, &selEnd, &isRect,
    	    &rectStart, &rectEnd))
    	return FALSE;

    /* This is kind of tricky. The perception of a line depends on the
       line wrap mode being used. So in theory, we should take into 
       account the layout of the text on the screen. However, the 
       routine to calculate a line number for a given character position
       (TextDPosToLineAndCol) only works for displayed lines, so we cannot
       use it. Therefore, we use this simple heuristic:
        - If a newline is found between the start and end of the selection,
	  we obviously have a multi-line selection.
	- If no newline is found, but the distance between the start and the
          end of the selection is larger than the number of characters 
	  displayed on a line, and we're in continuous wrap mode,
	  we also assume a multi-line selection.
    */
     
    lineStartStart = BufStartOfLine(window->buffer, selStart);
    lineStartEnd = BufStartOfLine(window->buffer, selEnd);
    /* If the line starts differ, we have a "\n" in between. */
    if (lineStartStart != lineStartEnd ) 
	return TRUE;     
    
    if (window->wrapMode != CONTINUOUS_WRAP)
	return FALSE; /* Same line */
	    
    /* Estimate the number of characters on a line */
    textD = ((TextWidget)window->textArea)->text.textD;
    if (textD->fontStruct->max_bounds.width > 0)
	lineWidth = textD->width / textD->fontStruct->max_bounds.width;
    else
	lineWidth = 1;
    if (lineWidth < 1) lineWidth = 1; /* Just in case */
    
    /* Estimate the numbers of line breaks from the start of the line to
       the start and ending positions of the selection and compare.*/
    if ((selStart-lineStartStart)/lineWidth !=
        (selEnd-lineStartStart)/lineWidth )
       return TRUE; /* Spans multiple lines */
       
    return FALSE; /* Small selection; probably doesn't span lines */
}
#endif

void DoFindReplaceDlog(WindowInfo *window, int direction, int keepDialogs,
        int searchType, Time time)
{

    /* Create the dialog if it doesn't already exist */
    if (window->replaceDlog == NULL)
    	CreateReplaceDlog(window->shell, window);
    
    setTextField(window, time, window->replaceText);

    /* If the window is already up, just pop it to the top */
    if (XtIsManaged(window->replaceDlog)) {
	RaiseShellWindow(XtParent(window->replaceDlog));
	return;
    }
    	
    /* Blank the Replace with field */
    XmTextSetString(window->replaceWithText, "");
        
    /* Set the initial search type */
    initToggleButtons(searchType, window->replaceRegexToggle,
                      window->replaceCaseToggle, &window->replaceWordToggle,
                      &window->replaceLastLiteralCase,
                      &window->replaceLastRegexCase);
    
    /* Set the initial direction based on the direction argument */
    XmToggleButtonSetState(window->replaceRevToggle, 
	direction == SEARCH_FORWARD ? False: True, True);
    
    /* Set the state of the Keep Dialog Up button */
    XmToggleButtonSetState(window->replaceKeepBtn, keepDialogs, True);
    
#ifdef REPLACE_SCOPE
    /* Set the state of the scope radio buttons to "In Window".
       Notify to make sure that callbacks are called. 
       NOTE: due to an apparent bug in OpenMotif, the radio buttons may
       get stuck after resetting the scope to "In Window". Therefore we must
       use RadioButtonChangeState(), which contains a workaround. */
    if (window->wasSelected) {
	/* If a selection exists, the default scope depends on the preference
           of the user. */
	switch(GetPrefReplaceDefScope()) {
	   case REPL_DEF_SCOPE_SELECTION:
		/* The user prefers selection scope, no matter what the
		   size of the selection is. */	   
		RadioButtonChangeState(window->replaceScopeSelToggle, 
                                       True, True);
		break;
	   case REPL_DEF_SCOPE_SMART:
		if (selectionSpansMultipleLines(window)) {
		    /* If the selection spans multiple lines, the user most
		       likely wants to perform a replacement in the selection */
		    RadioButtonChangeState(window->replaceScopeSelToggle, 
                                           True, True);
		}
		else {
		    /* It's unlikely that the user wants a replacement in a
		       tiny selection only. */
		    RadioButtonChangeState(window->replaceScopeWinToggle,
                                           True, True);
		}
		break;
	   default:
	   	/* The user always wants window scope as default. */
		RadioButtonChangeState(window->replaceScopeWinToggle, 
                                       True, True);
		break;
	}
    }
    else {
       /* No selection -> always choose "In Window" as default. */
	RadioButtonChangeState(window->replaceScopeWinToggle, True, True);
    }
#endif

    UpdateReplaceActionButtons(window);
    
    /* Start the search history mechanism at the current history item */
    window->rHistIndex = 0;
    
    /* Display the dialog */
    ManageDialogCenteredOnPointer(window->replaceDlog);
    
    /* Workaround: LessTif (as of version 0.89) needs reminding of who had
       the focus when the dialog was unmanaged.  When re-managed, focus is
       lost and events fall through to the window below. */
    XmProcessTraversal(window->replaceText, XmTRAVERSE_CURRENT);
}

static void setTextField(WindowInfo *window, Time time, Widget textField)
{
    XEvent nextEvent;
    char *primary_selection = 0;
    SelectionInfo *selectionInfo = XtNew(SelectionInfo);

    if (GetPrefFindReplaceUsesSelection()) {
        selectionInfo->done = 0;
        selectionInfo->window = window;
        selectionInfo->selection = 0;
        XtGetSelectionValue(window->textArea, XA_PRIMARY, XA_STRING,
                            (XtSelectionCallbackProc)getSelectionCB, selectionInfo, time);
        while (selectionInfo->done == 0) {
            XtAppNextEvent(XtWidgetToApplicationContext(window->textArea), &nextEvent);
            ServerDispatchEvent(&nextEvent);
        }
        primary_selection = selectionInfo->selection;
    }
    if (primary_selection == 0) {
        primary_selection = XtNewString("");
    }

    /* Update the field */
    XmTextSetString(textField, primary_selection);

    XtFree(primary_selection);
    XtFree((char*)selectionInfo);
}    

static void getSelectionCB(Widget w, SelectionInfo *selectionInfo, Atom *selection,
        Atom *type, char *value, int *length, int *format)
{
    WindowInfo *window = selectionInfo->window;

    /* return an empty string if we can't get the selection data */
    if (*type == XT_CONVERT_FAIL || *type != XA_STRING || value == NULL || *length == 0) {
        XtFree(value);
        selectionInfo->selection = 0;
        selectionInfo->done = 1;
        return;
    }
    /* return an empty string if the data is not of the correct format. */
    if (*format != 8) {
        DialogF(DF_WARN, window->shell, 1, "Invalid Format",
                "NEdit can't handle non 8-bit text", "OK");
        XtFree(value);
        selectionInfo->selection = 0;
        selectionInfo->done = 1;
        return;
    }
    selectionInfo->selection = XtMalloc(*length+1);
    memcpy(selectionInfo->selection, value, *length);
    selectionInfo->selection[*length] = 0;
    XtFree(value);
    selectionInfo->done = 1;
}

void DoFindDlog(WindowInfo *window, int direction, int keepDialogs,
        int searchType, Time time)
{

    /* Create the dialog if it doesn't already exist */
    if (window->findDlog == NULL)
    	CreateFindDlog(window->shell, window);
    
    setTextField(window, time, window->findText);

    /* If the window is already up, just pop it to the top */
    if (XtIsManaged(window->findDlog)) {
	RaiseShellWindow(XtParent(window->findDlog));
	return;
    }

    /* Set the initial search type */
    initToggleButtons(searchType, window->findRegexToggle,
                      window->findCaseToggle, &window->findWordToggle,
                      &window->findLastLiteralCase,
                      &window->findLastRegexCase);
  
    /* Set the initial direction based on the direction argument */
    XmToggleButtonSetState(window->findRevToggle,
	direction == SEARCH_FORWARD ? False : True, True);
    
    /* Set the state of the Keep Dialog Up button */
    XmToggleButtonSetState(window->findKeepBtn, keepDialogs, True);
    
    /* Set the state of the Find button */
    fUpdateActionButtons(window);

    /* start the search history mechanism at the current history item */
    window->fHistIndex = 0;
    
    /* Display the dialog */
    ManageDialogCenteredOnPointer(window->findDlog);

    /* Workaround: LessTif (as of version 0.89) needs reminding of who had
       the focus when the dialog was unmanaged.  When re-managed, focus is
       lost and events fall through to the window below. */
    XmProcessTraversal(window->findText, XmTRAVERSE_CURRENT);
}

void DoReplaceMultiFileDlog(WindowInfo *window)
{
    char	searchString[SEARCHMAX], replaceString[SEARCHMAX];
    int		direction, searchType;
    
    /* Validate and fetch the find and replace strings from the dialog */
    if (!getReplaceDlogInfo(window, &direction, searchString, replaceString,
    	    &searchType))
  	return;
    
    /* Don't let the user select files when no replacement can be made */
    if (*searchString == '\0') {
       /* Set the initial focus of the dialog back to the search string */
       resetReplaceTabGroup(window);
       /* pop down the replace dialog */
       if (!XmToggleButtonGetState(window->replaceKeepBtn))
    	   unmanageReplaceDialogs(window);
       return;
    }
    
    /* Create the dialog if it doesn't already exist */
    if (window->replaceMultiFileDlog == NULL)
    	CreateReplaceMultiFileDlog(window);

    /* Raising the window doesn't make sense. It is modal, so we 
       can't get here unless it is unmanaged */
    /* Prepare a list of writable windows */
    collectWritableWindows(window);
    
    /* Initialize/update the list of files. */
    uploadFileListItems(window, False);
    
    /* Display the dialog */
    ManageDialogCenteredOnPointer(window->replaceMultiFileDlog);
}

/*
** If a window is closed (possibly via the window manager) while it is on the
** multi-file replace dialog list of any other window (or even the same one),
** we must update those lists or we end up with dangling references.
** Normally, there can be only one of those dialogs at the same time
** (application modal), but Lesstif doesn't (always) honor application
** modalness, so there can be more than one dialog. 
*/
void RemoveFromMultiReplaceDialog(WindowInfo *doomedWindow)
{
    WindowInfo *w;
    
    for (w=WindowList; w!=NULL; w=w->next) 
       if (w->writableWindows) 
          /* A multi-file replacement dialog is up for this window */
          checkMultiReplaceListForDoomedW(w, doomedWindow);
}

void CreateReplaceDlog(Widget parent, WindowInfo *window)
{
    Arg    	args[50];
    int    	argcnt, defaultBtnOffset;
    XmString	st1;
    Widget	form, btnForm;
#ifdef REPLACE_SCOPE
    Widget	scopeForm, replaceAllBtn;
#else
    Widget	label3, allForm;
#endif
    Widget	inWinBtn, inSelBtn, inMultiBtn;
    Widget    	searchTypeBox;
    Widget    	label2, label1, label, replaceText, findText;
    Widget    	findBtn,  cancelBtn, replaceBtn;
    Widget    	replaceFindBtn;
    Widget	searchDirBox, reverseBtn, keepBtn;
    char 	title[MAXPATHLEN + 19];
    Dimension	shadowThickness;
 
    argcnt = 0;
    XtSetArg(args[argcnt], XmNautoUnmanage, False); argcnt++;
    form = CreateFormDialog(parent, "replaceDialog", args, argcnt);
    XtVaSetValues(form, XmNshadowThickness, 0, NULL);
    if (GetPrefKeepSearchDlogs()) {
    	sprintf(title, "Replace/Find (in %s)", window->filename);
    	XtVaSetValues(XtParent(form), XmNtitle, title, NULL);
    } else
    	XtVaSetValues(XtParent(form), XmNtitle, "Replace/Find", NULL);

    argcnt = 0;
    XtSetArg(args[argcnt], XmNtopAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNbottomAttachment, XmATTACH_NONE); argcnt++;
    XtSetArg(args[argcnt], XmNleftAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNrightAttachment, XmATTACH_NONE); argcnt++;
    XtSetArg(args[argcnt], XmNleftOffset, 4); argcnt++;
    XtSetArg(args[argcnt], XmNtopOffset, 6); argcnt++;
    XtSetArg(args[argcnt], XmNalignment, XmALIGNMENT_BEGINNING); argcnt++;
    XtSetArg(args[argcnt], XmNlabelString, st1=MKSTRING("String to Find:"));
    	    argcnt++;
    XtSetArg(args[argcnt], XmNmnemonic, 't'); argcnt++;
    label1 = XmCreateLabel(form, "label1", args, argcnt);
    XmStringFree(st1);
    XtManageChild(label1);
 
    argcnt = 0;
    XtSetArg(args[argcnt], XmNtopAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNbottomAttachment, XmATTACH_NONE); argcnt++;
    XtSetArg(args[argcnt], XmNleftAttachment, XmATTACH_NONE); argcnt++;
    XtSetArg(args[argcnt], XmNrightAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNrightOffset, 6); argcnt++;
    XtSetArg(args[argcnt], XmNtopOffset, 6); argcnt++;
    XtSetArg(args[argcnt], XmNalignment, XmALIGNMENT_END); argcnt++;
    XtSetArg(args[argcnt], XmNlabelString, st1=MKSTRING(
    	   "(use up arrow key to recall previous)")); argcnt++;
    label2 = XmCreateLabel(form, "label2", args, argcnt);
    XmStringFree(st1);
    XtManageChild(label2);
 
    argcnt = 0;
    XtSetArg(args[argcnt], XmNtraversalOn, True); argcnt++;
    XtSetArg(args[argcnt], XmNhighlightThickness, 2); argcnt++;
    XtSetArg(args[argcnt], XmNtopAttachment, XmATTACH_WIDGET); argcnt++;
    XtSetArg(args[argcnt], XmNbottomAttachment, XmATTACH_NONE); argcnt++;
    XtSetArg(args[argcnt], XmNleftAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNrightAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNtopWidget, label1); argcnt++;
    XtSetArg(args[argcnt], XmNleftOffset, 6); argcnt++;
    XtSetArg(args[argcnt], XmNrightOffset, 6); argcnt++;
    XtSetArg(args[argcnt], XmNmaxLength, SEARCHMAX); argcnt++;
    findText = XmCreateText(form, "replaceString", args, argcnt);
    XtAddCallback(findText, XmNfocusCallback, (XtCallbackProc)rFocusCB, window);
    XtAddCallback(findText, XmNvalueChangedCallback, 
      (XtCallbackProc)rFindTextValueChangedCB, window);
    XtAddEventHandler(findText, KeyPressMask, False,
    	    (XtEventHandler)rFindArrowKeyCB, window);
    RemapDeleteKey(findText);
    XtManageChild(findText);
    XmAddTabGroup(findText);
    XtVaSetValues(label1, XmNuserData, findText, NULL); /* mnemonic processing */
 
    argcnt = 0;
    XtSetArg(args[argcnt], XmNtopAttachment, XmATTACH_WIDGET); argcnt++;
    XtSetArg(args[argcnt], XmNbottomAttachment, XmATTACH_NONE); argcnt++;
    XtSetArg(args[argcnt], XmNleftAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNrightAttachment, XmATTACH_NONE); argcnt++;
    XtSetArg(args[argcnt], XmNtopWidget, findText); argcnt++;
    XtSetArg(args[argcnt], XmNleftOffset, 6); argcnt++;
    XtSetArg(args[argcnt], XmNtopOffset, 6); argcnt++;
    XtSetArg(args[argcnt], XmNalignment, XmALIGNMENT_BEGINNING); argcnt++;
    XtSetArg(args[argcnt], XmNlabelString,
    	     st1=MKSTRING("Replace With:")); argcnt++;
    XtSetArg(args[argcnt], XmNmnemonic, 'W'); argcnt++;
    label = XmCreateLabel(form, "label", args, argcnt);
    XmStringFree(st1);
    XtManageChild(label);
 
    argcnt = 0;
    XtSetArg(args[argcnt], XmNtraversalOn, True); argcnt++;
    XtSetArg(args[argcnt], XmNhighlightThickness, 2); argcnt++;
    XtSetArg(args[argcnt], XmNtopAttachment, XmATTACH_WIDGET); argcnt++;
    XtSetArg(args[argcnt], XmNbottomAttachment, XmATTACH_NONE); argcnt++;
    XtSetArg(args[argcnt], XmNleftAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNrightAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNtopWidget, label); argcnt++;
    XtSetArg(args[argcnt], XmNleftOffset, 6); argcnt++;
    XtSetArg(args[argcnt], XmNrightOffset, 6); argcnt++;
    XtSetArg(args[argcnt], XmNmaxLength, SEARCHMAX); argcnt++;
    replaceText = XmCreateText(form, "replaceWithString", args, argcnt);
    XtAddEventHandler(replaceText, KeyPressMask, False,
    	    (XtEventHandler)replaceArrowKeyCB, window);
    RemapDeleteKey(replaceText);
    XtManageChild(replaceText);
    XmAddTabGroup(replaceText);
    XtVaSetValues(label, XmNuserData, replaceText, NULL); /* mnemonic processing */

    argcnt = 0;
    XtSetArg(args[argcnt], XmNorientation, XmHORIZONTAL); argcnt++;
    XtSetArg(args[argcnt], XmNpacking, XmPACK_TIGHT); argcnt++;
    XtSetArg(args[argcnt], XmNmarginHeight, 0); argcnt++;
    XtSetArg(args[argcnt], XmNtopAttachment, XmATTACH_WIDGET); argcnt++;
    XtSetArg(args[argcnt], XmNleftAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNrightAttachment, XmATTACH_NONE); argcnt++;
    XtSetArg(args[argcnt], XmNtopWidget, replaceText); argcnt++;
    XtSetArg(args[argcnt], XmNleftOffset, 2); argcnt++;
    XtSetArg(args[argcnt], XmNrightOffset, 4); argcnt++;
    searchTypeBox = XmCreateRowColumn(form, "searchTypeBox", args, argcnt);
    XtManageChild(searchTypeBox);
    XmAddTabGroup(searchTypeBox);
 
    argcnt = 0;
    XtSetArg(args[argcnt], XmNtraversalOn, True); argcnt++;
    XtSetArg(args[argcnt], XmNhighlightThickness, 2); argcnt++;
    XtSetArg(args[argcnt], XmNlabelString, 
    	     st1=MKSTRING("Regular Expression")); argcnt++;
    XtSetArg(args[argcnt], XmNmnemonic, 'R'); argcnt++;
    window->replaceRegexToggle = XmCreateToggleButton(searchTypeBox, "regExp", args, argcnt);
    XmStringFree(st1);
    XtManageChild(window->replaceRegexToggle);
    XtAddCallback(window->replaceRegexToggle, XmNvalueChangedCallback, (XtCallbackProc) replaceRegExpToggleCB, window);

    argcnt = 0;
    XtSetArg(args[argcnt], XmNtraversalOn, True); argcnt++;
    XtSetArg(args[argcnt], XmNhighlightThickness, 2); argcnt++;
    XtSetArg(args[argcnt], XmNlabelString, st1=MKSTRING("Case Sensitive")); argcnt++;
    XtSetArg(args[argcnt], XmNmnemonic, 'C'); argcnt++;
    window->replaceCaseToggle = XmCreateToggleButton(searchTypeBox, "caseSensitive", args, argcnt);
    XmStringFree(st1);
    XtManageChild(window->replaceCaseToggle);
    XtAddCallback(window->replaceCaseToggle, XmNvalueChangedCallback, (XtCallbackProc) replaceCaseToggleCB, window);
    
    argcnt = 0;
    XtSetArg(args[argcnt], XmNtraversalOn, True); argcnt++;
    XtSetArg(args[argcnt], XmNhighlightThickness, 2); argcnt++;
    XtSetArg(args[argcnt], XmNlabelString, st1=MKSTRING("Whole Word")); argcnt++;
    XtSetArg(args[argcnt], XmNmnemonic, 'h'); argcnt++;
    window->replaceWordToggle = XmCreateToggleButton(searchTypeBox, "wholeWord", args, argcnt);
    XmStringFree(st1);
    XtManageChild(window->replaceWordToggle);
    
    argcnt = 0;
    XtSetArg(args[argcnt], XmNorientation, XmHORIZONTAL); argcnt++;
    XtSetArg(args[argcnt], XmNpacking, XmPACK_TIGHT); argcnt++;
    XtSetArg(args[argcnt], XmNmarginHeight, 0); argcnt++;
    XtSetArg(args[argcnt], XmNtopAttachment, XmATTACH_WIDGET); argcnt++;
    XtSetArg(args[argcnt], XmNtopOffset, 0); argcnt++;
    XtSetArg(args[argcnt], XmNtopWidget, searchTypeBox); argcnt++;
    XtSetArg(args[argcnt], XmNleftAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNleftOffset, 2); argcnt++;
    XtSetArg(args[argcnt], XmNradioBehavior, False); argcnt++;
    searchDirBox = XmCreateRowColumn(form, "searchDirBox", args, argcnt);
    XtManageChild(searchDirBox);
    XmAddTabGroup(searchDirBox);
 
    argcnt = 0;
    XtSetArg(args[argcnt], XmNlabelString,
    	     st1=MKSTRING("Search Backward")); argcnt++;
    XtSetArg(args[argcnt], XmNmnemonic, 'B'); argcnt++;
    reverseBtn = XmCreateToggleButton(searchDirBox, "reverse", args, argcnt);
    XmStringFree(st1);
    XtManageChild(reverseBtn);
    
    argcnt = 0;
    XtSetArg(args[argcnt], XmNlabelString,
    	     st1=MKSTRING("Keep Dialog")); argcnt++;
    XtSetArg(args[argcnt], XmNmnemonic, 'K'); argcnt++;
    XtSetArg(args[argcnt], XmNtopAttachment, XmATTACH_WIDGET); argcnt++;
    XtSetArg(args[argcnt], XmNtopOffset, 0); argcnt++;
    XtSetArg(args[argcnt], XmNtopWidget, searchTypeBox); argcnt++;
    XtSetArg(args[argcnt], XmNrightAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNrightOffset, 4); argcnt++;
    keepBtn = XmCreateToggleButton(form, "keep", args, argcnt);
    XtAddCallback(keepBtn, XmNvalueChangedCallback,
    	    (XtCallbackProc)rKeepCB, window);
    XmStringFree(st1);
    XtManageChild(keepBtn);
    XmAddTabGroup(keepBtn);
    
#ifdef REPLACE_SCOPE
    argcnt = 0;
    XtSetArg(args[argcnt], XmNorientation, XmHORIZONTAL); argcnt++;
    XtSetArg(args[argcnt], XmNpacking, XmPACK_TIGHT); argcnt++;
    XtSetArg(args[argcnt], XmNmarginHeight, 0); argcnt++;
    XtSetArg(args[argcnt], XmNleftAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNrightAttachment, XmATTACH_NONE); argcnt++;
    XtSetArg(args[argcnt], XmNtopAttachment, XmATTACH_WIDGET); argcnt++;
    XtSetArg(args[argcnt], XmNbottomAttachment, XmATTACH_NONE); argcnt++;
    XtSetArg(args[argcnt], XmNtopWidget, searchDirBox); argcnt++;
    XtSetArg(args[argcnt], XmNleftOffset, 2); argcnt++;
    XtSetArg(args[argcnt], XmNrightOffset, 6); argcnt++;
    XtSetArg(args[argcnt], XmNradioBehavior, True); argcnt++;
    XtSetArg(args[argcnt], XmNradioAlwaysOne, True); argcnt++;
    scopeForm = XmCreateRowColumn(form, "scope", args, argcnt);
    XtManageChild(scopeForm);
    XmAddTabGroup(scopeForm);
    
    argcnt = 0;
    XtSetArg(args[argcnt], XmNtraversalOn, True); argcnt++;
    XtSetArg(args[argcnt], XmNhighlightThickness, 2); argcnt++;
    XtSetArg(args[argcnt], XmNlabelString, st1=MKSTRING("In Window")); 
        argcnt++;
    XtSetArg(args[argcnt], XmNmnemonic, 'i'); argcnt++;
    XtSetArg(args[argcnt], XmNtopAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNbottomAttachment, XmATTACH_NONE); argcnt++;
    XtSetArg(args[argcnt], XmNleftAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNrightAttachment, XmATTACH_NONE); argcnt++;
    inWinBtn = XmCreateToggleButton(scopeForm, "inWindow", args, argcnt);
    XtAddCallback(inWinBtn, XmNvalueChangedCallback, 
    	(XtCallbackProc)rScopeWinCB, window);
    XmStringFree(st1);
    XtManageChild(inWinBtn);
 
    argcnt = 0;
    XtSetArg(args[argcnt], XmNtraversalOn, True); argcnt++;
    XtSetArg(args[argcnt], XmNhighlightThickness, 2); argcnt++;
    XtSetArg(args[argcnt], XmNlabelString,
    	     st1=MKSTRING("In Selection")); argcnt++;
    XtSetArg(args[argcnt], XmNmnemonic, 'S'); argcnt++;
    XtSetArg(args[argcnt], XmNtopAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNbottomAttachment, XmATTACH_NONE); argcnt++;
    XtSetArg(args[argcnt], XmNleftAttachment, XmATTACH_WIDGET); argcnt++;
    XtSetArg(args[argcnt], XmNrightAttachment, XmATTACH_NONE); argcnt++;
    XtSetArg(args[argcnt], XmNleftWidget, inWinBtn); argcnt++;
    inSelBtn = XmCreateToggleButton(scopeForm, "inSel", args, argcnt);
    XtAddCallback(inSelBtn, XmNvalueChangedCallback, 
	(XtCallbackProc)rScopeSelCB, window);
    XmStringFree(st1);
    XtManageChild(inSelBtn);
    
    argcnt = 0;
    XtSetArg(args[argcnt], XmNtraversalOn, True); argcnt++;
    XtSetArg(args[argcnt], XmNhighlightThickness, 2); argcnt++;
    XtSetArg(args[argcnt], XmNlabelString,
    	     st1=MKSTRING("In Multiple Files")); argcnt++;
    XtSetArg(args[argcnt], XmNmnemonic, 'M'); argcnt++;
    XtSetArg(args[argcnt], XmNtopAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNbottomAttachment, XmATTACH_NONE); argcnt++;
    XtSetArg(args[argcnt], XmNleftAttachment, XmATTACH_WIDGET); argcnt++;
    XtSetArg(args[argcnt], XmNrightAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNleftWidget, inSelBtn); argcnt++;
    inMultiBtn = XmCreateToggleButton(scopeForm, "multiFile", args, argcnt);
    XtAddCallback(inMultiBtn, XmNvalueChangedCallback,
    	    (XtCallbackProc)rScopeMultiCB, window);
    XmStringFree(st1);
    XtManageChild(inMultiBtn);
#else
    argcnt = 0;
    XtSetArg(args[argcnt], XmNleftAttachment, XmATTACH_NONE); argcnt++;
    XtSetArg(args[argcnt], XmNrightAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNtopAttachment, XmATTACH_WIDGET); argcnt++;
    XtSetArg(args[argcnt], XmNbottomAttachment, XmATTACH_NONE); argcnt++;
    XtSetArg(args[argcnt], XmNtopWidget, searchDirBox); argcnt++;
    XtSetArg(args[argcnt], XmNleftOffset, 6); argcnt++;
    XtSetArg(args[argcnt], XmNrightOffset, 6); argcnt++;
    allForm = XmCreateForm(form, "all", args, argcnt);
    XtManageChild(allForm);
    XmAddTabGroup(allForm);
    
    argcnt = 0;
    XtSetArg(args[argcnt], XmNtopAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNbottomAttachment, XmATTACH_NONE); argcnt++;
    XtSetArg(args[argcnt], XmNleftAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNrightAttachment, XmATTACH_NONE); argcnt++;
    XtSetArg(args[argcnt], XmNleftOffset, 4); argcnt++;
    XtSetArg(args[argcnt], XmNtopOffset, 6); argcnt++;
    XtSetArg(args[argcnt], XmNalignment, XmALIGNMENT_BEGINNING); argcnt++;
    XtSetArg(args[argcnt], XmNlabelString, st1=MKSTRING("Replace all in:"));
    	    argcnt++;
    label3 = XmCreateLabel(allForm, "label3", args, argcnt);
    XmStringFree(st1);
    XtManageChild(label3);
 
    argcnt = 0;
    XtSetArg(args[argcnt], XmNtraversalOn, True); argcnt++;
    XtSetArg(args[argcnt], XmNhighlightThickness, 2); argcnt++;
    XtSetArg(args[argcnt], XmNlabelString, st1=MKSTRING("Window")); 
        argcnt++;
    XtSetArg(args[argcnt], XmNmnemonic, 'i'); argcnt++;
    XtSetArg(args[argcnt], XmNtopAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNbottomAttachment, XmATTACH_NONE); argcnt++;
    XtSetArg(args[argcnt], XmNleftAttachment, XmATTACH_WIDGET); argcnt++;
    XtSetArg(args[argcnt], XmNrightAttachment, XmATTACH_NONE); argcnt++;
    XtSetArg(args[argcnt], XmNleftWidget, label3); argcnt++;
    inWinBtn = XmCreatePushButton(allForm, "inWindow", args, argcnt);
    XtAddCallback(inWinBtn, XmNactivateCallback, 
    	(XtCallbackProc)replaceAllCB, window);
    XmStringFree(st1);
    XtManageChild(inWinBtn);
 
    argcnt = 0;
    XtSetArg(args[argcnt], XmNtraversalOn, True); argcnt++;
    XtSetArg(args[argcnt], XmNhighlightThickness, 2); argcnt++;
    XtSetArg(args[argcnt], XmNlabelString,
    	     st1=MKSTRING("Selection")); argcnt++;
    XtSetArg(args[argcnt], XmNmnemonic, 'S'); argcnt++;
    XtSetArg(args[argcnt], XmNtopAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNbottomAttachment, XmATTACH_NONE); argcnt++;
    XtSetArg(args[argcnt], XmNleftAttachment, XmATTACH_WIDGET); argcnt++;
    XtSetArg(args[argcnt], XmNrightAttachment, XmATTACH_NONE); argcnt++;
    XtSetArg(args[argcnt], XmNleftWidget, inWinBtn); argcnt++;
    inSelBtn = XmCreatePushButton(allForm, "inSel", args, argcnt);
    XtAddCallback(inSelBtn, XmNactivateCallback, 
	(XtCallbackProc)rInSelCB, window);
    XmStringFree(st1);
    XtManageChild(inSelBtn);
    
    argcnt = 0;
    XtSetArg(args[argcnt], XmNtraversalOn, True); argcnt++;
    XtSetArg(args[argcnt], XmNhighlightThickness, 2); argcnt++;
    XtSetArg(args[argcnt], XmNlabelString,
    	     st1=MKSTRING("Multiple Files...")); argcnt++;
    XtSetArg(args[argcnt], XmNmnemonic, 'M'); argcnt++;
    XtSetArg(args[argcnt], XmNtopAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNbottomAttachment, XmATTACH_NONE); argcnt++;
    XtSetArg(args[argcnt], XmNleftAttachment, XmATTACH_WIDGET); argcnt++;
    XtSetArg(args[argcnt], XmNrightAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNleftWidget, inSelBtn); argcnt++;
    inMultiBtn = XmCreatePushButton(allForm, "multiFile", args, argcnt);
    XtAddCallback(inMultiBtn, XmNactivateCallback,
    	    (XtCallbackProc)replaceMultiFileCB, window);
    XmStringFree(st1);
    XtManageChild(inMultiBtn);
    
#endif
    
    argcnt = 0;
    XtSetArg(args[argcnt], XmNleftAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNrightAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNtopAttachment, XmATTACH_WIDGET); argcnt++;
    XtSetArg(args[argcnt], XmNbottomAttachment, XmATTACH_NONE); argcnt++;
#ifdef REPLACE_SCOPE
    XtSetArg(args[argcnt], XmNtopWidget, scopeForm); argcnt++;
#else
    XtSetArg(args[argcnt], XmNtopWidget, allForm); argcnt++;
#endif
    XtSetArg(args[argcnt], XmNleftOffset, 6); argcnt++;
    XtSetArg(args[argcnt], XmNrightOffset, 6); argcnt++;
    btnForm = XmCreateForm(form, "buttons", args, argcnt);
    XtManageChild(btnForm);
    XmAddTabGroup(btnForm);

    argcnt = 0;
    XtSetArg(args[argcnt], XmNtraversalOn, True); argcnt++;
    XtSetArg(args[argcnt], XmNhighlightThickness, 2); argcnt++;
    XtSetArg(args[argcnt], XmNlabelString, st1=MKSTRING("Replace")); argcnt++;
    XtSetArg(args[argcnt], XmNshowAsDefault, (short)1); argcnt++;
    XtSetArg(args[argcnt], XmNtopAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNleftAttachment, XmATTACH_POSITION); argcnt++;
    XtSetArg(args[argcnt], XmNrightAttachment, XmATTACH_POSITION); argcnt++;
    XtSetArg(args[argcnt], XmNbottomAttachment, XmATTACH_FORM); argcnt++;
#ifdef REPLACE_SCOPE
    XtSetArg(args[argcnt], XmNleftPosition, 0); argcnt++;
    XtSetArg(args[argcnt], XmNrightPosition, 21); argcnt++;
#else
    XtSetArg(args[argcnt], XmNleftPosition, 0); argcnt++;
    XtSetArg(args[argcnt], XmNrightPosition, 25); argcnt++;
#endif
    replaceBtn = XmCreatePushButton(btnForm, "replace", args, argcnt);
    XtAddCallback(replaceBtn, XmNactivateCallback, (XtCallbackProc)replaceCB, window);
    XmStringFree(st1);
    XtManageChild(replaceBtn);
    XtVaGetValues(replaceBtn, XmNshadowThickness, &shadowThickness, 0);
    defaultBtnOffset = shadowThickness + 4;
	
    argcnt = 0;
    XtSetArg(args[argcnt], XmNtraversalOn, True); argcnt++;
    XtSetArg(args[argcnt], XmNhighlightThickness, 2); argcnt++;
    XtSetArg(args[argcnt], XmNlabelString, st1=MKSTRING("Find")); argcnt++;
    XtSetArg(args[argcnt], XmNmnemonic, 'F'); argcnt++;
    XtSetArg(args[argcnt], XmNtopAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNbottomAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNleftAttachment, XmATTACH_POSITION); argcnt++;
    XtSetArg(args[argcnt], XmNrightAttachment, XmATTACH_POSITION); argcnt++;
#ifdef REPLACE_SCOPE
    XtSetArg(args[argcnt], XmNleftPosition, 21); argcnt++;
    XtSetArg(args[argcnt], XmNrightPosition, 33); argcnt++;
#else
    XtSetArg(args[argcnt], XmNleftPosition, 25); argcnt++;
    XtSetArg(args[argcnt], XmNrightPosition, 42); argcnt++;
#endif
    XtSetArg(args[argcnt], XmNtopOffset, defaultBtnOffset); argcnt++;
    XtSetArg(args[argcnt], XmNbottomOffset, defaultBtnOffset); argcnt++;
    findBtn = XmCreatePushButton(btnForm, "find", args, argcnt);
    XtAddCallback(findBtn, XmNactivateCallback, (XtCallbackProc)rFindCB, window);
    XmStringFree(st1);
    XtManageChild(findBtn);
 
    argcnt = 0;
    XtSetArg(args[argcnt], XmNtraversalOn, True); argcnt++;
    XtSetArg(args[argcnt], XmNhighlightThickness, 2); argcnt++;
    XtSetArg(args[argcnt], XmNlabelString, st1=MKSTRING("Replace & Find")); argcnt++;
    XtSetArg(args[argcnt], XmNmnemonic, 'n'); argcnt++;
    XtSetArg(args[argcnt], XmNtopAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNbottomAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNleftAttachment, XmATTACH_POSITION); argcnt++;
    XtSetArg(args[argcnt], XmNrightAttachment, XmATTACH_POSITION); argcnt++;
#ifdef REPLACE_SCOPE
    XtSetArg(args[argcnt], XmNleftPosition, 33); argcnt++;
    XtSetArg(args[argcnt], XmNrightPosition, 62); argcnt++;
#else
    XtSetArg(args[argcnt], XmNleftPosition, 42); argcnt++;
    XtSetArg(args[argcnt], XmNrightPosition, 79); argcnt++;
#endif
    XtSetArg(args[argcnt], XmNtopOffset, defaultBtnOffset); argcnt++;
    XtSetArg(args[argcnt], XmNbottomOffset, defaultBtnOffset); argcnt++;
    replaceFindBtn = XmCreatePushButton(btnForm, "replacefind", args, argcnt);
    XtAddCallback(replaceFindBtn, XmNactivateCallback, (XtCallbackProc)replaceFindCB, window);
    XmStringFree(st1);
    XtManageChild(replaceFindBtn);
 
#ifdef REPLACE_SCOPE    
    argcnt = 0;
    XtSetArg(args[argcnt], XmNtraversalOn, True); argcnt++;
    XtSetArg(args[argcnt], XmNhighlightThickness, 2); argcnt++;
    XtSetArg(args[argcnt], XmNlabelString,
    	     st1=MKSTRING("Replace All")); argcnt++;
    XtSetArg(args[argcnt], XmNmnemonic, 'A'); argcnt++;
    XtSetArg(args[argcnt], XmNtopAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNbottomAttachment, XmATTACH_NONE); argcnt++;
    XtSetArg(args[argcnt], XmNleftAttachment, XmATTACH_POSITION); argcnt++;
    XtSetArg(args[argcnt], XmNrightAttachment, XmATTACH_POSITION); argcnt++;
    XtSetArg(args[argcnt], XmNleftPosition, 62); argcnt++;
    XtSetArg(args[argcnt], XmNrightPosition, 85); argcnt++;
    XtSetArg(args[argcnt], XmNtopOffset, defaultBtnOffset); argcnt++;
    replaceAllBtn = XmCreatePushButton(btnForm, "all", args, argcnt);
    XtAddCallback(replaceAllBtn, XmNactivateCallback,
    	    (XtCallbackProc)replaceAllScopeCB, window);
    XmStringFree(st1);
    XtManageChild(replaceAllBtn);
#endif
    
    argcnt = 0;
    XtSetArg(args[argcnt], XmNtraversalOn, True); argcnt++;
    XtSetArg(args[argcnt], XmNhighlightThickness, 2); argcnt++;
    XtSetArg(args[argcnt], XmNlabelString, st1=MKSTRING("Cancel")); argcnt++;
    XtSetArg(args[argcnt], XmNtopAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNbottomAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNleftAttachment, XmATTACH_POSITION); argcnt++;
    XtSetArg(args[argcnt], XmNrightAttachment, XmATTACH_POSITION); argcnt++;
#ifdef REPLACE_SCOPE
    XtSetArg(args[argcnt], XmNleftPosition, 85); argcnt++;
    XtSetArg(args[argcnt], XmNrightPosition, 100); argcnt++;
#else
    XtSetArg(args[argcnt], XmNleftPosition, 79); argcnt++;
    XtSetArg(args[argcnt], XmNrightPosition, 100); argcnt++;
#endif
    XtSetArg(args[argcnt], XmNtopOffset, defaultBtnOffset); argcnt++;
    XtSetArg(args[argcnt], XmNbottomOffset, defaultBtnOffset); argcnt++;
    cancelBtn = XmCreatePushButton(btnForm, "cancel", args, argcnt);
    XmStringFree(st1);
    XtAddCallback(cancelBtn, XmNactivateCallback, (XtCallbackProc)rCancelCB,
    	    window);
    XtManageChild(cancelBtn);

    XtVaSetValues(form, XmNcancelButton, cancelBtn, NULL);
    AddDialogMnemonicHandler(form, FALSE);
    
    window->replaceDlog = form;
    window->replaceText = findText;
    window->replaceWithText = replaceText;
    window->replaceRevToggle = reverseBtn;
    window->replaceKeepBtn = keepBtn;
    window->replaceBtns = btnForm;
    window->replaceBtn = replaceBtn;
    window->replaceAndFindBtn = replaceFindBtn;
    window->replaceFindBtn = findBtn;
    window->replaceSearchTypeBox = searchTypeBox;
#ifdef REPLACE_SCOPE
    window->replaceAllBtn = replaceAllBtn;
    window->replaceScopeWinToggle = inWinBtn;
    window->replaceScopeSelToggle = inSelBtn;
    window->replaceScopeMultiToggle = inMultiBtn;
#else
    window->replaceInWinBtn = inWinBtn;
    window->replaceAllBtn = inMultiBtn;
    window->replaceInSelBtn = inSelBtn;
#endif
}

void CreateFindDlog(Widget parent, WindowInfo *window)
{
    Arg    	args[50];
    int    	argcnt, defaultBtnOffset;
    XmString	st1;
    Widget	form, btnForm, searchTypeBox;
    Widget	findText, label1, label2, cancelBtn, findBtn;
    Widget	searchDirBox, reverseBtn, keepBtn;
    char 	title[MAXPATHLEN + 11];
    Dimension	shadowThickness;
 
    argcnt = 0;
    XtSetArg(args[argcnt], XmNautoUnmanage, False); argcnt++;
    form = CreateFormDialog(parent, "findDialog", args, argcnt);
    XtVaSetValues(form, XmNshadowThickness, 0, NULL);
    if (GetPrefKeepSearchDlogs()) {
    	sprintf(title, "Find (in %s)", window->filename);
    	XtVaSetValues(XtParent(form), XmNtitle, title, NULL);
    } else
    	XtVaSetValues(XtParent(form), XmNtitle, "Find", NULL);
 
    argcnt = 0;
    XtSetArg(args[argcnt], XmNtopAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNbottomAttachment, XmATTACH_NONE); argcnt++;
    XtSetArg(args[argcnt], XmNleftAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNrightAttachment, XmATTACH_NONE); argcnt++;
    XtSetArg(args[argcnt], XmNleftOffset, 6); argcnt++;
    XtSetArg(args[argcnt], XmNtopOffset, 6); argcnt++;
    XtSetArg(args[argcnt], XmNalignment, XmALIGNMENT_BEGINNING); argcnt++;
    XtSetArg(args[argcnt], XmNlabelString, st1=MKSTRING("String to Find:"));
    	    argcnt++;
    XtSetArg(args[argcnt], XmNmnemonic, 'S'); argcnt++;
    label1 = XmCreateLabel(form, "label1", args, argcnt);
    XmStringFree(st1);
    XtManageChild(label1);
 
    argcnt = 0;
    XtSetArg(args[argcnt], XmNtopAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNbottomAttachment, XmATTACH_NONE); argcnt++;
    XtSetArg(args[argcnt], XmNleftAttachment, XmATTACH_NONE); argcnt++;
    XtSetArg(args[argcnt], XmNrightAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNrightOffset, 6); argcnt++;
    XtSetArg(args[argcnt], XmNtopOffset, 6); argcnt++;
    XtSetArg(args[argcnt], XmNalignment, XmALIGNMENT_END); argcnt++;
    XtSetArg(args[argcnt], XmNlabelString, st1=MKSTRING(
    	   "(use up arrow key to recall previous)")); argcnt++;
    label2 = XmCreateLabel(form, "label2", args, argcnt);
    XmStringFree(st1);
    XtManageChild(label2);
 
    argcnt = 0;
    XtSetArg(args[argcnt], XmNtraversalOn, True); argcnt++;
    XtSetArg(args[argcnt], XmNhighlightThickness, 2); argcnt++;
    XtSetArg(args[argcnt], XmNtopAttachment, XmATTACH_WIDGET); argcnt++;
    XtSetArg(args[argcnt], XmNbottomAttachment, XmATTACH_NONE); argcnt++;
    XtSetArg(args[argcnt], XmNleftAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNrightAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNtopWidget, label1); argcnt++;
    XtSetArg(args[argcnt], XmNleftOffset, 6); argcnt++;
    XtSetArg(args[argcnt], XmNrightOffset, 6); argcnt++;
    XtSetArg(args[argcnt], XmNmaxLength, SEARCHMAX); argcnt++;
    findText = XmCreateText(form, "searchString", args, argcnt);
    XtAddCallback(findText, XmNfocusCallback, (XtCallbackProc)fFocusCB, window);
    XtAddCallback(findText, XmNvalueChangedCallback, 
      (XtCallbackProc)findTextValueChangedCB, window);
    XtAddEventHandler(findText, KeyPressMask, False,
    	    (XtEventHandler)findArrowKeyCB, window);
    RemapDeleteKey(findText);
    XtManageChild(findText);
    XmAddTabGroup(findText);
    XtVaSetValues(label1, XmNuserData, findText, NULL); /* mnemonic processing */

    argcnt = 0;
    XtSetArg(args[argcnt], XmNorientation, XmHORIZONTAL); argcnt++;
    XtSetArg(args[argcnt], XmNpacking, XmPACK_TIGHT); argcnt++;
    XtSetArg(args[argcnt], XmNmarginHeight, 0); argcnt++;
    XtSetArg(args[argcnt], XmNtopAttachment, XmATTACH_WIDGET); argcnt++;
    XtSetArg(args[argcnt], XmNleftAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNrightAttachment, XmATTACH_NONE); argcnt++;
    XtSetArg(args[argcnt], XmNtopWidget, findText); argcnt++;
    XtSetArg(args[argcnt], XmNleftOffset, 2); argcnt++;
    XtSetArg(args[argcnt], XmNrightOffset, 4); argcnt++;
    
    searchTypeBox = XmCreateRowColumn(form, "searchTypeBox", args, argcnt);
    XtManageChild(searchTypeBox);
    XmAddTabGroup(searchTypeBox);
 
    argcnt = 0;
    XtSetArg(args[argcnt], XmNtraversalOn, True); argcnt++;
    XtSetArg(args[argcnt], XmNhighlightThickness, 2); argcnt++;
    XtSetArg(args[argcnt], XmNlabelString, 
    	     st1=MKSTRING("Regular Expression")); argcnt++;
    XtSetArg(args[argcnt], XmNmnemonic, 'R'); argcnt++;
    window->findRegexToggle = XmCreateToggleButton(searchTypeBox, "regExp", args, argcnt);
    XmStringFree(st1);
    XtManageChild(window->findRegexToggle);
    XtAddCallback(window->findRegexToggle, XmNvalueChangedCallback, (XtCallbackProc) findRegExpToggleCB, window);
 
    argcnt = 0;
    XtSetArg(args[argcnt], XmNtraversalOn, True); argcnt++;
    XtSetArg(args[argcnt], XmNhighlightThickness, 2); argcnt++;
    XtSetArg(args[argcnt], XmNlabelString, st1=MKSTRING("Case Sensitive")); argcnt++;
    XtSetArg(args[argcnt], XmNmnemonic, 'C'); argcnt++;
    window->findCaseToggle = XmCreateToggleButton(searchTypeBox, "caseSensitive", args, argcnt);
    XmStringFree(st1);
    XtManageChild(window->findCaseToggle);
    XtAddCallback(window->findCaseToggle, XmNvalueChangedCallback, (XtCallbackProc) findCaseToggleCB, window);
    
    argcnt = 0;
    XtSetArg(args[argcnt], XmNtraversalOn, True); argcnt++;
    XtSetArg(args[argcnt], XmNhighlightThickness, 2); argcnt++;
    XtSetArg(args[argcnt], XmNlabelString, st1=MKSTRING("Whole Word")); argcnt++;
    XtSetArg(args[argcnt], XmNmnemonic, 'h'); argcnt++;
    window->findWordToggle = XmCreateToggleButton(searchTypeBox, "wholeWord", args, argcnt);
    XmStringFree(st1);
    XtManageChild(window->findWordToggle);
    
    argcnt = 0;
    XtSetArg(args[argcnt], XmNorientation, XmHORIZONTAL); argcnt++;
    XtSetArg(args[argcnt], XmNpacking, XmPACK_TIGHT); argcnt++;
    XtSetArg(args[argcnt], XmNmarginHeight, 0); argcnt++;
    XtSetArg(args[argcnt], XmNtopAttachment, XmATTACH_WIDGET); argcnt++;
    XtSetArg(args[argcnt], XmNtopOffset, 0); argcnt++;
    XtSetArg(args[argcnt], XmNtopWidget, searchTypeBox); argcnt++;
    XtSetArg(args[argcnt], XmNleftAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNleftOffset, 2); argcnt++;
    XtSetArg(args[argcnt], XmNradioBehavior, False); argcnt++;
    searchDirBox = XmCreateRowColumn(form, "searchDirBox", args, argcnt);
    XtManageChild(searchDirBox);
    XmAddTabGroup(searchDirBox);
    
    argcnt = 0;
    XtSetArg(args[argcnt], XmNlabelString,
    	     st1=MKSTRING("Search Backward")); argcnt++;
    XtSetArg(args[argcnt], XmNmnemonic, 'B'); argcnt++;
    reverseBtn = XmCreateToggleButton(searchDirBox, "reverse", args, argcnt);
    XmStringFree(st1);
    XtManageChild(reverseBtn);
    
    argcnt = 0;
    XtSetArg(args[argcnt], XmNlabelString,
    	     st1=MKSTRING("Keep Dialog")); argcnt++;
    XtSetArg(args[argcnt], XmNmnemonic, 'K'); argcnt++;
    XtSetArg(args[argcnt], XmNtopAttachment, XmATTACH_WIDGET); argcnt++;
    XtSetArg(args[argcnt], XmNtopOffset, 0); argcnt++;
    XtSetArg(args[argcnt], XmNtopWidget, searchTypeBox); argcnt++;
    XtSetArg(args[argcnt], XmNrightAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNrightOffset, 4); argcnt++;
    keepBtn = XmCreateToggleButton(form, "keep", args, argcnt);
    XtAddCallback(keepBtn, XmNvalueChangedCallback,
    	    (XtCallbackProc)fKeepCB, window);
    XmStringFree(st1);
    XtManageChild(keepBtn);
    XmAddTabGroup(keepBtn);

    argcnt = 0;
    XtSetArg(args[argcnt], XmNleftAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNrightAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNtopAttachment, XmATTACH_WIDGET); argcnt++;
    XtSetArg(args[argcnt], XmNbottomAttachment, XmATTACH_NONE); argcnt++;
    XtSetArg(args[argcnt], XmNtopWidget, searchDirBox); argcnt++;
    XtSetArg(args[argcnt], XmNleftOffset, 2); argcnt++;
    XtSetArg(args[argcnt], XmNrightOffset, 4); argcnt++;
    btnForm = XmCreateForm(form, "buttons", args, argcnt);
    XtManageChild(btnForm);
    XmAddTabGroup(btnForm);

    argcnt = 0;
    XtSetArg(args[argcnt], XmNtraversalOn, True); argcnt++;
    XtSetArg(args[argcnt], XmNhighlightThickness, 2); argcnt++;
    XtSetArg(args[argcnt], XmNlabelString, st1=MKSTRING("Find")); argcnt++;
    XtSetArg(args[argcnt], XmNshowAsDefault, (short)1); argcnt++;
    XtSetArg(args[argcnt], XmNtopAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNleftAttachment, XmATTACH_POSITION); argcnt++;
    XtSetArg(args[argcnt], XmNrightAttachment, XmATTACH_NONE); argcnt++;
    XtSetArg(args[argcnt], XmNbottomAttachment, XmATTACH_NONE); argcnt++;
    XtSetArg(args[argcnt], XmNleftPosition, 20); argcnt++;
    XtSetArg(args[argcnt], XmNbottomOffset, 6); argcnt++;
    findBtn = XmCreatePushButton(btnForm, "find", args, argcnt);
    XtAddCallback(findBtn, XmNactivateCallback, (XtCallbackProc)findCB, window);
    XmStringFree(st1);
    XtManageChild(findBtn);
    XtVaGetValues(findBtn, XmNshadowThickness, &shadowThickness, NULL);
    defaultBtnOffset = shadowThickness + 4;

    argcnt = 0;
    XtSetArg(args[argcnt], XmNtraversalOn, True); argcnt++;
    XtSetArg(args[argcnt], XmNhighlightThickness, 2); argcnt++;
    XtSetArg(args[argcnt], XmNlabelString, st1=MKSTRING("Cancel")); argcnt++;
    XtSetArg(args[argcnt], XmNtopAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNbottomAttachment, XmATTACH_NONE); argcnt++;
    XtSetArg(args[argcnt], XmNleftAttachment, XmATTACH_NONE); argcnt++;
    XtSetArg(args[argcnt], XmNrightAttachment, XmATTACH_POSITION); argcnt++;
    XtSetArg(args[argcnt], XmNrightPosition, 80); argcnt++;
    XtSetArg(args[argcnt], XmNtopOffset, defaultBtnOffset); argcnt++;
    cancelBtn = XmCreatePushButton(btnForm, "cancel", args, argcnt);
    XtAddCallback(cancelBtn, XmNactivateCallback, (XtCallbackProc)fCancelCB,
    	    window);
    XmStringFree(st1);
    XtManageChild(cancelBtn);
    XtVaSetValues(form, XmNcancelButton, cancelBtn, NULL);
    AddDialogMnemonicHandler(form, FALSE);
    
    window->findDlog = form;
    window->findText = findText;
    window->findRevToggle = reverseBtn;
    window->findKeepBtn = keepBtn;
    window->findBtns = btnForm;
    window->findBtn = findBtn;
    window->findSearchTypeBox = searchTypeBox;
}

void CreateReplaceMultiFileDlog(WindowInfo *window) 
{
    Arg		args[50];
    int		argcnt, defaultBtnOffset;
    XmString	st1;
    Widget	list, label1, form, pathBtn;
    Widget	btnForm, replaceBtn, selectBtn, deselectBtn, cancelBtn;
    Dimension	shadowThickness;
    
    argcnt = 0;
    XtSetArg(args[argcnt], XmNautoUnmanage, False); argcnt++;
    XtSetArg (args[argcnt], XmNdialogStyle, XmDIALOG_FULL_APPLICATION_MODAL);
	    argcnt ++;

    /* Ideally, we should create the multi-file dialog as a child widget
       of the replace dialog. However, if we do this, the main window
       can hide the multi-file dialog when raised (I'm not sure why, but 
       it's something that I observed with fvwm). By using the main window
       as the parent, it is possible that the replace dialog _partially_
       covers the multi-file dialog, but this much better than the multi-file
       dialog being covered completely by the main window */
    form = CreateFormDialog(window->shell, "replaceMultiFileDialog", 
           			     args, argcnt);
    XtVaSetValues(form, XmNshadowThickness, 0, NULL);
    XtVaSetValues(XtParent(form), XmNtitle, "Replace All in Multiple Files", 
		  NULL);
    
    /* Label at top left. */
    argcnt = 0;
    XtSetArg(args[argcnt], XmNtopAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNbottomAttachment, XmATTACH_NONE); argcnt++;
    XtSetArg(args[argcnt], XmNleftAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNrightAttachment, XmATTACH_NONE); argcnt++;
    /* Offset = 6 + (highlightThickness + detailShadowThickness) of the
       toggle button (see below). Unfortunately, detailShadowThickness is
       a Motif 2.x property, so we can't measure it. The default is 2 pixels.
       To make things even more complicated, the SunOS 5.6 / Solaris 2.6 
       version of Motif 1.2 seems to use a detailShadowThickness of 0 ...
       So we'll have to live with a slight misalignment on that platform
       (those Motif libs are known to have many other problems). */
    XtSetArg(args[argcnt], XmNtopOffset, 10); argcnt++;
    XtSetArg(args[argcnt], XmNleftOffset, 6); argcnt++;
    XtSetArg(args[argcnt], XmNalignment, XmALIGNMENT_BEGINNING); argcnt++;
    XtSetArg(args[argcnt], XmNlabelString, 
       st1=MKSTRING("Files in which to Replace All:")); argcnt++;
    XtSetArg(args[argcnt], XmNmnemonic, 'F'); argcnt++;
    label1 = XmCreateLabel(form, "label1", args, argcnt);
    XmStringFree(st1);
    XtManageChild(label1);
    
    /* Pathname toggle button at top right (always unset by default) */
    argcnt = 0;
    XtSetArg(args[argcnt], XmNtraversalOn, True); argcnt++;
    XtSetArg(args[argcnt], XmNhighlightThickness, 2); argcnt++;
    XtSetArg(args[argcnt], XmNleftAttachment, XmATTACH_NONE); argcnt++;
    XtSetArg(args[argcnt], XmNrightAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNtopAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNbottomAttachment, XmATTACH_NONE); argcnt++;
    XtSetArg(args[argcnt], XmNset, False); argcnt++;
    XtSetArg(args[argcnt], XmNrightOffset, 6); argcnt++;
    XtSetArg(args[argcnt], XmNtopOffset, 6); argcnt++;
    XtSetArg(args[argcnt], XmNalignment, XmALIGNMENT_END); argcnt++;
    XtSetArg(args[argcnt], XmNlabelString,
    	     st1=MKSTRING("Show Path Names")); argcnt++;
    XtSetArg(args[argcnt], XmNmnemonic, 'P'); argcnt++;
    pathBtn = XmCreateToggleButton(form, "path", args, argcnt);
    XmStringFree(st1);
    XtAddCallback(pathBtn, XmNvalueChangedCallback,
    	    (XtCallbackProc)rMultiFilePathCB, window);
    XtManageChild(pathBtn);
    
    /*
     * Buttons at bottom. Place them before the list, such that we can
     * attach the list to the label and the button box. In that way only
     * the lists resizes vertically when the dialog is resized; users expect
     * the list to resize, not the buttons.
     */
     
    argcnt = 0;
    XtSetArg(args[argcnt], XmNleftAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNrightAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNtopAttachment, XmATTACH_NONE); argcnt++;
    XtSetArg(args[argcnt], XmNbottomAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNleftOffset, 6); argcnt++;
    XtSetArg(args[argcnt], XmNrightOffset, 6); argcnt++;
    XtSetArg(args[argcnt], XmNtopOffset, 6); argcnt++;
    XtSetArg(args[argcnt], XmNresizable, (short)0); argcnt++;
    btnForm = XmCreateForm(form, "buttons", args, argcnt);
    XtManageChild(btnForm);
    
    /* Replace */
    argcnt = 0;
    XtSetArg(args[argcnt], XmNtraversalOn, True); argcnt++;
    XtSetArg(args[argcnt], XmNhighlightThickness, 2); argcnt++;
    XtSetArg(args[argcnt], XmNlabelString, st1=MKSTRING("Replace")); argcnt++;
    XtSetArg(args[argcnt], XmNshowAsDefault, (short)1); argcnt++;
    XtSetArg(args[argcnt], XmNmnemonic, 'R'); argcnt++;
    XtSetArg(args[argcnt], XmNtopAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNbottomAttachment, XmATTACH_NONE); argcnt++;
    XtSetArg(args[argcnt], XmNleftAttachment, XmATTACH_POSITION); argcnt++;
    XtSetArg(args[argcnt], XmNrightAttachment, XmATTACH_POSITION); argcnt++;
    XtSetArg(args[argcnt], XmNleftPosition, 0); argcnt++;
    XtSetArg(args[argcnt], XmNrightPosition, 25); argcnt++;
    replaceBtn = XmCreatePushButton(btnForm, "replace", args, argcnt);
    XmStringFree(st1);
    XtAddCallback(replaceBtn, XmNactivateCallback,
       (XtCallbackProc)rMultiFileReplaceCB, window);
    /*
     * _DON'T_ set the replace button as default (as in other dialogs).
     * Multi-selection lists have the nasty property of selecting the 
     * current item when <enter> is pressed.
     * In that way, the user could inadvertently select an additional file
     * (most likely the last one that was deselected). 
     * The user has to activate the replace button explictly (either with
     * a mouse click or with the shortcut key).
     *
     * XtVaSetValues(form, XmNdefaultButton, replaceBtn, NULL); */
     
    XtManageChild(replaceBtn);
    XtVaGetValues(replaceBtn, XmNshadowThickness, &shadowThickness, NULL);
    defaultBtnOffset = shadowThickness + 4;

    /* Select All */
    argcnt = 0;
    XtSetArg(args[argcnt], XmNtraversalOn, True); argcnt++;
    XtSetArg(args[argcnt], XmNhighlightThickness, 2); argcnt++;
    XtSetArg(args[argcnt], XmNlabelString, st1=MKSTRING("Select All")); 
       argcnt++;
    XtSetArg(args[argcnt], XmNmnemonic, 'S'); argcnt++;
    XtSetArg(args[argcnt], XmNtopAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNbottomAttachment, XmATTACH_NONE); argcnt++;
    XtSetArg(args[argcnt], XmNleftAttachment, XmATTACH_POSITION); argcnt++;
    XtSetArg(args[argcnt], XmNrightAttachment, XmATTACH_POSITION); argcnt++;
    XtSetArg(args[argcnt], XmNleftPosition, 25); argcnt++;
    XtSetArg(args[argcnt], XmNrightPosition, 50); argcnt++;
    XtSetArg(args[argcnt], XmNtopOffset, defaultBtnOffset); argcnt++;
    selectBtn = XmCreatePushButton(btnForm, "select", args, argcnt);
    XmStringFree(st1);
    XtAddCallback(selectBtn, XmNactivateCallback,
       (XtCallbackProc)rMultiFileSelectAllCB, window);
    XtManageChild(selectBtn);

    /* Deselect All */
    argcnt = 0;
    XtSetArg(args[argcnt], XmNtraversalOn, True); argcnt++;
    XtSetArg(args[argcnt], XmNhighlightThickness, 2); argcnt++;
    XtSetArg(args[argcnt], XmNlabelString, st1=MKSTRING("Deselect All")); 
       argcnt++;
    XtSetArg(args[argcnt], XmNmnemonic, 'D'); argcnt++;
    XtSetArg(args[argcnt], XmNtopAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNbottomAttachment, XmATTACH_NONE); argcnt++;
    XtSetArg(args[argcnt], XmNleftAttachment, XmATTACH_POSITION); argcnt++;
    XtSetArg(args[argcnt], XmNrightAttachment, XmATTACH_POSITION); argcnt++;
    XtSetArg(args[argcnt], XmNleftPosition, 50); argcnt++;
    XtSetArg(args[argcnt], XmNrightPosition, 75); argcnt++;
    XtSetArg(args[argcnt], XmNtopOffset, defaultBtnOffset); argcnt++;
    deselectBtn = XmCreatePushButton(btnForm, "deselect", args, argcnt);
    XmStringFree(st1);
    XtAddCallback(deselectBtn, XmNactivateCallback,
       (XtCallbackProc)rMultiFileDeselectAllCB, window);
    XtManageChild(deselectBtn);

    /* Cancel */
    argcnt = 0;
    XtSetArg(args[argcnt], XmNtraversalOn, True); argcnt++;
    XtSetArg(args[argcnt], XmNhighlightThickness, 2); argcnt++;
    XtSetArg(args[argcnt], XmNlabelString, st1=MKSTRING("Cancel")); argcnt++;
    XtSetArg(args[argcnt], XmNmnemonic, 'C'); argcnt++;
    XtSetArg(args[argcnt], XmNtopAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNbottomAttachment, XmATTACH_NONE); argcnt++;
    XtSetArg(args[argcnt], XmNleftAttachment, XmATTACH_POSITION); argcnt++;
    XtSetArg(args[argcnt], XmNrightAttachment, XmATTACH_POSITION); argcnt++;
    XtSetArg(args[argcnt], XmNleftPosition, 75); argcnt++;
    XtSetArg(args[argcnt], XmNrightPosition, 100); argcnt++;
    XtSetArg(args[argcnt], XmNtopOffset, defaultBtnOffset); argcnt++;
    cancelBtn = XmCreatePushButton(btnForm, "cancel", args, argcnt);
    XmStringFree(st1);
    XtAddCallback(cancelBtn, XmNactivateCallback, 
       (XtCallbackProc)rMultiFileCancelCB, window);
    XtManageChild(cancelBtn);
    
    /* The list of files */
    argcnt = 0;
    XtSetArg(args[argcnt], XmNtraversalOn, True); argcnt++;
    XtSetArg(args[argcnt], XmNtopAttachment, XmATTACH_WIDGET); argcnt++;
    XtSetArg(args[argcnt], XmNbottomAttachment, XmATTACH_WIDGET); argcnt++;
    XtSetArg(args[argcnt], XmNleftAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNrightAttachment, XmATTACH_FORM); argcnt++;
    XtSetArg(args[argcnt], XmNbottomWidget, btnForm); argcnt++;
    XtSetArg(args[argcnt], XmNtopWidget, label1); argcnt++;
    XtSetArg(args[argcnt], XmNleftOffset, 10); argcnt++;
    XtSetArg(args[argcnt], XmNvisibleItemCount, 10); argcnt++;
    XtSetArg(args[argcnt], XmNtopOffset, 6); argcnt++;
    XtSetArg(args[argcnt], XmNbottomOffset, 6); argcnt++;
    XtSetArg(args[argcnt], XmNrightOffset, 10); argcnt++;
    /* An alternative is to use the EXTENDED_SELECT, but that one
       is less suited for keyboard manipulation (moving the selection cursor
       with the keyboard deselects everything). */
    XtSetArg(args[argcnt], XmNselectionPolicy, XmMULTIPLE_SELECT); argcnt++;
    list = XmCreateScrolledList(form, "list_of_files", args, argcnt);
    AddMouseWheelSupport(list);
    XtManageChild(list);
    
    /* Traverse: list -> buttons -> path name toggle button */
    XmAddTabGroup(list);
    XmAddTabGroup(btnForm);
    XmAddTabGroup(pathBtn);
    
    XtVaSetValues(label1, XmNuserData, list, NULL); /* mnemonic processing */
    
    /* Cancel/Mnemonic stuff. */
    XtVaSetValues(form, XmNcancelButton, cancelBtn, NULL);
    AddDialogMnemonicHandler(form, FALSE);
    
    window->replaceMultiFileDlog = form;
    window->replaceMultiFileList = list;
    window->replaceMultiFilePathBtn = pathBtn;
       
    /* Install a handler that frees the list of writable windows when
       the dialog is unmapped. */
    XtAddCallback(form, XmNunmapCallback, 
	    	    (XtCallbackProc)freeWritableWindowsCB, window); 
} 

/*
** Iterates through the list of writable windows of a window, and removes
** the doomed window if necessary.
*/
static void checkMultiReplaceListForDoomedW(WindowInfo* window, 
						     WindowInfo* doomedWindow)
{
    WindowInfo        *w;
    int               i;

    /* If the window owning the list and the doomed window are one and the
       same, we just close the multi-file replacement dialog. */
    if (window == doomedWindow) {
       XtUnmanageChild(window->replaceMultiFileDlog);
       return;
    }

    /* Check whether the doomed window is currently listed */
    for (i = 0; i < window->nWritableWindows; ++i) {
      w = window->writableWindows[i];
      if (w == doomedWindow) {
          removeDoomedWindowFromList(window, i);
          break;
      } 
    }   
}

/*
** Removes a window that is about to be closed from the list of files in
** which to replace. If the list becomes empty, the dialog is popped down.
*/
static void removeDoomedWindowFromList(WindowInfo* window, int index)
{
    int       entriesToMove;

    /* If the list would become empty, we remove the dialog */
    if (window->nWritableWindows <= 1) {
      XtUnmanageChild(window->replaceMultiFileDlog);
      return;
    }

    entriesToMove = window->nWritableWindows - index - 1;
    memmove(&(window->writableWindows[index]),
            &(window->writableWindows[index+1]),
            (size_t)(entriesToMove*sizeof(WindowInfo*)));
    window->nWritableWindows -= 1;
    
    XmListDeletePos(window->replaceMultiFileList, index + 1);
}

/*
** These callbacks fix a Motif 1.1 problem that the default button gets the
** keyboard focus when a dialog is created.  We want the first text field
** to get the focus, so we don't set the default button until the text field
** has the focus for sure.  I have tried many other ways and this is by far
** the least nasty.
*/
static void fFocusCB(Widget w, WindowInfo *window, caddr_t *callData) 
{
    window = WidgetToWindow(w);
    SET_ONE_RSRC(window->findDlog, XmNdefaultButton, window->findBtn);
}
static void rFocusCB(Widget w, WindowInfo *window, caddr_t *callData) 
{
    window = WidgetToWindow(w);
    SET_ONE_RSRC(window->replaceDlog, XmNdefaultButton, window->replaceBtn);
}

/* when keeping a window up, clue the user what window it's associated with */
static void rKeepCB(Widget w, WindowInfo *window, caddr_t *callData) 
{
    char title[MAXPATHLEN + 19];

    window = WidgetToWindow(w);

    if (XmToggleButtonGetState(w)) {
    	sprintf(title, "Replace/Find (in %s)", window->filename);
    	XtVaSetValues(XtParent(window->replaceDlog), XmNtitle, title, NULL);
    } else
    	XtVaSetValues(XtParent(window->replaceDlog), XmNtitle, "Replace/Find", NULL);
}
static void fKeepCB(Widget w, WindowInfo *window, caddr_t *callData) 
{
    char title[MAXPATHLEN + 11];

    window = WidgetToWindow(w);

    if (XmToggleButtonGetState(w)) {
    	sprintf(title, "Find (in %s)", window->filename);
    	XtVaSetValues(XtParent(window->findDlog), XmNtitle, title, NULL);
    } else
    	XtVaSetValues(XtParent(window->findDlog), XmNtitle, "Find", NULL);
}

static void replaceCB(Widget w, WindowInfo *window,
		      XmAnyCallbackStruct *callData) 
{
    char searchString[SEARCHMAX], replaceString[SEARCHMAX];
    int direction, searchType;
    char *params[5];
    
    window = WidgetToWindow(w);

    /* Validate and fetch the find and replace strings from the dialog */
    if (!getReplaceDlogInfo(window, &direction, searchString, replaceString,
    	    &searchType))
    	return;

    /* Set the initial focus of the dialog back to the search string */
    resetReplaceTabGroup(window);
    
    /* Find the text and replace it */
    params[0] = searchString;
    params[1] = replaceString;
    params[2] = directionArg(direction);
    params[3] = searchTypeArg(searchType);
    params[4] = searchWrapArg(GetPrefSearchWraps());
    XtCallActionProc(window->lastFocus, "replace", callData->event, params, 5);
    
    /* Pop down the dialog */
    if (!XmToggleButtonGetState(window->replaceKeepBtn))
    	unmanageReplaceDialogs(window);
}

static void replaceAllCB(Widget w, WindowInfo *window,
			 XmAnyCallbackStruct *callData) 
{
    char searchString[SEARCHMAX], replaceString[SEARCHMAX];
    int direction, searchType;
    char *params[3];
    
    window = WidgetToWindow(w);

    /* Validate and fetch the find and replace strings from the dialog */
    if (!getReplaceDlogInfo(window, &direction, searchString, replaceString,
    	    &searchType))
    	return;

    /* Set the initial focus of the dialog back to the search string	*/
    resetReplaceTabGroup(window);

    /* do replacement */
    params[0] = searchString;
    params[1] = replaceString;
    params[2] = searchTypeArg(searchType);
    XtCallActionProc(window->lastFocus, "replace_all", callData->event,
    	    params, 3);
    
    /* pop down the dialog */
    if (!XmToggleButtonGetState(window->replaceKeepBtn))
    	unmanageReplaceDialogs(window);
}

static void replaceMultiFileCB(Widget w, WindowInfo *window,
				   XmAnyCallbackStruct *callData) 
{
    window = WidgetToWindow(w);
    DoReplaceMultiFileDlog(window);
}

/*
** Callback that frees the list of windows the multi-file replace
** dialog is unmapped.
**/
static void freeWritableWindowsCB(Widget w, WindowInfo* window,
                                  XmAnyCallbackStruct *callData)
{
    window = WidgetToWindow(w);
    XtFree((XtPointer)window->writableWindows);
    window->writableWindows = NULL;
    window->nWritableWindows = 0;
}

/*
** Comparison function for sorting windows by title for the window menu
*/
static int compareWindowNames(const void *windowA, const void *windowB)
{
      return strcmp((*((WindowInfo**)windowA))->filename,
      	    (*((WindowInfo**)windowB))->filename);
}
 
/*
** Count no. of windows
*/
static int countWindows(void)
{
    int nWindows;
    const WindowInfo *w;

    for (w=WindowList, nWindows=0; w!=NULL; w=w->next, ++nWindows);
    
    return nWindows;
}

/*
** Count no. of writable windows, but first update the status of all files.
*/
static int countWritableWindows(void)
{
    int nWritable, nBefore, nAfter;
    WindowInfo *w;

    nBefore = countWindows();
    for (w=WindowList, nWritable=0; w!=NULL; w=w->next) {
	/* We must be very careful! The status check may trigger a pop-up
	   dialog when the file has changed on disk, and the user may destroy
	   arbitrary windows in response. */
	CheckForChangesToFile(w);
	nAfter = countWindows();
	if (nAfter != nBefore) {
	    /* The user has destroyed a file; start counting all over again */
	    nBefore = nAfter;
	    w = WindowList;
	    nWritable = 0;
	    continue;
	}
	if (!IS_ANY_LOCKED(w->lockReasons)) ++nWritable;
    }
    return nWritable;
}

/*
** Collects a list of writable windows (sorted by file name). 
** The previous list, if any is freed first. 
**/
static void collectWritableWindows(WindowInfo* window)
{
    int nWritable = countWritableWindows();
    int i;
    WindowInfo *w;
    WindowInfo **windows;
    
    if (window->writableWindows)
    {
       XtFree((XtPointer)window->writableWindows);
    }

    /* Make a sorted list of writable windows */
    windows = (WindowInfo **)XtMalloc(sizeof(WindowInfo *) * nWritable);
    for (w=WindowList, i=0; w!=NULL; w=w->next)
       if (!IS_ANY_LOCKED(w->lockReasons)) windows[i++] = w;
    qsort(windows, nWritable, sizeof(WindowInfo *), compareWindowNames);
    
    window->writableWindows = windows;
    window->nWritableWindows = nWritable;
} 

static void rMultiFileReplaceCB(Widget w, WindowInfo *window, 
   XmAnyCallbackStruct *callData) 
{
    char 	searchString[SEARCHMAX], replaceString[SEARCHMAX];
    int 	direction, searchType;
    char 	*params[4];
    int 	nSelected, i;
    WindowInfo 	*writableWin;
    Bool 	replaceFailed, noWritableLeft;

    window = WidgetToWindow(w);
    nSelected = 0;
    for (i=0; i<window->nWritableWindows; ++i)
       if (XmListPosSelected(window->replaceMultiFileList, i+1))
          ++nSelected;

    if (!nSelected)
    {
        DialogF(DF_INF, XtParent(window->replaceMultiFileDlog), 1, "No Files",
                "No files selected!", "OK");
       return; /* Give the user another chance */
    }

    /* Set the initial focus of the dialog back to the search string */
    resetReplaceTabGroup(window);
    
    /*
     * Protect the user against him/herself; Maybe this is a bit too much?
     */
    if (DialogF(DF_QUES, window->shell, 2, "Multi-File Replacement",
            "Multi-file replacements are difficult to undo.\n"
            "Proceed with the replacement ?", "Yes", "Cancel") != 1)
    {
        /* pop down the multi-file dialog only */
        XtUnmanageChild(window->replaceMultiFileDlog);

        return;
    }

    /* Fetch the find and replace strings from the dialog; 
       they should have been validated already, but since Lesstif may not
       honor modal dialogs, it is possible that the user modified the 
       strings again, so we should verify them again too. */
    if (!getReplaceDlogInfo(window, &direction, searchString, replaceString,
 	 		  &searchType))
	return;

    /* Set the initial focus of the dialog back to the search string */
    resetReplaceTabGroup(window);
    
    params[0] = searchString;
    params[1] = replaceString;
    params[2] = searchTypeArg(searchType);

    replaceFailed = True;
    noWritableLeft = True;
    /* Perform the replacements and mark the selected files (history) */
    for (i=0; i<window->nWritableWindows; ++i) {
	writableWin = window->writableWindows[i];
	if (XmListPosSelected(window->replaceMultiFileList, i+1)) {
	/* First check again whether the file is still writable. If the
	   file status has changed or the file was locked in the mean time
	   (possible due to Lesstif modal dialog bug), we just skip the 
	   window. */
	    if (!IS_ANY_LOCKED(writableWin->lockReasons)) {
		noWritableLeft = False;
		writableWin->multiFileReplSelected = True;
		writableWin->multiFileBusy = True; /* Avoid multi-beep/dialog */
		writableWin->replaceFailed = False;
		XtCallActionProc(writableWin->lastFocus, "replace_all",
		    callData->event, params, 3);
		writableWin->multiFileBusy = False;
		if (!writableWin->replaceFailed)
		    replaceFailed = False;
	    }
	} else {
	    writableWin->multiFileReplSelected = False;
	}
    }                          
        
    if (!XmToggleButtonGetState(window->replaceKeepBtn)) {
       /* Pop down both replace dialogs. */
       unmanageReplaceDialogs(window);
    } else {
       /* pow down only the file selection dialog */
       XtUnmanageChild(window->replaceMultiFileDlog);
    }
    
    /* We suppressed multiple beeps/dialogs. If there wasn't any file in
       which the replacement succeeded, we should still warn the user */
    if (replaceFailed) {
	if (GetPrefSearchDlogs()) {
	    if (noWritableLeft) {
		DialogF(DF_INF, window->shell, 1, "Read-only Files",
                        "All selected files have become read-only.", "OK");
	    } else {
		DialogF(DF_INF, window->shell, 1, "String not found",
                        "String was not found", "OK");
            }
	} else {
           XBell(TheDisplay, 0);
        }
    }
}

static void rMultiFileCancelCB(Widget w, WindowInfo *window, caddr_t callData) 
{
    window = WidgetToWindow(w);

    /* Set the initial focus of the dialog back to the search string	*/
    resetReplaceTabGroup(window);

    /* pop down the multi-window replace dialog */
    XtUnmanageChild(window->replaceMultiFileDlog);
}

static void rMultiFileSelectAllCB(Widget w, WindowInfo *window, 
   XmAnyCallbackStruct *callData) 
{
    int i;
    char policy;
    Widget list;
    
    window = WidgetToWindow(w);
    list = window->replaceMultiFileList;
    
    /*
     * If the list is in extended selection mode, we can't select more 
     * than one item (probably because XmListSelectPos is equivalent 
     * to a button1 click; I don't think that there is an equivalent 
     * for CTRL-button1). Therefore, we temporarily put the list into 
     * multiple selection mode.
     * Note: this is not really necessary if the list is in multiple select
     *       mode all the time (as it currently is). 
     */
    XtVaGetValues(list, XmNselectionPolicy, &policy, NULL);
    XtVaSetValues(list, XmNselectionPolicy, XmMULTIPLE_SELECT, NULL);
    
    /* Is there no other way (like "select all") ? */
    XmListDeselectAllItems(window->replaceMultiFileList); /* select toggles */
    
    for (i=0; i<window->nWritableWindows; ++i) {
       XmListSelectPos(list, i+1, FALSE);
    }
    
    /* Restore the original policy. */
    XtVaSetValues(list, XmNselectionPolicy, policy, NULL);
}

static void rMultiFileDeselectAllCB(Widget w, WindowInfo *window,  
   XmAnyCallbackStruct *callData) 
{
    window = WidgetToWindow(w);
    XmListDeselectAllItems(window->replaceMultiFileList);
}

static void rMultiFilePathCB(Widget w, WindowInfo *window,  
   XmAnyCallbackStruct *callData) 
{
    window = WidgetToWindow(w);
    uploadFileListItems(window, True);  /* Replace */
}

/*
 * Uploads the file items to the multi-file replament dialog list.
 * A boolean argument indicates whether the elements currently in the 
 * list have to be replaced or not.
 * Depending on the state of the "Show path names" toggle button, either
 * the file names or the path names are listed.
 */
static void uploadFileListItems(WindowInfo* window, Bool replace)
{
    XmStringTable names;
    int           nWritable, i, *selected, selectedCount;
    char          buf[MAXPATHLEN+1], policy;
    Bool          usePathNames;
    WindowInfo    *w;
    Widget        list;

    nWritable = window->nWritableWindows;
    list = window->replaceMultiFileList;
    
    names = (XmStringTable) XtMalloc(nWritable * sizeof(XmString*));
    
    usePathNames = XmToggleButtonGetState(window->replaceMultiFilePathBtn);
    
    /* Note: the windows are sorted alphabetically by _file_ name. This
             order is _not_ changed when we switch to path names. That
             would be confusing for the user */
    
    for (i = 0; i < nWritable; ++i) {
       w = window->writableWindows[i];
       if (usePathNames && window->filenameSet) {
          sprintf(buf, "%s%s", w->path, w->filename);
       } else {
          sprintf(buf, "%s", w->filename);
       }
       names[i] = XmStringCreateSimple(buf);
    }
    
    /*
     * If the list is in extended selection mode, we can't pre-select 
     * more than one item in (probably because XmListSelectPos is 
     * equivalent to a button1 click; I don't think that there is an 
     * equivalent for CTRL-button1). Therefore, we temporarily put the 
     * list into multiple selection mode.
     */
    XtVaGetValues(list, XmNselectionPolicy, &policy, NULL);
    XtVaSetValues(list, XmNselectionPolicy, XmMULTIPLE_SELECT, NULL);
    if (replace) {
       /* Note: this function is obsolete in Motif 2.x, but it is available
                for compatibility reasons */
       XmListGetSelectedPos(list, &selected,  &selectedCount);
       
       XmListReplaceItemsPos(list, names, nWritable, 1);
       
       /* Maintain the selections */
       XmListDeselectAllItems(list);
       for (i = 0; i < selectedCount; ++i) {
          XmListSelectPos(list, selected[i], False);
       }
       
       XtFree((XtPointer)selected);
    } else {
       Arg args[1];
       int nVisible;
       int firstSelected = 0;
       
       /* Remove the old list, if any */
       XmListDeleteAllItems(list);
       
       /* Initial settings */
       XmListAddItems(list, names, nWritable, 1);
       
       /* Pre-select the files from the last run. */   
       selectedCount = 0;
       for (i = 0; i < nWritable; ++i) {
          if (window->writableWindows[i]->multiFileReplSelected) {
             XmListSelectPos(list, i+1, False);
             ++selectedCount;
             /* Remember the first selected item */
             if (firstSelected == 0) firstSelected = i+1;
          }
       }
       /* If no files are selected, we select them all. Normally this only
          happens the first time the dialog is used, but it looks "silly" 
          if the dialog pops up with nothing selected. */
       if (selectedCount == 0) {
          for (i = 0; i < nWritable; ++i) {
             XmListSelectPos(list, i+1, False);
          }
          firstSelected = 1;
       }
       
       /* Make sure that the first selected item is visible; otherwise, the
          user could get the impression that nothing is selected. By
          visualizing at least the first selected item, the user will more
          easily be confident that the previous selection is still active. */
       XtSetArg(args[0], XmNvisibleItemCount, &nVisible);
       XtGetValues(list, args, 1);
       /* Make sure that we don't create blank lines at the bottom by
          positioning too far. */
       if (nWritable <= nVisible) {
          /* No need to shift the visible position */
          firstSelected = 1;
       }
       else {
          int maxFirst = nWritable - nVisible + 1;
          if (firstSelected > maxFirst)
             firstSelected = maxFirst;
       }
       XmListSetPos(list, firstSelected);
    }
    
    /* Put the list back into its original selection policy. */
    XtVaSetValues(list, XmNselectionPolicy, policy, NULL);
    
    for (i = 0; i < nWritable; ++i)
       XmStringFree(names[i]);
    XtFree((XtPointer)names);
}

/*
** Unconditionally pops down the replace dialog and the
** replace-in-multiple-files dialog, if it exists.
*/
static void unmanageReplaceDialogs(WindowInfo *window)
{
    /* If the replace dialog goes down, the multi-file replace dialog must
       go down too */
    if (window->replaceMultiFileDlog &&
      XtIsManaged(window->replaceMultiFileDlog)) {
          XtUnmanageChild(window->replaceMultiFileDlog);
    }
        
    if (window->replaceDlog &&
      XtIsManaged(window->replaceDlog)) {
          XtUnmanageChild(window->replaceDlog);
    }
}

static void rInSelCB(Widget w, WindowInfo *window,
			 XmAnyCallbackStruct *callData) 
{
    char searchString[SEARCHMAX], replaceString[SEARCHMAX];
    int direction, searchType;
    char *params[3];
    
    window = WidgetToWindow(w);

    /* Validate and fetch the find and replace strings from the dialog */
    if (!getReplaceDlogInfo(window, &direction, searchString, replaceString,
    	    &searchType))
    	return;

    /* Set the initial focus of the dialog back to the search string */
    resetReplaceTabGroup(window);

    /* do replacement */
    params[0] = searchString;
    params[1] = replaceString;
    params[2] = searchTypeArg(searchType);
    XtCallActionProc(window->lastFocus, "replace_in_selection",
    	    callData->event, params, 3);
    
    /* pop down the dialog */
    if (!XmToggleButtonGetState(window->replaceKeepBtn))
    	unmanageReplaceDialogs(window);
}

static void rCancelCB(Widget w, WindowInfo *window, caddr_t callData) 
{
    window = WidgetToWindow(w);

    /* Set the initial focus of the dialog back to the search string	*/
    resetReplaceTabGroup(window);

    /* pop down the dialog */
    unmanageReplaceDialogs(window);
}

static void fCancelCB(Widget w, WindowInfo *window, caddr_t callData) 
{
    window = WidgetToWindow(w);

    /* Set the initial focus of the dialog back to the search string	*/
    resetFindTabGroup(window);
    
    /* pop down the dialog */
    XtUnmanageChild(window->findDlog);
}

static void rFindCB(Widget w, WindowInfo *window,XmAnyCallbackStruct *callData) 
{
    char searchString[SEARCHMAX], replaceString[SEARCHMAX];
    int direction, searchType;
    char *params[4];
    
    window = WidgetToWindow(w);

    /* Validate and fetch the find and replace strings from the dialog */
    if (!getReplaceDlogInfo(window, &direction, searchString, replaceString,
    	    &searchType))
    	return;

    /* Set the initial focus of the dialog back to the search string	*/
    resetReplaceTabGroup(window);
    
    /* Find the text and mark it */
    params[0] = searchString;
    params[1] = directionArg(direction);
    params[2] = searchTypeArg(searchType);
    params[3] = searchWrapArg(GetPrefSearchWraps());
    XtCallActionProc(window->lastFocus, "find", callData->event, params, 4);
    
    /* Doctor the search history generated by the action to include the
       replace string (if any), so the replace string can be used on
       subsequent replaces, even though no actual replacement was done. */
    if (historyIndex(1) != -1 &&
    		!strcmp(SearchHistory[historyIndex(1)], searchString)) {
	XtFree(ReplaceHistory[historyIndex(1)]);
	ReplaceHistory[historyIndex(1)] = XtNewString(replaceString);
    }

    /* Pop down the dialog */
    if (!XmToggleButtonGetState(window->replaceKeepBtn))
    	unmanageReplaceDialogs(window);
}

static void replaceFindCB(Widget w, WindowInfo *window, XmAnyCallbackStruct *callData) 
{
    char searchString[SEARCHMAX+1], replaceString[SEARCHMAX+1];
    int direction, searchType;
    char *params[4];
    
    window = WidgetToWindow(w);

    /* Validate and fetch the find and replace strings from the dialog */
    if (!getReplaceDlogInfo(window, &direction, searchString, replaceString,
            &searchType))
        return;

    /* Set the initial focus of the dialog back to the search string */
    resetReplaceTabGroup(window);
    
    /* Find the text and replace it */
    params[0] = searchString;
    params[1] = replaceString;
    params[2] = directionArg(direction);
    params[3] = searchTypeArg(searchType);
    XtCallActionProc(window->lastFocus, "replace_find", callData->event, params, 4);
    
    /* Pop down the dialog */
    if (!XmToggleButtonGetState(window->replaceKeepBtn))
    	unmanageReplaceDialogs(window);
}

static void rSetActionButtons(WindowInfo* window,
                              int replaceBtn,
                              int replaceFindBtn,
                              int replaceAndFindBtn,
#ifndef REPLACE_SCOPE
                              int replaceInWinBtn,
                              int replaceInSelBtn,
#endif      
                              int replaceAllBtn)
{
    XtSetSensitive(window->replaceBtn,        replaceBtn);
    XtSetSensitive(window->replaceFindBtn,    replaceFindBtn);
    XtSetSensitive(window->replaceAndFindBtn, replaceAndFindBtn);
#ifndef REPLACE_SCOPE
    XtSetSensitive(window->replaceInWinBtn, replaceInWinBtn);
    XtSetSensitive(window->replaceInSelBtn, replaceInSelBtn);
#endif
    XtSetSensitive(window->replaceAllBtn,     replaceAllBtn);
} 

void UpdateReplaceActionButtons(WindowInfo* window)
{
    /* Is there any text in the search for field */
    int searchText = textFieldNonEmpty(window->replaceText);
#ifdef REPLACE_SCOPE
    switch (window->replaceScope)
    {
        case REPL_SCOPE_WIN:
	    /* Enable all buttons, if there is any text in the search field. */
	    rSetActionButtons(window, searchText, searchText, searchText, searchText);
            break;

        case REPL_SCOPE_SEL:
	    /* Only enable Replace All, if a selection exists and text in search field. */
	    rSetActionButtons(window, False, False, False, searchText && window->wasSelected);
            break;

        case REPL_SCOPE_MULTI:
	    /* Only enable Replace All, if text in search field. */
	    rSetActionButtons(window, False, False, False, searchText);
            break;
    }
#else
    rSetActionButtons(window, searchText, searchText, searchText,
                      searchText, searchText && window->wasSelected,
                      searchText && (countWritableWindows() > 1));
#endif
}

#ifdef REPLACE_SCOPE
/*
** The next 3 callback adapt the sensitivity of the replace dialog push 
** buttons to the state of the scope radio buttons.
*/
static void rScopeWinCB(Widget w, WindowInfo *window, 
    XmAnyCallbackStruct *callData)
{
    window = WidgetToWindow(w);
    if (XmToggleButtonGetState(window->replaceScopeWinToggle)) {
	window->replaceScope = REPL_SCOPE_WIN;
        UpdateReplaceActionButtons(window);
    }
}

static void rScopeSelCB(Widget w, WindowInfo *window, 
    XmAnyCallbackStruct *callData)
{
    window = WidgetToWindow(w);
    if (XmToggleButtonGetState(window->replaceScopeSelToggle)) {
	window->replaceScope = REPL_SCOPE_SEL;
        UpdateReplaceActionButtons(window);
    }
}

static void rScopeMultiCB(Widget w, WindowInfo *window, 
    XmAnyCallbackStruct *callData)
{
    window = WidgetToWindow(w);
    if (XmToggleButtonGetState(window->replaceScopeMultiToggle)) {
	window->replaceScope = REPL_SCOPE_MULTI;
        UpdateReplaceActionButtons(window);
    }
}

/*
** This routine dispatches a push on the replace-all button to the appropriate
** callback, depending on the state of the scope radio buttons.
*/
static void replaceAllScopeCB(Widget w, WindowInfo *window, 
    XmAnyCallbackStruct *callData)
{
    window = WidgetToWindow(w);
    switch(window->replaceScope) {
	case REPL_SCOPE_WIN:
           replaceAllCB(w, window, callData);
           break;
        case REPL_SCOPE_SEL:
           rInSelCB(w, window, callData);
           break;
        case REPL_SCOPE_MULTI:
           replaceMultiFileCB(w, window, callData);
           break;
    }        
}
#endif

static int textFieldNonEmpty(Widget w)
{
    char *str = XmTextGetString(w);
    int nonEmpty = (str[0] != '\0');
    XtFree(str);
    return(nonEmpty);
}

static void rFindTextValueChangedCB(Widget w, WindowInfo *window, XKeyEvent *event)
{
    window = WidgetToWindow(w);
    UpdateReplaceActionButtons(window);
}

static void rFindArrowKeyCB(Widget w, WindowInfo *window, XKeyEvent *event)
{
    KeySym keysym = XLookupKeysym(event, 0);
    int index;
    char *searchStr, *replaceStr;
    int searchType;
    
    window = WidgetToWindow(w);
    index = window->rHistIndex;
    
    /* only process up and down arrow keys */
    if (keysym != XK_Up && keysym != XK_Down)
    	return;
    
    /* increment or decrement the index depending on which arrow was pressed */
    index += (keysym == XK_Up) ? 1 : -1;

    /* if the index is out of range, beep and return */
    if (index != 0 && historyIndex(index) == -1) {
    	XBell(TheDisplay, 0);
    	return;
    }
    
    window = WidgetToWindow(w);

    /* determine the strings and button settings to use */
    if (index == 0) {
    	searchStr = "";
    	replaceStr = "";
    	searchType = GetPrefSearch();
    } else {
	searchStr = SearchHistory[historyIndex(index)];
	replaceStr = ReplaceHistory[historyIndex(index)];
	searchType = SearchTypeHistory[historyIndex(index)];
    }
    
    /* Set the buttons and fields with the selected search type */
    initToggleButtons(searchType, window->replaceRegexToggle,
                      window->replaceCaseToggle, &window->replaceWordToggle,
                      &window->replaceLastLiteralCase,
                      &window->replaceLastRegexCase);
    
    XmTextSetString(window->replaceText, searchStr);
    XmTextSetString(window->replaceWithText, replaceStr);
    
    /* Set the state of the Replace, Find ... buttons */
    UpdateReplaceActionButtons(window);

    window->rHistIndex = index;
}

static void replaceArrowKeyCB(Widget w, WindowInfo *window, XKeyEvent *event)
{
    KeySym keysym = XLookupKeysym(event, 0);
    int index;
    
    window = WidgetToWindow(w);
    index = window->rHistIndex;

    /* only process up and down arrow keys */
    if (keysym != XK_Up && keysym != XK_Down)
    	return;
    
    /* increment or decrement the index depending on which arrow was pressed */
    index += (keysym == XK_Up) ? 1 : -1;

    /* if the index is out of range, beep and return */
    if (index != 0 && historyIndex(index) == -1) {
    	XBell(TheDisplay, 0);
    	return;
    }
    
    window = WidgetToWindow(w);

    /* change only the replace field information */
    if (index == 0)
    	XmTextSetString(window->replaceWithText, "");
    else
    	XmTextSetString(window->replaceWithText,
    		ReplaceHistory[historyIndex(index)]);
    window->rHistIndex = index;
}

static void fUpdateActionButtons(WindowInfo *window)
{
    int buttonState = textFieldNonEmpty(window->findText);
    XtSetSensitive(window->findBtn, buttonState);
}

static void findTextValueChangedCB(Widget w, WindowInfo *window, XKeyEvent *event)
{
    window = WidgetToWindow(w);
    fUpdateActionButtons(window);
}

static void findArrowKeyCB(Widget w, WindowInfo *window, XKeyEvent *event)
{
    KeySym keysym = XLookupKeysym(event, 0);
    int index;
    char *searchStr;
    int searchType;
    
    window = WidgetToWindow(w);
    index = window->fHistIndex;
    
    /* only process up and down arrow keys */
    if (keysym != XK_Up && keysym != XK_Down)
    	return;
    
    /* increment or decrement the index depending on which arrow was pressed */
    index += (keysym == XK_Up) ? 1 : -1;

    /* if the index is out of range, beep and return */
    if (index != 0 && historyIndex(index) == -1) {
    	XBell(TheDisplay, 0);
    	return;
    }
    

    /* determine the strings and button settings to use */
    if (index == 0) {
    	searchStr = "";
    	searchType = GetPrefSearch();
    } else {
	searchStr = SearchHistory[historyIndex(index)];
	searchType = SearchTypeHistory[historyIndex(index)];
    }
    
    /* Set the buttons and fields with the selected search type */
    initToggleButtons(searchType, window->findRegexToggle,
                      window->findCaseToggle, &window->findWordToggle,
                      &window->findLastLiteralCase,
                      &window->findLastRegexCase);
    XmTextSetString(window->findText, searchStr);

    /* Set the state of the Find ... button */
    fUpdateActionButtons(window);

    window->fHistIndex = index;
}

static void findCB(Widget w, WindowInfo *window,XmAnyCallbackStruct *callData) 
{
    char searchString[SEARCHMAX];
    int direction, searchType;
    char *params[4];
    
    window = WidgetToWindow(w);

    /* fetch find string, direction and type from the dialog */
    if (!getFindDlogInfo(window, &direction, searchString, &searchType))
    	return;

    /* Set the initial focus of the dialog back to the search string	*/
    resetFindTabGroup(window);
    
    /* find the text and mark it */
    params[0] = searchString;
    params[1] = directionArg(direction);
    params[2] = searchTypeArg(searchType);
    params[3] = searchWrapArg(GetPrefSearchWraps());
    XtCallActionProc(window->lastFocus, "find", callData->event, params, 4);

    /* pop down the dialog */
    if (!XmToggleButtonGetState(window->findKeepBtn))
        XtUnmanageChild(window->findDlog);
}

/*
** Fetch and verify (particularly regular expression) search and replace
** strings and search type from the Replace dialog.  If the strings are ok,
** save a copy in the search history, copy them in to "searchString",
** "replaceString', which are assumed to be at least SEARCHMAX in length,
** return search type in "searchType", and return TRUE as the function
** value.  Otherwise, return FALSE.
*/
static int getReplaceDlogInfo(WindowInfo *window, int *direction,
	char *searchString, char *replaceString, int *searchType)
{
    char *replaceText, *replaceWithText;
    regexp *compiledRE = NULL;
    char *compileMsg;
    
    /* Get the search and replace strings, search type, and direction
       from the dialog */
    replaceText = XmTextGetString(window->replaceText);
    replaceWithText = XmTextGetString(window->replaceWithText);
    
    if(XmToggleButtonGetState(window->replaceRegexToggle)) {
      int regexDefault;
      if(XmToggleButtonGetState(window->replaceCaseToggle)) {
      	*searchType = SEARCH_REGEX;
	regexDefault = REDFLT_STANDARD;
      } else {
      	*searchType = SEARCH_REGEX_NOCASE;
	regexDefault = REDFLT_CASE_INSENSITIVE;
      }
      /* If the search type is a regular expression, test compile it 
         immediately and present error messages */
      compiledRE = CompileRE(replaceText, &compileMsg, regexDefault);
      if (compiledRE == NULL) {
   	  DialogF(DF_WARN, XtParent(window->replaceDlog), 1, "Search String",
                  "Please respecify the search string:\n%s", "OK", compileMsg);
	  XtFree(replaceText);
	  XtFree(replaceWithText);
 	  return FALSE;
      }
      free((char*)compiledRE);
    } else {
      if(XmToggleButtonGetState(window->replaceCaseToggle)) {
      	if(XmToggleButtonGetState(window->replaceWordToggle))
	  *searchType = SEARCH_CASE_SENSE_WORD;
	else
	  *searchType = SEARCH_CASE_SENSE;
      } else {
      	if(XmToggleButtonGetState(window->replaceWordToggle))
	  *searchType = SEARCH_LITERAL_WORD;
	else
	  *searchType = SEARCH_LITERAL;
      }
    }
    
    *direction = XmToggleButtonGetState(window->replaceRevToggle) ? 
	SEARCH_BACKWARD : SEARCH_FORWARD;
    
    /* Return strings */
    if (strlen(replaceText) >= SEARCHMAX) {
	DialogF(DF_WARN, XtParent(window->replaceDlog), 1, "String too long",
                "Search string too long.", "OK");
	XtFree(replaceText);
	XtFree(replaceWithText);
	return FALSE;
    }
    if (strlen(replaceWithText) >= SEARCHMAX) {
	DialogF(DF_WARN, XtParent(window->replaceDlog), 1, "String too long",
                "Replace string too long.", "OK");
	XtFree(replaceText);
	XtFree(replaceWithText);
	return FALSE;
    }
    strcpy(searchString, replaceText);
    strcpy(replaceString, replaceWithText);
    XtFree(replaceText);
    XtFree(replaceWithText);
    return TRUE;
}

/*
** Fetch and verify (particularly regular expression) search string,
** direction, and search type from the Find dialog.  If the search string
** is ok, save a copy in the search history, copy it to "searchString",
** which is assumed to be at least SEARCHMAX in length, return search type
** in "searchType", and return TRUE as the function value.  Otherwise,
** return FALSE.
*/
static int getFindDlogInfo(WindowInfo *window, int *direction,
	char *searchString, int *searchType)
{
    char *findText;
    regexp *compiledRE = NULL;
    char *compileMsg;
    
    /* Get the search string, search type, and direction from the dialog */
    findText = XmTextGetString(window->findText);
    
    if(XmToggleButtonGetState(window->findRegexToggle)) {
      int regexDefault;
      if(XmToggleButtonGetState(window->findCaseToggle)) {
      	*searchType = SEARCH_REGEX;
	regexDefault = REDFLT_STANDARD;
      } else {
      	*searchType = SEARCH_REGEX_NOCASE;
	regexDefault = REDFLT_CASE_INSENSITIVE;
      }
      /* If the search type is a regular expression, test compile it 
         immediately and present error messages */
      compiledRE = CompileRE(findText, &compileMsg, regexDefault);
      if (compiledRE == NULL) {
   	  DialogF(DF_WARN, XtParent(window->findDlog), 1, "Regex Error",
                  "Please respecify the search string:\n%s", "OK", compileMsg);
 	  return FALSE;
      }
      free((char *)compiledRE);
    } else {
      if(XmToggleButtonGetState(window->findCaseToggle)) {
      	if(XmToggleButtonGetState(window->findWordToggle))
	  *searchType = SEARCH_CASE_SENSE_WORD;
	else
	  *searchType = SEARCH_CASE_SENSE;
      } else {
      	if(XmToggleButtonGetState(window->findWordToggle))
	  *searchType = SEARCH_LITERAL_WORD;
	else
	  *searchType = SEARCH_LITERAL;
      }
    }
    
    *direction = XmToggleButtonGetState(window->findRevToggle) ? 
	SEARCH_BACKWARD : SEARCH_FORWARD;
    
    if (isRegexType(*searchType)) {
    }

    /* Return the search string */
    if (strlen(findText) >= SEARCHMAX) {
	DialogF(DF_WARN, XtParent(window->findDlog), 1, "String too long",
                "Search string too long.", "OK");
	XtFree(findText);
	return FALSE;
    }
    strcpy(searchString, findText);
    XtFree(findText);
    return TRUE;
}

int SearchAndSelectSame(WindowInfo *window, int direction, int searchWrap)
{
    if (NHist < 1) {
    	XBell(TheDisplay, 0);
    	return FALSE;
    }
    
    return SearchAndSelect(window, direction, SearchHistory[historyIndex(1)],
    	    SearchTypeHistory[historyIndex(1)], searchWrap);
}

/*
** Search for "searchString" in "window", and select the matching text in
** the window when found (or beep or put up a dialog if not found).  Also
** adds the search string to the global search history.
*/
int SearchAndSelect(WindowInfo *window, int direction, const char *searchString,
	int searchType, int searchWrap)
{
    int startPos, endPos;
    int beginPos, cursorPos, selStart, selEnd;
    
    /* Save a copy of searchString in the search history */
    saveSearchHistory(searchString, NULL, searchType, FALSE);
        
    /* set the position to start the search so we don't find the same
       string that was found on the last search	*/
    if (searchMatchesSelection(window, searchString, searchType,
    	    &selStart, &selEnd, NULL, NULL)) {
    	/* selection matches search string, start before or after sel.	*/
	if (direction == SEARCH_BACKWARD) {
	    beginPos = selStart-1;
	} else {
	    beginPos = selEnd;
	}
    } else {
    	selStart = -1; selEnd = -1;
    	/* no selection, or no match, search relative cursor */
    	cursorPos = TextGetCursorPos(window->lastFocus);
	if (direction == SEARCH_BACKWARD) {
	    /* use the insert position - 1 for backward searches */
	    beginPos = cursorPos-1;
	} else {
	    /* use the insert position for forward searches */
	    beginPos = cursorPos;
	}
    }

    /* when the i-search bar is active and search is repeated there 
       (Return), the action "find" is called (not: "find_incremental").
       "find" calls this function SearchAndSelect.
       To keep track of the iSearchLastBeginPos correctly in the
       repeated i-search case it is necessary to call the following
       function here, otherwise there are no beeps on the repeated
       incremental search wraps.  */
    iSearchRecordLastBeginPos(window, direction, beginPos);

    /* do the search.  SearchWindow does appropriate dialogs and beeps */
    if (!SearchWindow(window, direction, searchString, searchType, searchWrap,
    	    beginPos, &startPos, &endPos, NULL, NULL))
    	return FALSE;
    	
    /* if the search matched an empty string (possible with regular exps)
       beginning at the start of the search, go to the next occurrence,
       otherwise repeated finds will get "stuck" at zero-length matches */
    if (direction==SEARCH_FORWARD && beginPos==startPos && beginPos==endPos)
    	if (!SearchWindow(window, direction, searchString, searchType, searchWrap,
    		beginPos+1, &startPos, &endPos, NULL, NULL))
    	    return FALSE;
    
    /* if matched text is already selected, just beep */
    if (selStart==startPos && selEnd==endPos) {
    	XBell(TheDisplay, 0);
    	return FALSE;
    }

    /* select the text found string */
    BufSelect(window->buffer, startPos, endPos);
    MakeSelectionVisible(window, window->lastFocus);
    TextSetCursorPos(window->lastFocus, endPos);
    
    return TRUE;
}

void SearchForSelected(WindowInfo *window, int direction, int searchType,
    int searchWrap, Time time)
{
   SearchSelectedCallData *callData = XtNew(SearchSelectedCallData);
   callData->direction = direction;
   callData->searchType = searchType;
   callData->searchWrap = searchWrap;
   XtGetSelectionValue(window->textArea, XA_PRIMARY, XA_STRING,
    	    (XtSelectionCallbackProc)selectedSearchCB, callData, time);
}

static void selectedSearchCB(Widget w, XtPointer callData, Atom *selection,
	Atom *type, char *value, int *length, int *format)
{
    WindowInfo *window = WidgetToWindow(w);
    SearchSelectedCallData *callDataItems = (SearchSelectedCallData *)callData;
    int searchType;
    char searchString[SEARCHMAX+1];
    
    window = WidgetToWindow(w);

    /* skip if we can't get the selection data or it's too long */
    if (*type == XT_CONVERT_FAIL || value == NULL) {
    	if (GetPrefSearchDlogs())
   	    DialogF(DF_WARN, window->shell, 1, "Wrong Selection",
                    "Selection not appropriate for searching", "OK");
    	else
    	    XBell(TheDisplay, 0);
        XtFree(callData);
	return;
    }
    if (*length > SEARCHMAX) {
    	if (GetPrefSearchDlogs())
   	    DialogF(DF_WARN, window->shell, 1, "Selection too long",
                    "Selection too long", "OK");
    	else
    	    XBell(TheDisplay, 0);
	XtFree(value);
        XtFree(callData);
	return;
    }
    if (*length == 0) {
    	XBell(TheDisplay, 0);
	XtFree(value);
        XtFree(callData);
	return;
    }
    /* should be of type text??? */
    if (*format != 8) {
    	fprintf(stderr, "NEdit: can't handle non 8-bit text\n");
    	XBell(TheDisplay, 0);
	XtFree(value);
        XtFree(callData);
	return;
    }
    /* make the selection the current search string */
    strncpy(searchString, value, *length);
    searchString[*length] = '\0';
    XtFree(value);
    
    /* Use the passed method for searching, unless it is regex, since this
       kind of search is by definition a literal search */
    searchType = callDataItems->searchType;
    if (searchType == SEARCH_REGEX )
      searchType = SEARCH_CASE_SENSE;
    else if (searchType == SEARCH_REGEX_NOCASE)
	      searchType = SEARCH_LITERAL;

    /* search for it in the window */
    SearchAndSelect(window, callDataItems->direction, searchString,
        searchType, callDataItems->searchWrap);
    XtFree(callData);
}

/*
** Pop up and clear the incremental search line and prepare to search.
*/
void BeginISearch(WindowInfo *window, int direction)
{
    window->iSearchStartPos = -1;
    XmTextSetString(window->iSearchText, "");
    XmToggleButtonSetState(window->iSearchRevToggle,
	    direction == SEARCH_BACKWARD, FALSE);
    /* Note: in contrast to the replace and find dialogs, the regex and
       case toggles are not reset to their default state when the incremental
       search bar is redisplayed. I'm not sure whether this is the best
       choice. If not, an initToggleButtons() call should be inserted
       here. But in that case, it might be appropriate to have different
       default search modes for i-search and replace/find. */
    TempShowISearch(window, TRUE);
    XmProcessTraversal(window->iSearchText, XmTRAVERSE_CURRENT);
}

/*
** Incremental searching is anchored at the position where the cursor
** was when the user began typing the search string.  Call this routine
** to forget about this original anchor, and if the search bar is not
** permanently up, pop it down.
*/
void EndISearch(WindowInfo *window)
{
    /* Note: Please maintain this such that it can be freely peppered in
       mainline code, without callers having to worry about performance
       or visual glitches.  */
    
    /* Forget the starting position used for the current run of searches */
    window->iSearchStartPos = -1;
    
    /* Mark the end of incremental search history overwriting */
    saveSearchHistory("", NULL, 0, FALSE);
    
    /* Pop down the search line (if it's not pegged up in Preferences) */
    TempShowISearch(window, FALSE);
}

/* 
** Reset window->iSearchLastBeginPos to the resulting initial
** search begin position for incremental searches.
*/
static void iSearchRecordLastBeginPos(WindowInfo *window, int direction, 
	int initPos) 
{
    window->iSearchLastBeginPos = initPos;
    if (direction == SEARCH_BACKWARD) 
      	window->iSearchLastBeginPos--;
}      

/*
** Search for "searchString" in "window", and select the matching text in
** the window when found (or beep or put up a dialog if not found).  If
** "continued" is TRUE and a prior incremental search starting position is
** recorded, search from that original position, otherwise, search from the
** current cursor position.
*/
int SearchAndSelectIncremental(WindowInfo *window, int direction,
	const char *searchString, int searchType, int searchWrap, int continued)
{
    int beginPos, startPos, endPos;

    /* If there's a search in progress, start the search from the original
       starting position, otherwise search from the cursor position. */
    if (!continued || window->iSearchStartPos == -1) {
	window->iSearchStartPos = TextGetCursorPos(window->lastFocus);
	iSearchRecordLastBeginPos(window, direction, window->iSearchStartPos);
    }
    beginPos = window->iSearchStartPos;

    /* If the search string is empty, beep eventually if text wrapped
       back to the initial position, re-init iSearchLastBeginPos, 
       clear the selection, set the cursor back to what would be the 
       beginning of the search, and return. */
    if(searchString[0] == 0) {
     	int beepBeginPos = (direction == SEARCH_BACKWARD) ? beginPos-1:beginPos;
      	iSearchTryBeepOnWrap(window, direction, beepBeginPos, beepBeginPos);
	iSearchRecordLastBeginPos(window, direction, window->iSearchStartPos);
	BufUnselect(window->buffer);
	TextSetCursorPos(window->lastFocus, beginPos);
	return TRUE;
    }

    /* Save the string in the search history, unless we're cycling thru
       the search history itself, which can be detected by matching the
       search string with the search string of the current history index. */
    if(!(window->iSearchHistIndex > 1 && !strcmp(searchString, 
	    SearchHistory[historyIndex(window->iSearchHistIndex)]))) {
   	saveSearchHistory(searchString, NULL, searchType, TRUE);
	/* Reset the incremental search history pointer to the beginning */
	window->iSearchHistIndex = 1;
    }
        
    /* begin at insert position - 1 for backward searches */
    if (direction == SEARCH_BACKWARD)
	beginPos--;

    /* do the search.  SearchWindow does appropriate dialogs and beeps */
    if (!SearchWindow(window, direction, searchString, searchType, searchWrap,
	    beginPos, &startPos, &endPos, NULL, NULL))
	return FALSE;

    window->iSearchLastBeginPos = startPos;

    /* if the search matched an empty string (possible with regular exps)
       beginning at the start of the search, go to the next occurrence,
       otherwise repeated finds will get "stuck" at zero-length matches */
    if (direction==SEARCH_FORWARD && beginPos==startPos && beginPos==endPos)
	if (!SearchWindow(window, direction, searchString, searchType, searchWrap,
	    beginPos+1, &startPos, &endPos, NULL, NULL))
	    return FALSE;

    window->iSearchLastBeginPos = startPos;

    /* select the text found string */
    BufSelect(window->buffer, startPos, endPos);
    MakeSelectionVisible(window, window->lastFocus);
    TextSetCursorPos(window->lastFocus, endPos);

    return TRUE;
}

/*
** Attach callbacks to the incremental search bar widgets.  This also fudges
** up the translations on the text widget so Shift+Return will call the
** activate callback (along with Return and Ctrl+Return).  It does this
** because incremental search uses the activate callback from the text
** widget to detect when the user has pressed Return to search for the next
** occurrence of the search string, and Shift+Return, which is the natural
** command for a reverse search does not naturally trigger this callback.
*/
void SetISearchTextCallbacks(WindowInfo *window)
{
    static XtTranslations tableText = NULL;
    static char *translationsText = "Shift<KeyPress>Return: activate()\n";
    
    static XtTranslations tableClear = NULL;
    static char *translationsClear =
        "<Btn2Down>:Arm()\n<Btn2Up>: isearch_clear_and_paste() Disarm()\n";

    static XtActionsRec actions[] = {
        { "isearch_clear_and_paste", iSearchTextClearAndPasteAP }
    };

    if (tableText == NULL)
    	tableText = XtParseTranslationTable(translationsText);
    XtOverrideTranslations(window->iSearchText, tableText);
    
    if (tableClear == NULL) {
        /* make sure actions are loaded */
        XtAppAddActions(XtWidgetToApplicationContext(window->iSearchText),
            actions, XtNumber(actions));
        tableClear = XtParseTranslationTable(translationsClear);
    }
    XtOverrideTranslations(window->iSearchClearButton, tableClear);
    
    XtAddCallback(window->iSearchText, XmNactivateCallback, 
      (XtCallbackProc)iSearchTextActivateCB, window);
    XtAddCallback(window->iSearchText, XmNvalueChangedCallback, 
      (XtCallbackProc)iSearchTextValueChangedCB, window);
    XtAddEventHandler(window->iSearchText, KeyPressMask, False,
      (XtEventHandler)iSearchTextKeyEH, window);
    
    /* Attach callbacks to deal with the optional sticky case sensitivity
       behaviour. Do this before installing the search callbacks to make 
       sure that the proper search parameters are taken into account. */
    XtAddCallback(window->iSearchCaseToggle, XmNvalueChangedCallback,
	    (XtCallbackProc)iSearchCaseToggleCB, window);
    XtAddCallback(window->iSearchRegexToggle, XmNvalueChangedCallback,
	    (XtCallbackProc)iSearchRegExpToggleCB, window);
    
    /* When search parameters (direction or search type), redo the search */
    XtAddCallback(window->iSearchCaseToggle, XmNvalueChangedCallback,
	    (XtCallbackProc)iSearchTextValueChangedCB, window);
    XtAddCallback(window->iSearchRegexToggle, XmNvalueChangedCallback,
	    (XtCallbackProc)iSearchTextValueChangedCB, window);
    XtAddCallback(window->iSearchRevToggle, XmNvalueChangedCallback,
	    (XtCallbackProc)iSearchTextValueChangedCB, window);

    /* find button: just like pressing return */
    XtAddCallback(window->iSearchFindButton, XmNactivateCallback,
	    (XtCallbackProc)iSearchTextActivateCB, window);
    /* clear button: empty the search text widget */
    XtAddCallback(window->iSearchClearButton, XmNactivateCallback,
	    (XtCallbackProc)iSearchTextClearCB, window);
}

/*
** Remove callbacks before resetting the incremental search text to avoid any
** cursor movement and/or clearing of selections.
*/
static void iSearchTextSetString(Widget w, WindowInfo *window,
	char *str)
{
    /* remove callbacks which would be activated by emptying the text */
    XtRemoveAllCallbacks(window->iSearchText, XmNvalueChangedCallback);
    XtRemoveAllCallbacks(window->iSearchText, XmNactivateCallback);
    /* empty the text */
    XmTextSetString(window->iSearchText, str ? str : "");
    /* put back the callbacks */
    XtAddCallback(window->iSearchText, XmNactivateCallback, 
      (XtCallbackProc)iSearchTextActivateCB, window);
    XtAddCallback(window->iSearchText, XmNvalueChangedCallback, 
      (XtCallbackProc)iSearchTextValueChangedCB, window);
}

/*
** Action routine for Mouse Button 2 on the iSearchClearButton: resets the
** string then calls the activate callback for the text directly.
*/
static void iSearchTextClearAndPasteAP(Widget w, XEvent *event, String *args,
        Cardinal *nArg)
{
    WindowInfo *window;
    char *selText;
    XmAnyCallbackStruct cbdata;

    memset(&cbdata, 0, sizeof (cbdata));
    cbdata.event = event;

    window = WidgetToWindow(w);

    selText = GetAnySelection(window);
    iSearchTextSetString(w, window, selText);
    if (selText) {
        XmTextSetInsertionPosition(window->iSearchText, strlen(selText));
        XtFree(selText);
    }
    iSearchTextActivateCB(w, window, &cbdata);
}

/*
** User pressed the clear incremental search bar button. Remove callbacks
** before resetting the text to avoid any cursor movement and/or clearing
** of selections.
*/
static void iSearchTextClearCB(Widget w, WindowInfo *window,
	XmAnyCallbackStruct *callData)
{
    window = WidgetToWindow(w);

    iSearchTextSetString(w, window, NULL);
}

/*
** User pressed return in the incremental search bar.  Do a new search with
** the search string displayed.  The direction of the search is toggled if
** the Ctrl key or the Shift key is pressed when the text field is activated.
*/
static void iSearchTextActivateCB(Widget w, WindowInfo *window,
	XmAnyCallbackStruct *callData) 
{
    char *params[4];
    char *searchString;
    int searchType, direction;

    window = WidgetToWindow(w);
       
    /* Fetch the string, search type and direction from the incremental
       search bar widgets at the top of the window */
    searchString = XmTextGetString(window->iSearchText);
    if(XmToggleButtonGetState(window->iSearchCaseToggle)) {
      if(XmToggleButtonGetState(window->iSearchRegexToggle)) 
	searchType = SEARCH_REGEX;
      else 
	searchType = SEARCH_CASE_SENSE;
    } else {
      if(XmToggleButtonGetState(window->iSearchRegexToggle)) 
	searchType = SEARCH_REGEX_NOCASE;
      else 
	searchType = SEARCH_LITERAL;
    }
    direction = XmToggleButtonGetState(window->iSearchRevToggle) ?
	    SEARCH_BACKWARD : SEARCH_FORWARD;
    
    /* Reverse the search direction if the Ctrl or Shift key was pressed */
    if (callData->event->xbutton.state & (ShiftMask | ControlMask))
	direction = direction == SEARCH_FORWARD ?
		SEARCH_BACKWARD : SEARCH_FORWARD;
	
    /* find the text and mark it */
    params[0] = searchString;
    params[1] = directionArg(direction);
    params[2] = searchTypeArg(searchType);
    params[3] = searchWrapArg(GetPrefSearchWraps());
    XtCallActionProc(window->lastFocus, "find", callData->event, params, 4);
    XtFree(searchString);
}

/*
** Called when user types in the incremental search line.  Redoes the
** search for the new search string.
*/
static void iSearchTextValueChangedCB(Widget w, WindowInfo *window,
	XmAnyCallbackStruct *callData) 
{
    char *params[5];
    char *searchString;
    int searchType, direction, nParams;
   
    window = WidgetToWindow(w);
    
    /* Fetch the string, search type and direction from the incremental
       search bar widgets at the top of the window */
    searchString = XmTextGetString(window->iSearchText);
    if(XmToggleButtonGetState(window->iSearchCaseToggle)) {
      if(XmToggleButtonGetState(window->iSearchRegexToggle)) 
	searchType = SEARCH_REGEX;
      else 
	searchType = SEARCH_CASE_SENSE;
    } else {
      if(XmToggleButtonGetState(window->iSearchRegexToggle)) 
	searchType = SEARCH_REGEX_NOCASE;
      else 
	searchType = SEARCH_LITERAL;
    }
    direction = XmToggleButtonGetState(window->iSearchRevToggle) ?
	    SEARCH_BACKWARD : SEARCH_FORWARD;

    /* If the search type is a regular expression, test compile it.  If it
       fails, silently skip it.  (This allows users to compose the expression
       in peace when they have unfinished syntax, but still get beeps when
       correct syntax doesn't match) */
    if (isRegexType(searchType)) {
	regexp *compiledRE = NULL;
	char *compileMsg;
	compiledRE = CompileRE(searchString, &compileMsg, 
	                       defaultRegexFlags(searchType));
	if (compiledRE == NULL) {
	    XtFree(searchString);
	    return;
	}
	free((char *)compiledRE);
    }
    
    /* Call the incremental search action proc to do the searching and
       selecting (this allows it to be recorded for learn/replay).  If
       there's an incremental search already in progress, mark the operation
       as "continued" so the search routine knows to re-start the search
       from the original starting position */
    nParams = 0;
    params[nParams++] = searchString;
    params[nParams++] = directionArg(direction);
    params[nParams++] = searchTypeArg(searchType);
    params[nParams++] = searchWrapArg(GetPrefSearchWraps());
    if (window->iSearchStartPos != -1)
	params[nParams++] = "continued";
    XtCallActionProc(window->lastFocus, "find_incremental",
	    callData->event, params, nParams);
    XtFree(searchString);
}

/*
** Process arrow keys for history recall, and escape key for leaving
** incremental search bar.
*/
static void iSearchTextKeyEH(Widget w, WindowInfo *window,
	XKeyEvent *event, Boolean *continueDispatch)
{
    KeySym keysym = XLookupKeysym(event, 0);
    int index;
    char *searchStr;
    int searchType;

    /* only process up and down arrow keys */
    if (keysym != XK_Up && keysym != XK_Down && keysym != XK_Escape) {
	*continueDispatch = TRUE;
	return;
    }

    window = WidgetToWindow(w);
    index = window->iSearchHistIndex;
    *continueDispatch = FALSE;

    /* allow escape key to cancel search */
    if (keysym == XK_Escape) {
	XmProcessTraversal(window->lastFocus, XmTRAVERSE_CURRENT);
	EndISearch(window);
	return;
    }
    
    /* increment or decrement the index depending on which arrow was pressed */
    index += (keysym == XK_Up) ? 1 : -1;

    /* if the index is out of range, beep and return */
    if (index != 0 && historyIndex(index) == -1) {
	XBell(TheDisplay, 0);
	return;
    }

    /* determine the strings and button settings to use */
    if (index == 0) {
	searchStr = "";
	searchType = GetPrefSearch();
    } else {
	searchStr = SearchHistory[historyIndex(index)];
	searchType = SearchTypeHistory[historyIndex(index)];
    }

    /* Set the info used in the value changed callback before calling
      XmTextSetString(). */
    window->iSearchHistIndex = index;
    initToggleButtons(searchType, window->iSearchRegexToggle,
                      window->iSearchCaseToggle, NULL,
                      &window->iSearchLastLiteralCase,
                      &window->iSearchLastRegexCase);
    
    /* Beware the value changed callback is processed as part of this call */
    XmTextSetString(window->iSearchText, searchStr);
    XmTextSetInsertionPosition(window->iSearchText, 
	    XmTextGetLastPosition(window->iSearchText));
}

/*
** Check the character before the insertion cursor of textW and flash
** matching parenthesis, brackets, or braces, by temporarily highlighting
** the matching character (a timer procedure is scheduled for removing the
** highlights)
*/
void FlashMatching(WindowInfo *window, Widget textW)
{
    char c;
    void *style;
    int pos, matchIndex;
    int startPos, endPos, searchPos, matchPos;
    int constrain;
    
    /* if a marker is already drawn, erase it and cancel the timeout */
    if (window->flashTimeoutID != 0) {
    	eraseFlash(window);
    	XtRemoveTimeOut(window->flashTimeoutID);
    	window->flashTimeoutID = 0;
    }
    
    /* no flashing required */
    if (window->showMatchingStyle == NO_FLASH) {
	return;
    }

    /* don't flash matching characters if there's a selection */
    if (window->buffer->primary.selected)
   	return;

    /* get the character to match and the position to start from */
    pos = TextGetCursorPos(textW) - 1;
    if (pos < 0)
    	return;
    c = BufGetCharacter(window->buffer, pos);
    style = GetHighlightInfo(window, pos);
    
    /* is the character one we want to flash? */
    for (matchIndex = 0; matchIndex<N_FLASH_CHARS; matchIndex++) {
        if (MatchingChars[matchIndex].c == c)
	    break;
    }
    if (matchIndex == N_FLASH_CHARS)
	return;

    /* constrain the search to visible text only when in single-pane mode
       AND using delimiter flashing (otherwise search the whole buffer) */
    constrain = ((window->nPanes == 0) && 
        (window->showMatchingStyle == FLASH_DELIMIT));
          
    if (MatchingChars[matchIndex].direction == SEARCH_BACKWARD) {
    	startPos = constrain ? TextFirstVisiblePos(textW) : 0;
    	endPos = pos;
    	searchPos = endPos;
    } else {
    	startPos = pos;
    	endPos = constrain ? TextLastVisiblePos(textW) :
    	    	window->buffer->length;
    	searchPos = startPos;
    }
    
    /* do the search */
    if (!findMatchingChar(window, c, style, searchPos, startPos, endPos, 
        &matchPos))
    	return;

    if (window->showMatchingStyle == FLASH_DELIMIT) {
	/* Highlight either the matching character ... */
	BufHighlight(window->buffer, matchPos, matchPos+1);
    } else {
	/* ... or the whole range. */
  	if (MatchingChars[matchIndex].direction == SEARCH_BACKWARD) {
	    BufHighlight(window->buffer, matchPos, pos+1);
	} else {
	    BufHighlight(window->buffer, matchPos+1, pos);
	}
    }
      
    /* Set up a timer to erase the box after 1.5 seconds */
    window->flashTimeoutID = XtAppAddTimeOut(
    	    XtWidgetToApplicationContext(window->shell), 1500,
    	    flashTimeoutProc, window);
    window->flashPos = matchPos;
}

void SelectToMatchingCharacter(WindowInfo *window)
{
    int selStart, selEnd;
    int startPos, endPos, matchPos;
    textBuffer *buf = window->buffer;

    /* get the character to match and its position from the selection, or
       the character before the insert point if nothing is selected.
       Give up if too many characters are selected */
    if (!GetSimpleSelection(buf, &selStart, &selEnd)) {
	selEnd = TextGetCursorPos(window->lastFocus);
        if (window->overstrike)
	    selEnd += 1;
	selStart = selEnd - 1;
	if (selStart < 0) {
	    XBell(TheDisplay, 0);
	    return;
	}
    }
    if ((selEnd - selStart) != 1) {
    	XBell(TheDisplay, 0);
	return;
    }
    
    /* Search for it in the buffer */
    if (!findMatchingChar(window, BufGetCharacter(buf, selStart),
        GetHighlightInfo(window, selStart), selStart, 0, buf->length, &matchPos)) {
    	XBell(TheDisplay, 0);
	return;
    }
    startPos = (matchPos > selStart) ? selStart : matchPos;
    endPos = (matchPos > selStart) ? matchPos : selStart;

    /* select the text between the matching characters */
    BufSelect(buf, startPos, endPos+1);
}

void GotoMatchingCharacter(WindowInfo *window)
{
    int selStart, selEnd;
    int matchPos;
    textBuffer *buf = window->buffer;

    /* get the character to match and its position from the selection, or
       the character before the insert point if nothing is selected.
       Give up if too many characters are selected */
    if (!GetSimpleSelection(buf, &selStart, &selEnd)) {
	selEnd = TextGetCursorPos(window->lastFocus);
        if (window->overstrike)
	    selEnd += 1;
	selStart = selEnd - 1;
	if (selStart < 0) {
	    XBell(TheDisplay, 0);
	    return;
	}
    }
    if ((selEnd - selStart) != 1) {
    	XBell(TheDisplay, 0);
	return;
    }
    
    /* Search for it in the buffer */
    if (!findMatchingChar(window, BufGetCharacter(buf, selStart),
	    GetHighlightInfo(window, selStart), selStart, 0, 
	    buf->length, &matchPos)) {
    	XBell(TheDisplay, 0);
	return;
    }
    
    /* temporarily shut off autoShowInsertPos before setting the cursor
       position so MakeSelectionVisible gets a chance to place the cursor
       string at a pleasing position on the screen (otherwise, the cursor would
       be automatically scrolled on screen and MakeSelectionVisible would do
       nothing) */
    XtVaSetValues(window->lastFocus, textNautoShowInsertPos, False, NULL);
    TextSetCursorPos(window->lastFocus, matchPos+1);
    MakeSelectionVisible(window, window->lastFocus);
    XtVaSetValues(window->lastFocus, textNautoShowInsertPos, True, NULL);
}

static int findMatchingChar(WindowInfo *window, char toMatch, 
    void* styleToMatch, int charPos, int startLimit, int endLimit, 
    int *matchPos)
{
    int nestDepth, matchIndex, direction, beginPos, pos;
    char matchChar, c;
    void *style = NULL;
    textBuffer *buf = window->buffer;
    int matchSyntaxBased = window->matchSyntaxBased;

    /* If we don't match syntax based, fake a matching style. */
    if (!matchSyntaxBased) style = styleToMatch;
    
    /* Look up the matching character and match direction */
    for (matchIndex = 0; matchIndex<N_MATCH_CHARS; matchIndex++) {
        if (MatchingChars[matchIndex].c == toMatch)
	    break;
    }
    if (matchIndex == N_MATCH_CHARS)
	return FALSE;
    matchChar = MatchingChars[matchIndex].match;
    direction = MatchingChars[matchIndex].direction;
    
    /* find it in the buffer */
    beginPos = (direction==SEARCH_FORWARD) ? charPos+1 : charPos-1;
    nestDepth = 1;
    if (direction == SEARCH_FORWARD) {
    	for (pos=beginPos; pos<endLimit; pos++) {
	    c=BufGetCharacter(buf, pos);
	    if (c == matchChar) {
		if (matchSyntaxBased) style = GetHighlightInfo(window, pos);
		if (style == styleToMatch) {
		    nestDepth--;
		    if (nestDepth == 0) {
			*matchPos = pos;
			return TRUE;
		    }
		}
	    } else if (c == toMatch) {
		if (matchSyntaxBased) style = GetHighlightInfo(window, pos);
		if (style == styleToMatch)
		    nestDepth++;
	    }
	}
    } else { /* SEARCH_BACKWARD */
	for (pos=beginPos; pos>=startLimit; pos--) {
	    c=BufGetCharacter(buf, pos);
	    if (c == matchChar) {
		if (matchSyntaxBased) style = GetHighlightInfo(window, pos);
		if (style == styleToMatch) {
		    nestDepth--;
		    if (nestDepth == 0) {
			*matchPos = pos;
			return TRUE;
		    }
		}
	    } else if (c == toMatch) {
		if (matchSyntaxBased) style = GetHighlightInfo(window, pos);
		if (style == styleToMatch)
		    nestDepth++;
	    }
	}
    }
    return FALSE;
}

/*
** Xt timer procedure for erasing the matching parenthesis marker.
*/
static void flashTimeoutProc(XtPointer clientData, XtIntervalId *id)
{
    eraseFlash((WindowInfo *)clientData);
    ((WindowInfo *)clientData)->flashTimeoutID = 0;
}

/*
** Erase the marker drawn on a matching parenthesis bracket or brace
** character.
*/
static void eraseFlash(WindowInfo *window)
{
    BufUnhighlight(window->buffer);
}

/*
** Search and replace using previously entered search strings (from dialog
** or selection).
*/
int ReplaceSame(WindowInfo *window, int direction, int searchWrap)
{
    if (NHist < 1) {
    	XBell(TheDisplay, 0);
    	return FALSE;
    }

    return SearchAndReplace(window, direction, SearchHistory[historyIndex(1)],
    	    ReplaceHistory[historyIndex(1)],
    	    SearchTypeHistory[historyIndex(1)], searchWrap);
}

/*
** Search and replace using previously entered search strings (from dialog
** or selection).
*/
int ReplaceFindSame(WindowInfo *window, int direction, int searchWrap)
{
    if (NHist < 1) {
        XBell(TheDisplay, 0);
        return FALSE;
    }

    return ReplaceAndSearch(window, direction, SearchHistory[historyIndex(1)],
                            ReplaceHistory[historyIndex(1)],
                            SearchTypeHistory[historyIndex(1)], searchWrap);
}

/*
** Replace selection with "replaceString" and search for string "searchString" in window "window", 
** using algorithm "searchType" and direction "direction"
*/
int ReplaceAndSearch(WindowInfo *window, int direction, const char *searchString,
                     const char *replaceString, int searchType, int searchWrap)
{
    int startPos = 0, endPos = 0, replaceLen = 0;
    int searchExtentBW, searchExtentFW;
    int replaced;

    /* Save a copy of search and replace strings in the search history */
    saveSearchHistory(searchString, replaceString, searchType, FALSE);
    
    replaced = 0;

    /* Replace the selected text only if it matches the search string */
    if (searchMatchesSelection(window, searchString, searchType,
	                       &startPos, &endPos, &searchExtentBW,
			       &searchExtentFW)) {
	/* replace the text */
	if (isRegexType(searchType)) {
    	    char replaceResult[SEARCHMAX+1], *foundString;
	    foundString = BufGetRange(window->buffer, searchExtentBW,
				      searchExtentFW+1);
    	    replaceUsingRE(searchString, replaceString, foundString,
		    startPos-searchExtentBW,
		    replaceResult, SEARCHMAX, startPos == 0 ? '\0' :
		    BufGetCharacter(window->buffer, startPos-1),
		    GetWindowDelimiters(window), defaultRegexFlags(searchType));
	    XtFree(foundString);
    	    BufReplace(window->buffer, startPos, endPos, replaceResult);
    	    replaceLen = strlen(replaceResult);
	} else {
            BufReplace(window->buffer, startPos, endPos, replaceString);
            replaceLen = strlen(replaceString);
	}

        /* Position the cursor so the next search will work correctly based */
        /* on the direction of the search */
        TextSetCursorPos(window->lastFocus, startPos +
                         ((direction == SEARCH_FORWARD) ? replaceLen : 0));
        replaced = 1;
    }

    /* do the search; beeps/dialogs are taken care of */
    SearchAndSelect(window, direction, searchString, searchType, searchWrap);

    return replaced;
}           

/*
** Search for string "searchString" in window "window", using algorithm
** "searchType" and direction "direction", and replace it with "replaceString"
** Also adds the search and replace strings to the global search history.
*/
int SearchAndReplace(WindowInfo *window, int direction, const char *searchString,
	const char *replaceString, int searchType, int searchWrap)
{
    int startPos, endPos, replaceLen, searchExtentBW, searchExtentFW;
    int found;
    int beginPos, cursorPos;
    
    /* Save a copy of search and replace strings in the search history */
    saveSearchHistory(searchString, replaceString, searchType, FALSE);
    
    /* If the text selected in the window matches the search string, 	*/
    /* the user is probably using search then replace method, so	*/
    /* replace the selected text regardless of where the cursor is.	*/
    /* Otherwise, search for the string.				*/
    if (!searchMatchesSelection(window, searchString, searchType,
    	    &startPos, &endPos, &searchExtentBW, &searchExtentFW)) {
	/* get the position to start the search */
	cursorPos = TextGetCursorPos(window->lastFocus);
	if (direction == SEARCH_BACKWARD) {
	    /* use the insert position - 1 for backward searches */
	    beginPos = cursorPos-1;
	} else {
	    /* use the insert position for forward searches */
	    beginPos = cursorPos;
	}
	/* do the search */
	found = SearchWindow(window, direction, searchString, searchType, searchWrap,
		beginPos, &startPos, &endPos, &searchExtentBW, &searchExtentFW);
	if (!found)
	    return FALSE;
    }
    
    /* replace the text */
    if (isRegexType(searchType)) {
    	char replaceResult[SEARCHMAX], *foundString;
	foundString = BufGetRange(window->buffer, searchExtentBW, searchExtentFW+1);
    	replaceUsingRE(searchString, replaceString, foundString,
		startPos - searchExtentBW,
		replaceResult, SEARCHMAX, startPos == 0 ? '\0' :
		BufGetCharacter(window->buffer, startPos-1),
		GetWindowDelimiters(window), defaultRegexFlags(searchType));
	XtFree(foundString);
    	BufReplace(window->buffer, startPos, endPos, replaceResult);
    	replaceLen = strlen(replaceResult);
    } else {
    	BufReplace(window->buffer, startPos, endPos, replaceString);
    	replaceLen = strlen(replaceString);
    }
    
    /* after successfully completing a replace, selected text attracts
       attention away from the area of the replacement, particularly
       when the selection represents a previous search. so deselect */
    BufUnselect(window->buffer);
    
    /* temporarily shut off autoShowInsertPos before setting the cursor
       position so MakeSelectionVisible gets a chance to place the replaced
       string at a pleasing position on the screen (otherwise, the cursor would
       be automatically scrolled on screen and MakeSelectionVisible would do
       nothing) */
    XtVaSetValues(window->lastFocus, textNautoShowInsertPos, False, NULL);
    TextSetCursorPos(window->lastFocus, startPos +
    	((direction == SEARCH_FORWARD) ? replaceLen : 0));
    MakeSelectionVisible(window, window->lastFocus);
    XtVaSetValues(window->lastFocus, textNautoShowInsertPos, True, NULL);
    
    return TRUE;
}

/*
** Replace all occurences of "searchString" in "window" with "replaceString"
** within the current primary selection in "window". Also adds the search and
** replace strings to the global search history.
*/
int ReplaceInSelection(WindowInfo *window, const char *searchString,
	const char *replaceString, int searchType)
{
    int selStart, selEnd, beginPos, startPos, endPos, realOffset, replaceLen;
    int found, anyFound, isRect, rectStart, rectEnd, lineStart, cursorPos;
    int extentBW, extentFW;
    char *fileString;
    textBuffer *tempBuf;
    
    /* save a copy of search and replace strings in the search history */
    saveSearchHistory(searchString, replaceString, searchType, FALSE);
    
    /* find out where the selection is */
    if (!BufGetSelectionPos(window->buffer, &selStart, &selEnd, &isRect,
    	    &rectStart, &rectEnd))
    	return FALSE;
	
    /* get the selected text */
    if (isRect) {
    	selStart = BufStartOfLine(window->buffer, selStart);
    	selEnd = BufEndOfLine(window->buffer, selEnd);
    	fileString = BufGetRange(window->buffer, selStart, selEnd);
    } else
    	fileString = BufGetSelectionText(window->buffer);
    
    /* create a temporary buffer in which to do the replacements to hide the
       intermediate steps from the display routines, and so everything can
       be undone in a single operation */
    tempBuf = BufCreate();
    BufSetAll(tempBuf, fileString);
    
    /* search the string and do the replacements in the temporary buffer */
    replaceLen = strlen(replaceString);
    found = TRUE;
    anyFound = FALSE;
    beginPos = 0;
    cursorPos = 0;
    realOffset = 0;
    while (found) {
	found = SearchString(fileString, searchString, SEARCH_FORWARD,
		searchType, FALSE, beginPos, &startPos, &endPos, &extentBW,
                &extentFW, GetWindowDelimiters(window));
	if (!found)
	    break;
	/* if the selection is rectangular, verify that the found
	   string is in the rectangle */
	if (isRect) {
	    lineStart = BufStartOfLine(window->buffer, selStart+startPos);
	    if (BufCountDispChars(window->buffer, lineStart, selStart+startPos) <
		    rectStart || BufCountDispChars(window->buffer, lineStart,
		    selStart+endPos) > rectEnd) {
		if (fileString[endPos] == '\0')
		    break;
		/* If the match starts before the left boundary of the
		   selection, and extends past it, we should not continue
		   search after the end of the (false) match, because we 
		   could miss a valid match starting between the left boundary
		   and the end of the false match. */
		if (BufCountDispChars(window->buffer, lineStart, 
				      selStart+startPos) < rectStart && 
		    BufCountDispChars(window->buffer, lineStart,
				      selStart+endPos) > rectStart) 
		    beginPos += 1;
		else
		    beginPos = (startPos == endPos) ? endPos+1 : endPos;
		continue;
	    }
	}
	/* Make sure the match did not start past the end (regular expressions
	   can consider the artificial end of the range as the end of a line,
	   and match a fictional whole line beginning there) */
	if (startPos == selEnd - selStart) {
	    found = False;
	    break;
	}
	/* replace the string and compensate for length change */
	if (isRegexType(searchType)) {
    	    char replaceResult[SEARCHMAX], *foundString;
	    foundString = BufGetRange(tempBuf, extentBW+realOffset,
		    extentFW+realOffset+1);
    	    replaceUsingRE(searchString, replaceString, foundString,
		    startPos-extentBW,
		    replaceResult, SEARCHMAX, startPos+realOffset == 0 ? '\0' :
		    BufGetCharacter(tempBuf, startPos+realOffset-1),
		    GetWindowDelimiters(window), defaultRegexFlags(searchType));
	    XtFree(foundString);
    	    BufReplace(tempBuf, startPos+realOffset, endPos+realOffset,
    		    replaceResult);
    	    replaceLen = strlen(replaceResult);
	} else
    	    BufReplace(tempBuf, startPos+realOffset, endPos+realOffset,
    		    replaceString);
    	realOffset += replaceLen - (endPos - startPos);
    	/* start again after match unless match was empty, then endPos+1 */
    	beginPos = (startPos == endPos) ? endPos+1 : endPos;
    	cursorPos = endPos;
	anyFound = TRUE;
	if (fileString[endPos] == '\0')
	    break;
    }
    XtFree(fileString);
    
    /* if nothing was found, tell user and return */
    if (!anyFound) {
    	if (GetPrefSearchDlogs()) {
    	    /* Avoid bug in Motif 1.1 by putting away search dialog
    	       before DialogF */
    	    if (window->findDlog && XtIsManaged(window->findDlog) &&
    	    	    !XmToggleButtonGetState(window->findKeepBtn))
    		XtUnmanageChild(window->findDlog);
    	    if (window->replaceDlog && XtIsManaged(window->replaceDlog) &&
    	    	    !XmToggleButtonGetState(window->replaceKeepBtn))
    		unmanageReplaceDialogs(window);
   	    DialogF(DF_INF, window->shell, 1, "String not found",
                "String was not found", "OK");
    	} else
    	    XBell(TheDisplay, 0);
 	BufFree(tempBuf);
 	return FALSE;
    }
    
    /* replace the selected range in the real buffer */
    fileString = BufGetAll(tempBuf);
    BufFree(tempBuf);
    BufReplace(window->buffer, selStart, selEnd, fileString);
    XtFree(fileString);
    
    /* set the insert point at the end of the last replacement */
    TextSetCursorPos(window->lastFocus, selStart + cursorPos + realOffset);
    
    /* leave non-rectangular selections selected (rect. ones after replacement
       are less useful since left/right positions are randomly adjusted) */
    if (!isRect)
    	BufSelect(window->buffer, selStart, selEnd + realOffset);

    return TRUE;
}

/*
** Replace all occurences of "searchString" in "window" with "replaceString".
** Also adds the search and replace strings to the global search history.
*/
int ReplaceAll(WindowInfo *window, const char *searchString,
        const char *replaceString, int searchType)
{
    char *fileString, *newFileString;
    int copyStart, copyEnd, replacementLen;
    
    /* reject empty string */
    if (*searchString == '\0')
    	return FALSE;
    
    /* save a copy of search and replace strings in the search history */
    saveSearchHistory(searchString, replaceString, searchType, FALSE);
	
    /* get the entire text buffer from the text area widget */
    fileString = BufGetAll(window->buffer);
    
    newFileString = ReplaceAllInString(fileString, searchString, replaceString,
	    searchType, &copyStart, &copyEnd, &replacementLen,
	    GetWindowDelimiters(window));
    XtFree(fileString);
    
    if (newFileString == NULL) {
        if (window->multiFileBusy) {
            window->replaceFailed = TRUE; /* only needed during multi-file 
                                             replacements */
        } else if (GetPrefSearchDlogs()) {
    	    if (window->findDlog && XtIsManaged(window->findDlog) &&
    	    	    !XmToggleButtonGetState(window->findKeepBtn))
    		XtUnmanageChild(window->findDlog);
    	    if (window->replaceDlog && XtIsManaged(window->replaceDlog) &&
    	    	    !XmToggleButtonGetState(window->replaceKeepBtn))
    		unmanageReplaceDialogs(window);
   	    DialogF(DF_INF, window->shell, 1, "String not found",
                "String was not found", "OK");
    	} else
    	    XBell(TheDisplay, 0);
	return FALSE;
    }
    
    /* replace the contents of the text widget with the substituted text */
    BufReplace(window->buffer, copyStart, copyEnd, newFileString);
    
    /* Move the cursor to the end of the last replacement */
    TextSetCursorPos(window->lastFocus, copyStart + replacementLen);

    XtFree(newFileString);
    return TRUE;	
}    

/*
** Replace all occurences of "searchString" in "inString" with "replaceString"
** and return an allocated string covering the range between the start of the
** first replacement (returned in "copyStart", and the end of the last
** replacement (returned in "copyEnd")
*/
char *ReplaceAllInString(char *inString, const char *searchString,
	const char *replaceString, int searchType, int *copyStart,
	int *copyEnd, int *replacementLength, const char *delimiters)
{
    int beginPos, startPos, endPos, lastEndPos;
    int found, nFound, removeLen, replaceLen, copyLen, addLen;
    char *outString, *fillPtr;
    int searchExtentBW, searchExtentFW;
    
    /* reject empty string */
    if (*searchString == '\0')
    	return NULL;
    
    /* rehearse the search first to determine the size of the buffer needed
       to hold the substituted text.  No substitution done here yet */
    replaceLen = strlen(replaceString);
    found = TRUE;
    nFound = 0;
    removeLen = 0;
    addLen = 0;
    beginPos = 0;
    *copyStart = -1;
    while (found) {
    	found = SearchString(inString, searchString, SEARCH_FORWARD, searchType,
		FALSE, beginPos, &startPos, &endPos, &searchExtentBW, 
                &searchExtentFW, delimiters);
	if (found) {
	    if (*copyStart < 0)
	    	*copyStart = startPos;
    	    *copyEnd = endPos;
    	    /* start next after match unless match was empty, then endPos+1 */
    	    beginPos = (startPos == endPos) ? endPos+1 : endPos;
	    nFound++;
	    removeLen += endPos - startPos;
	    if (isRegexType(searchType)) {
    		char replaceResult[SEARCHMAX];
    		replaceUsingRE(searchString, replaceString, &inString[searchExtentBW],
 			startPos-searchExtentBW,
     			replaceResult, SEARCHMAX, startPos == 0 ? '\0' :
			inString[startPos-1], delimiters,
                        defaultRegexFlags(searchType));
    		addLen += strlen(replaceResult);
    	    } else
    	    	addLen += replaceLen;
	    if (inString[endPos] == '\0')
		break;
	}
    }
    if (nFound == 0)
	return NULL;
    
    /* Allocate a new buffer to hold all of the new text between the first
       and last substitutions */
    copyLen = *copyEnd - *copyStart;
    outString = XtMalloc(copyLen - removeLen + addLen + 1);
    
    /* Scan through the text buffer again, substituting the replace string
       and copying the part between replaced text to the new buffer  */
    found = TRUE;
    beginPos = 0;
    lastEndPos = 0;
    fillPtr = outString;
    while (found) {
    	found = SearchString(inString, searchString, SEARCH_FORWARD, searchType,
		FALSE, beginPos, &startPos, &endPos, &searchExtentBW,
                &searchExtentFW, delimiters);
	if (found) {
	    if (beginPos != 0) {
		memcpy(fillPtr, &inString[lastEndPos], startPos - lastEndPos);
		fillPtr += startPos - lastEndPos;
	    }
	    if (isRegexType(searchType)) {
    		char replaceResult[SEARCHMAX];
    		replaceUsingRE(searchString, replaceString, &inString[searchExtentBW],
			startPos-searchExtentBW, 
    			replaceResult, SEARCHMAX, startPos == 0 ? '\0' :
			inString[startPos-1], delimiters,
	      	      	defaultRegexFlags(searchType));
    		replaceLen = strlen(replaceResult);
    		memcpy(fillPtr, replaceResult, replaceLen);
	    } else {
		memcpy(fillPtr, replaceString, replaceLen);
	    }
	    fillPtr += replaceLen;
	    lastEndPos = endPos;
	    /* start next after match unless match was empty, then endPos+1 */
	    beginPos = (startPos == endPos) ? endPos+1 : endPos;
	    if (inString[endPos] == '\0')
		break;
	}
    }
    *fillPtr = '\0';
    *replacementLength = fillPtr - outString;
    return outString;
}

/* 
** If this is an incremental search and BeepOnSearchWrap is on:
** Emit a beep if the search wrapped over BOF/EOF compared to
** the last startPos of the current incremental search.
*/
static void iSearchTryBeepOnWrap(WindowInfo *window, int direction, 
	int beginPos, int startPos) 
{
    if(GetPrefBeepOnSearchWrap())  {
	if(direction == SEARCH_FORWARD) {
	    if(  (startPos >= beginPos && window->iSearchLastBeginPos < beginPos)
	       ||(startPos < beginPos && window->iSearchLastBeginPos >= beginPos)) 
	    XBell(TheDisplay, 0);
	} else {
	    if(  (startPos <= beginPos && window->iSearchLastBeginPos > beginPos)
	       ||(startPos > beginPos && window->iSearchLastBeginPos <= beginPos))
	    XBell(TheDisplay, 0);
	}
    }
}

/*
** Search the text in "window", attempting to match "searchString"
*/
int SearchWindow(WindowInfo *window, int direction, const char *searchString,
	int searchType, int searchWrap, int beginPos, int *startPos, 
        int *endPos, int *extentBW, int *extentFW)
{
    char *fileString;
    int found, resp, fileEnd = window->buffer->length - 1, outsideBounds;
    
    /* reject empty string */
    if (*searchString == '\0')
    	return FALSE;
	
    /* get the entire text buffer from the text area widget */
    fileString = BufGetAll(window->buffer);
    
    /* If we're already outside the boundaries, we must consider wrapping
       immediately (Note: fileEnd+1 is a valid starting position. Consider
       searching for $ at the end of a file ending with \n.) */
    if ((direction == SEARCH_FORWARD && beginPos > fileEnd + 1)
            || (direction == SEARCH_BACKWARD && beginPos < 0))
    {
        outsideBounds = TRUE;
    } else
    {
        outsideBounds = FALSE;
    }
    
    /* search the string copied from the text area widget, and present
       dialogs, or just beep.  iSearchStartPos is not a perfect indicator that
       an incremental search is in progress.  A parameter would be better. */
    if (window->iSearchStartPos == -1) { /* normal search */
    	found = !outsideBounds &&
		SearchString(fileString, searchString, direction, searchType,
    	    	FALSE, beginPos, startPos, endPos, extentBW, extentFW,
		GetWindowDelimiters(window));
    	/* Avoid Motif 1.1 bug by putting away search dialog before DialogF */
    	if (window->findDlog && XtIsManaged(window->findDlog) &&
    	    	!XmToggleButtonGetState(window->findKeepBtn))
    	    XtUnmanageChild(window->findDlog);
    	if (window->replaceDlog && XtIsManaged(window->replaceDlog) &&
    	    	!XmToggleButtonGetState(window->replaceKeepBtn))
    	    unmanageReplaceDialogs(window);
        if (!found) {
            if (searchWrap) {
		if (direction == SEARCH_FORWARD && beginPos != 0) {
		    if(GetPrefBeepOnSearchWrap()) {
			XBell(TheDisplay, 0);
		    } else if (GetPrefSearchDlogs()) {
			resp = DialogF(DF_QUES, window->shell, 2, "Wrap Search",
				"Continue search from\nbeginning of file?", 
                                "Continue", "Cancel");
			if (resp == 2) {
			    XtFree(fileString);
			    return False;
			}
		    }
		    found = SearchString(fileString, searchString, direction,
			searchType, FALSE, 0, startPos, endPos, extentBW,
			extentFW, GetWindowDelimiters(window));
		} else if (direction == SEARCH_BACKWARD && beginPos != fileEnd) {
		    if(GetPrefBeepOnSearchWrap()) {
			XBell(TheDisplay, 0);
		    } else if (GetPrefSearchDlogs()) {
			resp = DialogF(DF_QUES, window->shell, 2, "Wrap Search",
				"Continue search\nfrom end of file?", "Continue",
				"Cancel");
			if (resp == 2) {
			    XtFree(fileString);
			    return False;
			}
		    }
                    found = SearchString(fileString, searchString, direction,
			searchType, FALSE, fileEnd + 1, startPos, endPos, extentBW,
			extentFW, GetWindowDelimiters(window));
		}
	    }
            if (!found) {
		if (GetPrefSearchDlogs()) {
		    DialogF(DF_INF, window->shell, 1, "String not found",
                    "String was not found","OK");
		} else {
		    XBell(TheDisplay, 0);
		}
	    }
	}
    } else { /* incremental search */
        if (outsideBounds && searchWrap) {
	    if (direction == SEARCH_FORWARD) beginPos = 0;
	    else beginPos = fileEnd+1;
            outsideBounds = FALSE;
        }
	found = !outsideBounds &&
            SearchString(fileString, searchString, direction,
	    searchType, searchWrap, beginPos, startPos, endPos,
	    extentBW, extentFW, GetWindowDelimiters(window));
	if (found) {
	    iSearchTryBeepOnWrap(window, direction, beginPos, *startPos);
	} else
	    XBell(TheDisplay, 0);
    }
    
    /* Free the text buffer copy returned from BufGetAll */
    XtFree(fileString);

    return found;
}

/*
** Search the null terminated string "string" for "searchString", beginning at
** "beginPos".  Returns the boundaries of the match in "startPos" and "endPos".
** searchExtentBW and searchExtentFW return the backwardmost and forwardmost 
** positions used to make the match, which are usually startPos and endPos, 
** but may extend further if positive lookahead or lookbehind was used in
** a regular expression match.  "delimiters" may be used to provide an
** alternative set of word delimiters for regular expression "<" and ">"
** characters, or simply passed as null for the default delimiter set.
*/
int SearchString(const char *string, const char *searchString, int direction,
       int searchType, int wrap, int beginPos, int *startPos, int *endPos,
       int *searchExtentBW, int *searchExtentFW, const char *delimiters)
{
    switch (searchType) {
      case SEARCH_CASE_SENSE_WORD:
      	 return searchLiteralWord(string, searchString, TRUE,  direction, wrap,
	 		       beginPos, startPos, endPos, delimiters);
      case SEARCH_LITERAL_WORD:
      	 return  searchLiteralWord(string, searchString, FALSE, direction, wrap,
	 		       beginPos, startPos, endPos, delimiters);
      case SEARCH_CASE_SENSE:
      	 return searchLiteral(string, searchString, TRUE, direction, wrap,
	 		       beginPos, startPos, endPos, searchExtentBW, 
                               searchExtentFW);
      case SEARCH_LITERAL:
      	 return  searchLiteral(string, searchString, FALSE, direction, wrap,
	 	beginPos, startPos, endPos, searchExtentBW, searchExtentFW);
      case SEARCH_REGEX:
      	 return  searchRegex(string, searchString, direction, wrap,
      	 	beginPos, startPos, endPos, searchExtentBW, searchExtentFW,
                delimiters, REDFLT_STANDARD);
      case SEARCH_REGEX_NOCASE:
      	 return  searchRegex(string, searchString, direction, wrap,
      	 	beginPos, startPos, endPos, searchExtentBW, searchExtentFW,
                delimiters, REDFLT_CASE_INSENSITIVE);
    }
    return FALSE; /* never reached, just makes compilers happy */
}

/* 
** Parses a search type description string. If the string contains a valid 
** search type description, returns TRUE and writes the corresponding 
** SearchType in searchType. Returns FALSE and leaves searchType untouched 
** otherwise. (Originally written by Markus Schwarzenberg; slightly adapted).
*/
int StringToSearchType(const char * string, int *searchType) 
{
    int i;
    for (i = 0; searchTypeStrings[i]; i++) {
        if (!strcmp(string, searchTypeStrings[i])) {
            break;
        }
    }
    if (!searchTypeStrings[i]) {
        return FALSE;
    }
    *searchType = i;
    return TRUE;
} 

/*
**  Searches for whole words (Markus Schwarzenberg).
**
**  If the first/last character of `searchString' is a "normal
**  word character" (not contained in `delimiters', not a whitespace)
**  then limit search to strings, who's next left/next right character
**  is contained in `delimiters' or is a whitespace or text begin or end.
**
**  If the first/last character of `searchString' itself is contained
**  in delimiters or is a white space, then the neighbour character of the
**  first/last character will not be checked, just a simple match 
**  will suffice in that case.
**  
*/
static int searchLiteralWord(const char *string, const char *searchString, int caseSense, 
	int direction, int wrap, int beginPos, int *startPos, int *endPos, 
        const char * delimiters)
{
/* This is critical code for the speed of searches.			    */
/* For efficiency, we define the macro DOSEARCH with the guts of the search */
/* routine and repeat it, changing the parameters of the outer loop for the */
/* searching, forwards, backwards, and before and after the begin point	    */
#define DOSEARCHWORD() \
    if (*filePtr == *ucString || *filePtr == *lcString) { \
	/* matched first character */ \
	ucPtr = ucString; \
	lcPtr = lcString; \
	tempPtr = filePtr; \
	while (*tempPtr == *ucPtr || *tempPtr == *lcPtr) { \
	    tempPtr++; ucPtr++; lcPtr++; \
	    if (   *ucPtr == 0 /* matched whole string */ \
		&& (cignore_R ||\
		    isspace((unsigned char)*tempPtr) ||\
		    strchr(delimiters, *tempPtr) ) \
		    /* next char right delimits word ? */ \
		&& (cignore_L ||\
                    filePtr==string || /* border case */ \
                    isspace((unsigned char)filePtr[-1]) ||\
                    strchr(delimiters,filePtr[-1]) ))\
                    /* next char left delimits word ? */ { \
		*startPos = filePtr - string; \
		*endPos = tempPtr - string; \
		return TRUE; \
	    } \
	} \
    }

    register const char *filePtr, *tempPtr, *ucPtr, *lcPtr;
    char lcString[SEARCHMAX], ucString[SEARCHMAX];
						
    int cignore_L=0, cignore_R=0;
		
    /* SEARCHMAX was fine in the original NEdit, but it should be done away 
       with now that searching can be done from macros without limits. 
       Returning search failure here is cheating users.  This limit is not 
       documented. */
    if (strlen(searchString) >= SEARCHMAX)
	return FALSE;
    
    /* If there is no language mode, we use the default list of delimiters */
    if (delimiters==NULL) delimiters = GetPrefDelimiters();
		
    if (   isspace((unsigned char)*searchString) 
	|| strchr(delimiters, *searchString))
	cignore_L=1;

    if (   isspace((unsigned char)searchString[strlen(searchString)-1])
	|| strchr(delimiters, searchString[strlen(searchString)-1]) )
	cignore_R=1;
   
    if (caseSense) {
        strcpy(ucString, searchString);
        strcpy(lcString, searchString);
    } else {
    	upCaseString(ucString, searchString);
    	downCaseString(lcString, searchString);
    }

    if (direction == SEARCH_FORWARD) {
	/* search from beginPos to end of string */
	for (filePtr=string+beginPos; *filePtr!=0; filePtr++) {
      	    DOSEARCHWORD() 
	}
	if (!wrap)
	    return FALSE;

	/* search from start of file to beginPos */
	for (filePtr=string; filePtr<=string+beginPos; filePtr++) {
      	    DOSEARCHWORD() 
	}
	return FALSE;
    } else {
	/* SEARCH_BACKWARD */
	/* search from beginPos to start of file. A negative begin pos */
	/* says begin searching from the far end of the file */
	if (beginPos >= 0) {
	    for (filePtr=string+beginPos; filePtr>=string; filePtr--) {
	    	DOSEARCHWORD() 
	    }
	}
	if (!wrap)
	    return FALSE;
	/* search from end of file to beginPos */
	/*... this strlen call is extreme inefficiency, but it's not obvious */
	/* how to get the text string length from the text widget (under 1.1)*/
	for (filePtr=string+strlen(string); filePtr>=string+beginPos; filePtr--) {
      	    DOSEARCHWORD() 
	}
	return FALSE;
    }
}


static int searchLiteral(const char *string, const char *searchString, int caseSense, 
	int direction, int wrap, int beginPos, int *startPos, int *endPos,
	int *searchExtentBW, int *searchExtentFW)
{
/* This is critical code for the speed of searches.			    */
/* For efficiency, we define the macro DOSEARCH with the guts of the search */
/* routine and repeat it, changing the parameters of the outer loop for the */
/* searching, forwards, backwards, and before and after the begin point	    */
#define DOSEARCH() \
    if (*filePtr == *ucString || *filePtr == *lcString) { \
	/* matched first character */ \
	ucPtr = ucString; \
	lcPtr = lcString; \
	tempPtr = filePtr; \
	while (*tempPtr == *ucPtr || *tempPtr == *lcPtr) { \
	    tempPtr++; ucPtr++; lcPtr++; \
	    if (*ucPtr == 0) { \
		/* matched whole string */ \
		*startPos = filePtr - string; \
		*endPos = tempPtr - string; \
		if (searchExtentBW != NULL) \
		    *searchExtentBW = *startPos; \
		if (searchExtentFW != NULL) \
		    *searchExtentFW = *endPos; \
		return TRUE; \
	    } \
	} \
    } \

    register const char *filePtr, *tempPtr, *ucPtr, *lcPtr;
    char lcString[SEARCHMAX], ucString[SEARCHMAX];

    /* SEARCHMAX was fine in the original NEdit, but it should be done away with
       now that searching can be done from macros without limits.  Returning
       search failure here is cheating users.  This limit is not documented. */
    if (strlen(searchString) >= SEARCHMAX)
	return FALSE;
    
    if (caseSense) {
        strcpy(ucString, searchString);
        strcpy(lcString, searchString);
    } else {
    	upCaseString(ucString, searchString);
    	downCaseString(lcString, searchString);
    }

    if (direction == SEARCH_FORWARD) {
	/* search from beginPos to end of string */
	for (filePtr=string+beginPos; *filePtr!=0; filePtr++) {
	    DOSEARCH()
	}
	if (!wrap)
	    return FALSE;
	/* search from start of file to beginPos	*/
	for (filePtr=string; filePtr<=string+beginPos; filePtr++) {
	    DOSEARCH()
	}
	return FALSE;
    } else {
    	/* SEARCH_BACKWARD */
	/* search from beginPos to start of file.  A negative begin pos	*/
	/* says begin searching from the far end of the file		*/
	if (beginPos >= 0) {
	    for (filePtr=string+beginPos; filePtr>=string; filePtr--) {
		DOSEARCH()
	    }
	}
	if (!wrap)
	    return FALSE;
	/* search from end of file to beginPos */
	/*... this strlen call is extreme inefficiency, but it's not obvious */
	/* how to get the text string length from the text widget (under 1.1)*/
	for (filePtr=string+strlen(string);
		filePtr>=string+beginPos; filePtr--) {
	    DOSEARCH()
	}
	return FALSE;
    }
}

static int searchRegex(const char *string, const char *searchString, int direction,
	int wrap, int beginPos, int *startPos, int *endPos, int *searchExtentBW,
	int *searchExtentFW, const char *delimiters, int defaultFlags)
{
    if (direction == SEARCH_FORWARD)
	return forwardRegexSearch(string, searchString, wrap, 
            beginPos, startPos, endPos, searchExtentBW, searchExtentFW, 
	    delimiters, defaultFlags);
    else
    	return backwardRegexSearch(string, searchString, wrap, 
	    beginPos, startPos, endPos, searchExtentBW, searchExtentFW,
            delimiters, defaultFlags);
}

static int forwardRegexSearch(const char *string, const char *searchString, int wrap,
	int beginPos, int *startPos, int *endPos, int *searchExtentBW,
        int *searchExtentFW, const char *delimiters, int defaultFlags)
{
    regexp *compiledRE = NULL;
    char *compileMsg;
    
    /* compile the search string for searching with ExecRE.  Note that
       this does not process errors from compiling the expression.  It
       assumes that the expression was checked earlier. */
    compiledRE = CompileRE(searchString, &compileMsg, defaultFlags);
    if (compiledRE == NULL)
	return FALSE;

    /* search from beginPos to end of string */
    if (ExecRE(compiledRE, NULL, string + beginPos, NULL, FALSE,
    	    beginPos==0 ? '\0' : string[beginPos-1], '\0', delimiters, string)) {
	*startPos = compiledRE->startp[0] - string;
	*endPos = compiledRE->endp[0] - string;
	if (searchExtentFW != NULL)
	    *searchExtentFW = compiledRE->extentpFW - string;
	if (searchExtentBW != NULL)
           *searchExtentBW = compiledRE->extentpBW - string;
	free((char *)compiledRE);
	return TRUE;
    }
    
    /* if wrap turned off, we're done */
    if (!wrap) {
    	free((char *)compiledRE);
	return FALSE;
    }
    
    /* search from the beginning of the string to beginPos */
    if (ExecRE(compiledRE, NULL, string, string + beginPos, FALSE, '\0',
	    string[beginPos], delimiters, string)) {
	*startPos = compiledRE->startp[0] - string;
	*endPos = compiledRE->endp[0] - string;
	if (searchExtentFW != NULL)
       	    *searchExtentFW = compiledRE->extentpFW - string;
	if (searchExtentBW != NULL)
	    *searchExtentBW = compiledRE->extentpBW - string;
	free((char *)compiledRE);
	return TRUE;
    }

    free((char *)compiledRE);
    return FALSE;
}

static int backwardRegexSearch(const char *string, const char *searchString, int wrap,
	int beginPos, int *startPos, int *endPos, int *searchExtentBW,
	int *searchExtentFW, const char *delimiters, int defaultFlags)
{
    regexp *compiledRE = NULL;
    char *compileMsg;
    int length;

    /* compile the search string for searching with ExecRE */
    compiledRE = CompileRE(searchString, &compileMsg, defaultFlags);
    if (compiledRE == NULL)
	return FALSE;

    /* search from beginPos to start of file.  A negative begin pos	*/
    /* says begin searching from the far end of the file.		*/
    if (beginPos >= 0) {
	if (ExecRE(compiledRE, NULL, string, string + beginPos, TRUE, '\0',
		'\0', delimiters, string)) {
	    *startPos = compiledRE->startp[0] - string;
	    *endPos = compiledRE->endp[0] - string;
	    if (searchExtentFW != NULL)
		*searchExtentFW = compiledRE->extentpFW - string;
	    if (searchExtentBW != NULL)
		*searchExtentBW = compiledRE->extentpBW - string;
	    free((char *)compiledRE);
	    return TRUE;
	}
    }
    
    /* if wrap turned off, we're done */
    if (!wrap) {
    	free((char *)compiledRE);
    	return FALSE;
    }
    
    /* search from the end of the string to beginPos */
    if (beginPos < 0)
    	beginPos = 0;
    length = strlen(string); /* sadly, this means scanning entire string */
    if (ExecRE(compiledRE, NULL, string + beginPos, string + length, TRUE,
    	    beginPos==0 ? '\0' : string[beginPos-1], '\0', delimiters, string)) {
	*startPos = compiledRE->startp[0] - string;
	*endPos = compiledRE->endp[0] - string;
	if (searchExtentFW != NULL)
	    *searchExtentFW = compiledRE->extentpFW - string;
	if (searchExtentBW != NULL)
	    *searchExtentBW = compiledRE->extentpBW - string;
	free((char *)compiledRE);
	return TRUE;
    }
    free((char *)compiledRE);
    return FALSE;
}

static void upCaseString(char *outString, const char *inString)
{
    char *outPtr;
    const char *inPtr;
    
    for (outPtr=outString, inPtr=inString; *inPtr!=0; inPtr++, outPtr++) {
    	*outPtr = toupper((unsigned char)*inPtr);
    }
    *outPtr = 0;
}

static void downCaseString(char *outString, const char *inString)
{
    char *outPtr;
    const char *inPtr;
    
    for (outPtr=outString, inPtr=inString; *inPtr!=0; inPtr++, outPtr++) {
    	*outPtr = tolower((unsigned char)*inPtr);
    }
    *outPtr = 0;
}

/*
** resetFindTabGroup & resetReplaceTabGroup are really gruesome kludges to
** set the keyboard traversal.  XmProcessTraversal does not work at
** all on these dialogs.  ...It seems to have started working around
** Motif 1.1.2
*/
static void resetFindTabGroup(WindowInfo *window)
{
    XmProcessTraversal(window->findText, XmTRAVERSE_CURRENT);
}
static void resetReplaceTabGroup(WindowInfo *window)
{
    XmProcessTraversal(window->replaceText, XmTRAVERSE_CURRENT);
}

/*
** Return TRUE if "searchString" exactly matches the text in the window's
** current primary selection using search algorithm "searchType".  If true,
** also return the position of the selection in "left" and "right".
*/
static int searchMatchesSelection(WindowInfo *window, const char *searchString,
	int searchType, int *left, int *right, int *searchExtentBW, 
	int *searchExtentFW)
{
    int selLen, selStart, selEnd, startPos, endPos, extentBW, extentFW, beginPos;
    int regexLookContext = isRegexType(searchType) ? 1000 : 0;
    char *string;
    int found, isRect, rectStart, rectEnd, lineStart = 0;
    
    /* find length of selection, give up on no selection or too long */
    if (!BufGetEmptySelectionPos(window->buffer, &selStart, &selEnd, &isRect,
    	    &rectStart, &rectEnd))
	return FALSE;
    if (selEnd - selStart > SEARCHMAX)
	return FALSE;
    
    /* if the selection is rectangular, don't match if it spans lines */
    if (isRect) {
    	lineStart = BufStartOfLine(window->buffer, selStart);
    	if (lineStart != BufStartOfLine(window->buffer, selEnd))
    	    return FALSE;
    }
    
    /* get the selected text plus some additional context for regular
       expression lookahead */
    if (isRect) {
	int stringStart = lineStart + rectStart - regexLookContext;
	if (stringStart < 0) stringStart = 0;
    	string = BufGetRange(window->buffer, stringStart,
		lineStart + rectEnd + regexLookContext);
    	selLen = rectEnd - rectStart;
	beginPos = lineStart + rectStart - stringStart;
    } else {
	int stringStart = selStart - regexLookContext;
	if (stringStart < 0) stringStart = 0;
	string = BufGetRange(window->buffer, stringStart,
		selEnd + regexLookContext);
    	selLen = selEnd - selStart;
	beginPos = selStart - stringStart;
    }
    if (*string == '\0') {
    	XtFree(string);
    	return FALSE;
    }

    /* search for the string in the selection (we are only interested 	*/
    /* in an exact match, but the procedure SearchString does important */
    /* stuff like applying the correct matching algorithm)		*/
    found = SearchString(string, searchString, SEARCH_FORWARD, searchType,
    	    FALSE, beginPos, &startPos, &endPos, &extentBW, &extentFW,
            GetWindowDelimiters(window));
    XtFree(string);

    /* decide if it is an exact match */
    if (!found)
    	return FALSE;
    if (startPos != beginPos || endPos - beginPos != selLen )
    	return FALSE;
    
    /* return the start and end of the selection */
    if (isRect)
    	GetSimpleSelection(window->buffer, left, right);
    else {
    	*left = selStart;
    	*right = selEnd;
    }
    if (searchExtentBW != NULL)
	*searchExtentBW = *left - (startPos - extentBW);
    
    if (searchExtentFW != NULL)
	*searchExtentFW = *right + extentFW - endPos;
    return TRUE;
}

/*
** Substitutes a replace string for a string that was matched using a
** regular expression.  This was added later and is rather ineficient
** because instead of using the compiled regular expression that was used
** to make the match in the first place, it re-compiles the expression
** and redoes the search on the already-matched string.  This allows the
** code to continue using strings to represent the search and replace
** items.
*/  
static void replaceUsingRE(const char *searchStr, const char *replaceStr, 
	const char *sourceStr, int beginPos, char *destStr, 
        int maxDestLen, int prevChar, const char *delimiters, int defaultFlags)
{
    regexp *compiledRE;
    char *compileMsg;
    
    compiledRE = CompileRE(searchStr, &compileMsg, defaultFlags);
    ExecRE(compiledRE, NULL, sourceStr+beginPos, NULL, False, prevChar,
   	   '\0', delimiters, sourceStr);
    SubstituteRE(compiledRE, replaceStr, destStr, maxDestLen);
    free((char *)compiledRE);
}

/*
** Store the search and replace strings, and search type for later recall.
** If replaceString is NULL, duplicate the last replaceString used.
** Contiguous incremental searches share the same history entry (each new
** search modifies the current search string, until a non-incremental search
** is made.  To mark the end of an incremental search, call saveSearchHistory
** again with an empty search string and isIncremental==False.
*/
static void saveSearchHistory(const char *searchString,
        const char *replaceString, int searchType, int isIncremental)
{
    char *sStr, *rStr;
    static int currentItemIsIncremental = FALSE;
    WindowInfo *w;
    
    /* Cancel accumulation of contiguous incremental searches (even if the
       information is not worthy of saving) if search is not incremental */
    if (!isIncremental)
	currentItemIsIncremental = FALSE;
    
    /* Don't save empty search strings */
    if (searchString[0] == '\0')
	return;
    
    /* If replaceString is NULL, duplicate the last one (if any) */
    if (replaceString == NULL)
    	replaceString = NHist >= 1 ? ReplaceHistory[historyIndex(1)] : "";
    
    /* Compare the current search and replace strings against the saved ones.
       If they are identical, don't bother saving */
    if (NHist >= 1 && searchType == SearchTypeHistory[historyIndex(1)] &&
    	    !strcmp(SearchHistory[historyIndex(1)], searchString) &&
    	    !strcmp(ReplaceHistory[historyIndex(1)], replaceString)) {
    	return;
    }
    
    /* If the current history item came from an incremental search, and the
       new one is also incremental, just update the entry */
    if (currentItemIsIncremental && isIncremental) {
    	XtFree(SearchHistory[historyIndex(1)]);
    	SearchHistory[historyIndex(1)] = XtNewString(searchString);
	SearchTypeHistory[historyIndex(1)] = searchType;
	return;
    }
    currentItemIsIncremental = isIncremental;
    
    if (NHist==0) {
    	for (w=WindowList; w!=NULL; w=w->next) {
    	    if (!IsTopDocument(w))
		continue;
	    XtSetSensitive(w->findAgainItem, True);
	    XtSetSensitive(w->replaceFindAgainItem, True);
	    XtSetSensitive(w->replaceAgainItem, True);
    	}
    }

    /* If there are more than MAX_SEARCH_HISTORY strings saved, recycle
       some space, free the entry that's about to be overwritten */
    if (NHist == MAX_SEARCH_HISTORY) {
    	XtFree(SearchHistory[HistStart]);
    	XtFree(ReplaceHistory[HistStart]);
    } else
    	NHist++;

    /* Allocate and copy the search and replace strings and add them to the
       circular buffers at HistStart, bump the buffer pointer to next pos. */
    sStr = XtMalloc(strlen(searchString) + 1);
    rStr = XtMalloc(strlen(replaceString) + 1);
    strcpy(sStr, searchString);
    strcpy(rStr, replaceString);
    SearchHistory[HistStart] = sStr;
    ReplaceHistory[HistStart] = rStr;
    SearchTypeHistory[HistStart] = searchType;
    HistStart++;
    if (HistStart >= MAX_SEARCH_HISTORY)
    	HistStart = 0;
}

/*
** return an index into the circular buffer arrays of history information
** for search strings, given the number of saveSearchHistory cycles back from
** the current time.
*/

static int historyIndex(int nCycles)
{
    int index;
    
    if (nCycles > NHist || nCycles <= 0)
    	return -1;
    index = HistStart - nCycles;
    if (index < 0)
    	index = MAX_SEARCH_HISTORY + index;
    return index;
}

/*
** Return a pointer to the string describing search type for search action
** routine parameters (see menu.c for processing of action routines)
*/
static char *searchTypeArg(int searchType)
{
    if (0 <= searchType && searchType < N_SEARCH_TYPES) {
        return searchTypeStrings[searchType];
    }
    return searchTypeStrings[SEARCH_LITERAL];
}

/*
** Return a pointer to the string describing search wrap for search action
** routine parameters (see menu.c for processing of action routines)
*/
static char *searchWrapArg(int searchWrap)
{
    if (searchWrap) {
    	return "wrap";
    }
    return "nowrap";
}

/*
** Return a pointer to the string describing search direction for search action
** routine parameters (see menu.c for processing of action routines)
*/
static char *directionArg(int direction)
{
    if (direction == SEARCH_BACKWARD)
    	return "backward";
    return "forward";
}

/*
** Checks whether a search mode in one of the regular expression modes.
*/
static int isRegexType(int searchType)
{
    return searchType == SEARCH_REGEX || searchType == SEARCH_REGEX_NOCASE;
}

/*
** Returns the default flags for regular expression matching, given a 
** regular expression search mode.
*/
static int defaultRegexFlags(int searchType)
{
    switch (searchType) {
	case SEARCH_REGEX:
	    return REDFLT_STANDARD;
	case SEARCH_REGEX_NOCASE:
	    return REDFLT_CASE_INSENSITIVE;
	default:
	    /* We should never get here, but just in case ... */
	    return REDFLT_STANDARD;
    }
}   

/* 
** The next 4 callbacks handle the states of find/replace toggle 
** buttons, which depend on the state of the "Regex" button, and the
** sensitivity of the Whole Word buttons.
** Callbacks are necessary for both "Regex" and "Case Sensitive"
** buttons to make sure the states are saved even after a cancel operation.
**
** If sticky case sensitivity is requested, the behaviour is as follows:
**   The first time "Regular expression" is checked, "Match case" gets
**   checked too. Thereafter, checking or unchecking "Regular expression"
**   restores the "Match case" button to the setting it had the last
**   time when literals or REs where used. 
** Without sticky behaviour, the state of the Regex button doesn't influence
** the state of the Case Sensitive button.
** 
** Independently, the state of the buttons is always restored to the 
** default state when a dialog is popped up, and when the user returns
** from stepping through the search history. 
**
** NOTE: similar call-backs exist for the incremental search bar; see window.c.
*/
static void findRegExpToggleCB(Widget w, XtPointer clientData, XtPointer callData)
{
    WindowInfo * window = WidgetToWindow(w);
    int searchRegex = XmToggleButtonGetState(w);
    int searchCaseSense = XmToggleButtonGetState(window->findCaseToggle);
    
    /* In sticky mode, restore the state of the Case Sensitive button */
    if(GetPrefStickyCaseSenseBtn()) {
	if(searchRegex) {
	    window->findLastLiteralCase = searchCaseSense;
	    XmToggleButtonSetState(window->findCaseToggle, 
		window->findLastRegexCase, False);
	} else {
	    window->findLastRegexCase = searchCaseSense;
	    XmToggleButtonSetState(window->findCaseToggle, 
		window->findLastLiteralCase, False);
	}
    }
    /* make the Whole Word button insensitive for regex searches */
    XtSetSensitive(window->findWordToggle, !searchRegex);
}

static void replaceRegExpToggleCB(Widget w, XtPointer clientData, XtPointer callData)
{
    WindowInfo * window = WidgetToWindow(w);
    int searchRegex = XmToggleButtonGetState(w);
    int searchCaseSense = XmToggleButtonGetState(window->replaceCaseToggle);
    
    /* In sticky mode, restore the state of the Case Sensitive button */
    if(GetPrefStickyCaseSenseBtn()) {
	if(searchRegex) {
      	    window->replaceLastLiteralCase = searchCaseSense;
	    XmToggleButtonSetState(window->replaceCaseToggle, 
		window->replaceLastRegexCase, False);
	} else {
      	    window->replaceLastRegexCase = searchCaseSense;
	    XmToggleButtonSetState(window->replaceCaseToggle, 
		window->replaceLastLiteralCase, False);
	}
    }
    /* make the Whole Word button insensitive for regex searches */
    XtSetSensitive(window->replaceWordToggle, !searchRegex);
}

static void iSearchRegExpToggleCB(Widget w, XtPointer clientData, XtPointer callData)
{
    WindowInfo * window = WidgetToWindow(w);
    int searchRegex = XmToggleButtonGetState(w);
    int searchCaseSense = XmToggleButtonGetState(window->iSearchCaseToggle);
    
    /* In sticky mode, restore the state of the Case Sensitive button */
    if(GetPrefStickyCaseSenseBtn()) {
	if(searchRegex) {
      	    window->iSearchLastLiteralCase = searchCaseSense;
	    XmToggleButtonSetState(window->iSearchCaseToggle, 
		window->iSearchLastRegexCase, False);
	} else {
      	    window->iSearchLastRegexCase = searchCaseSense;
	    XmToggleButtonSetState(window->iSearchCaseToggle, 
		window->iSearchLastLiteralCase, False);
	}
    }
    /* The iSearch bar has no Whole Word button to enable/disable. */
}
static void findCaseToggleCB(Widget w, XtPointer clientData, XtPointer callData)
{
    WindowInfo * window = WidgetToWindow(w);
    int searchCaseSense = XmToggleButtonGetState(w);
    
    /* Save the state of the Case Sensitive button 
       depending on the state of the Regex button*/
    if(XmToggleButtonGetState(window->findRegexToggle))
    	window->findLastRegexCase = searchCaseSense;
    else
	window->findLastLiteralCase = searchCaseSense;
}

static void replaceCaseToggleCB(Widget w, XtPointer clientData, XtPointer callData)
{
    WindowInfo * window = WidgetToWindow(w);
    int searchCaseSense = XmToggleButtonGetState(w);
    
    /* Save the state of the Case Sensitive button 
       depending on the state of the Regex button*/
    if(XmToggleButtonGetState(window->replaceRegexToggle))
    	window->replaceLastRegexCase = searchCaseSense;
    else
	window->replaceLastLiteralCase = searchCaseSense;
}

static void iSearchCaseToggleCB(Widget w, XtPointer clientData, XtPointer callData)
{
    WindowInfo * window = WidgetToWindow(w);
    int searchCaseSense = XmToggleButtonGetState(w);
    
    /* Save the state of the Case Sensitive button 
       depending on the state of the Regex button*/
    if(XmToggleButtonGetState(window->iSearchRegexToggle))
    	window->iSearchLastRegexCase = searchCaseSense;
    else
	window->iSearchLastLiteralCase = searchCaseSense;
}