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

;; Copyright (C) 1985, 1986, 1987, 1988,
;;  1990, 1992, 1993, 1994, 1995, 1997, 1999,
;;  2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc.

;; Author: Bill Wohler <wohler@newt.com>
;; Maintainer: Bill Wohler <wohler@newt.com>
;; Version: 7.85+cvs
;; Keywords: mail

;; This file is part of GNU Emacs.

;; GNU Emacs 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, or (at your option)
;; any later version.

;; GNU Emacs 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 GNU Emacs; see the file COPYING.  If not, write to the
;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
;; Boston, MA 02110-1301, USA.

;;; Commentary:

;; How to Use:
;;   M-x mh-rmail to read mail.  Type C-h m there for a list of commands.
;;   C-u M-x mh-rmail to visit any folder.
;;   M-x mh-smail to send mail.  From within the mail reader, "m" works, too.

;; Your .emacs might benefit from these bindings:
;;   (global-set-key "\C-cr" 'mh-rmail)
;;   (global-set-key "\C-xm" 'mh-smail)
;;   (global-set-key "\C-x4m" 'mh-smail-other-window)

;; MH (Message Handler) is a powerful mail reader.

;; The MH newsgroup is comp.mail.mh; the mailing list is mh-users@ics.uci.edu
;; (send to mh-users-request to be added). See the monthly Frequently Asked
;; Questions posting there for information on getting MH and MH-E:
;;   http://www.faqs.org/faqs/mail/mh-faq/part1/preamble.html

;; N.B. MH must have been compiled with the MHE compiler flag or several
;; features necessary for MH-E will be missing from MH commands, specifically
;; the -build switch to repl and forw.

;; MH-E is an Emacs interface to the MH mail system.

;; MH-E is supported in GNU Emacs 21 and 22 as well as XEmacs 21
;; (except for versions 21.5.9-21.5.16), with MH 6.8.4 on, nmh 1.0.4
;; on, and GNU mailutils 0.4 on.

;; Mailing Lists:
;;   mh-e-users@lists.sourceforge.net
;;   mh-e-announce@lists.sourceforge.net
;;   mh-e-devel@lists.sourceforge.net
;;
;;   Subscribe by sending a "subscribe" message to
;;   <list>-request@lists.sourceforge.net, or by using the web interface at
;;   https://sourceforge.net/mail/?group_id=13357

;; Bug Reports:
;;   https://sourceforge.net/tracker/?group_id=13357&atid=113357
;;   Include the output of M-x mh-version in any bug report.

;; Feature Requests:
;;   https://sourceforge.net/tracker/?atid=363357&group_id=13357&func=browse

;; Support:
;;   https://sourceforge.net/tracker/?group_id=13357&atid=213357

;;; Change Log:

;; Original version for Gosling emacs by Brian Reid, Stanford, 1982.
;; Modified by James Larus, BBN, July 1984 and UCB, 1984 & 1985.
;; Rewritten for GNU Emacs, James Larus, 1985.
;; Modified by Stephen Gildea, 1988.
;; Maintenance picked up by Bill Wohler and the
;; SourceForge Crew <http://mh-e.sourceforge.net/>, 2001.

;;; Code:

(provide 'mh-e)

(eval-when-compile (require 'mh-acros))
(mh-require-cl)

(require 'easymenu)
(require 'gnus-util)
(require 'mh-seq)
(require 'mh-utils)

(defconst mh-version "7.85+cvs" "Version number of MH-E.")

(defvar mh-partial-folder-mode-line-annotation "select"
  "Annotation when displaying part of a folder.
The string is displayed after the folder's name. nil for no
annotation.")



;;; Scan Line Formats

;; Parameterize MH-E to work with different scan formats.  The defaults work
;; with the standard MH scan listings, in which the first 4 characters on
;; the line are the message number, followed by two places for notations.

;; The following scan formats are passed to the scan program if the setting of
;; `mh-scan-format-file' is t. They are identical except the later one makes
;; use of the nmh `decode' function to decode RFC 2047 encodings. If you just
;; want to change the column of the notations, use the `mh-set-cmd-note'
;; function.

(defvar mh-scan-format-mh
  (concat
   "%4(msg)"
   "%<(cur)+%| %>"
   "%<{replied}-"
   "%?(nonnull(comp{to}))%<(mymbox{to})t%>"
   "%?(nonnull(comp{cc}))%<(mymbox{cc})c%>"
   "%?(nonnull(comp{bcc}))%<(mymbox{bcc})b%>"
   "%?(nonnull(comp{newsgroups}))n%>"
   "%<(zero) %>"
   "%02(mon{date})/%02(mday{date})%<{date} %|*%>"
   "%<(mymbox{from})%<{to}To:%14(friendly{to})%>%>"
   "%<(zero)%17(friendly{from})%>  "
   "%{subject}%<{body}<<%{body}%>")
  "*Scan format string for MH.
This string is passed to the scan program via the -format
argument. This format is identical to the default except that
additional hints for fontification have been added to the fifth
column (remember that in Emacs, the first column is 0).

The values of the fifth column, in priority order, are: \"-\" if
the message has been replied to, t if an address on the To: line
matches one of the mailboxes of the current user, \"c\" if the Cc:
line matches, \"b\" if the Bcc: line matches, and \"n\" if a
non-empty Newsgroups: header is present.")

(defvar mh-scan-format-nmh
  (concat
   "%4(msg)"
   "%<(cur)+%| %>"
   "%<{replied}-"
   "%?(nonnull(comp{to}))%<(mymbox{to})t%>"
   "%?(nonnull(comp{cc}))%<(mymbox{cc})c%>"
   "%?(nonnull(comp{bcc}))%<(mymbox{bcc})b%>"
   "%?(nonnull(comp{newsgroups}))n%>"
   "%<(zero) %>"
   "%02(mon{date})/%02(mday{date})%<{date} %|*%>"
   "%<(mymbox{from})%<{to}To:%14(decode(friendly{to}))%>%>"
   "%<(zero)%17(decode(friendly{from}))%>  "
   "%(decode{subject})%<{body}<<%{body}%>")
  "*Scan format string for nmh.
This string is passed to the scan program via the -format arg.
This format is identical to the default except that additional
hints for fontification have been added to the fifth
column (remember that in Emacs, the first column is 0).

The values of the fifth column, in priority order, are: \"-\" if
the message has been replied to, t if an address on the To: field
matches one of the mailboxes of the current user, \"c\" if the Cc:
field matches, \"b\" if the Bcc: field matches, and \"n\" if a
non-empty Newsgroups: field is present.")

(defvar mh-note-deleted ?D
  "Messages that have been deleted are marked by this character.
See also `mh-scan-deleted-msg-regexp'.")

(defvar mh-note-refiled ?^
  "Messages that have been refiled are marked by this character.
See also `mh-scan-refiled-msg-regexp'.")

(defvar mh-note-cur ?+
  "The current message (in MH, not in MH-E) is marked by this character.
See also `mh-scan-cur-msg-number-regexp'.")

(defvar mh-scan-good-msg-regexp  "^\\( *[0-9]+\\)[^D^0-9]"
  "This regular expression matches \"good\" messages.

It must match from the beginning of the line. Note that the
default setting of `mh-folder-font-lock-keywords' expects this
expression to contain at least one parenthesized expression which
matches the message number as in the default of

  \"^\\\\( *[0-9]+\\\\)[^D^0-9]\".

This expression includes the leading space within the parenthesis
since it looks better to highlight it as well. The highlighting
is done with the face `mh-folder-msg-number'. This regular
expression should be correct as it is needed by non-fontification
functions.")

(defvar mh-scan-deleted-msg-regexp "^\\( *[0-9]+\\)D"
  "This regular expression matches deleted messages.

It must match from the beginning of the line. Note that the
default setting of `mh-folder-font-lock-keywords' expects this
expression to contain at least one parenthesized expression which
matches the message number as in the default of

  \"^\\\\( *[0-9]+\\\\)D\".

This expression includes the leading space within the parenthesis
since it looks better to highlight it as well. The highlighting
is done with the face `mh-folder-deleted'. This regular
expression should be correct as it is needed by non-fontification
functions. See also `mh-note-deleted'.")

(defvar mh-scan-refiled-msg-regexp  "^\\( *[0-9]+\\)\\^"
  "This regular expression matches refiled messages.

It must match from the beginning of the line. Note that the
default setting of `mh-folder-font-lock-keywords' expects this
expression to contain at least one parenthesized expression which
matches the message number as in the default of

  \"^\\\\( *[0-9]+\\\\)\\\\^\".

This expression includes the leading space within the parenthesis
since it looks better to highlight it as well. The highlighting
is done with the face `mh-folder-refiled'. This regular
expression should be correct as it is needed by non-fontification
functions. See also `mh-note-refiled'.")

(defvar mh-scan-valid-regexp "^ *[0-9]"
  "This regular expression describes a valid scan line.

This is used to eliminate error messages that are occasionally
produced by \"inc\".")

(defvar mh-scan-cur-msg-number-regexp "^\\( *[0-9]+\\+\\).*"
  "This regular expression matches the current message.

It must match from the beginning of the line. Note that the
default setting of `mh-folder-font-lock-keywords' expects this
expression to contain at least one parenthesized expression which
matches the message number as in the default of

  \"^\\\\( *[0-9]+\\\\+\\\\).*\".

This expression includes the leading space and current message
marker \"+\" within the parenthesis since it looks better to
highlight these items as well. The highlighting is done with the
face `mh-folder-cur-msg-number'. This regular expression should
be correct as it is needed by non-fontification functions. See
also `mh-note-cur'.")

(defvar mh-scan-date-regexp "\\([0-9][0-9]/[0-9][0-9]\\)"
  "This regular expression matches a valid date.

It must not be anchored to the beginning or the end of the line.
Note that the default setting of `mh-folder-font-lock-keywords'
expects this expression to contain only one parenthesized
expression which matches the date field as in the default of
\"\\\\([0-9][0-9]/[0-9][0-9]\\\\)\"}. If this regular expression
is not correct, the date will not be highlighted with the face
`mh-folder-date'.")

(defvar mh-scan-rcpt-regexp  "\\(To:\\)\\(..............\\)"
  "This regular expression specifies the recipient in messages you sent.

Note that the default setting of `mh-folder-font-lock-keywords'
expects this expression to contain two parenthesized expressions.
The first is expected to match the \"To:\" that the default scan
format file generates. The second is expected to match the
recipient's name as in the default of
\"\\\\(To:\\\\)\\\\(..............\\\\)\". If this regular
expression is not correct, the \"To:\" string will not be
highlighted with the face `mh-folder-to' and the recipient will
not be highlighted with the face `mh-folder-address'")

(defvar mh-scan-body-regexp "\\(<<\\([^\n]+\\)?\\)"
  "This regular expression matches the message body fragment.

Note that the default setting of `mh-folder-font-lock-keywords'
expects this expression to contain at least one parenthesized
expression which matches the body text as in the default of
\"\\\\(<<\\\\([^\\n]+\\\\)?\\\\)\". If this regular expression is
not correct, the body fragment will not be highlighted with the
face `mh-folder-body'.")

(defvar mh-scan-subject-regexp
  "^ *[0-9]+........[ ]*...................\\([Rr][Ee]\\(\\[[0-9]+\\]\\)?:\\s-*\\)*\\([^<\n]*\\)"
  "This regular expression matches the subject.

It must match from the beginning of the line. Note that the
default setting of `mh-folder-font-lock-keywords' expects this
expression to contain at least three parenthesized expressions.
The first is expected to match the \"Re:\" string, if any, and is
highlighted with the face `mh-folder-followup'. The second
matches an optional bracketed number after \"Re:\", such as in
\"Re[2]:\" (and is thus a sub-expression of the first expression)
and the third is expected to match the subject line itself which
is highlighted with the face `mh-folder-subject'. For example,
the default (broken on multiple lines for readability) is

  ^ *[0-9]+........[ ]*...................
  \\\\([Rr][Ee]\\\\(\\\\\\=[[0-9]+\\\\]\\\\)?:\\\\s-*\\\\)*
  \\\\([^<\\n]*\\\\)

This regular expression should be correct as it is needed by
non-fontification functions.")

(defvar mh-scan-sent-to-me-sender-regexp
  "^ *[0-9]+.\\([bct]\\).....[ ]*\\(..................\\)"
  "This regular expression matches messages sent to us.

Note that the default setting of `mh-folder-font-lock-keywords'
expects this expression to contain at least two parenthesized
expressions. The first should match the fontification hint (see
`mh-scan-format-nmh') and the second should match the user name
as in the default of

  ^ *[0-9]+.\\\\([bct]\\\\).....[ ]*\\\\(..................\\\\)

If this regular expression is not correct, the notation hints
will not be highlighted with the face
`mh-mh-folder-sent-to-me-hint' and the sender will not be
highlighted with the face `mh-folder-sent-to-me-sender'.")



(defvar mh-folder-font-lock-keywords
  (list
   ;; Folders when displaying index buffer
   (list "^\\+.*"
         '(0 'mh-index-folder))
   ;; Marked for deletion
   (list (concat mh-scan-deleted-msg-regexp ".*")
         '(0 'mh-folder-deleted))
   ;; Marked for refile
   (list (concat mh-scan-refiled-msg-regexp ".*")
         '(0 'mh-folder-refiled))
   ;; After subject
   (list mh-scan-body-regexp
         '(1 'mh-folder-body nil t))
   ;; Subject
   '(mh-folder-font-lock-subject
     (1 'mh-folder-followup append t)
     (2 'mh-folder-subject append t))
   ;; Current message number
   (list mh-scan-cur-msg-number-regexp
         '(1 'mh-folder-cur-msg-number))
   ;; Message number
   (list mh-scan-good-msg-regexp
         '(1 'mh-folder-msg-number))
   ;; Date
   (list mh-scan-date-regexp
         '(1 'mh-folder-date))
   ;; Messages from me (To:)
   (list mh-scan-rcpt-regexp
         '(1 'mh-folder-to)
         '(2 'mh-folder-address))
   ;; Messages to me
   (list mh-scan-sent-to-me-sender-regexp
         '(1 'mh-folder-sent-to-me-hint)
         '(2 'mh-folder-sent-to-me-sender)))
  "Keywords (regular expressions) used to fontify the MH-Folder buffer.")

(defvar mh-scan-cmd-note-width 1
  "Number of columns consumed by the cmd-note field in `mh-scan-format'.

This column will have one of the values: \" \", \"D\", \"^\", \"+\" and
where \" \" is the default value,

  \"D\" is the `mh-note-deleted' character,
  \"^\" is the `mh-note-refiled' character, and
  \"+\" is the `mh-note-cur' character.")

(defvar mh-scan-destination-width 1
  "Number of columns consumed by the destination field in `mh-scan-format'.

This column will have one of \" \", \"%\", \"-\", \"t\", \"c\", \"b\", or \"n\"
in it.

  \" \" blank space is the default character.
  \"%\" indicates that the message in in a named MH sequence.
  \"-\" indicates that the message has been annotated with a replied field.
  \"t\" indicates that the message contains mymbox in the To: field.
  \"c\" indicates that the message contains mymbox in the Cc: field.
  \"b\" indicates that the message contains mymbox in the Bcc: field.
  \"n\" indicates that the message contains a Newsgroups: field.")

(defvar mh-scan-date-width 5
  "Number of columns consumed by the date field in `mh-scan-format'.
This column will typically be of the form mm/dd.")

(defvar mh-scan-date-flag-width 1
  "Number of columns consumed to flag (in)valid dates in `mh-scan-format'.
This column will have \" \" for valid and \"*\" for invalid or
missing dates.")

(defvar mh-scan-from-mbox-width 17
  "Number of columns consumed with the \"From:\" line in `mh-scan-format'.
This column will have a friendly name or e-mail address of the
originator, or a \"To: address\" for outgoing e-mail messages.")

(defvar mh-scan-from-mbox-sep-width 2
  "Number of columns consumed by whitespace after from-mbox in `mh-scan-format'.
This column will only ever have spaces in it.")

(defvar mh-scan-field-destination-offset
  (+ mh-scan-cmd-note-width)
  "The offset from the `mh-cmd-note' for the destination column.")

(defvar mh-scan-field-from-start-offset
  (+ mh-scan-cmd-note-width
     mh-scan-destination-width
     mh-scan-date-width
     mh-scan-date-flag-width)
  "The offset from the `mh-cmd-note' to find the start of \"From:\" address.")

(defvar mh-scan-field-from-end-offset
  (+ mh-scan-field-from-start-offset mh-scan-from-mbox-width)
  "The offset from the `mh-cmd-note' to find the end of \"From:\" address.")

(defvar mh-scan-field-subject-start-offset
  (+ mh-scan-cmd-note-width
     mh-scan-destination-width
     mh-scan-date-width
     mh-scan-date-flag-width
     mh-scan-from-mbox-width
     mh-scan-from-mbox-sep-width)
  "The offset from the `mh-cmd-note' to find the start of the subject.")

(defun mh-folder-font-lock-subject (limit)
  "Return MH-E scan subject strings to font-lock between point and LIMIT."
  (if (not (re-search-forward mh-scan-subject-regexp limit t))
      nil
    (if (match-beginning 1)
        (set-match-data (list (match-beginning 1) (match-end 3)
                              (match-beginning 1) (match-end 3) nil nil))
      (set-match-data (list (match-beginning 3) (match-end 3)
                            nil nil (match-beginning 3) (match-end 3))))
    t))



;; Fontifify unseen mesages in bold.

(defmacro mh-generate-sequence-font-lock (seq prefix face)
  "Generate the appropriate code to fontify messages in SEQ.
PREFIX is used to generate unique names for the variables and
functions defined by the macro. So a different prefix should be
provided for every invocation.
FACE is the font-lock face used to display the matching scan lines."
  (let ((cache (intern (format "mh-folder-%s-seq-cache" prefix)))
        (func (intern (format "mh-folder-font-lock-%s" prefix))))
    `(progn
       (defvar ,cache nil
         "Internal cache variable used for font-lock in MH-E.
Should only be non-nil through font-lock stepping, and nil once
font-lock is done highlighting.")
       (make-variable-buffer-local ',cache)

       (defun ,func (limit)
         "Return unseen message lines to font-lock between point and LIMIT."
         (if (not ,cache) (setq ,cache (mh-seq-msgs (mh-find-seq ,seq))))
         (let ((cur-msg (mh-get-msg-num nil)))
           (cond ((not ,cache)
                  nil)
                 ((>= (point) limit)              ;Presumably at end of buffer
                  (setq ,cache nil)
                  nil)
                 ((member cur-msg ,cache)
                  (let ((bpoint (progn (beginning-of-line)(point)))
                        (epoint (progn (forward-line 1)(point))))
                    (if (<= limit (point)) (setq  ,cache nil))
                    (set-match-data (list bpoint epoint bpoint epoint))
                    t))
                 (t
                  ;; move forward one line at a time, checking each message
                  (while (and (= 0 (forward-line 1))
                              (> limit (point))
                              (not (member (mh-get-msg-num nil) ,cache))))
                  ;; Examine how we must have exited the loop...
                  (let ((cur-msg (mh-get-msg-num nil)))
                    (cond ((or (<= limit (point))
                               (not (member cur-msg ,cache)))
                           (setq ,cache nil)
                           nil)
                          ((member cur-msg ,cache)
                           (let ((bpoint (progn (beginning-of-line) (point)))
                                 (epoint (progn (forward-line 1) (point))))
                             (if (<= limit (point)) (setq ,cache nil))
                             (set-match-data
                              (list bpoint epoint bpoint epoint))
                             t))))))))

       (setq mh-folder-font-lock-keywords
             (append mh-folder-font-lock-keywords
                     (list (list ',func (list 1 '',face 'prepend t))))))))

(mh-generate-sequence-font-lock mh-unseen-seq unseen bold)
(mh-generate-sequence-font-lock mh-tick-seq tick mh-folder-tick)



;;; Internal variables:

(defvar mh-last-destination nil
  "Destination of last refile or write command.")

(defvar mh-last-destination-folder nil
  "Destination of last refile command.")

(defvar mh-last-destination-write nil
  "Destination of last write command.")

(defvar mh-folder-mode-map (make-keymap)
  "Keymap for MH folders.")

(defvar mh-arrow-marker nil
  "Marker for arrow display in fringe.")

(defvar mh-delete-list nil
  "List of message numbers to delete.
This variable can be used by
`mh-before-commands-processed-hook'.")

(defvar mh-refile-list nil
  "List of folder names in `mh-seq-list'.
This variable can be used by
`mh-before-commands-processed-hook'.")

(defvar mh-folders-changed nil
  "Lists which folders were affected by deletes and refiles.
This list will always include the current folder
`mh-current-folder'. This variable can be used by
`mh-after-commands-processed-hook'.")

(defvar mh-next-direction 'forward
  "Direction to move to next message.")

(defvar mh-view-ops ()
  "Stack of operations that change the folder view.
These operations include narrowing or threading.")

(defvar mh-folder-view-stack ()
  "Stack of previous folder views.")

(defvar mh-index-data nil
  "Info about index search results.")

(defvar mh-index-previous-search nil)
(defvar mh-index-msg-checksum-map nil)
(defvar mh-index-checksum-origin-map nil)
(defvar mh-index-sequence-search-flag nil)

(defvar mh-first-msg-num nil
  "Number of first message in buffer.")

(defvar mh-last-msg-num nil
  "Number of last msg in buffer.")

(defvar mh-mode-line-annotation nil
  "Message range displayed in buffer.")

(defvar mh-sequence-notation-history nil
  "Remember original notation that is overwritten by `mh-note-seq'.")

(defvar mh-colors-available-flag nil
  "Non-nil means colors are available.")



;;; Macros and generic functions:

(defun mh-mapc (function list)
  "Apply FUNCTION to each element of LIST for side effects only."
  (while list
    (funcall function (car list))
    (setq list (cdr list))))

(defun mh-scan-format ()
  "Return the output format argument for the scan program."
  (if (equal mh-scan-format-file t)
      (list "-format" (if (mh-variant-p 'nmh 'mu-mh)
                          (list (mh-update-scan-format
                                 mh-scan-format-nmh mh-cmd-note))
                        (list (mh-update-scan-format
                               mh-scan-format-mh mh-cmd-note))))
    (if (not (equal mh-scan-format-file nil))
        (list "-form" mh-scan-format-file))))



;;; Entry points:

;;;###autoload
(defun mh-rmail (&optional arg)
  "Incorporate new mail with MH.
Scan an MH folder if ARG is non-nil.

This function is an entry point to MH-E, the Emacs interface to
the MH mail system."
  (interactive "P")
  (mh-find-path)
  (if arg
      (call-interactively 'mh-visit-folder)
    (unless (get-buffer mh-inbox)
      (mh-visit-folder mh-inbox (symbol-name mh-unseen-seq)))
    (mh-inc-folder)))

;;;###autoload
(defun mh-nmail (&optional arg)
  "Check for new mail in inbox folder.
Scan an MH folder if ARG is non-nil.

This function is an entry point to MH-E, the Emacs interface to
the MH mail system."
  (interactive "P")
  (mh-find-path)                        ; init mh-inbox
  (if arg
      (call-interactively 'mh-visit-folder)
    (mh-visit-folder mh-inbox)))



;;; User executable MH-E commands:

(defun mh-delete-msg (range)
  "Delete RANGE\\<mh-folder-mode-map>.

To mark a message for deletion, use this command. A \"D\" is
placed by the message in the scan window, and the next undeleted
message is displayed. If the previous command had been
\\[mh-previous-undeleted-msg], then the next message displayed is
the first undeleted message previous to the message just deleted.
Use \\[mh-next-undeleted-msg] to force subsequent
\\[mh-delete-msg] commands to move forward to the next undeleted
message after deleting the message under the cursor.

The hook `mh-delete-msg-hook' is called after you mark a message
for deletion. For example, a past maintainer of MH-E used this
once when he kept statistics on his mail usage.

Check the documentation of `mh-interactive-range' to see how
RANGE is read in interactive use."
  (interactive (list (mh-interactive-range "Delete")))
  (mh-delete-msg-no-motion range)
  (if (looking-at mh-scan-deleted-msg-regexp)
      (mh-next-msg)))

(defun mh-delete-msg-no-motion (range)
  "Delete RANGE, don't move to next message.

This command marks the RANGE for deletion but leaves the cursor
at the current message in case you wish to perform other
operations on the message.

Check the documentation of `mh-interactive-range' to see how
RANGE is read in interactive use."
  (interactive (list (mh-interactive-range "Delete")))
  (mh-iterate-on-range () range
    (mh-delete-a-msg nil)))

(defun mh-execute-commands ()
  "Process outstanding delete and refile requests\\<mh-folder-mode-map>.

If you've marked messages to be deleted or refiled and you want
to go ahead and delete or refile the messages, use this command.
Many MH-E commands that may affect the numbering of the
messages (such as \\[mh-rescan-folder] or \\[mh-pack-folder])
will ask if you want to process refiles or deletes first and then
either run this command for you or undo the pending refiles and
deletes, which are lost.

This function runs `mh-before-commands-processed-hook' before the
commands are processed and `mh-after-commands-processed-hook'
after the commands are processed."
  (interactive)
  (if mh-folder-view-stack (mh-widen t))
  (mh-process-commands mh-current-folder)
  (mh-set-scan-mode)
  (mh-goto-cur-msg)                    ; after mh-set-scan-mode for efficiency
  (mh-make-folder-mode-line)
  t)                                    ; return t for write-file-functions

(defun mh-first-msg ()
  "Display first message."
  (interactive)
  (goto-char (point-min))
  (while (and (not (eobp)) (not (looking-at mh-scan-valid-regexp)))
    (forward-line 1)))

(defun mh-header-display ()
  "Display message with all header fields\\<mh-folder-mode-map>.

Use the command \\[mh-show] to show the message normally again."
  (interactive)
  (and (not mh-showing-with-headers)
       (or mh-mhl-format-file mh-clean-message-header-flag)
       (mh-invalidate-show-buffer))
  (let ((mh-decode-mime-flag nil)
        (mh-mhl-format-file nil)
        (mh-clean-message-header-flag nil))
    (mh-show-msg nil)
    (mh-in-show-buffer (mh-show-buffer)
      (goto-char (point-min))
      (mh-recenter 0))
    (setq mh-showing-with-headers t)))

(defun mh-inc-folder (&optional file folder)
  "Incorporate new mail into a folder.

You can incorporate mail from any file into the current folder by
specifying a prefix argument; you'll be prompted for the name of
the FILE to use as well as the destination FOLDER

The hook `mh-inc-folder-hook' is run after incorporating new
mail.

Do not call this function from outside MH-E; use \\[mh-rmail]
instead."
  (interactive (list (if current-prefix-arg
                         (expand-file-name
                          (read-file-name "inc mail from file: "
                                          mh-user-path)))
                     (if current-prefix-arg
                         (mh-prompt-for-folder "inc mail into" mh-inbox t))))
  (if (not folder)
      (setq folder mh-inbox))
  (let ((threading-needed-flag nil))
    (let ((config (current-window-configuration)))
      (when (and mh-show-buffer (get-buffer mh-show-buffer))
        (delete-windows-on mh-show-buffer))
      (cond ((not (get-buffer folder))
             (mh-make-folder folder)
             (setq threading-needed-flag mh-show-threads-flag)
             (setq mh-previous-window-config config))
            ((not (eq (current-buffer) (get-buffer folder)))
             (switch-to-buffer folder)
             (setq mh-previous-window-config config))))
    (mh-get-new-mail file)
    (when (and threading-needed-flag
               (save-excursion
                 (goto-char (point-min))
                 (or (null mh-large-folder)
                     (not (equal (forward-line (1+ mh-large-folder)) 0))
                     (and (message "Not threading since the number of messages exceeds `mh-large-folder'")
                          nil))))
      (mh-toggle-threads))
    (beginning-of-line)
    (if (and mh-showing-mode (looking-at mh-scan-valid-regexp)) (mh-show))
    (run-hooks 'mh-inc-folder-hook)))

(defun mh-last-msg ()
  "Display last message."
  (interactive)
  (goto-char (point-max))
  (while (and (not (bobp)) (not (looking-at mh-scan-valid-regexp)))
    (forward-line -1))
  (mh-recenter nil))

(defun mh-next-undeleted-msg (&optional count wait-after-complaining-flag)
  "Display next message.

This command can be given a prefix argument COUNT to specify how
many unread messages to skip.

In a program, pause for a second after printing message if we are
at the last undeleted message and optional argument
WAIT-AFTER-COMPLAINING-FLAG is non-nil."
  (interactive "p")
  (setq mh-next-direction 'forward)
  (forward-line 1)
  (cond ((re-search-forward mh-scan-good-msg-regexp nil t count)
         (beginning-of-line)
         (mh-maybe-show))
        (t (forward-line -1)
           (message "No more undeleted messages")
           (if wait-after-complaining-flag (sit-for 1)))))

(defun mh-folder-from-address ()
  "Derive folder name from sender.

The name of the folder is derived as follows:

  a) The folder name associated with the first address found in
     the list `mh-default-folder-list' is used. Each element in
     this list contains a \"Check Recipient\" item. If this item is
     turned on, then the address is checked against the recipient
     instead of the sender. This is useful for mailing lists.

  b) An alias prefixed by `mh-default-folder-prefix'
     corresponding to the address is used. The prefix is used to
     prevent clutter in your mail directory.

Return nil if a folder name was not derived, or if the variable
`mh-default-folder-must-exist-flag' is t and the folder does not
exist."
  ;; Loop for all entries in mh-default-folder-list
  (save-restriction
    (goto-char (point-min))
    (re-search-forward "\n\n" nil 'limit)
    (narrow-to-region (point-min) (point))
    (let ((to/cc (concat (or (message-fetch-field "to") "") ", "
                         (or (message-fetch-field "cc") "")))
          (from (or (message-fetch-field "from") ""))
          folder-name)
      (setq folder-name
            (loop for list in mh-default-folder-list
                  when (string-match (nth 0 list) (if (nth 2 list) to/cc from))
                  return (nth 1 list)
                  finally return nil))

      ;; Make sure a result from `mh-default-folder-list' begins with "+"
      ;; since 'mh-expand-file-name below depends on it
      (when (and folder-name (not (eq (aref folder-name 0) ?+)))
        (setq folder-name (concat "+" folder-name)))

      ;; If not, is there an alias for the address?
      (when (not folder-name)
        (let* ((from-header (mh-extract-from-header-value))
               (address (and from-header
                             (nth 1 (mail-extract-address-components
                                     from-header))))
               (alias (and address (mh-alias-address-to-alias address))))
          (when alias
            (setq folder-name
                  (and alias (concat "+" mh-default-folder-prefix alias))))))

      ;; If mh-default-folder-must-exist-flag set, check that folder exists.
      (if (and folder-name
               (or (not mh-default-folder-must-exist-flag)
                   (file-exists-p (mh-expand-file-name folder-name))))
          folder-name))))

(defun mh-prompt-for-refile-folder ()
  "Prompt the user for a folder in which the message should be filed.
The folder is returned as a string.

The default folder name is generated by the option
`mh-default-folder-for-message-function' if it is non-nil or
`mh-folder-from-address'."
  (mh-prompt-for-folder
   "Destination"
   (let ((refile-file (ignore-errors (mh-msg-filename (mh-get-msg-num t)))))
     (if (null refile-file) ""
       (save-excursion
         (set-buffer (get-buffer-create mh-temp-buffer))
         (erase-buffer)
         (insert-file-contents refile-file)
         (or (and mh-default-folder-for-message-function
                  (let ((buffer-file-name refile-file))
                    (funcall mh-default-folder-for-message-function)))
             (mh-folder-from-address)
             (and (eq 'refile (car mh-last-destination-folder))
                  (symbol-name (cdr mh-last-destination-folder)))
             ""))))
   t))

(defun mh-refile-msg (range folder &optional dont-update-last-destination-flag)
  "Refile (output) RANGE into FOLDER.

You are prompted for the folder name. Note that this command can also
be used to create folders. If you specify a folder that does not
exist, you will be prompted to create it.

The hook `mh-refile-msg-hook' is called after a message is marked to
be refiled.

Check the documentation of `mh-interactive-range' to see how RANGE is
read in interactive use.

In a program, the variables `mh-last-destination' and
`mh-last-destination-folder' are not updated if
DONT-UPDATE-LAST-DESTINATION-FLAG is non-nil."
  (interactive (list (mh-interactive-range "Refile")
                     (intern (mh-prompt-for-refile-folder))))
  (unless dont-update-last-destination-flag
    (setq mh-last-destination (cons 'refile folder)
          mh-last-destination-folder mh-last-destination))
  (mh-iterate-on-range () range
    (mh-refile-a-msg nil folder))
  (when (looking-at mh-scan-refiled-msg-regexp) (mh-next-msg)))

(defun mh-refile-or-write-again (range &optional interactive-flag)
  "Repeat last output command.

If you are refiling several messages into the same folder, you
can use this command to repeat the last
refile (\\[mh-refile-msg]) or write (\\[mh-write-msg-to-file]).
You can use a range.

Check the documentation of `mh-interactive-range' to see how RANGE is
read in interactive use.

In a program, a non-nil INTERACTIVE-FLAG means that the function was
called interactively."
  (interactive (list (mh-interactive-range "Redo") t))
  (if (null mh-last-destination)
      (error "No previous refile or write"))
  (cond ((eq (car mh-last-destination) 'refile)
         (mh-refile-msg range (cdr mh-last-destination))
         (message "Destination folder: %s" (cdr mh-last-destination)))
        (t
         (mh-iterate-on-range msg range
           (apply 'mh-write-msg-to-file msg (cdr mh-last-destination)))
         (mh-next-msg interactive-flag))))

(defun mh-quit ()
  "Quit the current MH-E folder.

When you want to quit using MH-E and go back to editing, you can use
this command. This buries the buffers of the current MH-E folder and
restores the buffers that were present when you first ran
\\[mh-rmail]. It also removes any MH-E working buffers whose name
begins with \" *mh-\" or \"*MH-E \". You can later restore your MH-E
session by selecting the \"+inbox\" buffer or by running \\[mh-rmail]
again.

The two hooks `mh-before-quit-hook' and `mh-quit-hook' are called by
this function. The former one is called before the quit occurs, so you
might use it to perform any MH-E operations; you could perform some
query and abort the quit or call `mh-execute-commands', for example.
The latter is not run in an MH-E context, so you might use it to
modify the window setup."
  (interactive)
  (run-hooks 'mh-before-quit-hook)
  (let ((show-buffer (get-buffer mh-show-buffer)))
    (when show-buffer
      (kill-buffer show-buffer)))
  (mh-update-sequences)
  (mh-destroy-postponed-handles)
  (bury-buffer (current-buffer))

  ;; Delete all MH-E temporary and working buffers.
  (dolist (buffer (buffer-list))
    (when (or (string-match "^ \\*mh-" (buffer-name buffer))
              (string-match "^\\*MH-E " (buffer-name buffer)))
      (kill-buffer buffer)))

  (if mh-previous-window-config
      (set-window-configuration mh-previous-window-config))
  (run-hooks 'mh-quit-hook))

(defun mh-page-msg (&optional lines)
  "Display next page in message.

You can give this command a prefix argument that specifies the
number of LINES to scroll. This command will also show the next
undeleted message if it is used at the bottom of a message."
  (interactive "P")
  (if mh-showing-mode
      (if mh-page-to-next-msg-flag
          (if (equal mh-next-direction 'backward)
              (mh-previous-undeleted-msg)
            (mh-next-undeleted-msg))
        (if (mh-in-show-buffer (mh-show-buffer)
              (pos-visible-in-window-p (point-max)))
            (progn
              (message
               "End of message (Type %s to read %s undeleted message)"
               (single-key-description last-input-event)
               (if (equal mh-next-direction 'backward)
                   "previous"
                 "next"))
              (setq mh-page-to-next-msg-flag t))
          (scroll-other-window lines)))
    (mh-show)))

(defun mh-previous-page (&optional lines)
  "Display next page in message.

You can give this command a prefix argument that specifies the
number of LINES to scroll."
  (interactive "P")
  (mh-in-show-buffer (mh-show-buffer)
    (scroll-down lines)))

(defun mh-previous-undeleted-msg (&optional count wait-after-complaining-flag)
  "Display previous message.

This command can be given a prefix argument COUNT to specify how
many unread messages to skip.

In a program, pause for a second after printing message if we are
at the last undeleted message and optional argument
WAIT-AFTER-COMPLAINING-FLAG is non-nil."
  (interactive "p")
  (setq mh-next-direction 'backward)
  (beginning-of-line)
  (cond ((re-search-backward mh-scan-good-msg-regexp nil t count)
         (mh-maybe-show))
        (t (message "No previous undeleted message")
           (if wait-after-complaining-flag (sit-for 1)))))

(defun mh-previous-unread-msg (&optional count)
  "Display previous unread message.

This command can be given a prefix argument COUNT to specify how
many unread messages to skip."
  (interactive "p")
  (unless (> count 0)
    (error "The function `mh-previous-unread-msg' expects positive argument"))
  (setq count (1- count))
  (let ((unread-sequence (cdr (assoc mh-unseen-seq mh-seq-list)))
        (cur-msg (mh-get-msg-num nil)))
    (cond ((and (not cur-msg) (not (bobp))
                ;; If we are at the end of the buffer back up one line and go
                ;; to unread message after that.
                (progn
                  (forward-line -1)
                  (setq cur-msg (mh-get-msg-num nil)))
                nil))
          ((or (null unread-sequence) (not cur-msg))
           ;; No unread message or there aren't any messages in buffer...
           (message "No more unread messages"))
          ((progn
             ;; Skip count messages...
             (while (and unread-sequence (>= (car unread-sequence) cur-msg))
               (setq unread-sequence (cdr unread-sequence)))
             (while (> count 0)
               (setq unread-sequence (cdr unread-sequence))
               (setq count (1- count)))
             (not (car unread-sequence)))
           (message "No more unread messages"))
          (t (loop for msg in unread-sequence
                   when (mh-goto-msg msg t) return nil
                   finally (message "No more unread messages"))))))

(defun mh-goto-next-button (backward-flag &optional criterion)
  "Search for next button satisfying criterion.

If BACKWARD-FLAG is non-nil search backward in the buffer for a mime
button.
If CRITERION is a function or a symbol which has a function binding
then that function must return non-nil at the button we stop."
  (unless (or (and (symbolp criterion) (fboundp criterion))
              (functionp criterion))
    (setq criterion (lambda (x) t)))
  ;; Move to the next button in the buffer satisfying criterion
  (goto-char (or (save-excursion
                   (beginning-of-line)
                   ;; Find point before current button
                   (let ((point-before-current-button
                          (save-excursion
                            (while (get-text-property (point) 'mh-data)
                              (unless (= (forward-line
                                          (if backward-flag 1 -1))
                                         0)
                                (if backward-flag
                                    (goto-char (point-min))
                                  (goto-char (point-max)))))
                            (point))))
                     ;; Skip over current button
                     (while (and (get-text-property (point) 'mh-data)
                                 (not (if backward-flag (bobp) (eobp))))
                       (forward-line (if backward-flag -1 1)))
                     ;; Stop at next MIME button if any exists.
                     (block loop
                       (while (/= (progn
                                    (unless (= (forward-line
                                                (if backward-flag -1 1))
                                               0)
                                      (if backward-flag
                                          (goto-char (point-max))
                                        (goto-char (point-min)))
                                      (beginning-of-line))
                                    (point))
                                  point-before-current-button)
                         (when (and (get-text-property (point) 'mh-data)
                                    (funcall criterion (point)))
                           (return-from loop (point))))
                       nil)))
                 (point))))

(defun mh-next-button (&optional backward-flag)
  "Go to the next button.

If the end of the buffer is reached then the search wraps over to
the start of the buffer.

If an optional prefix argument BACKWARD-FLAG is given, the cursor
will move to the previous button."
  (interactive (list current-prefix-arg))
  (unless mh-showing-mode
    (mh-show))
  (mh-in-show-buffer (mh-show-buffer)
    (mh-goto-next-button backward-flag)))

(defun mh-prev-button ()
  "Go to the previous button.

If the beginning of the buffer is reached then the search wraps
over to the end of the buffer."
  (interactive)
  (mh-next-button t))

(defun mh-folder-mime-action (part-index action include-security-flag)
  "Go to PART-INDEX and carry out ACTION.

If PART-INDEX is nil then go to the next part in the buffer. The
search for the next buffer wraps around if end of buffer is reached.
If argument INCLUDE-SECURITY-FLAG is non-nil then include security
info buttons when searching for a suitable parts."
  (unless mh-showing-mode
    (mh-show))
  (mh-in-show-buffer (mh-show-buffer)
    (let ((criterion
           (cond (part-index
                  (lambda (p)
                    (let ((part (get-text-property p 'mh-part)))
                      (and (integerp part) (= part part-index)))))
                 (t (lambda (p)
                      (if include-security-flag
                          (get-text-property p 'mh-data)
                        (integerp (get-text-property p 'mh-part)))))))
          (point (point)))
      (cond ((and (get-text-property point 'mh-part)
                  (or (null part-index)
                      (= (get-text-property point 'mh-part) part-index)))
             (funcall action))
            ((and (get-text-property point 'mh-data)
                  include-security-flag
                  (null part-index))
             (funcall action))
            (t
             (mh-goto-next-button nil criterion)
             (if (= (point) point)
                 (message "No matching MIME part found")
               (funcall action)))))))

(defun mh-folder-toggle-mime-part (part-index)
  "View attachment.

This command displays (or hides) the attachment associated with
the button under the cursor. If the cursor is not located over a
button, then the cursor first moves to the next button, wrapping
to the beginning of the message if necessary. This command has
the advantage over related commands of working from the MH-Folder
buffer.

You can also provide a numeric prefix argument PART-INDEX to view
the attachment labeled with that number. If Emacs does not know
how to display the attachment, then Emacs offers to save the
attachment in a file."
  (interactive "P")
  (when (consp part-index) (setq part-index (car part-index)))
  (mh-folder-mime-action part-index #'mh-press-button t))

(defun mh-folder-inline-mime-part (part-index)
  "Show attachment verbatim.

You can view the raw contents of an attachment with this command.
This command displays (or hides) the contents of the attachment
associated with the button under the cursor verbatim. If the
cursor is not located over a button, then the cursor first moves
to the next button, wrapping to the beginning of the message if
necessary.

You can also provide a numeric prefix argument PART-INDEX to view
the attachment labeled with that number."
  (interactive "P")
  (when (consp part-index) (setq part-index (car part-index)))
  (mh-folder-mime-action part-index #'mh-mime-inline-part nil))

(defun mh-folder-save-mime-part (part-index)
  "Save (output) attachment.

This command saves the attachment associated with the button under the
cursor. If the cursor is not located over a button, then the cursor
first moves to the next button, wrapping to the beginning of the
message if necessary.

You can also provide a numeric prefix argument PART-INDEX to save the
attachment labeled with that number.

This command prompts you for a filename and suggests a specific name
if it is available."
  (interactive "P")
  (when (consp part-index) (setq part-index (car part-index)))
  (mh-folder-mime-action part-index #'mh-mime-save-part nil))

(defun mh-reset-threads-and-narrowing ()
  "Reset all variables pertaining to threads and narrowing.
Also removes all content from the folder buffer."
  (setq mh-view-ops ())
  (setq mh-folder-view-stack ())
  (setq mh-thread-scan-line-map-stack ())
  (let ((buffer-read-only nil)) (erase-buffer)))

(defun mh-rescan-folder (&optional range dont-exec-pending)
  "Rescan folder\\<mh-folder-mode-map>.

This command is useful to grab all messages in your \"+inbox\" after
processing your new mail for the first time. If you don't want to
rescan the entire folder, this command will accept a RANGE. Check the
documentation of `mh-interactive-range' to see how RANGE is read in
interactive use.

This command will ask if you want to process refiles or deletes first
and then either run \\[mh-execute-commands] for you or undo the
pending refiles and deletes, which are lost.

In a program, the processing of outstanding commands is not performed
if DONT-EXEC-PENDING is non-nil."
  (interactive (list (if current-prefix-arg
                         (mh-read-range "Rescan" mh-current-folder t nil t
                                        mh-interpret-number-as-range-flag)
                       nil)))
  (setq mh-next-direction 'forward)
  (let ((threaded-flag (memq 'unthread mh-view-ops)))
    (mh-scan-folder mh-current-folder (or range "all") dont-exec-pending)
    (cond (threaded-flag (mh-toggle-threads))
          (mh-index-data (mh-index-insert-folder-headers)))))

(defun mh-write-msg-to-file (message file no-header)
  "Append MESSAGE to end of FILE\\<mh-folder-mode-map>.

You are prompted for the filename. If the file already exists,
the message is appended to it. You can also write the message to
the file without the header by specifying a prefix argument
NO-HEADER. Subsequent writes to the same file can be made with
the command \\[mh-refile-or-write-again]."
  (interactive
   (list (mh-get-msg-num t)
         (let ((default-dir (if (eq 'write (car mh-last-destination-write))
                                (file-name-directory
                                 (car (cdr mh-last-destination-write)))
                              default-directory)))
           (read-file-name (format "Save message%s in file: "
                                   (if current-prefix-arg " body" ""))
                           default-dir
                           (if (eq 'write (car mh-last-destination-write))
                               (car (cdr mh-last-destination-write))
                             (expand-file-name "mail.out" default-dir))))
         current-prefix-arg))
  (let ((msg-file-to-output (mh-msg-filename message))
        (output-file (mh-expand-file-name file)))
    (setq mh-last-destination (list 'write file (if no-header 'no-header))
          mh-last-destination-write mh-last-destination)
    (save-excursion
      (set-buffer (get-buffer-create mh-temp-buffer))
      (erase-buffer)
      (insert-file-contents msg-file-to-output)
      (goto-char (point-min))
      (if no-header (search-forward "\n\n"))
      (append-to-file (point) (point-max) output-file))))

(defun mh-toggle-showing ()
  "Toggle between MH-Folder and MH-Folder Show modes.

This command switches between MH-Folder mode and MH-Folder Show
mode. MH-Folder mode turns off the associated show buffer so that
you can perform operations on the messages quickly without
reading them. This is an excellent way to prune out your junk
mail or to refile a group of messages to another folder for later
examination."
  (interactive)
  (if mh-showing-mode
      (mh-set-scan-mode)
    (mh-show)))

(defun mh-undo (range)
  "Undo pending deletes or refiles in RANGE.

If you've deleted a message or refiled it, but changed your mind,
you can cancel the action before you've executed it. Use this
command to undo a refile on or deletion of a single message. You
can also undo refiles and deletes for messages that are found in
a given RANGE.

Check the documentation of `mh-interactive-range' to see how
RANGE is read in interactive use."
  (interactive (list (mh-interactive-range "Undo")))
  (cond ((numberp range)
         (let ((original-position (point)))
           (beginning-of-line)
           (while (not (or (looking-at mh-scan-deleted-msg-regexp)
                           (looking-at mh-scan-refiled-msg-regexp)
                           (and (eq mh-next-direction 'forward) (bobp))
                           (and (eq mh-next-direction 'backward)
                                (save-excursion (forward-line) (eobp)))))
             (forward-line (if (eq mh-next-direction 'forward) -1 1)))
           (if (or (looking-at mh-scan-deleted-msg-regexp)
                   (looking-at mh-scan-refiled-msg-regexp))
               (progn
                 (mh-undo-msg (mh-get-msg-num t))
                 (mh-maybe-show))
             (goto-char original-position)
             (error "Nothing to undo"))))
        (t (mh-iterate-on-range () range
             (mh-undo-msg nil))))
  (if (not (mh-outstanding-commands-p))
      (mh-set-folder-modified-p nil)))


(defun mh-folder-line-matches-show-buffer-p ()
  "Return t if the message under point in folder-mode is in the show buffer.
Return nil in any other circumstance (no message under point, no
show buffer, the message in the show buffer doesn't match."
  (and (eq major-mode 'mh-folder-mode)
       (mh-get-msg-num nil)
       mh-show-buffer
       (get-buffer mh-show-buffer)
       (buffer-file-name (get-buffer mh-show-buffer))
       (string-match ".*/\\([0-9]+\\)$"
                     (buffer-file-name (get-buffer mh-show-buffer)))
       (string-equal
        (match-string 1 (buffer-file-name (get-buffer mh-show-buffer)))
        (int-to-string (mh-get-msg-num nil)))))

(eval-when-compile (require 'gnus))

(defmacro mh-macro-expansion-time-gnus-version ()
  "Return Gnus version available at macro expansion time.
The macro evaluates the Gnus version at macro expansion time. If
MH-E was compiled then macro expansion happens at compile time."
gnus-version)

(defun mh-run-time-gnus-version ()
  "Return Gnus version available at run time."
  (require 'gnus)
  gnus-version)

;;;###autoload
(defun mh-version ()
  "Display version information about MH-E and the MH mail handling system."
  (interactive)
  (set-buffer (get-buffer-create mh-info-buffer))
  (erase-buffer)
  ;; MH-E version.
  (insert "MH-E " mh-version "\n\n")
  ;; MH-E compilation details.
  (insert "MH-E compilation details:\n")
  (let* ((compiled-mhe (byte-code-function-p (symbol-function 'mh-version)))
         (gnus-compiled-version (if compiled-mhe
                                    (mh-macro-expansion-time-gnus-version)
                                  "N/A")))
    (insert " Byte compiled:\t\t" (if compiled-mhe "yes" "no") "\n"
            " Gnus (compile-time):\t" gnus-compiled-version "\n"
            " Gnus (run-time):\t" (mh-run-time-gnus-version) "\n\n"))
  ;; Emacs version.
  (insert (emacs-version) "\n\n")
  ;; MH version.
  (if mh-variant-in-use
      (insert mh-variant-in-use "\n"
              " mh-progs:\t" mh-progs "\n"
              " mh-lib:\t" mh-lib "\n"
              " mh-lib-progs:\t" mh-lib-progs "\n\n")
    (insert "No MH variant detected\n"))
  ;; Linux version.
  (condition-case ()
      (call-process "uname" nil t nil "-a")
    (file-error))
  (goto-char (point-min))
  (display-buffer mh-info-buffer))

(defun mh-parse-flist-output-line (line &optional current-folder)
  "Parse LINE to generate folder name, unseen messages and total messages.
If CURRENT-FOLDER is non-nil then it contains the current folder
name and it is used to avoid problems in corner cases involving
folders whose names end with a '+' character."
  (with-temp-buffer
    (insert line)
    (goto-char (point-max))
    (let (folder unseen total p)
      (when (search-backward " out of " (point-min) t)
        (setq total (read-from-string
                     (buffer-substring-no-properties
                      (match-end 0) (line-end-position))))
        (when (search-backward " in sequence " (point-min) t)
          (setq p (point))
          (when (search-backward " has " (point-min) t)
            (setq unseen (read-from-string (buffer-substring-no-properties
                                            (match-end 0) p)))
            (while (eq (char-after) ? )
              (backward-char))
            (setq folder (buffer-substring-no-properties
                          (point-min) (1+ (point))))
            (when (and (equal (aref folder (1- (length folder))) ?+)
                       (equal current-folder folder))
              (setq folder (substring folder 0 (1- (length folder)))))
            (values (format "+%s" folder) (car unseen) (car total))))))))

(defun mh-folder-size-folder (folder)
  "Find size of FOLDER using \"folder\"."
  (with-temp-buffer
    (let ((u (length (cdr (assoc mh-unseen-seq
                                 (mh-read-folder-sequences folder nil))))))
      (call-process (expand-file-name "folder" mh-progs) nil t nil
                    "-norecurse" folder)
      (goto-char (point-min))
      (if (re-search-forward " has \\([0-9]+\\) " nil t)
          (values (car (read-from-string (match-string 1))) u folder)
        (values 0 u folder)))))

(defun mh-folder-size-flist (folder)
  "Find size of FOLDER using \"flist\"."
  (with-temp-buffer
    (call-process (expand-file-name "flist" mh-progs) nil t nil "-showzero"
                  "-norecurse" folder "-sequence" (symbol-name mh-unseen-seq))
    (goto-char (point-min))
    (multiple-value-bind (folder unseen total)
        (mh-parse-flist-output-line
         (buffer-substring (point) (line-end-position)))
      (values total unseen folder))))

(defun mh-folder-size (folder)
  "Find size of FOLDER."
  (if mh-flists-present-flag
      (mh-folder-size-flist folder)
    (mh-folder-size-folder folder)))

(defun mh-visit-folder (folder &optional range index-data)
  "Visit FOLDER.

When you want to read the messages that you have refiled into folders,
use this command to visit the folder. You are prompted for the folder
name.

The folder buffer will show just unseen messages if there are any;
otherwise, it will show all the messages in the buffer as long there
are fewer than `mh-large-folder' messages. If there are more, then you
are prompted for a range of messages to scan.

You can provide a prefix argument in order to specify a RANGE of
messages to show when you visit the folder. In this case, regions are
not used to specify the range and `mh-large-folder' is ignored. Check
the documentation of `mh-interactive-range' to see how RANGE is read
in interactive use.

Note that this command can also be used to create folders. If you
specify a folder that does not exist, you will be prompted to create
it.

Do not call this function from outside MH-E; use \\[mh-rmail] instead.

If, in a program, RANGE is nil (the default), then all messages in
FOLDER are displayed. If an index buffer is being created then
INDEX-DATA is used to initialize the index buffer specific data
structures."
  (interactive (let ((folder-name (mh-prompt-for-folder "Visit" mh-inbox t)))
                 (list folder-name
                       (mh-read-range "Scan" folder-name t nil
                                      current-prefix-arg
                                      mh-interpret-number-as-range-flag))))
  (let ((config (current-window-configuration))
        (current-buffer (current-buffer))
        (threaded-view-flag mh-show-threads-flag))
    (delete-other-windows)
    (save-excursion
      (when (get-buffer folder)
        (set-buffer folder)
        (setq threaded-view-flag (memq 'unthread mh-view-ops))))
    (when index-data
      (mh-make-folder folder)
      (setq mh-index-data (car index-data)
            mh-index-msg-checksum-map (make-hash-table :test #'equal)
            mh-index-checksum-origin-map (make-hash-table :test #'equal))
      (mh-index-update-maps folder (cadr index-data))
      (mh-index-create-sequences))
    (mh-scan-folder folder (or range "all"))
    (cond ((and threaded-view-flag
                (save-excursion
                  (goto-char (point-min))
                  (or (null mh-large-folder)
                      (not (equal (forward-line (1+ mh-large-folder)) 0))
                      (and (message "Not threading since the number of messages exceeds `mh-large-folder'")
                           nil))))
           (mh-toggle-threads))
          (mh-index-data
           (mh-index-insert-folder-headers)))
    (unless (eq current-buffer (current-buffer))
      (setq mh-previous-window-config config)))
  nil)


(defun mh-update-sequences ()
  "Flush MH-E's state out to MH.

This function updates the sequence specified by your
\"Unseen-Sequence:\" profile component, \"cur\", and the sequence
listed by the `mh-tick-seq' option which is \"tick\" by default.
The message at the cursor is used for \"cur\"."
  (interactive)
  ;; mh-update-sequences is the opposite of mh-read-folder-sequences,
  ;; which updates MH-E's state from MH.
  (let ((folder-set (mh-update-unseen))
        (new-cur (mh-get-msg-num nil)))
    (if new-cur
        (let ((seq-entry (mh-find-seq 'cur)))
          (mh-remove-cur-notation)
          (setcdr seq-entry
                  (list new-cur))       ;delete-seq-locally, add-msgs-to-seq
          (mh-define-sequence 'cur (list new-cur))
          (beginning-of-line)
          (if (looking-at mh-scan-good-msg-regexp)
              (mh-notate-cur)))
      (or folder-set
          (save-excursion
            ;; psg - mh-current-folder is nil if mh-summary-height < 4 !
            ;;       So I added this sanity check.
            (if (stringp mh-current-folder)
                (mh-exec-cmd-quiet t "folder" mh-current-folder "-fast")
              (mh-exec-cmd-quiet t "folder" "-fast")))))))



;;; Support routines.

(defun mh-delete-a-msg (message)
  "Delete MESSAGE.
If MESSAGE is nil then the message at point is deleted.
The hook `mh-delete-msg-hook' is called after you mark a message
for deletion. For example, a past maintainer of MH-E used this
once when he kept statistics on his mail usage."
  (save-excursion
    (if (numberp message)
        (mh-goto-msg message nil t)
      (beginning-of-line)
      (setq message (mh-get-msg-num t)))
    (if (looking-at mh-scan-refiled-msg-regexp)
        (error "Message %d is refiled; undo refile before deleting" message))
    (if (looking-at mh-scan-deleted-msg-regexp)
        nil
      (mh-set-folder-modified-p t)
      (setq mh-delete-list (cons message mh-delete-list))
      (mh-notate nil mh-note-deleted mh-cmd-note)
      (run-hooks 'mh-delete-msg-hook))))

(defun mh-refile-a-msg (message folder)
  "Refile MESSAGE in FOLDER.
If MESSAGE is nil then the message at point is refiled.
Folder is a symbol, not a string.
The hook `mh-refile-msg-hook' is called after a message is marked to
be refiled."
  (save-excursion
    (if (numberp message)
        (mh-goto-msg message nil t)
      (beginning-of-line)
      (setq message (mh-get-msg-num t)))
    (cond ((looking-at mh-scan-deleted-msg-regexp)
           (error "Message %d is deleted; undo delete before moving" message))
          ((looking-at mh-scan-refiled-msg-regexp)
           (if (y-or-n-p
                (format "Message %d already refiled; copy to %s as well? "
                        message folder))
               (mh-exec-cmd "refile" (mh-get-msg-num t) "-link"
                            "-src" mh-current-folder
                            (symbol-name folder))
             (message "Message not copied")))
          (t
           (mh-set-folder-modified-p t)
           (cond ((null (assoc folder mh-refile-list))
                  (push (list folder message) mh-refile-list))
                 ((not (member message (cdr (assoc folder mh-refile-list))))
                  (push message (cdr (assoc folder mh-refile-list)))))
           (mh-notate nil mh-note-refiled mh-cmd-note)
           (run-hooks 'mh-refile-msg-hook)))))

(defun mh-next-msg (&optional wait-after-complaining-flag)
  "Move backward or forward to the next undeleted message in the buffer.
If optional argument WAIT-AFTER-COMPLAINING-FLAG is non-nil and
we are at the last message, then wait for a second after telling
the user that there aren't any more unread messages."
  (if (eq mh-next-direction 'forward)
      (mh-next-undeleted-msg 1 wait-after-complaining-flag)
    (mh-previous-undeleted-msg 1 wait-after-complaining-flag)))

(defun mh-next-unread-msg (&optional count)
  "Display next unread message.

This command can be given a prefix argument COUNT to specify how
many unread messages to skip."
  (interactive "p")
  (unless (> count 0)
    (error "The function `mh-next-unread-msg' expects positive argument"))
  (setq count (1- count))
  (let ((unread-sequence (reverse (cdr (assoc mh-unseen-seq mh-seq-list))))
        (cur-msg (mh-get-msg-num nil)))
    (cond ((and (not cur-msg) (not (bobp))
                ;; If we are at the end of the buffer back up one line and go
                ;; to unread message after that.
                (progn
                  (forward-line -1)
                  (setq cur-msg (mh-get-msg-num nil)))
                nil))
          ((or (null unread-sequence) (not cur-msg))
           ;; No unread message or there aren't any messages in buffer...
           (message "No more unread messages"))
          ((progn
             ;; Skip messages
             (while (and unread-sequence (>= cur-msg (car unread-sequence)))
               (setq unread-sequence (cdr unread-sequence)))
             (while (> count 0)
               (setq unread-sequence (cdr unread-sequence))
               (setq count (1- count)))
             (not (car unread-sequence)))
           (message "No more unread messages"))
          (t (loop for msg in unread-sequence
                   when (mh-goto-msg msg t) return nil
                   finally (message "No more unread messages"))))))

(defun mh-set-scan-mode ()
  "Display the scan listing buffer, but do not show a message."
  (if (get-buffer mh-show-buffer)
      (delete-windows-on mh-show-buffer))
  (mh-showing-mode 0)
  (force-mode-line-update)
  (if mh-recenter-summary-flag
      (mh-recenter nil)))

(defun mh-undo-msg (msg)
  "Undo the deletion or refile of one MSG.
If MSG is nil then act on the message at point"
  (save-excursion
    (if (numberp msg)
        (mh-goto-msg msg t t)
      (beginning-of-line)
      (setq msg (mh-get-msg-num t)))
    (cond ((memq msg mh-delete-list)
           (setq mh-delete-list (delq msg mh-delete-list)))
          (t
           (dolist (folder-msg-list mh-refile-list)
             (setf (cdr folder-msg-list) (remove msg (cdr folder-msg-list))))
           (setq mh-refile-list (loop for x in mh-refile-list
                                      unless (null (cdr x)) collect x))))
    (mh-notate nil ?  mh-cmd-note)))



;;; The folder data abstraction.

(defvar mh-index-data-file ".mhe_index"
  "MH-E specific file where index seach info is stored.")

(defun mh-make-folder (name)
  "Create a new mail folder called NAME.
Make it the current folder."
  (switch-to-buffer name)
  (setq buffer-read-only nil)
  (erase-buffer)
  (if mh-adaptive-cmd-note-flag
      (mh-set-cmd-note (mh-msg-num-width-to-column (mh-msg-num-width name))))
  (setq buffer-read-only t)
  (mh-folder-mode)
  (mh-set-folder-modified-p nil)
  (setq buffer-file-name mh-folder-filename)
  (when (and (not mh-index-data)
             (file-exists-p (concat buffer-file-name mh-index-data-file)))
    (mh-index-read-data))
  (mh-make-folder-mode-line))

;; Ensure new buffers won't get this mode if default-major-mode is nil.
(put 'mh-folder-mode 'mode-class 'special)



;;; Build mh-folder-mode menu

;; Menu extracted from mh-menubar.el V1.1 (31 July 2001)
;; Menus for folder mode: folder, message, sequence (in that order)
;; folder-mode "Sequence" menu
(easy-menu-define
  mh-folder-sequence-menu mh-folder-mode-map "Menu for MH-E folder-sequence."
  '("Sequence"
    ["Add Message to Sequence..."       mh-put-msg-in-seq (mh-get-msg-num nil)]
    ["List Sequences for Message"       mh-msg-is-in-seq (mh-get-msg-num nil)]
    ["Delete Message from Sequence..."  mh-delete-msg-from-seq
     (mh-get-msg-num nil)]
    ["List Sequences in Folder..."      mh-list-sequences t]
    ["Delete Sequence..."               mh-delete-seq t]
    ["Narrow to Sequence..."            mh-narrow-to-seq t]
    ["Widen from Sequence"              mh-widen mh-folder-view-stack]
    "--"
    ["Narrow to Subject Sequence"       mh-narrow-to-subject t]
    ["Narrow to Tick Sequence"          mh-narrow-to-tick
     (and mh-tick-seq (mh-seq-msgs (mh-find-seq mh-tick-seq)))]
    ["Delete Rest of Same Subject"      mh-delete-subject t]
    ["Toggle Tick Mark"                 mh-toggle-tick t]
    "--"
    ["Push State Out to MH"             mh-update-sequences t]))

;; folder-mode "Message" menu
(easy-menu-define
  mh-folder-message-menu mh-folder-mode-map "Menu for MH-E folder-message."
  '("Message"
    ["Show Message"                     mh-show (mh-get-msg-num nil)]
    ["Show Message with Header"         mh-header-display (mh-get-msg-num nil)]
    ["Next Message"                     mh-next-undeleted-msg t]
    ["Previous Message"                 mh-previous-undeleted-msg t]
    ["Go to First Message"              mh-first-msg t]
    ["Go to Last Message"               mh-last-msg t]
    ["Go to Message by Number..."       mh-goto-msg t]
    ["Modify Message"                   mh-modify t]
    ["Delete Message"                   mh-delete-msg (mh-get-msg-num nil)]
    ["Refile Message"                   mh-refile-msg (mh-get-msg-num nil)]
    ["Undo Delete/Refile"               mh-undo (mh-outstanding-commands-p)]
    ["Execute Delete/Refile"            mh-execute-commands
     (mh-outstanding-commands-p)]
    "--"
    ["Compose a New Message"            mh-send t]
    ["Reply to Message..."              mh-reply (mh-get-msg-num nil)]
    ["Forward Message..."               mh-forward (mh-get-msg-num nil)]
    ["Redistribute Message..."          mh-redistribute (mh-get-msg-num nil)]
    ["Edit Message Again"               mh-edit-again (mh-get-msg-num nil)]
    ["Re-edit a Bounced Message"        mh-extract-rejected-mail t]
    "--"
    ["Copy Message to Folder..."        mh-copy-msg (mh-get-msg-num nil)]
    ["Print Message"                    mh-print-msg (mh-get-msg-num nil)]
    ["Write Message to File..."         mh-write-msg-to-file
     (mh-get-msg-num nil)]
    ["Pipe Message to Command..."       mh-pipe-msg (mh-get-msg-num nil)]
    ["Unpack Uuencoded Message..."      mh-store-msg (mh-get-msg-num nil)]
    ["Burst Digest Message"             mh-burst-digest (mh-get-msg-num nil)]))

;; folder-mode "Folder" menu
(easy-menu-define
  mh-folder-folder-menu mh-folder-mode-map  "Menu for MH-E folder."
  '("Folder"
    ["Incorporate New Mail"             mh-inc-folder t]
    ["Toggle Show/Folder"               mh-toggle-showing t]
    ["Execute Delete/Refile"            mh-execute-commands
     (mh-outstanding-commands-p)]
    ["Rescan Folder"                    mh-rescan-folder t]
    ["Thread Folder"                    mh-toggle-threads
     (not (memq 'unthread mh-view-ops))]
    ["Pack Folder"                      mh-pack-folder t]
    ["Sort Folder"                      mh-sort-folder t]
    "--"
    ["List Folders"                     mh-list-folders t]
    ["Visit a Folder..."                mh-visit-folder t]
    ["View New Messages"                mh-index-new-messages t]
    ["Search a Folder..."               mh-search-folder t]
    ["Indexed Search..."                mh-index-search t]
    "--"
    ["Quit MH-E"                        mh-quit t]))



(defmacro mh-remove-xemacs-horizontal-scrollbar ()
  "Get rid of the horizontal scrollbar that XEmacs insists on putting in."
  (when mh-xemacs-flag
    `(if (and (featurep 'scrollbar)
              (fboundp 'set-specifier))
         (set-specifier horizontal-scrollbar-visible-p nil
                        (cons (current-buffer) nil)))))

(defmacro mh-write-file-functions-compat ()
  "Return `write-file-functions' if it exists.
Otherwise return `local-write-file-hooks'. This macro exists
purely for compatibility. The former symbol is used in Emacs 21.4
onward while the latter is used in previous versions and XEmacs."
  (if (boundp 'write-file-functions)
      ''write-file-functions            ;Emacs 21.4
    ''local-write-file-hooks))          ;<Emacs 21.4, XEmacs

;; Register mh-folder-mode as supporting which-function-mode...
(load "which-func" t t)
(when (and (boundp 'which-func-modes)
           (not (member 'mh-folder-mode which-func-modes)))
  (push 'mh-folder-mode which-func-modes))

;; Shush compiler in non-bleeding edge versions of Emacs.
(eval-when-compile
  (defvar desktop-save-buffer)         ;Emacs 21.4
  (defvar font-lock-auto-fontify)
  (defvar font-lock-defaults)
  (defvar tool-bar-map))

(defvar mh-folder-buttons-init-flag nil)

;; Autoload cookie needed by desktop.el
;;;###autoload
(define-derived-mode mh-folder-mode fundamental-mode "MH-Folder"
  "Major MH-E mode for \"editing\" an MH folder scan listing.\\<mh-folder-mode-map>

You can show the message the cursor is pointing to, and step through
the messages. Messages can be marked for deletion or refiling into
another folder; these commands are executed all at once with a
separate command.

Options that control this mode can be changed with
\\[customize-group]; specify the \"mh\" group. In particular, please
see the `mh-scan-format-file' option if you wish to modify scan's
format.

When a folder is visited, the hook `mh-folder-mode-hook' is run.

Ranges
======
Many commands that operate on individual messages, such as
`mh-forward' or `mh-refile-msg' take a RANGE argument. This argument
can be used in several ways.

If you provide the prefix argument (\\[universal-argument]) to
these commands, then you will be prompted for the message range.
This can be any valid MH range which can include messages,
sequences, and the abbreviations (described in the mh(1) man
page):

<num1>-<num2>
    Indicates all messages in the range <num1> to <num2>, inclusive.
    The range must be nonempty.

<num>:N
<num>:+N
<num>:-N
    Up to N messages beginning with (or ending with) message num. Num
    may be any of the predefined symbols: first, prev, cur, next or
    last.

first:N
prev:N
next:N
last:N
    The first, previous, next or last messages, if they exist.

all
    All of the messages.

For example, a range that shows all of these things is `1 2 3
5-10 last:5 unseen'.

If the option `transient-mark-mode' is set to t and you set a
region in the MH-Folder buffer, then the MH-E command will
perform the operation on all messages in that region.

\\{mh-folder-mode-map}"
  (mh-do-in-gnu-emacs
   (unless mh-folder-buttons-init-flag
     (mh-tool-bar-folder-buttons-init)
     (setq mh-folder-buttons-init-flag t)))
  (make-local-variable 'font-lock-defaults)
  (setq font-lock-defaults '(mh-folder-font-lock-keywords t))
  (make-local-variable 'desktop-save-buffer)
  (setq desktop-save-buffer t)
  (mh-make-local-vars
   'mh-colors-available-flag (mh-colors-available-p)
                                        ; Do we have colors available
   'mh-current-folder (buffer-name)     ; Name of folder, a string
   'mh-show-buffer (format "show-%s" (buffer-name)) ; Buffer that displays msgs
   'mh-folder-filename                  ; e.g. "/usr/foobar/Mail/inbox/"
   (file-name-as-directory (mh-expand-file-name (buffer-name)))
   'mh-display-buttons-for-inline-parts-flag
   mh-display-buttons-for-inline-parts-flag ; Allow for display of buttons to
                                        ; be  toggled.
   'mh-arrow-marker (make-marker)       ; Marker where arrow is displayed
   'overlay-arrow-position nil          ; Allow for simultaneous display in
   'overlay-arrow-string ">"            ;  different MH-E buffers.
   'mh-showing-mode nil                 ; Show message also?
   'mh-delete-list nil                  ; List of msgs nums to delete
   'mh-refile-list nil                  ; List of folder names in mh-seq-list
   'mh-seq-list nil                     ; Alist of (seq . msgs) nums
   'mh-seen-list nil                    ; List of displayed messages
   'mh-next-direction 'forward          ; Direction to move to next message
   'mh-view-ops ()                      ; Stack that keeps track of the order
                                        ; in which narrowing/threading has been
                                        ; carried out.
   'mh-folder-view-stack ()             ; Stack of previous views of the
                                        ; folder.
   'mh-index-data nil                   ; If the folder was created by a call
                                        ; to mh-index-search this contains info
                                        ; about the search results.
   'mh-index-previous-search nil        ; Previous folder and search-regexp
   'mh-index-msg-checksum-map nil       ; msg -> checksum map
   'mh-index-checksum-origin-map nil    ; checksum -> ( orig-folder, orig-msg )
   'mh-index-sequence-search-flag nil   ; folder resulted from sequence search
   'mh-first-msg-num nil                ; Number of first msg in buffer
   'mh-last-msg-num nil                 ; Number of last msg in buffer
   'mh-msg-count nil                    ; Number of msgs in buffer
   'mh-mode-line-annotation nil         ; Indicates message range
   'mh-sequence-notation-history (make-hash-table)
                                        ; Remember what is overwritten by
                                        ; mh-note-seq.
   'imenu-create-index-function 'mh-index-create-imenu-index
                                        ; Setup imenu support
   'mh-previous-window-config nil)      ; Previous window configuration
  (mh-remove-xemacs-horizontal-scrollbar)
  (setq truncate-lines t)
  (auto-save-mode -1)
  (setq buffer-offer-save t)
  (mh-make-local-hook (mh-write-file-functions-compat))
  (add-hook (mh-write-file-functions-compat) 'mh-execute-commands nil t)
  (make-local-variable 'revert-buffer-function)
  (make-local-variable 'hl-line-mode)   ; avoid pollution
  (mh-funcall-if-exists hl-line-mode 1)
  (setq revert-buffer-function 'mh-undo-folder)
  (or (assq 'mh-showing-mode minor-mode-alist)
      (setq minor-mode-alist
            (cons '(mh-showing-mode " Show") minor-mode-alist)))
  (easy-menu-add mh-folder-sequence-menu)
  (easy-menu-add mh-folder-message-menu)
  (easy-menu-add mh-folder-folder-menu)
  (set (make-local-variable 'tool-bar-map) mh-folder-tool-bar-map)
  (mh-funcall-if-exists mh-tool-bar-init :folder)
  (if (and mh-xemacs-flag
           font-lock-auto-fontify)
      (turn-on-font-lock)))             ; Force font-lock in XEmacs.

(defun mh-toggle-mime-buttons ()
  "Toggle option `mh-display-buttons-for-inline-parts-flag'."
  (interactive)
  (setq mh-display-buttons-for-inline-parts-flag
        (not mh-display-buttons-for-inline-parts-flag))
  (mh-show nil t))

(defun mh-colors-available-p ()
  "Check if colors are available in the Emacs being used."
  (or mh-xemacs-flag
      (let ((color-cells (display-color-cells)))
        (and (numberp color-cells) (>= color-cells 8)))))

(defun mh-colors-in-use-p ()
  "Check if colors are being used in the folder buffer."
  (and mh-colors-available-flag font-lock-mode))

(defun mh-make-local-vars (&rest pairs)
  "Initialize local variables according to the variable-value PAIRS."

  (while pairs
    (set (make-local-variable (car pairs)) (car (cdr pairs)))
    (setq pairs (cdr (cdr pairs)))))

(defun mh-restore-desktop-buffer (desktop-buffer-file-name
                                  desktop-buffer-name
                                  desktop-buffer-misc)
  "Restore an MH folder buffer specified in a desktop file.
When desktop creates a buffer, DESKTOP-BUFFER-FILE-NAME holds the
file name to visit, DESKTOP-BUFFER-NAME holds the desired buffer
name, and DESKTOP-BUFFER-MISC holds a list of miscellaneous info
used by the `desktop-buffer-handlers' functions."
  (mh-find-path)
  (mh-visit-folder desktop-buffer-name)
  (current-buffer))

;; desktop-buffer-mode-handlers appeared in Emacs 22.
(if (fboundp 'desktop-buffer-mode-handlers)
    (add-to-list 'desktop-buffer-mode-handlers
                 '(mh-folder-mode . mh-restore-desktop-buffer)))

(defun mh-scan-folder (folder range &optional dont-exec-pending)
  "Scan FOLDER over RANGE.

After the scan is performed, switch to the buffer associated with
FOLDER.

Check the documentation of `mh-interactive-range' to see how RANGE is
read in interactive use.

The processing of outstanding commands is not performed if
DONT-EXEC-PENDING is non-nil."
  (when (stringp range)
    (setq range (delete "" (split-string range "[ \t\n]"))))
  (cond ((null (get-buffer folder))
         (mh-make-folder folder))
        (t
         (unless dont-exec-pending
           (mh-process-or-undo-commands folder)
           (mh-reset-threads-and-narrowing))
         (switch-to-buffer folder)))
  (mh-regenerate-headers range)
  (if (zerop (buffer-size))
      (if (equal range "all")
          (message "Folder %s is empty" folder)
        (message "No messages in %s, range %s" folder range))
    (mh-goto-cur-msg))
  (when (mh-outstanding-commands-p)
    (mh-notate-deleted-and-refiled)))

(defun mh-msg-num-width-to-column (width)
  "Return the column for notations given message number WIDTH.
Note that columns in Emacs start with 0.

If `mh-scan-format-file' is set to \"Use MH-E scan Format\" this
means that either `mh-scan-format-mh' or `mh-scan-format-nmh' are
in use. This function therefore assumes that the first column is
empty (to provide room for the cursor), the following WIDTH
columns contain the message number, and the column for notations
comes after that."
  (if (eq mh-scan-format-file t)
      (max (1+ width) 2)
    (error "%s %s" "Can't call `mh-msg-num-width-to-column' when"
           "`mh-scan-format-file' is not set to \"Use MH-E scan Format\"")))

(defun mh-set-cmd-note (column)
  "Set `mh-cmd-note' to COLUMN.
Note that columns in Emacs start with 0."
  (setq mh-cmd-note column))

(defun mh-regenerate-headers (range &optional update)
  "Scan folder over RANGE.
If UPDATE, append the scan lines, otherwise replace."
  (let ((folder mh-current-folder)
        (range (if (and range (atom range)) (list range) range))
        scan-start)
    (message "Scanning %s..." folder)
    (mh-remove-all-notation)
    (with-mh-folder-updating (nil)
      (if update
          (goto-char (point-max))
        (delete-region (point-min) (point-max))
        (if mh-adaptive-cmd-note-flag
            (mh-set-cmd-note (mh-msg-num-width-to-column (mh-msg-num-width
                                                          folder)))))
      (setq scan-start (point))
      (apply #'mh-exec-cmd-output
             mh-scan-prog nil
             (mh-scan-format)
             "-noclear" "-noheader"
             "-width" (window-width)
             folder range)
      (goto-char scan-start)
      (cond ((looking-at "scan: no messages in")
             (keep-lines mh-scan-valid-regexp)) ; Flush random scan lines
            ((looking-at (if (mh-variant-p 'mu-mh)
                             "scan: message set .* does not exist"
                           "scan: bad message list "))
             (keep-lines mh-scan-valid-regexp))
            ((looking-at "scan: "))     ; Keep error messages
            (t
             (keep-lines mh-scan-valid-regexp))) ; Flush random scan lines
      (setq mh-seq-list (mh-read-folder-sequences folder nil))
      (mh-notate-user-sequences)
      (or update
          (setq mh-mode-line-annotation
                (if (equal range '("all"))
                    nil
                  mh-partial-folder-mode-line-annotation)))
      (mh-make-folder-mode-line))
    (message "Scanning %s...done" folder)))

(defun mh-generate-new-cmd-note (folder)
  "Fix the `mh-cmd-note' value for this FOLDER.

After doing an `mh-get-new-mail' operation in this FOLDER, at least
one line that looks like a truncated message number was found.

Remove the text added by the last `mh-inc' command. It should be the
messages cur-last. Call `mh-set-cmd-note', adjusting the notation
column with the width of the largest message number in FOLDER.

Reformat the message number width on each line in the buffer and trim
the line length to fit in the window.

Rescan the FOLDER in the range cur-last in order to display the
messages that were removed earlier. They should all fit in the scan
line now with no message truncation."
  (save-excursion
    (let ((maxcol (1- (window-width)))
          (old-cmd-note mh-cmd-note)
          mh-cmd-note-fmt
          msgnum)
      ;; Nuke all of the lines just added by the last inc
      (delete-char (- (point-max) (point)))
      ;; Update the current buffer to reflect the new mh-cmd-note
      ;; value needed to display messages.
      (mh-set-cmd-note (mh-msg-num-width-to-column (mh-msg-num-width folder)))
      (setq mh-cmd-note-fmt (concat "%" (format "%d" mh-cmd-note) "d"))
      ;; Cleanup the messages that are in the buffer right now
      (goto-char (point-min))
      (cond ((memq 'unthread mh-view-ops)
             (mh-thread-add-spaces (- mh-cmd-note old-cmd-note)))
            (t (while (re-search-forward mh-scan-msg-number-regexp nil 0 1)
                 ;; reformat the number to fix in mh-cmd-note columns
                 (setq msgnum (string-to-number
                               (buffer-substring
                                (match-beginning 1) (match-end 1))))
                 (replace-match (format mh-cmd-note-fmt msgnum))
                 ;; trim the line to fix in the window
                 (end-of-line)
                 (let ((eol (point)))
                   (move-to-column maxcol)
                   (if (<= (point) eol)
                       (delete-char (- eol (point))))))))
      ;; now re-read the lost messages
      (goto-char (point-max))
      (prog1 (point)
        (mh-regenerate-headers "cur-last" t)))))

(defun mh-get-new-mail (maildrop-name)
  "Read new mail from MAILDROP-NAME into the current buffer.
Return in the current buffer."
  (let ((point-before-inc (point))
        (folder mh-current-folder)
        (new-mail-flag nil))
    (with-mh-folder-updating (t)
      (if maildrop-name
          (message "inc %s -file %s..." folder maildrop-name)
        (message "inc %s..." folder))
      (setq mh-next-direction 'forward)
      (goto-char (point-max))
      (mh-remove-cur-notation)
      (let ((start-of-inc (point)))
        (if maildrop-name
            ;; I think MH 5 used "-ms-file" instead of "-file",
            ;; which would make inc'ing from maildrops fail.
            (mh-exec-cmd-output mh-inc-prog nil folder
                                (mh-scan-format)
                                "-file" (expand-file-name maildrop-name)
                                "-width" (window-width)
                                "-truncate")
          (mh-exec-cmd-output mh-inc-prog nil
                              (mh-scan-format)
                              "-width" (window-width)))
        (if maildrop-name
            (message "inc %s -file %s...done" folder maildrop-name)
          (message "inc %s...done" folder))
        (goto-char start-of-inc)
        (cond ((save-excursion
                 (re-search-forward "^inc: no mail" nil t))
               (message "No new mail%s%s" (if maildrop-name " in " "")
                        (if maildrop-name maildrop-name "")))
              ((and (when mh-folder-view-stack
                      (let ((saved-text (buffer-substring-no-properties
                                         start-of-inc (point-max))))
                        (delete-region start-of-inc (point-max))
                        (unwind-protect (mh-widen t)
                          (mh-remove-cur-notation)
                          (goto-char (point-max))
                          (setq start-of-inc (point))
                          (insert saved-text)
                          (goto-char start-of-inc))))
                    nil))
              ((re-search-forward "^inc:" nil t) ; Error messages
               (error "Error incorporating mail"))
              ((and
                (equal mh-scan-format-file t)
                mh-adaptive-cmd-note-flag
                ;; Have we reached an edge condition?
                (save-excursion
                  (re-search-forward mh-scan-msg-overflow-regexp nil 0 1))
                (setq start-of-inc (mh-generate-new-cmd-note folder))
                nil))
              (t
               (setq new-mail-flag t)))
        (keep-lines mh-scan-valid-regexp) ; Flush random scan lines
        (let* ((sequences (mh-read-folder-sequences folder t))
               (new-cur (assoc 'cur sequences))
               (new-unseen (assoc mh-unseen-seq sequences)))
          (unless (assoc 'cur mh-seq-list)
            (push (list 'cur) mh-seq-list))
          (unless (assoc mh-unseen-seq mh-seq-list)
            (push (list mh-unseen-seq) mh-seq-list))
          (setcdr (assoc 'cur mh-seq-list) (cdr new-cur))
          (setcdr (assoc mh-unseen-seq mh-seq-list) (cdr new-unseen)))
        (when (equal (point-max) start-of-inc)
          (mh-notate-cur))
        (if new-mail-flag
            (progn
              (mh-make-folder-mode-line)
              (when (mh-speed-flists-active-p)
                (mh-speed-flists t mh-current-folder))
              (when (memq 'unthread mh-view-ops)
                (mh-thread-inc folder start-of-inc))
              (mh-goto-cur-msg))
          (goto-char point-before-inc))
        (mh-notate-user-sequences (cons start-of-inc (point-max)))))))

(defun mh-make-folder-mode-line (&optional ignored)
  "Set the fields of the mode line for a folder buffer.
The optional argument is now obsolete and IGNORED. It used to be
used to pass in what is now stored in the buffer-local variable
`mh-mode-line-annotation'."
  (save-excursion
    (save-window-excursion
      (mh-first-msg)
      (let ((new-first-msg-num (mh-get-msg-num nil)))
        (when (or (not (memq 'unthread mh-view-ops))
                  (null mh-first-msg-num)
                  (null new-first-msg-num)
                  (< new-first-msg-num mh-first-msg-num))
          (setq mh-first-msg-num new-first-msg-num)))
      (mh-last-msg)
      (let ((new-last-msg-num (mh-get-msg-num nil)))
        (when (or (not (memq 'unthread mh-view-ops))
                  (null mh-last-msg-num)
                  (null new-last-msg-num)
                  (> new-last-msg-num mh-last-msg-num))
          (setq mh-last-msg-num new-last-msg-num)))
      (setq mh-msg-count (if mh-first-msg-num
                             (count-lines (point-min) (point-max))
                           0))
      (setq mode-line-buffer-identification
            (list (format "    {%%b%s} %s msg%s"
                          (if mh-mode-line-annotation
                              (format "/%s" mh-mode-line-annotation)
                            "")
                          (if (zerop mh-msg-count)
                              "no"
                            (format "%d" mh-msg-count))
                          (if (zerop mh-msg-count)
                              "s"
                            (cond ((> mh-msg-count 1)
                                   (format "s (%d-%d)" mh-first-msg-num
                                           mh-last-msg-num))
                                  (mh-first-msg-num
                                   (format " (%d)" mh-first-msg-num))
                                  (""))))))
      (mh-logo-display))))

(defun mh-add-sequence-notation (msg internal-seq-flag)
  "Add sequence notation to the MSG on the current line.
If INTERNAL-SEQ-FLAG is non-nil, then refontify the scan line if
font-lock is turned on."
  (with-mh-folder-updating (t)
    (save-excursion
      (beginning-of-line)
      (if internal-seq-flag
          (progn
            ;; Change the buffer so that if transient-mark-mode is active
            ;; and there is an active region it will get deactivated as in
            ;; the case of user sequences.
            (mh-notate nil nil mh-cmd-note)
            (when font-lock-mode
              (font-lock-fontify-region (point) (line-end-position))))
        (forward-char (+ mh-cmd-note mh-scan-field-destination-offset))
        (let ((stack (gethash msg mh-sequence-notation-history)))
          (setf (gethash msg mh-sequence-notation-history)
                (cons (char-after) stack)))
        (mh-notate nil mh-note-seq
                   (+ mh-cmd-note mh-scan-field-destination-offset))))))

(defun mh-remove-sequence-notation (msg internal-seq-flag &optional all)
  "Remove sequence notation from the MSG on the current line.
If INTERNAL-SEQ-FLAG is non-nil, then `font-lock' was used to
highlight the sequence. In that case, no notation needs to be removed.
Otherwise the effect of inserting `mh-note-seq' needs to be reversed.
If ALL is non-nil, then all sequence marks on the scan line are
removed."
  (with-mh-folder-updating (t)
    ;; This takes care of internal sequences...
    (mh-notate nil nil mh-cmd-note)
    (unless internal-seq-flag
      ;; ... and this takes care of user sequences.
      (let ((stack (gethash msg mh-sequence-notation-history)))
        (while (and all (cdr stack))
          (setq stack (cdr stack)))
        (when stack
          (save-excursion
            (beginning-of-line)
            (forward-char (+ mh-cmd-note mh-scan-field-destination-offset))
            (delete-char 1)
            (insert (car stack))))
        (setf (gethash msg mh-sequence-notation-history) (cdr stack))))))

(defun mh-remove-cur-notation ()
  "Remove old cur notation."
  (let ((cur-msg (car (mh-seq-to-msgs 'cur))))
    (save-excursion
      (when (and cur-msg
                 (mh-goto-msg cur-msg t t)
                 (looking-at mh-scan-cur-msg-number-regexp))
        (mh-notate nil ?  mh-cmd-note)
        (setq overlay-arrow-position nil)))))

(defun mh-remove-all-notation ()
  "Remove all notations on all scan lines that MH-E introduces."
  (save-excursion
    (setq overlay-arrow-position nil)
    (goto-char (point-min))
    (mh-iterate-on-range msg (cons (point-min) (point-max))
      (mh-notate nil ?  mh-cmd-note)
      (mh-remove-sequence-notation msg nil t))
    (clrhash mh-sequence-notation-history)))


(defun mh-goto-cur-msg (&optional minimal-changes-flag)
  "Position the cursor at the current message.
When optional argument MINIMAL-CHANGES-FLAG is non-nil, the
function doesn't recenter the folder buffer."
  (let ((cur-msg (car (mh-seq-to-msgs 'cur))))
    (cond ((and cur-msg
                (mh-goto-msg cur-msg t t))
           (unless minimal-changes-flag
             (mh-notate-cur)
             (mh-recenter 0)
             (mh-maybe-show cur-msg)))
          (t
           (setq overlay-arrow-position nil)
           (message "No current message")))))

(defun mh-process-or-undo-commands (folder)
  "If FOLDER has outstanding commands, then either process or discard them.
Called by functions like `mh-sort-folder', so also invalidate
show buffer."
  (set-buffer folder)
  (if (mh-outstanding-commands-p)
      (if (or mh-do-not-confirm-flag
              (y-or-n-p
               "Process outstanding deletes and refiles? "))
          (mh-process-commands folder)
        (set-buffer folder)
        (mh-undo-folder)))
  (mh-update-unseen)
  (mh-invalidate-show-buffer))

(defun mh-process-commands (folder)
  "Process outstanding commands for FOLDER.

This function runs `mh-before-commands-processed-hook' before the
commands are processed and `mh-after-commands-processed-hook'
after the commands are processed."
  (message "Processing deletes and refiles for %s..." folder)
  (set-buffer folder)
  (with-mh-folder-updating (nil)
    ;; Run the before hook -- the refile and delete lists are still valid
    (run-hooks 'mh-before-commands-processed-hook)

    ;; Update the unseen sequence if it exists
    (mh-update-unseen)

    (let ((redraw-needed-flag mh-index-data)
          (folders-changed (list mh-current-folder))
          (seq-map (and mh-refile-list mh-refile-preserves-sequences-flag
                        (mh-create-sequence-map mh-seq-list)))
          (dest-map (and mh-refile-list mh-refile-preserves-sequences-flag
                         (make-hash-table))))
      ;; Remove invalid scan lines if we are in an index folder and then remove
      ;; the real messages
      (when mh-index-data
        (mh-index-delete-folder-headers)
        (setq folders-changed
              (append folders-changed (mh-index-execute-commands))))

      ;; Then refile messages
      (mh-mapc #'(lambda (folder-msg-list)
                   (let* ((dest-folder (symbol-name (car folder-msg-list)))
                          (last (car (mh-translate-range dest-folder "last")))
                          (msgs (cdr folder-msg-list)))
                     (push dest-folder folders-changed)
                     (setq redraw-needed-flag t)
                     (apply #'mh-exec-cmd
                            "refile" "-src" folder dest-folder
                            (mh-coalesce-msg-list msgs))
                     (mh-delete-scan-msgs msgs)
                     ;; Preserve sequences in destination folder...
                     (when mh-refile-preserves-sequences-flag
                       (clrhash dest-map)
                       (loop for i from (1+ (or last 0))
                             for msg in (sort (copy-sequence msgs) #'<)
                             do (loop for seq-name in (gethash msg seq-map)
                                      do (push i (gethash seq-name dest-map))))
                       (maphash
                        #'(lambda (seq msgs)
                            ;; Can't be run in the background, since the
                            ;; current folder is changed by mark this could
                            ;; lead to a race condition with the next refile.
                            (apply #'mh-exec-cmd "mark"
                                   "-sequence" (symbol-name seq) dest-folder
                                   "-add" (mapcar #'(lambda (x) (format "%s" x))
                                                  (mh-coalesce-msg-list msgs))))
                        dest-map))))
               mh-refile-list)
      (setq mh-refile-list ())

      ;; Now delete messages
      (cond (mh-delete-list
             (setq redraw-needed-flag t)
             (apply 'mh-exec-cmd "rmm" folder
                    (mh-coalesce-msg-list mh-delete-list))
             (mh-delete-scan-msgs mh-delete-list)
             (setq mh-delete-list nil)))

      ;; Don't need to remove sequences since delete and refile do so.
      ;; Mark cur message
      (if (> (buffer-size) 0)
          (mh-define-sequence 'cur (list (or (mh-get-msg-num nil) "last"))))

      ;; Redraw folder buffer if needed
      (when (and redraw-needed-flag)
        (when (mh-speed-flists-active-p)
          (apply #'mh-speed-flists t folders-changed))
        (cond ((memq 'unthread mh-view-ops) (mh-thread-inc folder (point-max)))
              (mh-index-data (mh-index-insert-folder-headers))))

      (and (buffer-file-name (get-buffer mh-show-buffer))
           (not (file-exists-p (buffer-file-name (get-buffer mh-show-buffer))))
           ;; If "inc" were to put a new msg in this file,
           ;; we would not notice, so mark it invalid now.
           (mh-invalidate-show-buffer))

      (setq mh-seq-list (mh-read-folder-sequences mh-current-folder nil))
      (mh-remove-all-notation)
      (mh-notate-user-sequences)

      ;; Run the after hook -- now folders-changed is valid,
      ;; but not the lists of specific messages.
      (let ((mh-folders-changed folders-changed))
        (run-hooks 'mh-after-commands-processed-hook)))

    (message "Processing deletes and refiles for %s...done" folder)))

(defun mh-update-unseen ()
  "Synchronize the unseen sequence with MH.
Return non-nil iff the MH folder was set.
The hook `mh-unseen-updated-hook' is called after the unseen sequence
is updated."
  (if mh-seen-list
      (let* ((unseen-seq (mh-find-seq mh-unseen-seq))
             (unseen-msgs (mh-seq-msgs unseen-seq)))
        (if unseen-msgs
            (progn
              (mh-undefine-sequence mh-unseen-seq mh-seen-list)
              (run-hooks 'mh-unseen-updated-hook)
              (while mh-seen-list
                (setq unseen-msgs (delq (car mh-seen-list) unseen-msgs))
                (setq mh-seen-list (cdr mh-seen-list)))
              (setcdr unseen-seq unseen-msgs)
              t)                        ;since we set the folder
          (setq mh-seen-list nil)))))

(defun mh-delete-scan-msgs (msgs)
  "Delete the scan listing lines for MSGS."
  (save-excursion
    (while msgs
      (when (mh-goto-msg (car msgs) t t)
        (when (memq 'unthread mh-view-ops)
          (mh-thread-forget-message (car msgs)))
        (mh-delete-line 1))
      (setq msgs (cdr msgs)))))

(defun mh-outstanding-commands-p ()
  "Return non-nil if there are outstanding deletes or refiles."
  (save-excursion
    (when (eq major-mode 'mh-show-mode)
      (set-buffer mh-show-folder-buffer))
    (or mh-delete-list mh-refile-list)))

(defun mh-coalesce-msg-list (messages)
  "Given a list of MESSAGES, return a list of message number ranges.
This is the inverse of `mh-read-msg-list', which expands ranges.
Message lists passed to MH programs should be processed by this
function to avoid exceeding system command line argument limits."
  (let ((msgs (sort (copy-sequence messages) 'mh-greaterp))
        (range-high nil)
        (prev -1)
        (ranges nil))
    (while prev
      (if range-high
          (if (or (not (numberp prev))
                  (not (equal (car msgs) (1- prev))))
              (progn                    ;non-sequential, flush old range
                (if (eq prev range-high)
                    (setq ranges (cons range-high ranges))
                  (setq ranges (cons (format "%s-%s" prev range-high) ranges)))
                (setq range-high nil))))
      (or range-high
          (setq range-high (car msgs))) ;start new or first range
      (setq prev (car msgs))
      (setq msgs (cdr msgs)))
    ranges))

(defun mh-greaterp (msg1 msg2)
  "Return the greater of two message indicators MSG1 and MSG2.
Strings are \"smaller\" than numbers.
Valid values are things like \"cur\", \"last\", 1, and 1820."
  (if (numberp msg1)
      (if (numberp msg2)
          (> msg1 msg2)
        t)
    (if (numberp msg2)
        nil
      (string-lessp msg2 msg1))))

(defun mh-lessp (msg1 msg2)
  "Return the lesser of two message indicators MSG1 and MSG2.
Strings are \"smaller\" than numbers.
Valid values are things like \"cur\", \"last\", 1, and 1820."
  (not (mh-greaterp msg1 msg2)))



;;; Basic sequence handling

(defun mh-delete-seq-locally (seq)
  "Remove MH-E's record of SEQ."
  (let ((entry (mh-find-seq seq)))
    (setq mh-seq-list (delq entry mh-seq-list))))

(defun mh-read-folder-sequences (folder save-refiles)
  "Read and return the predefined sequences for a FOLDER.
If SAVE-REFILES is non-nil, then keep the sequences
that note messages to be refiled."
  (let ((seqs ()))
    (cond (save-refiles
           (mh-mapc (function (lambda (seq) ; Save the refiling sequences
                                (if (mh-folder-name-p (mh-seq-name seq))
                                    (setq seqs (cons seq seqs)))))
                    mh-seq-list)))
    (save-excursion
      (if (eq 0 (mh-exec-cmd-quiet nil "mark" folder "-list"))
          (progn
            ;; look for name in line of form "cur: 4" or "myseq (private): 23"
            (while (re-search-forward "^[^: ]+" nil t)
              (setq seqs (cons (mh-make-seq (intern (buffer-substring
                                                     (match-beginning 0)
                                                     (match-end 0)))
                                            (mh-read-msg-list))
                               seqs)))
            (delete-region (point-min) (point))))) ; avoid race with
                                        ; mh-process-daemon
    seqs))

(defun mh-read-msg-list ()
  "Return a list of message numbers from point to the end of the line.
Expands ranges into set of individual numbers."
  (let ((msgs ())
        (end-of-line (save-excursion (end-of-line) (point)))
        num)
    (while (re-search-forward "[0-9]+" end-of-line t)
      (setq num (string-to-number (buffer-substring (match-beginning 0)
                                                    (match-end 0))))
      (cond ((looking-at "-")           ; Message range
             (forward-char 1)
             (re-search-forward "[0-9]+" end-of-line t)
             (let ((num2 (string-to-number
                          (buffer-substring (match-beginning 0)
                                            (match-end 0)))))
               (if (< num2 num)
                   (error "Bad message range: %d-%d" num num2))
               (while (<= num num2)
                 (setq msgs (cons num msgs))
                 (setq num (1+ num)))))
            ((not (zerop num))          ;"pick" outputs "0" to mean no match
             (setq msgs (cons num msgs)))))
    msgs))

(defun mh-notate-user-sequences (&optional range)
  "Mark user-defined sequences in RANGE.

Check the documentation of `mh-interactive-range' to see how
RANGE is read in interactive use; if nil all messages are
notated."
  (unless range
    (setq range (cons (point-min) (point-max))))
  (let ((seqs mh-seq-list)
        (msg-hash (make-hash-table)))
    (dolist (seq seqs)
      (dolist (msg (mh-seq-msgs seq))
        (push (car seq) (gethash msg msg-hash))))
    (mh-iterate-on-range msg range
      (loop for seq in (gethash msg msg-hash)
            do (mh-add-sequence-notation msg (mh-internal-seq seq))))))

(defvar mh-internal-seqs '(answered cur deleted forwarded printed))

(defun mh-internal-seq (name)
  "Return non-nil if NAME is the name of an internal MH-E sequence."
  (or (memq name mh-internal-seqs)
      (eq name mh-unseen-seq)
      (and (mh-colors-in-use-p) mh-tick-seq (eq name mh-tick-seq))
      (eq name mh-previous-seq)
      (mh-folder-name-p name)))

(defun mh-valid-seq-p (name)
  "Return non-nil if NAME is a valid MH sequence name."
  (and (symbolp name)
       (string-match "^[a-zA-Z][a-zA-Z0-9]*$" (symbol-name name))))

(defun mh-delete-msg-from-seq (range sequence &optional internal-flag)
  "Delete RANGE from SEQUENCE.

Check the documentation of `mh-interactive-range' to see how
RANGE is read in interactive use.

In a program, non-nil INTERNAL-FLAG means do not inform MH of the
change."
  (interactive (list (mh-interactive-range "Delete")
                     (mh-read-seq-default "Delete from" t)
                     nil))
  (let ((entry (mh-find-seq sequence))
        (user-sequence-flag (not (mh-internal-seq sequence)))
        (folders-changed (list mh-current-folder))
        (msg-list ()))
    (when entry
      (mh-iterate-on-range msg range
        (push msg msg-list)
        ;; Calling "mark" repeatedly takes too long. So we will pretend here
        ;; that we are just modifying an internal sequence...
        (when (memq msg (cdr entry))
          (mh-remove-sequence-notation msg (not user-sequence-flag)))
        (mh-delete-a-msg-from-seq msg sequence t))
      ;; ... and here we will "mark" all the messages at one go.
      (unless internal-flag (mh-undefine-sequence sequence msg-list))
      (when (and mh-index-data (not internal-flag))
        (setq folders-changed
              (append folders-changed
                      (mh-index-delete-from-sequence sequence msg-list))))
      (when (and (eq sequence mh-unseen-seq) (mh-speed-flists-active-p))
        (apply #'mh-speed-flists t folders-changed)))))

(defun mh-catchup (range)
  "Delete RANGE from the \"unseen\" sequence.

Check the documentation of `mh-interactive-range' to see how
RANGE is read in interactive use."
  (interactive (list (mh-interactive-range "Catchup"
                                           (cons (point-min) (point-max)))))
  (mh-delete-msg-from-seq range mh-unseen-seq))

(defun mh-delete-a-msg-from-seq (msg sequence internal-flag)
  "Delete MSG from SEQUENCE.
If INTERNAL-FLAG is non-nil, then do not inform MH of the
change."
  (let ((entry (mh-find-seq sequence)))
    (when (and entry (memq msg (mh-seq-msgs entry)))
      (if (not internal-flag)
          (mh-undefine-sequence sequence (list msg)))
      (setcdr entry (delq msg (mh-seq-msgs entry))))))

(defun mh-undefine-sequence (seq msgs)
  "Remove from the SEQ the list of MSGS."
  (when (and (mh-valid-seq-p seq) msgs)
    (apply #'mh-exec-cmd "mark" mh-current-folder "-delete"
           "-sequence" (symbol-name seq) (mh-coalesce-msg-list msgs))))

(defun mh-define-sequence (seq msgs)
  "Define the SEQ to contain the list of MSGS.
Do not mark pseudo-sequences or empty sequences.
Signals an error if SEQ is an invalid name."
  (if (and msgs
           (mh-valid-seq-p seq)
           (not (mh-folder-name-p seq)))
      (save-excursion
        (mh-exec-cmd-error nil "mark" mh-current-folder "-add" "-zero"
                           "-sequence" (symbol-name seq)
                           (mh-coalesce-msg-list msgs)))))

(defun mh-seq-containing-msg (msg &optional include-internal-flag)
  "Return a list of the sequences containing MSG.
If INCLUDE-INTERNAL-FLAG non-nil, include MH-E internal sequences
in list."
  (let ((l mh-seq-list)
        (seqs ()))
    (while l
      (and (memq msg (mh-seq-msgs (car l)))
           (or include-internal-flag
               (not (mh-internal-seq (mh-seq-name (car l)))))
           (setq seqs (cons (mh-seq-name (car l)) seqs)))
      (setq l (cdr l)))
    seqs))



;;; Build mh-folder-mode keymap:

(suppress-keymap mh-folder-mode-map)

;; Use defalias to make sure the documented primary key bindings
;; appear in menu lists.
(defalias 'mh-alt-show 'mh-show)
(defalias 'mh-alt-refile-msg 'mh-refile-msg)
(defalias 'mh-alt-send 'mh-send)
(defalias 'mh-alt-visit-folder 'mh-visit-folder)

;; Save the "b" binding for a future `back'. Maybe?
(gnus-define-keys  mh-folder-mode-map
  " "           mh-page-msg
  "!"           mh-refile-or-write-again
  "'"           mh-toggle-tick
  ","           mh-header-display
  "."           mh-alt-show
  ";"           mh-toggle-mh-decode-mime-flag
  ">"           mh-write-msg-to-file
  "?"           mh-help
  "E"           mh-extract-rejected-mail
  "M"           mh-modify
  "\177"        mh-previous-page
  "\C-d"        mh-delete-msg-no-motion
  "\t"          mh-index-next-folder
  [backtab]     mh-index-previous-folder
  "\M-\t"       mh-index-previous-folder
  "\e<"         mh-first-msg
  "\e>"         mh-last-msg
  "\ed"         mh-redistribute
  "\r"          mh-show
  "^"           mh-alt-refile-msg
  "c"           mh-copy-msg
  "d"           mh-delete-msg
  "e"           mh-edit-again
  "f"           mh-forward
  "g"           mh-goto-msg
  "i"           mh-inc-folder
  "k"           mh-delete-subject-or-thread
  "m"           mh-alt-send
  "n"           mh-next-undeleted-msg
  "\M-n"        mh-next-unread-msg
  "o"           mh-refile-msg
  "p"           mh-previous-undeleted-msg
  "\M-p"        mh-previous-unread-msg
  "q"           mh-quit
  "r"           mh-reply
  "s"           mh-send
  "t"           mh-toggle-showing
  "u"           mh-undo
  "v"           mh-index-visit-folder
  "x"           mh-execute-commands
  "|"           mh-pipe-msg)

(gnus-define-keys (mh-folder-map "F" mh-folder-mode-map)
  "?"           mh-prefix-help
  "'"           mh-index-ticked-messages
  "S"           mh-sort-folder
  "c"           mh-catchup
  "f"           mh-alt-visit-folder
  "i"           mh-index-search
  "k"           mh-kill-folder
  "l"           mh-list-folders
  "n"           mh-index-new-messages
  "o"           mh-alt-visit-folder
  "p"           mh-pack-folder
  "q"           mh-index-sequenced-messages
  "r"           mh-rescan-folder
  "s"           mh-search-folder
  "u"           mh-undo-folder
  "v"           mh-visit-folder)

(define-key mh-folder-mode-map "I" mh-inc-spool-map)

(gnus-define-keys (mh-junk-map "J" mh-folder-mode-map)
  "?"           mh-prefix-help
  "b"           mh-junk-blacklist
  "w"           mh-junk-whitelist)

(gnus-define-keys (mh-ps-print-map "P" mh-folder-mode-map)
  "?"           mh-prefix-help
  "C"           mh-ps-print-toggle-color
  "F"           mh-ps-print-toggle-faces
  "f"           mh-ps-print-msg-file
  "l"		mh-print-msg
  "p"           mh-ps-print-msg)

(gnus-define-keys (mh-sequence-map "S" mh-folder-mode-map)
  "'"           mh-narrow-to-tick
  "?"           mh-prefix-help
  "d"           mh-delete-msg-from-seq
  "k"           mh-delete-seq
  "l"           mh-list-sequences
  "n"           mh-narrow-to-seq
  "p"           mh-put-msg-in-seq
  "s"           mh-msg-is-in-seq
  "w"           mh-widen)

(gnus-define-keys (mh-thread-map "T" mh-folder-mode-map)
  "?"           mh-prefix-help
  "u"           mh-thread-ancestor
  "p"           mh-thread-previous-sibling
  "n"           mh-thread-next-sibling
  "t"           mh-toggle-threads
  "d"           mh-thread-delete
  "o"           mh-thread-refile)

(gnus-define-keys (mh-limit-map "/" mh-folder-mode-map)
  "'"           mh-narrow-to-tick
  "?"           mh-prefix-help
  "c"           mh-narrow-to-cc
  "f"           mh-narrow-to-from
  "r"           mh-narrow-to-range
  "s"           mh-narrow-to-subject
  "t"           mh-narrow-to-to
  "w"           mh-widen)

(gnus-define-keys (mh-extract-map "X" mh-folder-mode-map)
  "?"           mh-prefix-help
  "s"           mh-store-msg            ;shar
  "u"           mh-store-msg)           ;uuencode

(gnus-define-keys (mh-digest-map "D" mh-folder-mode-map)
  " "           mh-page-digest
  "?"           mh-prefix-help
  "\177"        mh-page-digest-backwards
  "b"           mh-burst-digest)

(gnus-define-keys (mh-mime-map "K" mh-folder-mode-map)
  "?"           mh-prefix-help
  "a"           mh-mime-save-parts
  "e"           mh-display-with-external-viewer
  "i"           mh-folder-inline-mime-part
  "o"           mh-folder-save-mime-part
  "t"           mh-toggle-mime-buttons
  "v"           mh-folder-toggle-mime-part
  "\t"          mh-next-button
  [backtab]     mh-prev-button
  "\M-\t"       mh-prev-button)

(cond
 (mh-xemacs-flag
  (define-key mh-folder-mode-map [button2] 'mh-show-mouse))
 (t
  (define-key mh-folder-mode-map [mouse-2] 'mh-show-mouse)))

;; "C-c /" prefix is used in mh-folder-mode by pgp.el and mailcrypt



;;; Help Messages

;; If you add a new prefix, add appropriate text to the nil key.
;;
;; In general, messages are grouped logically. Taking the main commands for
;; example, the first line is "ways to view messages," the second line is
;; "things you can do with messages", and the third is "composing" messages.
;;
;; When adding a new prefix, ensure that the help message contains "what" the
;; prefix is for. For example, if the word "folder" were not present in the
;; "F" entry, it would not be clear what these commands operated upon.
(defvar mh-help-messages
  '((nil "[i]nc, [.]show, [,]show all, [n]ext, [p]revious,\n"
         "[d]elete, [o]refile, e[x]ecute,\n"
         "[s]end, [r]eply,\n"
         "[;]toggle MIME decoding.\n"
         "Prefix characters:\n [F]older, [S]equence, [J]unk, MIME [K]eys,"
         "\n [T]hread, [/]limit, e[X]tract, [D]igest, [I]nc spools.")

    (?F "[l]ist; [v]isit folder;\n"
        "[n]ew messages; [']ticked messages; [s]earch; [i]ndexed search;\n"
        "[p]ack; [S]ort; [r]escan; [k]ill")
    (?P "[p]rint message to [f]ile; old-style [l]pr printing;\n"
        "Toggle printing of [C]olors, [F]aces")
    (?S "[p]ut message in sequence, [n]arrow, [']narrow to ticked, [w]iden,\n"
        "[s]equences, [l]ist,\n"
        "[d]elete message from sequence, [k]ill sequence")
    (?T "[t]oggle, [d]elete, [o]refile thread")
    (?/ "Limit to [c]c, [f]rom, [r]ange, [s]ubject, [t]o; [w]iden")
    (?X "un[s]har, [u]udecode message")
    (?D "[b]urst digest")
    (?K "[v]iew, [i]nline, [o]utput/save MIME part; save [a]ll parts; \n"
        "[TAB] next; [SHIFT-TAB] previous")
    (?J "[b]lacklist, [w]hitelist message"))
  "Key binding cheat sheet.

This is an associative array which is used to show the most common commands.
The key is a prefix char. The value is one or more strings which are
concatenated together and displayed in the minibuffer if ? is pressed after
the prefix character. The special key nil is used to display the
non-prefixed commands.

The substitutions described in `substitute-command-keys' are performed as
well.")



(dolist (mess '("^Cursor not pointing to message$"
                "^There is no other window$"))
  (add-to-list 'debug-ignored-errors mess))

(provide 'mh-e)

;; Local Variables:
;; indent-tabs-mode: nil
;; sentence-end-double-space: nil
;; End:

;; arch-tag: cce884de-bd37-4104-9963-e4439d5ed22b
;;; mh-e.el ends here