summaryrefslogtreecommitdiff
path: root/lisp/gnus/gnus-sum.el
blob: 856e95c0ba0e203f64395c63c48d3bb45216209e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
;;; gnus-sum.el --- summary mode commands for Gnus  -*- lexical-binding:t -*-

;; Copyright (C) 1996-2021 Free Software Foundation, Inc.

;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
;; Keywords: news

;; 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 3 of the License, 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.  If not, see <https://www.gnu.org/licenses/>.

;;; Commentary:

;;; Code:

(require 'cl-lib)

(defvar tool-bar-mode)
(defvar gnus-category-predicate-alist)
(defvar gnus-category-predicate-cache)
(defvar gnus-inhibit-article-treatments)
(defvar gnus-inhibit-demon)
(defvar gnus-tmp-article-number)
(defvar gnus-tmp-closing-bracket)
(defvar gnus-tmp-current)
(defvar gnus-tmp-dummy)
(defvar gnus-tmp-expirable)
(defvar gnus-tmp-from)
(defvar gnus-tmp-group-name)
(defvar gnus-tmp-header)
(defvar gnus-tmp-indentation)
(defvar gnus-tmp-level)
(defvar gnus-tmp-lines)
(defvar gnus-tmp-name)
(defvar gnus-tmp-number)
(defvar gnus-tmp-opening-bracket)
(defvar gnus-tmp-process)
(defvar gnus-tmp-replied)
(defvar gnus-tmp-score)
(defvar gnus-tmp-score-char)
(defvar gnus-tmp-subject)
(defvar gnus-tmp-subject-or-nil)
(defvar gnus-tmp-thread)
(defvar gnus-tmp-unread)
(defvar gnus-tmp-unread-and-unselected)
(defvar gnus-tmp-unread-and-unticked)
(defvar gnus-tmp-user-defined)
(defvar gnus-use-article-prefetch)

(require 'gnus)
(require 'gnus-group)
(require 'gnus-spec)
(require 'gnus-range)
(require 'gnus-int)
(require 'gnus-undo)
(require 'gnus-util)
(require 'gmm-utils)
(require 'mm-decode)
(require 'shr)
(require 'url)
(require 'nnoo)
(eval-when-compile
  (require 'subr-x))

(autoload 'gnus-summary-limit-include-cached "gnus-cache" nil
  '(gnus-summary-mode))
(autoload 'gnus-cache-write-active "gnus-cache")
(autoload 'gnus-pick-line-number "gnus-salt" nil t)
(autoload 'nnselect-article-rsv "nnselect" nil nil)
(autoload 'nnselect-article-group "nnselect" nil nil)
(autoload 'gnus-nnselect-group-p "nnselect" nil nil)

(defcustom gnus-kill-summary-on-exit t
  "If non-nil, kill the summary buffer when you exit from it.
If nil, the summary will become a \"*Dead Summary*\" buffer, and
it will be killed sometime later."
  :group 'gnus-summary-exit
  :type 'boolean)

(defcustom gnus-summary-next-group-on-exit t
  "If non-nil, go to the next unread newsgroup on summary exit.
See `gnus-group-goto-unread'."
  :link '(custom-manual "(gnus)Group Maneuvering")
  :group 'gnus-summary-exit
  :version "23.1" ;; No Gnus
  :type 'boolean)

(defcustom gnus-summary-stop-at-end-of-message nil
  "If non-nil, don't select the next message when using `SPC'."
  :link '(custom-manual "(gnus)Group Maneuvering")
  :group 'gnus-summary-maneuvering
  :version "24.1"
  :type 'boolean)

(defcustom gnus-fetch-old-headers nil
  "Non-nil means that Gnus will try to build threads by grabbing old headers.
If an unread article in the group refers to an older, already
read (or just marked as read) article, the old article will not
normally be displayed in the Summary buffer.  If this variable is
t, Gnus will attempt to grab the headers to the old articles, and
thereby build complete threads.  If the value is the symbol `some',
all old headers will be fetched but only enough headers to connect
otherwise loose threads will be displayed.  This variable can
also be a number.  In that case, no more than that number of old
headers will be fetched.  If the value is the symbol `invisible',
all old headers will be fetched, but none will be displayed.

The server has to support NOV for any of this to work.

This feature can seriously impact performance it ignores all
locally cached header entries.  Setting it to t for groups for a
server that doesn't expire articles (such as news.gmane.org),
leads to very slow summary generation."
  :group 'gnus-thread
  :type '(choice (const :tag "off" nil)
		 (const :tag "on" t)
		 (const some)
		 (const invisible)
		 number
		 (sexp :menu-tag "other" t)))

(defcustom gnus-refer-thread-limit 500
  "The number of old headers to fetch when doing \\<gnus-summary-mode-map>\\[gnus-summary-refer-thread].
If t, fetch all the available old headers."
  :group 'gnus-thread
  :type '(choice number
		 (sexp :menu-tag "other" t)))

(define-obsolete-variable-alias 'gnus-refer-thread-use-nnir
  'gnus-refer-thread-use-search "28.1")

(defcustom gnus-refer-thread-use-search nil
  "Search an entire server when referring threads.
A nil value will only search for thread-related articles in the
current group."
  :version "28.1"
  :group 'gnus-thread
  :type 'boolean)

(defcustom gnus-refer-thread-limit-to-thread nil
  "If non-nil referring a thread will limit the summary buffer to
articles in the thread.  A nil value will add the thread articles
to the summary buffer."
  :version "25.1"
  :group 'gnus-thread
  :type 'boolean)

(defcustom gnus-summary-make-false-root 'adopt
  "nil means that Gnus won't gather loose threads.
If the root of a thread has expired or been read in a previous
session, the information necessary to build a complete thread has been
lost.  Instead of having many small sub-threads from this original thread
scattered all over the summary buffer, Gnus can gather them.

If non-nil, Gnus will try to gather all loose sub-threads from an
original thread into one large thread.

If this variable is non-nil, it should be one of `none', `adopt',
`dummy' or `empty'.

If this variable is `none', Gnus will not make a false root, but just
present the sub-threads after another.
If this variable is `dummy', Gnus will create a dummy root that will
have all the sub-threads as children.
If this variable is `adopt', Gnus will make one of the \"children\"
the parent and mark all the step-children as such.
If this variable is `empty', the \"children\" are printed with empty
subject fields.  (Or rather, they will be printed with a string
given by the `gnus-summary-same-subject' variable.)"
  :group 'gnus-thread
  :type '(choice (const :tag "off" nil)
		 (const none)
		 (const dummy)
		 (const adopt)
		 (const empty)))

(defcustom gnus-summary-make-false-root-always nil
  "Always make a false dummy root."
  :version "22.1"
  :group 'gnus-thread
  :type 'boolean)

(defcustom gnus-summary-gather-exclude-subject "^ *$\\|^(none)$"
  "A regexp to match subjects to be excluded from loose thread gathering.
As loose thread gathering is done on subjects only, that means that
there can be many false gatherings performed.  By rooting out certain
common subjects, gathering might become saner."
  :group 'gnus-thread
  :type 'regexp)

(defcustom gnus-summary-gather-subject-limit nil
  "Maximum length of subject comparisons when gathering loose threads.
Use nil to compare full subjects.  Setting this variable to a low
number will help gather threads that have been corrupted by
newsreaders chopping off subject lines, but it might also mean that
unrelated articles that have subject that happen to begin with the
same few characters will be incorrectly gathered.

If this variable is `fuzzy', Gnus will use a fuzzy algorithm when
comparing subjects."
  :group 'gnus-thread
  :type '(choice (const :tag "off" nil)
		 (const fuzzy)
		 (sexp :menu-tag "on" t)))

(defcustom gnus-simplify-subject-functions nil
  "List of functions taking a string argument that simplify subjects.
The functions are applied recursively.

Useful functions to put in this list include:
`gnus-simplify-subject-re', `gnus-simplify-subject-fuzzy',
`gnus-simplify-whitespace', and `gnus-simplify-all-whitespace'."
  :group 'gnus-thread
  :type '(repeat function))

(defcustom gnus-simplify-ignored-prefixes nil
  "Remove matches for this regexp from subject lines when simplifying fuzzily."
  :group 'gnus-thread
  :type '(choice (const :tag "off" nil)
		 regexp))

(defcustom gnus-build-sparse-threads nil
  "If non-nil, fill in the gaps in threads.
If set to the symbol `some', only fill in the gaps that are
needed to tie loose threads together.  If the symbol `more', fill
in all leaf nodes that Gnus can find.  If t (or any other value),
fill in all gaps that Gnus manages to guess."
  :group 'gnus-thread
  :type '(choice (const :tag "off" nil)
		 (const some)
		 (const more)
		 (sexp :menu-tag "all" t)))

(defcustom gnus-summary-thread-gathering-function
  #'gnus-gather-threads-by-subject
  "Function used for gathering loose threads.
There are two pre-defined functions: `gnus-gather-threads-by-subject',
which only takes Subjects into consideration; and
`gnus-gather-threads-by-references', which compared the References
headers of the articles to find matches."
  :group 'gnus-thread
  :type '(radio (function-item gnus-gather-threads-by-subject)
		(function-item gnus-gather-threads-by-references)
		(function :tag "other")))

(defcustom gnus-summary-same-subject ""
  "String indicating that the current article has the same subject as the previous.
This variable will only be used if the value of
`gnus-summary-make-false-root' is `empty'."
  :group 'gnus-summary-format
  :type 'string)

(defcustom gnus-summary-goto-unread nil
  "If t, many commands will go to the next unread article.
This applies to marking commands as well as other commands that
\"naturally\" select the next article, like, for instance, `SPC' at
the end of an article.

If nil, the marking commands do NOT go to the next unread article
\(they go to the next article instead).  If `never', commands that
usually go to the next unread article, will go to the next article,
whether it is read or not."
  :version "24.1"
  :group 'gnus-summary-marks
  :link '(custom-manual "(gnus)Setting Marks")
  :type '(choice (const :tag "off" nil)
		 (const never)
		 (sexp :menu-tag "on" t)))

(defcustom gnus-summary-default-score 0
  "Default article score level.
All scores generated by the score files will be added to this score.
If this variable is nil, scoring will be disabled."
  :group 'gnus-score-default
  :type '(choice (const :tag "disable")
		 integer))

(defcustom gnus-summary-default-high-score 0
  "Default threshold for a high scored article.
An article will be highlighted as high scored if its score is greater
than this score."
  :version "22.1"
  :group 'gnus-score-default
  :type 'integer)

(defcustom gnus-summary-default-low-score 0
  "Default threshold for a low scored article.
An article will be highlighted as low scored if its score is smaller
than this score."
  :version "22.1"
  :group 'gnus-score-default
  :type 'integer)

(defcustom gnus-summary-zcore-fuzz 0
  "Fuzziness factor for the zcore in the summary buffer.
Articles with scores closer than this to `gnus-summary-default-score'
will not be marked."
  :group 'gnus-summary-format
  :type 'integer)

(defcustom gnus-simplify-subject-fuzzy-regexp nil
  "Strings to be removed when doing fuzzy matches.
This can either be a regular expression or list of regular expressions
that will be removed from subject strings if fuzzy subject
simplification is selected."
  :group 'gnus-thread
  :type '(repeat regexp))

(defcustom gnus-show-threads t
  "If non-nil, display threads in summary mode."
  :group 'gnus-thread
  :type 'boolean)

(defcustom gnus-thread-hide-subtree nil
  "If non-nil, hide all threads initially.
This can be a predicate specifier which says which threads to hide.
If threads are hidden, you have to run the command
`gnus-summary-show-thread' by hand or select an article."
  :group 'gnus-thread
  :type '(radio (sexp :format "Non-nil\n"
		      :match (lambda (widget value)
			       (and value (not (functionp value))))
		      :value t)
		(const nil)
		(sexp :tag "Predicate specifier")))

(defcustom gnus-thread-hide-killed t
  "If non-nil, hide killed threads automatically."
  :group 'gnus-thread
  :type 'boolean)

(defcustom gnus-thread-ignore-subject t
  "If non-nil, ignore subjects when creating threads.

If nil, articles that have different subjects from their parents will
start separate threads.

Threads that are split because the subject changes will still be
sorted as if they were part of the same thread, and
`gnus-thread-sort-functions' will not apply to these split
threads."
  :group 'gnus-thread
  :type 'boolean)

(defcustom gnus-thread-operation-ignore-subject t
  "If non-nil, subjects will be ignored when doing thread commands.
This affects commands like `gnus-summary-kill-thread' and
`gnus-summary-lower-thread'.

If this variable is nil, articles in the same thread with different
subjects will not be included in the operation in question.  If this
variable is `fuzzy', only articles that have subjects that are fuzzily
equal will be included."
  :group 'gnus-thread
  :type '(choice (const :tag "off" nil)
		 (const fuzzy)
		 (sexp :tag "on" t)))

(defcustom gnus-thread-indent-level 4
  "Number that says how much each sub-thread should be indented."
  :group 'gnus-thread
  :type 'integer)

(defcustom gnus-auto-extend-newsgroup t
  "If non-nil, extend newsgroup forward and backward when requested."
  :group 'gnus-summary-choose
  :type 'boolean)

(defcustom gnus-auto-select-first t
  "If non-nil, select an article on group entry.
An article is selected automatically when entering a group
e.g. with \\<gnus-group-mode-map>\\[gnus-group-read-group], or via `gnus-summary-next-page' or
`gnus-summary-catchup-and-goto-next-group'.

Which article is selected is controlled by the variable
`gnus-auto-select-subject'.

If you want to prevent automatic selection of articles in some
newsgroups, set the variable to nil in `gnus-select-group-hook'."
  ;; Commands include...
  ;; \\<gnus-group-mode-map>\\[gnus-group-read-group]
  ;; \\<gnus-summary-mode-map>\\[gnus-summary-next-page]
  ;; \\<gnus-summary-mode-map>\\[gnus-summary-catchup-and-goto-next-group]
  :group 'gnus-group-select
  :type '(choice (const :tag "none" nil)
		 (sexp :menu-tag "first" t)))

(defcustom gnus-auto-select-subject 'unseen-or-unread
  "Says what subject to place under point when entering a group.

This variable can either be the symbols `first' (place point on the
first subject), `unread' (place point on the subject line of the first
unread article), `best' (place point on the subject line of the
highest-scored article), `unseen' (place point on the subject line of
the first unseen article), `unseen-or-unread' (place point on the subject
line of the first unseen article or, if all articles have been seen, on the
subject line of the first unread article), or a function to be called to
place point on some subject line."
  :version "24.1"
  :group 'gnus-group-select
  :type '(choice (const best)
		 (const unread)
		 (const first)
		 (const unseen)
	         (const unseen-or-unread)
		 (function :tag "Function to call")))

(defcustom gnus-auto-select-next t
  "If non-nil, offer to go to the next group from the end of the previous.
If the value is t and the next newsgroup is empty, Gnus will exit
summary mode and go back to group mode.  If the value is neither nil
nor t, Gnus will select the following unread newsgroup.  In
particular, if the value is the symbol `quietly', the next unread
newsgroup will be selected without any confirmation, and if it is
`almost-quietly', the next group will be selected without any
confirmation if you are located on the last article in the group.
Finally, if this variable is `slightly-quietly', the `\\<gnus-summary-mode-map>\\[gnus-summary-catchup-and-goto-next-group]' command
will go to the next group without confirmation."
  :group 'gnus-summary-maneuvering
  :type '(choice (const :tag "off" nil)
		 (const quietly)
		 (const almost-quietly)
		 (const slightly-quietly)
		 (sexp :menu-tag "on" t)))

(defcustom gnus-paging-select-next t
  "Control whether to select the next/prev article when paging.
If non-nil, select the next article when reaching the end of the
article (or the previous article when paging backwards).

If nil, don't do anything at the end/start of the articles."
  :version "28.1"
  :group 'gnus-summary-maneuvering
  :type 'boolean)

(defcustom gnus-auto-select-same nil
  "If non-nil, select the next article with the same subject.
If there are no more articles with the same subject, go to
the first unread article."
  :group 'gnus-summary-maneuvering
  :type 'boolean)

(defcustom gnus-auto-select-on-ephemeral-exit 'next-noselect
  "What article should be selected after exiting an ephemeral group.
Valid values include:

`next'
  Select the next article.
`next-unread'
  Select the next unread article.
`next-noselect'
  Move the cursor to the next article.  This is the default.
`next-unread-noselect'
  Move the cursor to the next unread article.

If it has any other value or there is no next (unread) article, the
article selected before entering to the ephemeral group will appear."
  :version "23.1" ;; No Gnus
  :group 'gnus-summary-maneuvering
  :type '(choice :format "%{%t%}:\n %[Value Menu%] %v"
		 (const next) (const next-unread)
		 (const next-noselect) (const next-unread-noselect)
		 (sexp :tag "other" :value nil)))

(defcustom gnus-auto-goto-ignores 'unfetched
  "Says how to handle unfetched articles when maneuvering.

This variable can either be the symbols nil (maneuver to any
article), `undownloaded' (maneuvering while unplugged ignores articles
that have not been fetched), `always-undownloaded' (maneuvering always
ignores articles that have not been fetched), `unfetched' (maneuvering
ignores articles whose headers have not been fetched).

NOTE: The list of unfetched articles will always be nil when plugged
and, when unplugged, a subset of the undownloaded article list."
  :version "22.1"
  :group 'gnus-summary-maneuvering
  :type '(choice (const :tag "None" nil)
                 (const :tag "Undownloaded when unplugged" undownloaded)
                 (const :tag "Undownloaded" always-undownloaded)
                 (const :tag "Unfetched" unfetched)))

(defcustom gnus-summary-check-current nil
  "If non-nil, consider the current article when moving.
The \"unread\" movement commands will stay on the same line if the
current article is unread."
  :group 'gnus-summary-maneuvering
  :type 'boolean)

(defcustom gnus-auto-center-summary
  (max (or (bound-and-true-p scroll-margin) 0) 2)
  "If non-nil, always center the current summary buffer.
In particular, if `vertical' do only vertical recentering.  If non-nil
and non-`vertical', do both horizontal and vertical recentering."
  :group 'gnus-summary-maneuvering
  :type '(choice (const :tag "none" nil)
		 (const vertical)
		 (integer :tag "height")
		 (sexp :menu-tag "both" t)))

(defcustom gnus-auto-center-group t
  "If non-nil, always center the group buffer."
  :group 'gnus-summary-maneuvering
  :type 'boolean)

(defcustom gnus-show-all-headers nil
  "If non-nil, don't hide any headers."
  :group 'gnus-article-hiding
  :group 'gnus-article-headers
  :type 'boolean)

(defcustom gnus-summary-ignore-duplicates nil
  "If non-nil, ignore articles with identical Message-ID headers."
  :group 'gnus-summary
  :type 'boolean)

(defcustom gnus-single-article-buffer nil
  "If non-nil, display all articles in the same buffer.
If nil, each group will get its own article buffer."
  :version "24.1"
  :group 'gnus-article-various
  :type 'boolean)

(defcustom gnus-widen-article-window nil
  "If non-nil, selecting the article buffer will display only the article buffer."
  :version "24.1"
  :group 'gnus-article-various
  :type 'boolean)

(defcustom gnus-break-pages t
  "If non-nil, do page breaking on articles.
The page delimiter is specified by the `gnus-page-delimiter'
variable."
  :group 'gnus-article-various
  :type 'boolean)

(defcustom gnus-move-split-methods nil
  "Variable used to suggest where articles are to be moved to.
It uses the same syntax as the `gnus-split-methods' variable.
However, whereas `gnus-split-methods' specifies file names as targets,
this variable specifies group names."
  :group 'gnus-summary-mail
  :type '(repeat (choice (list :value (fun) function)
			 (cons :value ("" "") regexp (repeat string))
			 (sexp :value nil))))

(defcustom gnus-move-group-prefix-function #'gnus-group-real-prefix
  "Function used to compute default prefix for article move/copy/etc prompts.
The function should take one argument, a group name, and return a
string with the suggested prefix."
  :group 'gnus-summary-mail
  :type 'function)

;; FIXME: Although the custom type is `character' for the following variables,
;; using multibyte characters (Latin-1, UTF-8) doesn't work.  -- rs

(defcustom gnus-unread-mark ?           ;Whitespace
  "Mark used for unread articles."
  :group 'gnus-summary-marks
  :type 'character)

(defcustom gnus-ticked-mark ?!
  "Mark used for ticked articles."
  :group 'gnus-summary-marks
  :type 'character)

(defcustom gnus-dormant-mark ??
  "Mark used for dormant articles."
  :group 'gnus-summary-marks
  :type 'character)

(defcustom gnus-del-mark ?r
  "Mark used for del'd articles."
  :group 'gnus-summary-marks
  :type 'character)

(defcustom gnus-read-mark ?R
  "Mark used for read articles."
  :group 'gnus-summary-marks
  :type 'character)

(defcustom gnus-expirable-mark ?E
  "Mark used for expirable articles."
  :group 'gnus-summary-marks
  :type 'character)

(defcustom gnus-killed-mark ?K
  "Mark used for killed articles."
  :group 'gnus-summary-marks
  :type 'character)

(defcustom gnus-spam-mark ?$
  "Mark used for spam articles."
  :version "22.1"
  :group 'gnus-summary-marks
  :type 'character)

(defcustom gnus-kill-file-mark ?X
  "Mark used for articles killed by kill files."
  :group 'gnus-summary-marks
  :type 'character)

(defcustom gnus-low-score-mark ?Y
  "Mark used for articles with a low score."
  :group 'gnus-summary-marks
  :type 'character)

(defcustom gnus-catchup-mark ?C
  "Mark used for articles that are caught up."
  :group 'gnus-summary-marks
  :type 'character)

(defcustom gnus-replied-mark ?A
  "Mark used for articles that have been replied to."
  :group 'gnus-summary-marks
  :type 'character)

(defcustom gnus-forwarded-mark ?F
  "Mark used for articles that have been forwarded."
  :version "22.1"
  :group 'gnus-summary-marks
  :type 'character)

(defcustom gnus-recent-mark ?N
  "Mark used for articles that are recent."
  :version "22.1"
  :group 'gnus-summary-marks
  :type 'character)

(defcustom gnus-cached-mark ?*
  "Mark used for articles that are in the cache."
  :group 'gnus-summary-marks
  :type 'character)

(defcustom gnus-saved-mark ?S
  "Mark used for articles that have been saved."
  :group 'gnus-summary-marks
  :type 'character)

(defcustom gnus-unseen-mark ?.
  "Mark used for articles that haven't been seen."
  :version "22.1"
  :group 'gnus-summary-marks
  :type 'character)

(defcustom gnus-no-mark ?               ;Whitespace
  "Mark used for articles that have no other secondary mark."
  :version "22.1"
  :group 'gnus-summary-marks
  :type 'character)

(defcustom gnus-ancient-mark ?O
  "Mark used for ancient articles."
  :group 'gnus-summary-marks
  :type 'character)

(defcustom gnus-sparse-mark ?Q
  "Mark used for sparsely reffed articles."
  :group 'gnus-summary-marks
  :type 'character)

(defcustom gnus-canceled-mark ?G
  "Mark used for canceled articles."
  :group 'gnus-summary-marks
  :type 'character)

(defcustom gnus-duplicate-mark ?M
  "Mark used for duplicate articles."
  :group 'gnus-summary-marks
  :type 'character)

(defcustom gnus-undownloaded-mark ?-
  "Mark used for articles that weren't downloaded."
  :version "22.1"
  :group 'gnus-summary-marks
  :type 'character)

(defcustom gnus-downloaded-mark ?+
  "Mark used for articles that were downloaded."
  :group 'gnus-summary-marks
  :type 'character)

(defcustom gnus-downloadable-mark ?%
  "Mark used for articles that are to be downloaded."
  :group 'gnus-summary-marks
  :type 'character)

(defcustom gnus-unsendable-mark ?=
  "Mark used for articles that won't be sent."
  :group 'gnus-summary-marks
  :type 'character)

(defcustom gnus-score-over-mark ?+
  "Score mark used for articles with high scores."
  :group 'gnus-summary-marks
  :type 'character)

(defcustom gnus-score-below-mark ?-
  "Score mark used for articles with low scores."
  :group 'gnus-summary-marks
  :type 'character)

(defcustom gnus-empty-thread-mark ?     ;Whitespace
  "There is no thread under the article."
  :group 'gnus-summary-marks
  :type 'character)

(defcustom gnus-not-empty-thread-mark ?=
  "There is a thread under the article."
  :group 'gnus-summary-marks
  :type 'character)

(defcustom gnus-view-pseudo-asynchronously nil
  "If non-nil, Gnus will view pseudo-articles asynchronously."
  :group 'gnus-extract-view
  :type 'boolean)

(defcustom gnus-auto-expirable-marks
  (list gnus-killed-mark gnus-del-mark gnus-catchup-mark
	gnus-low-score-mark gnus-ancient-mark gnus-read-mark
	gnus-duplicate-mark)
  "The list of marks converted into expiration if a group is auto-expirable."
  :version "24.1"
  :group 'gnus-summary
  :type '(repeat character))

(defcustom gnus-inhibit-user-auto-expire t
  "If non-nil, user marking commands will not mark an article as expirable.
This is true even if the group has auto-expire turned on."
  :version "21.1"
  :group 'gnus-summary
  :type 'boolean)

(defcustom gnus-mark-copied-or-moved-articles-as-expirable nil
  "If non-nil, mark articles copied or moved to auto-expire group as expirable.
If nil, the expirable marks will be unchanged except that the marks
will be removed when copying or moving articles to a group that has
not turned auto-expire on.  If non-nil, articles that have been read
will be marked as expirable when being copied or moved to a group in
which auto-expire is turned on."
  :version "23.2"
  :type 'boolean
  :group 'gnus-summary-marks)

(defcustom gnus-view-pseudos nil
  "If `automatic', pseudo-articles will be viewed automatically.
If `not-confirm', pseudos will be viewed automatically, and the user
will not be asked to confirm the command."
  :group 'gnus-extract-view
  :type '(choice (const :tag "off" nil)
		 (const automatic)
		 (const not-confirm)))

(defcustom gnus-view-pseudos-separately t
  "If non-nil, one pseudo-article will be created for each file to be viewed.
If nil, all files that use the same viewing command will be given as a
list of parameters to that command."
  :group 'gnus-extract-view
  :type 'boolean)

(defcustom gnus-insert-pseudo-articles t
  "If non-nil, insert pseudo-articles when decoding articles."
  :group 'gnus-extract-view
  :type 'boolean)

(defcustom gnus-summary-dummy-line-format
  "   %(:                             :%) %S\n"
  "The format specification for the dummy roots in the summary buffer.
It works along the same lines as a normal formatting string,
with some simple extensions.

%S  The subject

General format specifiers can also be used.
See `(gnus)Formatting Variables'."
  :link '(custom-manual "(gnus)Formatting Variables")
  :group 'gnus-threading
  :type 'string)

(defcustom gnus-summary-mode-line-format "Gnus: %g [%A] %Z"
  "The format specification for the summary mode line.
It works along the same lines as a normal formatting string,
with some simple extensions:

%G  Group name
%p  Unprefixed group name
%A  Current article number
%z  Current article score
%V  Gnus version
%U  Number of unread articles in the group
%e  Number of unselected articles in the group
%Z  A string with unread/unselected article counts
%g  Shortish group name
%S  Subject of the current article
%u  User-defined spec
%s  Current score file name
%d  Number of dormant articles
%r  Number of articles that have been marked as read in this session
%E  Number of articles expunged by the score files"
  :group 'gnus-summary-format
  :type 'string)

(defcustom gnus-list-identifiers nil
  "Regexp that matches list identifiers to be removed from subject.
This can also be a list of regexps."
  :version "21.1"
  :group 'gnus-summary-format
  :group 'gnus-article-hiding
  :type '(choice (const :tag "none" nil)
		 (regexp :value ".*")
		 (repeat :value (".*") regexp)))

(defcustom gnus-summary-mark-below 0
  "Mark all articles with a score below this variable as read.
This variable is local to each summary buffer and usually set by the
score file."
  :group 'gnus-score-default
  :type 'integer)

(defun gnus-widget-reversible-match (_widget value)
  "Ignoring WIDGET, convert VALUE to internal form.
VALUE should have the form `FOO' or `(not FOO)', where FOO is an symbol."
  ;; (debug value)
  (or (symbolp value)
      (and (listp value)
           (eq (length value) 2)
           (eq (nth 0 value) 'not)
           (symbolp (nth 1 value)))))

(defun gnus-widget-reversible-to-internal (_widget value)
  "Ignoring WIDGET, convert VALUE to internal form.
VALUE should have the form `FOO' or `(not FOO)', where FOO is an atom.
FOO is converted to (FOO nil) and (not FOO) is converted to (FOO t)."
  ;; (debug value)
  (if (atom value)
      (list value nil)
    (list (nth 1 value) t)))

(defun gnus-widget-reversible-to-external (_widget value)
  "Ignoring WIDGET, convert VALUE to external form.
VALUE should have the form `(FOO nil)' or `(FOO t)', where FOO is an atom.
\(FOO  nil) is converted to FOO and (FOO t) is converted to (not FOO)."
  ;; (debug value)
  (if (nth 1 value)
      (list 'not (nth 0 value))
    (nth 0 value)))

(define-widget 'gnus-widget-reversible 'group
  "A `group' that convert values."
  :match 'gnus-widget-reversible-match
  :value-to-internal 'gnus-widget-reversible-to-internal
  :value-to-external 'gnus-widget-reversible-to-external)

(defcustom gnus-article-sort-functions '(gnus-article-sort-by-number)
  "List of functions used for sorting articles in the summary buffer.

Each function takes two articles and returns non-nil if the first
article should be sorted before the other.  If you use more than one
function, the primary sort function should be the last.  You should
probably always include `gnus-article-sort-by-number' in the list of
sorting functions -- preferably first.  Also note that sorting by date
is often much slower than sorting by number, and the sorting order is
very similar.  (Sorting by date means sorting by the time the message
was sent, sorting by number means sorting by arrival time.)

Each item can also be a list `(not F)' where F is a function;
this reverses the sort order.

Ready-made functions include `gnus-article-sort-by-number',
`gnus-article-sort-by-author', `gnus-article-sort-by-subject',
`gnus-article-sort-by-date', `gnus-article-sort-by-score',
`gnus-article-sort-by-rsv', `gnus-article-sort-by-newsgroups',
and `gnus-article-sort-by-random'.

When threading is turned on, the variable `gnus-thread-sort-functions'
controls how articles are sorted."
  :group 'gnus-summary-sort
  :type '(repeat (gnus-widget-reversible
                  (choice (function-item gnus-article-sort-by-number)
                          (function-item gnus-article-sort-by-author)
                          (function-item gnus-article-sort-by-subject)
                          (function-item gnus-article-sort-by-date)
                          (function-item gnus-article-sort-by-score)
                          (function-item gnus-article-sort-by-rsv)
                          (function-item gnus-article-sort-by-newsgroups)
                          (function-item gnus-article-sort-by-random)
                          (function :tag "other"))
                  (boolean :tag "Reverse order"))))

(defcustom gnus-thread-sort-functions '(gnus-thread-sort-by-number)
  "List of functions used for sorting threads in the summary buffer.
By default, threads are sorted by article number.

Each function takes two threads and returns non-nil if the first
thread should be sorted before the other.  If you use more than one
function, the primary sort function should be the last.  You should
probably always include `gnus-thread-sort-by-number' in the list of
sorting functions -- preferably first.  Also note that sorting by date
is often much slower than sorting by number, and the sorting order is
very similar.  (Sorting by date means sorting by the time the message
was sent, sorting by number means sorting by arrival time.)

Each list item can also be a list `(not F)' where F is a
function; this specifies reversed sort order.

Ready-made functions include `gnus-thread-sort-by-number',
`gnus-thread-sort-by-author', `gnus-thread-sort-by-recipient'
`gnus-thread-sort-by-subject', `gnus-thread-sort-by-date',
`gnus-thread-sort-by-score', `gnus-thread-sort-by-most-recent-number',
`gnus-thread-sort-by-most-recent-date', `gnus-thread-sort-by-newsgroups',
`gnus-thread-sort-by-random', and `gnus-thread-sort-by-total-score' (see
`gnus-thread-score-function').

When threading is turned off, the variable
`gnus-article-sort-functions' controls how articles are sorted.

By default, threads and their subthreads are sorted according to
the value of this variable.  To use a different sorting order for
subthreads, customize `gnus-subthread-sort-functions'."
  :group 'gnus-summary-sort
  :type '(repeat
          (gnus-widget-reversible
           (choice (function-item gnus-thread-sort-by-number)
                   (function-item gnus-thread-sort-by-author)
                   (function-item gnus-thread-sort-by-recipient)
                   (function-item gnus-thread-sort-by-subject)
                   (function-item gnus-thread-sort-by-date)
                   (function-item gnus-thread-sort-by-score)
                   (function-item gnus-thread-sort-by-rsv)
                   (function-item gnus-thread-sort-by-most-recent-number)
                   (function-item gnus-thread-sort-by-most-recent-date)
                   (function-item gnus-thread-sort-by-newsgroups)
                   (function-item gnus-thread-sort-by-random)
                   (function-item gnus-thread-sort-by-total-score)
                   (function :tag "other"))
           (boolean :tag "Reverse order"))))

(defcustom gnus-subthread-sort-functions 'gnus-thread-sort-functions
  "List of functions used for sorting subthreads in the summary buffer.
By default, subthreads are sorted the same as threads, i.e.,
according to the value of `gnus-thread-sort-functions'."
  :version "24.4"
  :group 'gnus-summary-sort
  :type '(choice
	  (const :tag "Sort subthreads like threads" gnus-thread-sort-functions)
	  (repeat
	   (gnus-widget-reversible
	    (choice (function-item gnus-thread-sort-by-number)
		    (function-item gnus-thread-sort-by-author)
		    (function-item gnus-thread-sort-by-recipient)
		    (function-item gnus-thread-sort-by-subject)
		    (function-item gnus-thread-sort-by-date)
		    (function-item gnus-thread-sort-by-score)
		    (function-item gnus-thread-sort-by-most-recent-number)
		    (function-item gnus-thread-sort-by-most-recent-date)
                    (function-item gnus-thread-sort-by-newsgroups)
		    (function-item gnus-thread-sort-by-random)
		    (function-item gnus-thread-sort-by-total-score)
		    (function :tag "other"))
	    (boolean :tag "Reverse order")))))

(defcustom gnus-thread-score-function #'+
  "Function used for calculating the total score of a thread.

The function is called with the scores of the article and each
subthread and should then return the score of the thread.

Some functions you can use are `+', `max', or `min'."
  :group 'gnus-summary-sort
  :type 'function)

(defcustom gnus-summary-expunge-below nil
  "All articles that have a score less than this variable will be expunged.
This variable is local to the summary buffers."
  :group 'gnus-score-default
  :type '(choice (const :tag "off" nil)
		 integer))

(defcustom gnus-thread-expunge-below nil
  "All threads that have a total score less than this variable will be expunged.
See `gnus-thread-score-function' for en explanation of what a
\"thread score\" is.

This variable is local to the summary buffers."
  :group 'gnus-threading
  :group 'gnus-score-default
  :type '(choice (const :tag "off" nil)
		 integer))

(defcustom gnus-summary-menu-hook nil
  "Hook run after the creation of the summary mode menu."
  :group 'gnus-summary-visual
  :type 'hook)

(defcustom gnus-summary-exit-hook nil
  "A hook called on exit from the summary buffer.
It will be called with point in the group buffer."
  :group 'gnus-summary-exit
  :type 'hook)

(defcustom gnus-summary-prepare-hook nil
  "A hook called after the summary buffer has been generated.
If you want to modify the summary buffer, you can use this hook."
  :group 'gnus-summary-various
  :type 'hook)

(defcustom gnus-summary-prepared-hook nil
  "A hook called as the last thing after the summary buffer has been generated."
  :group 'gnus-summary-various
  :type 'hook)

(defcustom gnus-summary-generate-hook nil
  "A hook run just before generating the summary buffer.
This hook is commonly used to customize threading variables and the
like."
  :group 'gnus-summary-various
  :type 'hook)

(defcustom gnus-select-group-hook nil
  "A hook called when a newsgroup is selected.

If you'd like to simplify subjects like the
`gnus-summary-next-same-subject' command does, you can use the
following hook:

 (add-hook gnus-select-group-hook
	   (lambda ()
	     (mapcar (lambda (header)
		       (setf (mail-header-subject header)
		             (gnus-simplify-subject
		              (mail-header-subject header) \\='re-only)))
		     gnus-newsgroup-headers)))"
  :group 'gnus-group-select
  :type 'hook)

(defcustom gnus-select-article-hook nil
  "A hook called when an article is selected."
  :group 'gnus-summary-choose
  :options '(gnus-agent-fetch-selected-article)
  :type 'hook)

(defcustom gnus-visual-mark-article-hook
  (list 'gnus-highlight-selected-summary)
  "Hook run after selecting an article in the summary buffer.
It is meant to be used for highlighting the article in some way.  It
is not run if `gnus-visual' is nil."
  :group 'gnus-summary-visual
  :type 'hook)

(defcustom gnus-parse-headers-hook nil
  "A hook called before parsing the headers."
  :group 'gnus-various
  :type 'hook)

(defcustom gnus-exit-group-hook nil
  "A hook called when exiting summary mode.
This hook is not called from the non-updating exit commands like `Q'."
  :group 'gnus-various
  :type 'hook)

(defcustom gnus-summary-update-hook nil
  "A hook called when a summary line is changed.
The hook will not be called if `gnus-visual' is nil.

The default function `gnus-summary-highlight-line' will
highlight the line according to the `gnus-summary-highlight'
variable."
  :group 'gnus-summary-visual
  :type 'hook)

(defcustom gnus-mark-article-hook '(gnus-summary-mark-read-and-unread-as-read)
  "A hook called when an article is selected for the first time.
The hook is intended to mark an article as read (or unread)
automatically when it is selected."
  :group 'gnus-summary-choose
  :type 'hook)

(defcustom gnus-group-no-more-groups-hook nil
  "A hook run when returning to group mode having no more (unread) groups."
  :group 'gnus-group-select
  :type 'hook)

(defcustom gnus-ps-print-hook nil
  "A hook run before ps-printing something from Gnus."
  :group 'gnus-summary
  :type 'hook)

(defcustom gnus-summary-article-move-hook nil
  "A hook called after an article is moved, copied, respooled, or crossposted."
  :version "22.1"
  :group 'gnus-summary
  :type 'hook)

(defcustom gnus-summary-article-delete-hook nil
  "A hook called after an article is deleted."
  :version "22.1"
  :group 'gnus-summary
  :type 'hook)

(defcustom gnus-summary-article-expire-hook nil
  "A hook called after an article is expired."
  :version "22.1"
  :group 'gnus-summary
  :type 'hook)

(defcustom gnus-summary-display-arrow (display-graphic-p)
  "If non-nil, display an arrow highlighting the current article."
  :version "22.1"
  :group 'gnus-summary
  :type 'boolean)

(defcustom gnus-summary-selected-face 'gnus-summary-selected
  "Face used for highlighting the current article in the summary buffer."
  :group 'gnus-summary-visual
  :type 'face)

(defvar gnus-tmp-downloaded nil)

(defcustom gnus-summary-highlight
  '(((eq mark gnus-canceled-mark)
     . gnus-summary-cancelled)
    ((and uncached (> score default-high))
     . gnus-summary-high-undownloaded)
    ((and uncached (< score default-low))
     . gnus-summary-low-undownloaded)
    (uncached
     . gnus-summary-normal-undownloaded)
    ((and (> score default-high)
	  (or (eq mark gnus-dormant-mark)
	      (eq mark gnus-ticked-mark)))
     . gnus-summary-high-ticked)
    ((and (< score default-low)
	  (or (eq mark gnus-dormant-mark)
	      (eq mark gnus-ticked-mark)))
     . gnus-summary-low-ticked)
    ((or (eq mark gnus-dormant-mark)
	 (eq mark gnus-ticked-mark))
     . gnus-summary-normal-ticked)
    ((and (> score default-high) (eq mark gnus-ancient-mark))
     . gnus-summary-high-ancient)
    ((and (< score default-low) (eq mark gnus-ancient-mark))
     . gnus-summary-low-ancient)
    ((eq mark gnus-ancient-mark)
     . gnus-summary-normal-ancient)
    ((and (> score default-high) (eq mark gnus-unread-mark))
     . gnus-summary-high-unread)
    ((and (< score default-low) (eq mark gnus-unread-mark))
     . gnus-summary-low-unread)
    ((eq mark gnus-unread-mark)
     . gnus-summary-normal-unread)
    ((> score default-high)
     . gnus-summary-high-read)
    ((< score default-low)
     . gnus-summary-low-read)
    (t
     . gnus-summary-normal-read))
  "Controls the highlighting of summary buffer lines.

A list of (FORM . FACE) pairs.  When deciding how a particular
summary line should be displayed, each form is evaluated.  The content
of the face field after the first true form is used.  You can change
how those summary lines are displayed, by editing the face field.

You can use the following variables in the FORM field.

score:        The article's score.
default:      The default article score.
default-high: The default score for high scored articles.
default-low:  The default score for low scored articles.
mark:         The article's mark.
uncached:     Non-nil if the article is uncached."
  :group 'gnus-summary-visual
  :type '(repeat (cons (sexp :tag "Form" nil)
		       face)))
(put 'gnus-summary-highlight 'risky-local-variable t)

(defcustom gnus-alter-header-function nil
  "Function called to allow alteration of article header structures.
The function is called with one parameter, the article header vector,
which it may alter in any way."
  :type '(choice (const :tag "None" nil)
		 function)
  :group 'gnus-summary)

(defvar gnus-decode-encoded-word-function #'mail-decode-encoded-word-string
  "Function used to decode a string with encoded words.")

(defvar gnus-decode-encoded-address-function
  #'mail-decode-encoded-address-string
  "Function used to decode addresses with encoded words.")

(defcustom gnus-extra-headers '(To Cc Keywords Gcc Newsgroups X-GM-LABELS)
  "Extra headers to parse."
  :version "25.1"
  :group 'gnus-summary
  :type '(repeat symbol))

(defcustom gnus-ignored-from-addresses
  (and user-mail-address
       (not (string= user-mail-address ""))
       (regexp-quote user-mail-address))
  "From headers that may be suppressed in favor of To headers.
This can be a regexp, a list of regexps or a function.

If a function, an email string is passed as the argument."
  :version "21.1"
  :group 'gnus-summary
  :type '(choice regexp
		 (repeat :tag "Regexp List" regexp)
                 function))

(defsubst gnus-ignored-from-addresses ()
  (cond ((functionp gnus-ignored-from-addresses)
         gnus-ignored-from-addresses)
        (t (gmm-regexp-concat gnus-ignored-from-addresses))))

(defcustom gnus-summary-to-prefix "-> "
  "String prefixed to the To field in the summary line when
using `gnus-ignored-from-addresses'."
  :version "22.1"
  :group 'gnus-summary
  :type 'string)

(defcustom gnus-summary-newsgroup-prefix "=> "
  "String prefixed to the Newsgroup field in the summary
line when using the option `gnus-ignored-from-addresses'."
  :version "22.1"
  :group 'gnus-summary
  :type 'string)

(defcustom gnus-newsgroup-ignored-charsets '(unknown-8bit x-unknown)
  "List of charsets that should be ignored.
When these charsets are used in the \"charset\" parameter, the
default charset will be used instead."
  :version "21.1"
  :type '(repeat symbol)
  :group 'gnus-charset)

(defcustom gnus-newsgroup-maximum-articles nil
  "The maximum number of articles a newsgroup.
If this is a number, old articles in a newsgroup exceeding this number
are silently ignored.  If it is nil, no article is ignored.  Note that
setting this variable to a number might prevent you from reading very
old articles."
  :group 'gnus-group-select
  :version "22.2"
  :type '(choice (const :tag "No limit" nil)
		 integer))

(gnus-define-group-parameter
 ignored-charsets
 :type list
 :function-document
 "Return the ignored charsets of GROUP."
 :variable gnus-group-ignored-charsets-alist
 :variable-default
 '(("alt\\.chinese\\.text" iso-8859-1))
 :variable-document
 "Alist of regexps (to match group names) and charsets that should be ignored.
When these charsets are used in the \"charset\" parameter, the
default charset will be used instead."
 :variable-group gnus-charset
 :variable-type '(repeat (cons (regexp :tag "Group")
			       (repeat symbol)))
 :parameter-type '(choice :tag "Ignored charsets"
			  :value nil
			  (repeat (symbol)))
 :parameter-document       "\
List of charsets that should be ignored.

When these charsets are used in the \"charset\" parameter, the
default charset will be used instead.")

(defcustom gnus-group-highlight-words-alist nil
  "Alist of group regexps and highlight regexps.
This variable uses the same syntax as `gnus-emphasis-alist'."
  :version "21.1"
  :type '(repeat (cons (regexp :tag "Group")
		       (repeat (list (regexp :tag "Highlight regexp")
				     (number :tag "Group for entire word" 0)
				     (number :tag "Group for displayed part" 0)
				     (symbol :tag "Face"
					     gnus-emphasis-highlight-words)))))
  :group 'gnus-summary-visual)

(defcustom gnus-summary-show-article-charset-alist
  nil
  "Alist of number and charset.
The article will be shown with the charset corresponding to the
numbered argument.
For example: ((1 . cn-gb-2312) (2 . big5))."
  :version "21.1"
  :type '(repeat (cons (number :tag "Argument" 1)
		       (symbol :tag "Charset")))
  :group 'gnus-charset)

(defcustom gnus-preserve-marks t
  "Whether marks are preserved when moving, copying and respooling messages."
  :version "21.1"
  :type 'boolean
  :group 'gnus-summary-marks)

(defcustom gnus-alter-articles-to-read-function
  (lambda (_group article-list) article-list)
  "Function to be called to alter the list of articles to be selected.
This option defaults to a lambda form that simply returns the
list of articles unchanged.  Use `add-function' to set one or
more custom filter functions."
  :type 'function
  :group 'gnus-summary)

(defcustom gnus-orphan-score nil
  "All orphans get this score added.  Set in the score file."
  :group 'gnus-score-default
  :type '(choice (const nil)
		 integer))

(defcustom gnus-summary-save-parts-default-mime "image/.*"
  "A regexp to match MIME parts when saving multiple parts of a
message with `gnus-summary-save-parts' (\\<gnus-summary-mode-map>\\[gnus-summary-save-parts]).
This regexp will be used by default when prompting the user for which
type of files to save."
  :group 'gnus-summary
  :type 'regexp)

(defcustom gnus-read-all-available-headers nil
  "Whether Gnus should parse all headers made available to it.
This is mostly relevant for slow back ends where the user may
wish to widen the summary buffer to include all headers
that were fetched."
  :version "22.1"
  :group 'gnus-summary
  :type '(choice boolean regexp))

(defcustom gnus-summary-pipe-output-default-command nil
  "Command (and optional arguments) used to pipe article to subprocess.
This will be used as the default command if it is non-nil.  The value
will be updated if you modify it when executing the command
`gnus-summary-pipe-output' or the function `gnus-summary-save-in-pipe'."
  :version "23.1" ;; No Gnus
  :group 'gnus-summary
  :type '(radio (const :tag "None" nil) (string :tag "Command")))

(defcustom gnus-summary-muttprint-program "muttprint"
  "Command (and optional arguments) used to run Muttprint.
The value will be updated if you modify it when executing the command
`gnus-summary-muttprint'."
  :version "22.1"
  :group 'gnus-summary
  :type 'string)

(defcustom gnus-article-loose-mime t
  "If non-nil, don't require MIME-Version header.
Some brain-damaged MUA/MTA, e.g. Lotus Domino 5.0.6 clients, does not
supply the MIME-Version header or deliberately strip it from the mail.
If non-nil (the default), Gnus will treat some articles as MIME
even if the MIME-Version header is missing."
  :version "22.1"
  :type 'boolean
  :group 'gnus-article-mime)

(defcustom gnus-article-emulate-mime t
  "If non-nil, use MIME emulation for uuencode and the like.
This means that Gnus will search message bodies for text that look
like uuencoded bits, yEncoded bits, and so on, and present that using
the normal Gnus MIME machinery."
  :version "22.1"
  :type 'boolean
  :group 'gnus-article-mime)

;;; Internal variables

(defvar gnus-summary-display-cache nil)
(defvar gnus-article-mime-handles nil)
(defvar gnus-article-decoded-p nil)
(defvar gnus-article-charset nil)
(defvar gnus-article-ignored-charsets nil)
(defvar gnus-scores-exclude-files nil)
(defvar gnus-page-broken nil)

(defvar gnus-original-article nil)
(defvar gnus-article-internal-prepare-hook nil)
(defvar gnus-newsgroup-process-stack nil)

(defvar gnus-thread-indent-array nil)
(defvar gnus-thread-indent-array-level gnus-thread-indent-level)
(defvar gnus-sort-gathered-threads-function #'gnus-thread-sort-by-number
  "Function to sort articles within a thread after it has been gathered together.")

(defvar gnus-summary-save-parts-type-history nil)
(defvar gnus-summary-save-parts-last-directory mm-default-directory)

;; Avoid highlighting in kill files.
(defvar gnus-summary-inhibit-highlight nil)
(defvar gnus-newsgroup-selected-overlay nil)
(defvar gnus-inhibit-limiting nil)
(defvar gnus-newsgroup-adaptive-score-file nil)
(defvar gnus-current-score-file nil)
(defvar gnus-current-move-group nil)
(defvar gnus-current-copy-group nil)
(defvar gnus-current-crosspost-group nil)
(defvar gnus-newsgroup-display nil)

(defvar gnus-newsgroup-dependencies nil
  "A hash table holding dependencies between messages.")
;; Dependencies are held in a tree structure: a list with the root
;; message as car, and each immediate child a sublist (perhaps
;; containing further sublists).  Each message is represented as a
;; vector of headers.  Each message's list can be looked up in the
;; dependency table using the message's Message-ID as the key.  The
;; root key is the string "none".

(defvar gnus-newsgroup-adaptive nil)
(defvar gnus-summary-display-article-function nil)
(defvar gnus-summary-highlight-line-function nil
  "Function called after highlighting a summary line.")

(defvar gnus-summary-line-format-alist
  `((?N ,(macroexpand '(mail-header-number gnus-tmp-header)) ?d)
    (?S ,(macroexpand '(mail-header-subject gnus-tmp-header)) ?s)
    (?s gnus-tmp-subject-or-nil ?s)
    (?n gnus-tmp-name ?s)
    (?A (car (cdr (funcall gnus-extract-address-components gnus-tmp-from)))
	?s)
    (?a (or (car (funcall gnus-extract-address-components gnus-tmp-from))
	    gnus-tmp-from)
        ?s)
    (?F gnus-tmp-from ?s)
    (?x ,(macroexpand '(mail-header-xref gnus-tmp-header)) ?s)
    (?D ,(macroexpand '(mail-header-date gnus-tmp-header)) ?s)
    (?d (gnus-dd-mmm (mail-header-date gnus-tmp-header)) ?s)
    (?o (gnus-date-iso8601 (mail-header-date gnus-tmp-header)) ?s)
    (?M ,(macroexpand '(mail-header-id gnus-tmp-header)) ?s)
    (?r ,(macroexpand '(mail-header-references gnus-tmp-header)) ?s)
    (?c (or (mail-header-chars gnus-tmp-header) 0) ?d)
    (?k (gnus-summary-line-message-size gnus-tmp-header) ?s)
    (?L gnus-tmp-lines ?s)
    (?Z (or (nnselect-article-rsv (mail-header-number gnus-tmp-header))
	    0) ?d)
    (?G (or (nnselect-article-group (mail-header-number gnus-tmp-header))
	    "") ?s)
    (?g (or (gnus-group-short-name
	     (nnselect-article-group (mail-header-number gnus-tmp-header)))
	    "") ?s)
    (?O gnus-tmp-downloaded ?c)
    (?I gnus-tmp-indentation ?s)
    (?T (if (= gnus-tmp-level 0) "" (make-string (frame-width) ? )) ?s)
    (?R gnus-tmp-replied ?c)
    (?\[ gnus-tmp-opening-bracket ?s)
    (?\] gnus-tmp-closing-bracket ?s)
    (?\> (make-string gnus-tmp-level ? ) ?s)
    (?\< (make-string (max 0 (- 20 gnus-tmp-level)) ? ) ?s)
    (?i gnus-tmp-score ?d)
    (?z gnus-tmp-score-char ?c)
    (?V (gnus-thread-total-score
         (and (boundp 'gnus-tmp-thread) (car gnus-tmp-thread)))
        ?d)
    (?U gnus-tmp-unread ?c)
    (?f (gnus-summary-from-or-to-or-newsgroups gnus-tmp-header gnus-tmp-from)
	?s)
    (?t (gnus-summary-number-of-articles-in-thread
	 (and (boundp 'gnus-tmp-thread) (car gnus-tmp-thread)) gnus-tmp-level)
	?d)
    (?e (gnus-summary-number-of-articles-in-thread
	 (and (boundp 'gnus-tmp-thread) (car gnus-tmp-thread)) gnus-tmp-level t)
	?c)
    (?u gnus-tmp-user-defined ?s)
    (?P (gnus-pick-line-number) ?d)
    (?B gnus-tmp-thread-tree-header-string ?s)
    (user-date (gnus-user-date
		,(macroexpand '(mail-header-date gnus-tmp-header)))
               ?s))
  "An alist of format specifications that can appear in summary lines.
These are paired with what variables they correspond with, along with
the type of the variable (string, integer, character, etc).")

(defvar gnus-summary-dummy-line-format-alist
  '((?S gnus-tmp-subject ?s)
    (?N gnus-tmp-number ?d)
    (?u gnus-tmp-user-defined ?s)))

(defvar gnus-summary-mode-line-format-alist
  '((?G gnus-tmp-group-name ?s)
    (?g (gnus-short-group-name gnus-tmp-group-name) ?s)
    (?p (gnus-group-real-name gnus-tmp-group-name) ?s)
    (?A gnus-tmp-article-number ?d)
    (?Z gnus-tmp-unread-and-unselected ?s)
    (?V gnus-version ?s)
    (?U gnus-tmp-unread-and-unticked ?d)
    (?S gnus-tmp-subject ?s)
    (?e gnus-tmp-unselected ?d)
    (?u gnus-tmp-user-defined ?s)
    (?d (length gnus-newsgroup-dormant) ?d)
    (?t (length gnus-newsgroup-marked) ?d)
    (?h (length gnus-newsgroup-spam-marked) ?d)
    (?r (length gnus-newsgroup-reads) ?d)
    (?z (gnus-summary-article-score gnus-tmp-article-number) ?d)
    (?E gnus-newsgroup-expunged-tally ?d)
    (?s (gnus-current-score-file-nondirectory) ?s)))

;; This is here rather than in gnus-art for compilation reasons.
(defvar gnus-article-mode-line-format-alist
  (append '((?w (gnus-article-wash-status) ?s)
	    (?m (gnus-article-mime-part-status) ?s))
	  gnus-summary-mode-line-format-alist))

(defvar gnus-last-search-regexp nil
  "Default regexp for article search command.")

(defvar gnus-last-shell-command nil
  "Default shell command on article.")

(defvar gnus-newsgroup-agentized nil
  "Locally bound in each summary buffer to indicate if server has been agentized.")
(defvar gnus-newsgroup-begin nil)
(defvar gnus-newsgroup-end nil)
(defvar gnus-newsgroup-last-rmail nil)
(defvar gnus-newsgroup-last-mail nil)
(defvar gnus-newsgroup-last-folder nil)
(defvar gnus-newsgroup-last-file nil)
(defvar gnus-newsgroup-last-directory nil)
(defvar gnus-newsgroup-auto-expire nil)
(defvar gnus-newsgroup-active nil)
(defvar gnus-newsgroup-highest nil)

(defvar gnus-newsgroup-data nil)
(defvar gnus-newsgroup-data-reverse nil)
(defvar gnus-newsgroup-limit nil)
(defvar gnus-newsgroup-limits nil)
(defvar gnus-summary-use-undownloaded-faces nil)

(defvar gnus-newsgroup-unreads nil
  "Sorted list of unread articles in the current newsgroup.")

(defvar gnus-newsgroup-unselected nil
  "Sorted list of unselected unread articles in the current newsgroup.")

(defvar gnus-newsgroup-reads nil
  "Alist of read articles and article marks in the current newsgroup.")

(defvar gnus-newsgroup-expunged-tally nil)

(defvar gnus-newsgroup-marked nil
  "Sorted list of ticked articles in current newsgroup (a subset of unread art).")

(defvar gnus-newsgroup-spam-marked nil
  "List of ranges of articles that have been marked as spam.")

(defvar gnus-newsgroup-killed nil
  "List of ranges of articles that have been through the scoring process.")

(defvar gnus-newsgroup-cached nil
  "Sorted list of articles that come from the article cache.")

(defvar gnus-newsgroup-saved nil
  "List of articles that have been saved.")

(defvar gnus-newsgroup-kill-headers nil)

(defvar gnus-newsgroup-replied nil
  "List of articles that have been replied to in the current newsgroup.")

(defvar gnus-newsgroup-forwarded nil
  "List of articles that have been forwarded in the current newsgroup.")

(defvar gnus-newsgroup-expirable nil
  "Sorted list of articles in the current newsgroup that can be expired.")

(defvar gnus-newsgroup-processable nil
  "List of articles in the current newsgroup that can be processed.")

(defvar gnus-newsgroup-downloadable nil
  "Sorted list of articles in the current newsgroup that can be processed.")

(defvar gnus-newsgroup-unfetched nil
  "Sorted list of articles in the current newsgroup whose headers have
not been fetched into the agent.

This list will always be a subset of gnus-newsgroup-undownloaded.")

(defvar gnus-newsgroup-undownloaded nil
  "List of articles in the current newsgroup that haven't been downloaded.")

(defvar gnus-newsgroup-unsendable nil
  "List of articles in the current newsgroup that won't be sent.")

(defvar gnus-newsgroup-bookmarks nil
  "List of articles in the current newsgroup that have bookmarks.")

(defvar gnus-newsgroup-dormant nil
  "Sorted list of dormant articles in the current newsgroup.")

(defvar gnus-newsgroup-unseen nil
  "List of unseen articles in the current newsgroup.")

(defvar gnus-newsgroup-seen nil
  "Range of seen articles in the current newsgroup.")

(defvar gnus-newsgroup-unexist nil
  "Range of unexisting articles in the current newsgroup.")

(defvar gnus-newsgroup-articles nil
  "List of articles in the current newsgroup.")

(defvar gnus-newsgroup-scored nil
  "List of scored articles in the current newsgroup.")

(defvar gnus-newsgroup-headers nil
  "List of article headers in the current newsgroup.")

(defvar gnus-newsgroup-threads nil)

(defvar gnus-newsgroup-prepared nil
  "Whether the current group has been prepared properly.")

(defvar gnus-newsgroup-ancient nil
  "List of `gnus-fetch-old-headers' articles in the current newsgroup.")

(defvar gnus-newsgroup-sparse nil)

(defvar gnus-newsgroup-selection nil)

(defvar gnus-current-article nil)
(defvar gnus-article-current nil)
(defvar gnus-current-headers nil)
(defvar gnus-have-all-headers nil)
(defvar gnus-last-article nil)
(defvar gnus-newsgroup-history nil)
(defvar gnus-newsgroup-charset nil)
(defvar gnus-newsgroup-ephemeral-charset nil)
(defvar gnus-newsgroup-ephemeral-ignored-charsets nil)

(defvar gnus-article-before-search nil)

(defvar gnus-summary-local-variables
  '(gnus-newsgroup-name

    ;; Marks lists
    gnus-newsgroup-unreads
    gnus-newsgroup-unselected
    gnus-newsgroup-marked
    gnus-newsgroup-spam-marked
    gnus-newsgroup-reads
    gnus-newsgroup-saved
    gnus-newsgroup-replied
    gnus-newsgroup-forwarded
    gnus-newsgroup-expirable
    gnus-newsgroup-killed
    gnus-newsgroup-unseen
    gnus-newsgroup-seen
    gnus-newsgroup-unexist
    gnus-newsgroup-cached
    gnus-newsgroup-downloadable
    gnus-newsgroup-undownloaded
    gnus-newsgroup-unsendable

    gnus-newsgroup-selection

    gnus-newsgroup-begin gnus-newsgroup-end
    gnus-newsgroup-last-rmail gnus-newsgroup-last-mail
    gnus-newsgroup-last-folder gnus-newsgroup-last-file
    gnus-newsgroup-last-directory
    gnus-newsgroup-auto-expire
    gnus-newsgroup-processable
    gnus-newsgroup-unfetched
    gnus-newsgroup-articles
    gnus-newsgroup-bookmarks gnus-newsgroup-dormant
    gnus-newsgroup-headers gnus-newsgroup-threads
    gnus-newsgroup-prepared gnus-summary-highlight-line-function
    gnus-current-article gnus-current-headers gnus-have-all-headers
    gnus-last-article gnus-article-internal-prepare-hook
    (gnus-summary-article-delete-hook . global)
    (gnus-summary-article-move-hook . global)
    gnus-newsgroup-dependencies gnus-newsgroup-selected-overlay
    gnus-newsgroup-scored gnus-newsgroup-kill-headers
    gnus-thread-expunge-below
    gnus-score-alist gnus-current-score-file
    (gnus-summary-expunge-below . global)
    (gnus-summary-mark-below . global)
    (gnus-orphan-score . global)
    gnus-newsgroup-active gnus-scores-exclude-files
    gnus-newsgroup-highest
    gnus-newsgroup-history gnus-newsgroup-ancient
    gnus-newsgroup-sparse gnus-newsgroup-process-stack
    (gnus-newsgroup-adaptive . gnus-use-adaptive-scoring)
    gnus-newsgroup-adaptive-score-file (gnus-reffed-article-number . -1)
    (gnus-newsgroup-expunged-tally . 0)
    gnus-cache-removable-articles
    gnus-newsgroup-data gnus-newsgroup-data-reverse
    gnus-newsgroup-limit gnus-newsgroup-limits
    gnus-newsgroup-charset gnus-newsgroup-display
    gnus-summary-use-undownloaded-faces)
  "Variables that are buffer-local to the summary buffers.")

(defvar gnus-newsgroup-variables nil
  "A list of variables that have separate values in different newsgroups.
A list of newsgroup (summary buffer) local variables, or cons of
variables and their default expressions to be evalled (when the default
values are not nil), that should be made global while the summary buffer
is active.

Note: The default expressions will be evaluated (using function `eval')
before assignment to the local variable rather than just assigned to it.
If the default expression is the symbol `global', that symbol will not
be evaluated but the global value of the local variable will be used
instead.

These variables can be used to set variables in the group parameters
while still allowing them to affect operations done in other buffers.
For example:

\(setq gnus-newsgroup-variables
     \\='(message-use-followup-to
       (gnus-visible-headers .
	 \"^From:\\\\|^Newsgroups:\\\\|^Subject:\\\\|^Date:\\\\|^To:\")))
")

(eval-when-compile
  ;; Bind features so that require will believe that gnus-sum has
  ;; already been loaded (avoids infinite recursion)
  (with-no-warnings (defvar features))  ;Not just a local variable.
  (let ((features (cons 'gnus-sum features)))
    ;; FIXME: Break this mutual dependency.
    (require 'gnus-art)))

;; MIME stuff.

(defvar gnus-decode-encoded-word-methods
  '(mail-decode-encoded-word-string)
  "List of methods used to decode encoded words.

This variable is a list of FUNCTION or (REGEXP . FUNCTION).  If item
is FUNCTION, FUNCTION will be apply to all newsgroups.  If item is a
\(REGEXP . FUNCTION), FUNCTION will be applied only to the newsgroups
whose names match REGEXP.

For example:
\((\"chinese\" . gnus-decode-encoded-word-string-by-guess)
 mail-decode-encoded-word-string
 (\"chinese\" . rfc1843-decode-string))")

(defvar gnus-decode-encoded-word-methods-cache nil)

(defun gnus-multi-decode-encoded-word-string (string)
  "Apply the functions from `gnus-encoded-word-methods' that match."
  (unless (and gnus-decode-encoded-word-methods-cache
	       (eq gnus-newsgroup-name
		   (car gnus-decode-encoded-word-methods-cache)))
    (setq gnus-decode-encoded-word-methods-cache (list gnus-newsgroup-name))
    (dolist (method gnus-decode-encoded-word-methods)
      (if (symbolp method)
	  (nconc gnus-decode-encoded-word-methods-cache (list method))
	(if (and gnus-newsgroup-name
		 (string-match (car method) gnus-newsgroup-name))
	    (nconc gnus-decode-encoded-word-methods-cache
		   (list (cdr method)))))))
  (dolist (method (cdr gnus-decode-encoded-word-methods-cache) string)
    (setq string (funcall method string))))

;; Subject simplification.

(defun gnus-simplify-whitespace (str)
  "Remove excessive whitespace from STR."
  ;; Multiple spaces.
  (while (string-match "[ \t][ \t]+" str)
    (setq str (concat (substring str 0 (match-beginning 0))
			" "
			(substring str (match-end 0)))))
  ;; Leading spaces.
  (when (string-match "^[ \t]+" str)
    (setq str (substring str (match-end 0))))
  ;; Trailing spaces.
  (when (string-match "[ \t]+$" str)
    (setq str (substring str 0 (match-beginning 0))))
  str)

(defun gnus-simplify-all-whitespace (str)
  "Remove all whitespace from STR."
  (while (string-match "[ \t\n]+" str)
    (setq str (replace-match "" nil nil str)))
  str)

(defsubst gnus-simplify-subject-re (subject)
  "Remove \"Re:\" from subject lines."
  (if (string-match message-subject-re-regexp subject)
      (substring subject (match-end 0))
    subject))

(defun gnus-simplify-subject (subject &optional re-only)
  "Remove `Re:' and words in parentheses.
If RE-ONLY is non-nil, strip leading `Re:'s only."
  (let ((case-fold-search t))		;Ignore case.
    ;; Remove `Re:', `Re^N:', `Re(n)', and `Re[n]:'.
    (when (string-match "\\`\\(re\\([[(^][0-9]+[])]?\\)?:[ \t]*\\)+" subject)
      (setq subject (substring subject (match-end 0))))
    ;; Remove uninteresting prefixes.
    (when (and (not re-only)
	       gnus-simplify-ignored-prefixes
	       (string-match gnus-simplify-ignored-prefixes subject))
      (setq subject (substring subject (match-end 0))))
    ;; Remove words in parentheses from end.
    (unless re-only
      (while (string-match "[ \t\n]*([^()]*)[ \t\n]*\\'" subject)
	(setq subject (substring subject 0 (match-beginning 0)))))
    ;; Return subject string.
    subject))

;; Remove any leading "re:"s, any trailing paren phrases, and simplify
;; all whitespace.
(defsubst gnus-simplify-buffer-fuzzy-step (regexp &optional newtext)
  (goto-char (point-min))
  (while (re-search-forward regexp nil t)
    (replace-match (or newtext ""))))

(defun gnus-simplify-buffer-fuzzy (regexp)
  "Simplify string in the buffer fuzzily.
The string in the accessible portion of the current buffer is simplified.
It is assumed to be a single-line subject.
Whitespace is generally cleaned up, and miscellaneous leading/trailing
matter is removed.  Additional things can be deleted by setting
`gnus-simplify-subject-fuzzy-regexp'."
  (let ((case-fold-search t)
	(modified-tick))
    (gnus-simplify-buffer-fuzzy-step "\t" " ")

    (while (not (eq modified-tick (buffer-modified-tick)))
      (setq modified-tick (buffer-modified-tick))
      (cond
       ((listp regexp)
	(mapc #'gnus-simplify-buffer-fuzzy-step regexp))
       (regexp
	(gnus-simplify-buffer-fuzzy-step regexp)))
      (gnus-simplify-buffer-fuzzy-step "^ *\\[[-+?*!][-+?*!]\\] *")
      (gnus-simplify-buffer-fuzzy-step
       "^ *\\(re\\|fw\\|fwd\\)[[{(^0-9]*[])}]?[:;] *")
      (gnus-simplify-buffer-fuzzy-step "^[[].*:\\( .*\\)[]]$" "\\1"))

    (gnus-simplify-buffer-fuzzy-step " *[[{(][^()\n]*[]})] *$")
    (gnus-simplify-buffer-fuzzy-step "  +" " ")
    (gnus-simplify-buffer-fuzzy-step " $")
    (gnus-simplify-buffer-fuzzy-step "^ +")))

(defun gnus-simplify-subject-fuzzy (subject)
  "Simplify a subject string fuzzily.
See `gnus-simplify-buffer-fuzzy' for details."
  (save-excursion
    (let ((regexp gnus-simplify-subject-fuzzy-regexp))
      (gnus-set-work-buffer)
      (let ((case-fold-search t))
	;; Remove uninteresting prefixes.
	(when (and gnus-simplify-ignored-prefixes
		   (string-match gnus-simplify-ignored-prefixes subject))
	  (setq subject (substring subject (match-end 0))))
	(insert subject)
	(inline (gnus-simplify-buffer-fuzzy regexp))
	(buffer-string)))))

(defsubst gnus-simplify-subject-fully (subject)
  "Simplify a subject string according to `gnus-summary-gather-subject-limit'."
  (cond
   (gnus-simplify-subject-functions
    (gnus-map-function gnus-simplify-subject-functions subject))
   ((null gnus-summary-gather-subject-limit)
    (gnus-simplify-subject-re subject))
   ((eq gnus-summary-gather-subject-limit 'fuzzy)
    (gnus-simplify-subject-fuzzy subject))
   ((numberp gnus-summary-gather-subject-limit)
    (truncate-string-to-width (gnus-simplify-subject-re subject)
			      gnus-summary-gather-subject-limit))
   (t
    subject)))

(defsubst gnus-subject-equal (s1 s2 &optional simple-first)
  "Check whether two subjects are equal.
If optional argument SIMPLE-FIRST is t, first argument is already
simplified."
  (cond
   ((null simple-first)
    (equal (gnus-simplify-subject-fully s1)
	   (gnus-simplify-subject-fully s2)))
   (t
    (equal s1
	   (gnus-simplify-subject-fully s2)))))

(defun gnus-summary-bubble-group ()
  "Increase the score of the current group.
This is a handy function to add to `gnus-summary-exit-hook' to
increase the score of each group you read."
  (gnus-group-add-score gnus-newsgroup-name))


;;;
;;; Gnus summary mode
;;;

(defvar gnus-article-commands-menu)

;; Non-orthogonal keys

(gnus-define-keys gnus-summary-mode-map
  " " gnus-summary-next-page
  [?\S-\ ] gnus-summary-prev-page
  "\177" gnus-summary-prev-page
  [delete] gnus-summary-prev-page
  "\r" gnus-summary-scroll-up
  "\M-\r" gnus-summary-scroll-down
  "n" gnus-summary-next-unread-article
  "p" gnus-summary-prev-unread-article
  "N" gnus-summary-next-article
  "P" gnus-summary-prev-article
  "\M-\C-n" gnus-summary-next-same-subject
  "\M-\C-p" gnus-summary-prev-same-subject
  "\M-n" gnus-summary-next-unread-subject
  "\M-p" gnus-summary-prev-unread-subject
  "." gnus-summary-first-unread-article
  "," gnus-summary-best-unread-article
  "[" gnus-summary-prev-unseen-article
  "]" gnus-summary-next-unseen-article
  "\M-s\M-s" gnus-summary-search-article-forward
  "\M-s\M-r" gnus-summary-search-article-backward
  "\M-r" gnus-summary-search-article-backward
  "\M-S" gnus-summary-repeat-search-article-forward
  "\M-R" gnus-summary-repeat-search-article-backward
  "<" gnus-summary-beginning-of-article
  ">" gnus-summary-end-of-article
  "j" gnus-summary-goto-article
  "^" gnus-summary-refer-parent-article
  "\M-^" gnus-summary-refer-article
  "u" gnus-summary-tick-article-forward
  "!" gnus-summary-tick-article-forward
  "U" gnus-summary-tick-article-backward
  "d" gnus-summary-mark-as-read-forward
  "D" gnus-summary-mark-as-read-backward
  "E" gnus-summary-mark-as-expirable
  "\M-u" gnus-summary-clear-mark-forward
  "\M-U" gnus-summary-clear-mark-backward
  "k" gnus-summary-kill-same-subject-and-select
  "\C-k" gnus-summary-kill-same-subject
  "\M-\C-k" gnus-summary-kill-thread
  "\M-\C-l" gnus-summary-lower-thread
  "e" gnus-summary-edit-article
  "#" gnus-summary-mark-as-processable
  "\M-#" gnus-summary-unmark-as-processable
  "\M-\C-t" gnus-summary-toggle-threads
  "\M-\C-s" gnus-summary-show-thread
  "\M-\C-h" gnus-summary-hide-thread
  "\M-\C-f" gnus-summary-next-thread
  "\M-\C-b" gnus-summary-prev-thread
  [(meta down)] gnus-summary-next-thread
  [(meta up)] gnus-summary-prev-thread
  "\M-\C-u" gnus-summary-up-thread
  "\M-\C-d" gnus-summary-down-thread
  "&" gnus-summary-execute-command
  "c" gnus-summary-catchup-and-exit
  "\C-w" gnus-summary-mark-region-as-read
  "\C-t" toggle-truncate-lines
  "?" gnus-summary-mark-as-dormant
  "\C-c\M-\C-s" gnus-summary-limit-include-expunged
  "\C-c\C-s\C-n" gnus-summary-sort-by-number
  "\C-c\C-s\C-m\C-n" gnus-summary-sort-by-most-recent-number
  "\C-c\C-s\C-l" gnus-summary-sort-by-lines
  "\C-c\C-s\C-c" gnus-summary-sort-by-chars
  "\C-c\C-s\C-m\C-m" gnus-summary-sort-by-marks
  "\C-c\C-s\C-a" gnus-summary-sort-by-author
  "\C-c\C-s\C-t" gnus-summary-sort-by-recipient
  "\C-c\C-s\C-s" gnus-summary-sort-by-subject
  "\C-c\C-s\C-d" gnus-summary-sort-by-date
  "\C-c\C-s\C-m\C-d" gnus-summary-sort-by-most-recent-date
  "\C-c\C-s\C-i" gnus-summary-sort-by-score
  "\C-c\C-s\C-o" gnus-summary-sort-by-original
  "\C-c\C-s\C-r" gnus-summary-sort-by-random
  "\C-c\C-s\C-u" gnus-summary-sort-by-newsgroups
  "\C-c\C-s\C-x" gnus-summary-sort-by-extra
  "=" gnus-summary-expand-window
  "\C-x\C-s" gnus-summary-reselect-current-group
  "\M-g" gnus-summary-rescan-group
  "\C-c\C-r" gnus-summary-caesar-message
  "f" gnus-summary-followup
  "F" gnus-summary-followup-with-original
  "C" gnus-summary-cancel-article
  "r" gnus-summary-reply
  "R" gnus-summary-reply-with-original
  "\C-c\C-f" gnus-summary-mail-forward
  "o" gnus-summary-save-article
  "\C-o" gnus-summary-save-article-mail
  "|" gnus-summary-pipe-output
  "\M-k" gnus-summary-edit-local-kill
  "\M-K" gnus-summary-edit-global-kill
  ;; "V" gnus-version
  "\C-c\C-d" gnus-summary-describe-group
  "\C-c\C-p" gnus-summary-make-group-from-search
  "q" gnus-summary-exit
  "Q" gnus-summary-exit-no-update
  "\C-c\C-i" gnus-info-find-node
  [mouse-2] gnus-mouse-pick-article
  [follow-link] mouse-face
  "m" gnus-summary-mail-other-window
  "a" gnus-summary-post-news
  "x" gnus-summary-limit-to-unread
  "s" gnus-summary-isearch-article
  "\t" gnus-summary-button-forward
  [backtab] gnus-summary-button-backward
  "w" gnus-summary-browse-url
  "t" gnus-summary-toggle-header
  "g" gnus-summary-show-article
  "l" gnus-summary-goto-last-article
  "\C-c\C-v\C-v" gnus-uu-decode-uu-view
  "\C-d" gnus-summary-enter-digest-group
  "\M-\C-d" gnus-summary-read-document
  "\M-\C-e" gnus-summary-edit-parameters
  "\M-\C-a" gnus-summary-customize-parameters
  "\C-c\C-b" gnus-bug
  "*" gnus-cache-enter-article
  "\M-*" gnus-cache-remove-article
  "\M-&" gnus-summary-universal-argument
  "\C-l" gnus-recenter
  "I" gnus-summary-increase-score
  "L" gnus-summary-lower-score
  "\M-i" gnus-symbolic-argument
  "h" gnus-summary-select-article-buffer

  "b" gnus-article-view-part
  "\M-t" gnus-summary-toggle-display-buttonized

  "V" gnus-summary-score-map
  "X" gnus-uu-extract-map
  "S" gnus-summary-send-map)

;; Sort of orthogonal keymap
(gnus-define-keys (gnus-summary-mark-map "M" gnus-summary-mode-map)
  "t" gnus-summary-tick-article-forward
  "!" gnus-summary-tick-article-forward
  "d" gnus-summary-mark-as-read-forward
  "r" gnus-summary-mark-as-read-forward
  "c" gnus-summary-clear-mark-forward
  " " gnus-summary-clear-mark-forward
  "e" gnus-summary-mark-as-expirable
  "x" gnus-summary-mark-as-expirable
  "?" gnus-summary-mark-as-dormant
  "b" gnus-summary-set-bookmark
  "B" gnus-summary-remove-bookmark
  "#" gnus-summary-mark-as-processable
  "\M-#" gnus-summary-unmark-as-processable
  "S" gnus-summary-limit-include-expunged
  "C" gnus-summary-catchup
  "H" gnus-summary-catchup-to-here
  "h" gnus-summary-catchup-from-here
  "\C-c" gnus-summary-catchup-all
  "k" gnus-summary-kill-same-subject-and-select
  "K" gnus-summary-kill-same-subject
  "P" gnus-uu-mark-map)

(gnus-define-keys (gnus-summary-mscore-map "V" gnus-summary-mark-map)
  "c" gnus-summary-clear-above
  "u" gnus-summary-tick-above
  "m" gnus-summary-mark-above
  "k" gnus-summary-kill-below)

(gnus-define-keys (gnus-summary-limit-map "/" gnus-summary-mode-map)
  "/" gnus-summary-limit-to-subject
  "n" gnus-summary-limit-to-articles
  "b" gnus-summary-limit-to-bodies
  "h" gnus-summary-limit-to-headers
  "w" gnus-summary-pop-limit
  "s" gnus-summary-limit-to-subject
  "a" gnus-summary-limit-to-author
  "u" gnus-summary-limit-to-unread
  "m" gnus-summary-limit-to-marks
  "M" gnus-summary-limit-exclude-marks
  "v" gnus-summary-limit-to-score
  "*" gnus-summary-limit-include-cached
  "D" gnus-summary-limit-include-dormant
  "T" gnus-summary-limit-include-thread
  "d" gnus-summary-limit-exclude-dormant
  "t" gnus-summary-limit-to-age
  "." gnus-summary-limit-to-unseen
  "x" gnus-summary-limit-to-extra
  "p" gnus-summary-limit-to-display-predicate
  "E" gnus-summary-limit-include-expunged
  "c" gnus-summary-limit-exclude-childless-dormant
  "C" gnus-summary-limit-mark-excluded-as-read
  "o" gnus-summary-insert-old-articles
  "N" gnus-summary-insert-new-articles
  "S" gnus-summary-limit-to-singletons
  "r" gnus-summary-limit-to-replied
  "R" gnus-summary-limit-to-recipient
  "A" gnus-summary-limit-to-address)

(gnus-define-keys (gnus-summary-goto-map "G" gnus-summary-mode-map)
  "n" gnus-summary-next-unread-article
  "p" gnus-summary-prev-unread-article
  "N" gnus-summary-next-article
  "P" gnus-summary-prev-article
  "\C-n" gnus-summary-next-same-subject
  "\C-p" gnus-summary-prev-same-subject
  "\M-n" gnus-summary-next-unread-subject
  "\M-p" gnus-summary-prev-unread-subject
  "f" gnus-summary-first-unread-article
  "b" gnus-summary-best-unread-article
  "u" gnus-summary-next-unseen-article
  "U" gnus-summary-prev-unseen-article
  "j" gnus-summary-goto-article
  "g" gnus-summary-goto-subject
  "l" gnus-summary-goto-last-article
  "o" gnus-summary-pop-article)

(gnus-define-keys (gnus-summary-thread-map "T" gnus-summary-mode-map)
  "k" gnus-summary-kill-thread
  "E" gnus-summary-expire-thread
  "l" gnus-summary-lower-thread
  "i" gnus-summary-raise-thread
  "T" gnus-summary-toggle-threads
  "t" gnus-summary-rethread-current
  "^" gnus-summary-reparent-thread
  "\M-^" gnus-summary-reparent-children
  "s" gnus-summary-show-thread
  "S" gnus-summary-show-all-threads
  "h" gnus-summary-hide-thread
  "H" gnus-summary-hide-all-threads
  "n" gnus-summary-next-thread
  "p" gnus-summary-prev-thread
  "u" gnus-summary-up-thread
  "o" gnus-summary-top-thread
  "d" gnus-summary-down-thread
  "#" gnus-uu-mark-thread
  "\M-#" gnus-uu-unmark-thread)

(gnus-define-keys (gnus-summary-buffer-map "Y" gnus-summary-mode-map)
  "g" gnus-summary-prepare
  "c" gnus-summary-insert-cached-articles
  "d" gnus-summary-insert-dormant-articles
  "t" gnus-summary-insert-ticked-articles)

(gnus-define-keys (gnus-summary-exit-map "Z" gnus-summary-mode-map)
  "c" gnus-summary-catchup-and-exit
  "C" gnus-summary-catchup-all-and-exit
  "E" gnus-summary-exit-no-update
  "Q" gnus-summary-exit
  "Z" gnus-summary-exit
  "n" gnus-summary-catchup-and-goto-next-group
  "p" gnus-summary-catchup-and-goto-prev-group
  "R" gnus-summary-reselect-current-group
  "G" gnus-summary-rescan-group
  "N" gnus-summary-next-group
  "s" gnus-summary-save-newsrc
  "P" gnus-summary-prev-group)

(gnus-define-keys (gnus-summary-article-map "A" gnus-summary-mode-map)
  " " gnus-summary-next-page
  "n" gnus-summary-next-page
  [?\S-\ ] gnus-summary-prev-page
  "\177" gnus-summary-prev-page
  [delete] gnus-summary-prev-page
  "p" gnus-summary-prev-page
  "\r" gnus-summary-scroll-up
  "\M-\r" gnus-summary-scroll-down
  "<" gnus-summary-beginning-of-article
  ">" gnus-summary-end-of-article
  "b" gnus-summary-beginning-of-article
  "e" gnus-summary-end-of-article
  "^" gnus-summary-refer-parent-article
  "r" gnus-summary-refer-parent-article
  "C" gnus-summary-show-complete-article
  "D" gnus-summary-enter-digest-group
  "R" gnus-summary-refer-references
  "T" gnus-summary-refer-thread
  "W" gnus-warp-to-article
  "g" gnus-summary-show-article
  "s" gnus-summary-isearch-article
  "\t" gnus-summary-button-forward
  [backtab] gnus-summary-button-backward
  "w" gnus-summary-browse-url
  "P" gnus-summary-print-article
  "S" gnus-sticky-article
  "M" gnus-mailing-list-insinuate
  "t" gnus-article-babel)

(gnus-define-keys (gnus-summary-wash-map "W" gnus-summary-mode-map)
  "b" gnus-article-add-buttons
  "B" gnus-article-add-buttons-to-head
  "o" gnus-article-treat-overstrike
  "e" gnus-article-emphasize
  "w" gnus-article-fill-cited-article
  "Q" gnus-article-fill-long-lines
  "L" gnus-article-toggle-truncate-lines
  "C" gnus-article-capitalize-sentences
  "c" gnus-article-remove-cr
  "q" gnus-article-de-quoted-unreadable
  "6" gnus-article-de-base64-unreadable
  "Z" gnus-article-decode-HZ
  "A" gnus-article-treat-ansi-sequences
  "h" gnus-article-wash-html
  "u" gnus-article-unsplit-urls
  "s" gnus-summary-force-verify-and-decrypt
  "f" gnus-article-display-x-face
  "l" gnus-summary-stop-page-breaking
  "r" gnus-summary-caesar-message
  "m" gnus-summary-morse-message
  "t" gnus-summary-toggle-header
  "g" gnus-treat-smiley
  "v" gnus-summary-verbose-headers
  "a" gnus-article-strip-headers-in-body ;; mnemonic: wash archive
  "p" gnus-article-verify-x-pgp-sig
  "d" gnus-article-treat-smartquotes
  "U" gnus-article-treat-non-ascii
  "i" gnus-summary-idna-message)

(gnus-define-keys (gnus-summary-wash-deuglify-map "Y" gnus-summary-wash-map)
  ;; mnemonic: deuglif*Y*
  "u" gnus-article-outlook-unwrap-lines
  "a" gnus-article-outlook-repair-attribution
  "c" gnus-article-outlook-rearrange-citation
  "f" gnus-article-outlook-deuglify-article) ;; mnemonic: full deuglify

(gnus-define-keys (gnus-summary-wash-hide-map "W" gnus-summary-wash-map)
  "a" gnus-article-hide
  "h" gnus-article-hide-headers
  "b" gnus-article-hide-boring-headers
  "s" gnus-article-hide-signature
  "c" gnus-article-hide-citation
  "C" gnus-article-hide-citation-in-followups
  "l" gnus-article-hide-list-identifiers
  "B" gnus-article-strip-banner
  "P" gnus-article-hide-pem
  "\C-c" gnus-article-hide-citation-maybe)

(gnus-define-keys (gnus-summary-wash-highlight-map "H" gnus-summary-wash-map)
  "a" gnus-article-highlight
  "h" gnus-article-highlight-headers
  "c" gnus-article-highlight-citation
  "s" gnus-article-highlight-signature)

(gnus-define-keys (gnus-summary-wash-header-map "G" gnus-summary-wash-map)
  "f" gnus-article-treat-fold-headers
  "u" gnus-article-treat-unfold-headers
  "n" gnus-article-treat-fold-newsgroups)

(gnus-define-keys (gnus-summary-wash-display-map "D" gnus-summary-wash-map)
  "x" gnus-article-display-x-face
  "d" gnus-article-display-face
  "s" gnus-treat-smiley
  "D" gnus-article-remove-images
  "W" gnus-article-show-images
  "f" gnus-treat-from-picon
  "m" gnus-treat-mail-picon
  "n" gnus-treat-newsgroups-picon
  "g" gnus-treat-from-gravatar
  "h" gnus-treat-mail-gravatar)

(gnus-define-keys (gnus-summary-wash-mime-map "M" gnus-summary-wash-map)
  "w" gnus-article-decode-mime-words
  "c" gnus-article-decode-charset
  "h" gnus-mime-buttonize-attachments-in-header
  "v" gnus-mime-view-all-parts
  "b" gnus-article-view-part)

(gnus-define-keys (gnus-summary-wash-time-map "T" gnus-summary-wash-map)
  "z" gnus-article-date-ut
  "u" gnus-article-date-ut
  "l" gnus-article-date-local
  "p" gnus-article-date-english
  "e" gnus-article-date-lapsed
  "o" gnus-article-date-original
  "i" gnus-article-date-iso8601
  "s" gnus-article-date-user)

(gnus-define-keys (gnus-summary-wash-empty-map "E" gnus-summary-wash-map)
  "t" gnus-article-remove-trailing-blank-lines
  "l" gnus-article-strip-leading-blank-lines
  "m" gnus-article-strip-multiple-blank-lines
  "a" gnus-article-strip-blank-lines
  "A" gnus-article-strip-all-blank-lines
  "s" gnus-article-strip-leading-space
  "e" gnus-article-strip-trailing-space
  "w" gnus-article-remove-leading-whitespace)

(gnus-define-keys (gnus-summary-help-map "H" gnus-summary-mode-map)
  "v" gnus-version
  "d" gnus-summary-describe-group
  "h" gnus-summary-describe-briefly
  "i" gnus-info-find-node)

(gnus-define-keys (gnus-summary-backend-map "B" gnus-summary-mode-map)
  "e" gnus-summary-expire-articles
  "\M-\C-e" gnus-summary-expire-articles-now
  "\177" gnus-summary-delete-article
  [delete] gnus-summary-delete-article
  [backspace] gnus-summary-delete-article
  "m" gnus-summary-move-article
  "r" gnus-summary-respool-article
  "w" gnus-summary-edit-article
  "c" gnus-summary-copy-article
  "B" gnus-summary-crosspost-article
  "q" gnus-summary-respool-query
  "t" gnus-summary-respool-trace
  "i" gnus-summary-import-article
  "I" gnus-summary-create-article
  "p" gnus-summary-article-posted-p)

(gnus-define-keys (gnus-summary-save-map "O" gnus-summary-mode-map)
  "o" gnus-summary-save-article
  "m" gnus-summary-save-article-mail
  "F" gnus-summary-write-article-file
  "r" gnus-summary-save-article-rmail
  "f" gnus-summary-save-article-file
  "b" gnus-summary-save-article-body-file
  "B" gnus-summary-write-article-body-file
  "h" gnus-summary-save-article-folder
  "v" gnus-summary-save-article-vm
  "p" gnus-summary-pipe-output
  "P" gnus-summary-muttprint)

(gnus-define-keys (gnus-summary-mime-map "K" gnus-summary-mode-map)
  "b" gnus-summary-display-buttonized
  "m" gnus-summary-repair-multipart
  "v" gnus-article-view-part
  "o" gnus-article-save-part
  "O" gnus-article-save-part-and-strip
  "r" gnus-article-replace-part
  "d" gnus-article-delete-part
  "t" gnus-article-view-part-as-type
  "j" gnus-article-jump-to-part
  "c" gnus-article-copy-part
  "C" gnus-article-view-part-as-charset
  "e" gnus-article-view-part-externally
  "H" gnus-article-browse-html-article
  "E" gnus-article-encrypt-body
  "i" gnus-article-inline-part
  "|" gnus-article-pipe-part)

(gnus-define-keys (gnus-uu-mark-map "P" gnus-summary-mark-map)
  "p" gnus-summary-mark-as-processable
  "u" gnus-summary-unmark-as-processable
  "U" gnus-summary-unmark-all-processable
  "v" gnus-uu-mark-over
  "s" gnus-uu-mark-series
  "r" gnus-uu-mark-region
  "g" gnus-uu-unmark-region
  "R" gnus-uu-mark-by-regexp
  "G" gnus-uu-unmark-by-regexp
  "t" gnus-uu-mark-thread
  "T" gnus-uu-unmark-thread
  "a" gnus-uu-mark-all
  "b" gnus-uu-mark-buffer
  "S" gnus-uu-mark-sparse
  "k" gnus-summary-kill-process-mark
  "y" gnus-summary-yank-process-mark
  "w" gnus-summary-save-process-mark
  "i" gnus-uu-invert-processable)

(gnus-define-keys (gnus-uu-extract-map "X" gnus-summary-mode-map)
  ;;"x" gnus-uu-extract-any
  "m" gnus-summary-save-parts
  "u" gnus-uu-decode-uu
  "U" gnus-uu-decode-uu-and-save
  "s" gnus-uu-decode-unshar
  "S" gnus-uu-decode-unshar-and-save
  "o" gnus-uu-decode-save
  "O" gnus-uu-decode-save
  "b" gnus-uu-decode-binhex
  "B" gnus-uu-decode-binhex
  "Y" gnus-uu-decode-yenc
  "p" gnus-uu-decode-postscript
  "P" gnus-uu-decode-postscript-and-save)

(gnus-define-keys
    (gnus-uu-extract-view-map "v" gnus-uu-extract-map)
  "u" gnus-uu-decode-uu-view
  "U" gnus-uu-decode-uu-and-save-view
  "s" gnus-uu-decode-unshar-view
  "S" gnus-uu-decode-unshar-and-save-view
  "o" gnus-uu-decode-save-view
  "O" gnus-uu-decode-save-view
  "b" gnus-uu-decode-binhex-view
  "B" gnus-uu-decode-binhex-view
  "p" gnus-uu-decode-postscript-view
  "P" gnus-uu-decode-postscript-and-save-view)

(defvar gnus-article-post-menu nil)

(defconst gnus-summary-menu-maxlen 20)

(defun gnus-summary-menu-split (menu)
  ;; If we have lots of elements, divide them into groups of 20
  ;; and make a pane (or submenu) for each one.
  (if (> (length menu) (/ (* gnus-summary-menu-maxlen 3) 2))
      (let ((menu menu) sublists next
	    (i 1))
	(while menu
	  ;; Pull off the next gnus-summary-menu-maxlen elements
	  ;; and make them the next element of sublist.
	  (setq next (nthcdr gnus-summary-menu-maxlen menu))
	  (if next
	      (setcdr (nthcdr (1- gnus-summary-menu-maxlen) menu)
		      nil))
	  (setq sublists (cons (cons (format "%s ... %s" (aref (car menu) 0)
					     (aref (car (last menu)) 0)) menu)
			       sublists))
	  (setq i (1+ i))
	  (setq menu next))
	(nreverse sublists))
    ;; Few elements--put them all in one pane.
    menu))

(defun gnus-summary-make-menu-bar ()
  (gnus-turn-off-edit-menu 'summary)

  (unless (boundp 'gnus-summary-misc-menu)

    (easy-menu-define
      gnus-summary-kill-menu gnus-summary-mode-map ""
      (cons
       "Score"
       (nconc
	(list
	 ["Customize" gnus-score-customize t])
	(gnus-make-score-map 'increase)
	(gnus-make-score-map 'lower)
	'(("Mark"
	   ["Kill below" gnus-summary-kill-below t]
	   ["Mark above" gnus-summary-mark-above t]
	   ["Tick above" gnus-summary-tick-above t]
	   ["Clear above" gnus-summary-clear-above t])
	  ["Current article score" gnus-summary-current-score t]
	  ["Current thread score" (gnus-summary-current-score 'total) t]
	  ["Set score" gnus-summary-set-score t]
	  ["Switch current score file..." gnus-score-change-score-file t]
	  ["Set mark below..." gnus-score-set-mark-below t]
	  ["Set expunge below..." gnus-score-set-expunge-below t]
	  ["Edit current score file" gnus-score-edit-current-scores t]
	  ["Edit score file..." gnus-score-edit-file t]
	  ["Trace score" gnus-score-find-trace t]
	  ["Find words" gnus-score-find-favorite-words t]
	  ["Rescore buffer" gnus-summary-rescore t]
	  ["Increase score..." gnus-summary-increase-score t]
	  ["Lower score..." gnus-summary-lower-score t]))))

    ;; Define both the Article menu in the summary buffer and the
    ;; equivalent Commands menu in the article buffer here for
    ;; consistency.
    (let ((innards
	   `(("Hide"
	      ["All" gnus-article-hide t]
	      ["Headers" gnus-article-hide-headers t]
	      ["Signature" gnus-article-hide-signature t]
	      ["Citation" gnus-article-hide-citation t]
	      ["List identifiers" gnus-article-hide-list-identifiers t]
	      ["Banner" gnus-article-strip-banner t]
	      ["Boring headers" gnus-article-hide-boring-headers t])
	     ("Highlight"
	      ["All" gnus-article-highlight t]
	      ["Headers" gnus-article-highlight-headers t]
	      ["Signature" gnus-article-highlight-signature t]
	      ["Citation" gnus-article-highlight-citation t])
	     ("MIME"
	      ["Words" gnus-article-decode-mime-words t]
	      ["Charset" gnus-article-decode-charset t]
	      ["QP" gnus-article-de-quoted-unreadable t]
	      ["Base64" gnus-article-de-base64-unreadable t]
	      ["View MIME buttons" gnus-summary-display-buttonized t]
	      ["View MIME buttons in header"
	       gnus-mime-buttonize-attachments-in-header t]
	      ["View all" gnus-mime-view-all-parts t]
	      ["Verify and Decrypt" gnus-summary-force-verify-and-decrypt t]
	      ["Encrypt body" gnus-article-encrypt-body
	       :active (not (gnus-group-read-only-p))
	       :help "Encrypt the message body on disk"]
	      ["Extract all parts..." gnus-summary-save-parts t]
	      ("Multipart"
	       ["Repair multipart" gnus-summary-repair-multipart t]
	       ["Pipe part..." gnus-article-pipe-part t]
	       ["Inline part" gnus-article-inline-part t]
	       ["View part as type..." gnus-article-view-part-as-type t]
	       ["Encrypt body" gnus-article-encrypt-body
		:active (not (gnus-group-read-only-p))
	       :help "Encrypt the message body on disk"]
	       ["View part externally" gnus-article-view-part-externally t]
	       ["View HTML parts in browser" gnus-article-browse-html-article t]
	       ["View part with charset..." gnus-article-view-part-as-charset t]
	       ["Copy part" gnus-article-copy-part t]
	       ["Save part..." gnus-article-save-part t]
	       ["View part" gnus-article-view-part t]))
	     ("Date"
	      ["Local" gnus-article-date-local t]
	      ["ISO8601" gnus-article-date-iso8601 t]
	      ["UT" gnus-article-date-ut t]
	      ["Original" gnus-article-date-original t]
	      ["Lapsed" gnus-article-date-lapsed t]
	      ["User-defined" gnus-article-date-user t])
	     ("Display"
	      ["Display HTML images" gnus-article-show-images t]
	      ["Remove images" gnus-article-remove-images t]
	      ["Toggle smiley" gnus-treat-smiley t]
	      ["Show X-Face" gnus-article-display-x-face t]
	      ["Show picons in From" gnus-treat-from-picon t]
	      ["Show picons in mail headers" gnus-treat-mail-picon t]
	      ["Show picons in news headers" gnus-treat-newsgroups-picon t]
              ["Show Gravatars in From" gnus-treat-from-gravatar t]
	      ["Show Gravatars in mail headers" gnus-treat-mail-gravatar t]
	      ("View as different encoding"
	       ,@(gnus-summary-menu-split
		  (mapcar
		   (lambda (cs)
		     ;; Since easymenu under Emacs doesn't allow
		     ;; lambda forms for menu commands, we should
		     ;; provide intern'ed function symbols.
		     (let ((command (intern (format "\
gnus-summary-show-article-from-menu-as-charset-%s" cs))))
		       (fset command
			     (lambda ()
			       (interactive)
			       (let ((gnus-summary-show-article-charset-alist
				      `((1 . ,cs))))
				 (gnus-summary-show-article 1))))
                       (function-put command 'completion-predicate #'ignore)
		       `[,(symbol-name cs) ,command t]))
		   (sort (coding-system-list) #'string<)))))
	     ("Washing"
	      ("Remove Blanks"
	       ["Leading" gnus-article-strip-leading-blank-lines t]
	       ["Multiple" gnus-article-strip-multiple-blank-lines t]
	       ["Trailing" gnus-article-remove-trailing-blank-lines t]
	       ["All of the above" gnus-article-strip-blank-lines t]
	       ["All" gnus-article-strip-all-blank-lines t]
	       ["Leading space" gnus-article-strip-leading-space t]
	       ["Trailing space" gnus-article-strip-trailing-space t]
	       ["Leading space in headers"
		gnus-article-remove-leading-whitespace t])
	      ["Overstrike" gnus-article-treat-overstrike t]
	      ["Smartquotes" gnus-article-treat-smartquotes t]
	      ["Non-ASCII" gnus-article-treat-non-ascii t]
	      ["Emphasis" gnus-article-emphasize t]
	      ["Word wrap" gnus-article-fill-cited-article t]
	      ["Fill long lines" gnus-article-fill-long-lines t]
	      ["Toggle truncate long lines" gnus-article-toggle-truncate-lines t]
	      ["Capitalize sentences" gnus-article-capitalize-sentences t]
	      ["Remove CR" gnus-article-remove-cr t]
	      ["Quoted-Printable" gnus-article-de-quoted-unreadable t]
	      ["Base64" gnus-article-de-base64-unreadable t]
	      ["Rot 13" gnus-summary-caesar-message
	       :help "\"Caesar rotate\" article by 13"]
	      ["De-IDNA" gnus-summary-idna-message t]
	      ["Morse decode" gnus-summary-morse-message t]
	      ["Unix pipe..." gnus-summary-pipe-message t]
	      ["Add buttons" gnus-article-add-buttons t]
	      ["Add buttons to head" gnus-article-add-buttons-to-head t]
	      ["Stop page breaking" gnus-summary-stop-page-breaking t]
	      ["Verbose header" gnus-summary-verbose-headers t]
	      ["Toggle header" gnus-summary-toggle-header t]
	      ["Unfold headers" gnus-article-treat-unfold-headers t]
	      ["Fold newsgroups" gnus-article-treat-fold-newsgroups t]
	      ["Html" gnus-article-wash-html t]
	      ["Unsplit URLs" gnus-article-unsplit-urls t]
	      ["Verify X-PGP-Sig" gnus-article-verify-x-pgp-sig t]
	      ["Decode HZ" gnus-article-decode-HZ t]
	      ["ANSI sequences" gnus-article-treat-ansi-sequences t]
	      ("(Outlook) Deuglify"
	       ["Unwrap lines" gnus-article-outlook-unwrap-lines t]
	       ["Repair attribution" gnus-article-outlook-repair-attribution t]
	       ["Rearrange citation" gnus-article-outlook-rearrange-citation t]
	       ["Full (Outlook) deuglify"
		gnus-article-outlook-deuglify-article t])
	      )
	     ("Output"
	      ["Save in default format..." gnus-summary-save-article
	       :help "Save article using default method"]
	      ["Save in file..." gnus-summary-save-article-file
	       :help "Save article in file"]
	      ["Save in Unix mail format..." gnus-summary-save-article-mail t]
	      ["Save in MH folder..." gnus-summary-save-article-folder t]
	      ["Save in VM folder..." gnus-summary-save-article-vm t]
	      ["Save in RMAIL mbox..." gnus-summary-save-article-rmail t]
	      ["Save body in file..." gnus-summary-save-article-body-file t]
	      ["Pipe through a filter..." gnus-summary-pipe-output t]
	      ["Print with Muttprint..." gnus-summary-muttprint t]
	      ["Print" gnus-summary-print-article
	       :help "Generate and print a PostScript image"])
	     ("Copy, move,... (Backend)"
	      :help "Copying, moving, expiring articles..."
	      ["Respool article..." gnus-summary-respool-article t]
	      ["Move article..." gnus-summary-move-article
	       (gnus-check-backend-function
		'request-move-article gnus-newsgroup-name)]
	      ["Copy article..." gnus-summary-copy-article t]
	      ["Crosspost article..." gnus-summary-crosspost-article
	       (gnus-check-backend-function
		'request-replace-article gnus-newsgroup-name)]
	      ["Import file..." gnus-summary-import-article
	       (gnus-check-backend-function
		'request-accept-article gnus-newsgroup-name)]
	      ["Create article..." gnus-summary-create-article
	       (gnus-check-backend-function
		'request-accept-article gnus-newsgroup-name)]
	      ["Check if posted" gnus-summary-article-posted-p t]
	      ["Edit article" gnus-summary-edit-article
	       (not (gnus-group-read-only-p))]
	      ["Delete article" gnus-summary-delete-article
	       (gnus-check-backend-function
		'request-expire-articles gnus-newsgroup-name)]
	      ["Query respool" gnus-summary-respool-query t]
	      ["Trace respool" gnus-summary-respool-trace t]
	      ["Delete expirable articles" gnus-summary-expire-articles-now
	       (gnus-check-backend-function
		'request-expire-articles gnus-newsgroup-name)])
	     ("Extract"
	      ["Uudecode" gnus-uu-decode-uu :help "Decode uuencoded article(s)"]
	      ["Uudecode and save" gnus-uu-decode-uu-and-save t]
	      ["Unshar" gnus-uu-decode-unshar t]
	      ["Unshar and save" gnus-uu-decode-unshar-and-save t]
	      ["Save" gnus-uu-decode-save t]
	      ["Binhex" gnus-uu-decode-binhex t]
	      ["PostScript" gnus-uu-decode-postscript t]
	      ["All MIME parts" gnus-summary-save-parts t])
	     ("Cache"
	      ["Enter article" gnus-cache-enter-article t]
	      ["Remove article" gnus-cache-remove-article t])
	     ["Translate" gnus-article-babel t]
	     ["Select article buffer" gnus-summary-select-article-buffer t]
	     ["Make article buffer sticky" gnus-sticky-article t]
	     ["Enter digest buffer" gnus-summary-enter-digest-group t]
	     ["Isearch article..." gnus-summary-isearch-article t]
	     ["Beginning of the article" gnus-summary-beginning-of-article t]
	     ["End of the article" gnus-summary-end-of-article t]
	     ["Fetch parent of article" gnus-summary-refer-parent-article t]
	     ["Fetch referenced articles" gnus-summary-refer-references t]
	     ["Fetch current thread" gnus-summary-refer-thread t]
	     ["Fetch article with id..." gnus-summary-refer-article t]
	     ["Setup Mailing List Params" gnus-mailing-list-insinuate t]
	     ["Redisplay" gnus-summary-show-article t]
	     ["Raw article" gnus-summary-show-raw-article :keys "C-u g"])))
      (easy-menu-define
	gnus-summary-article-menu gnus-summary-mode-map ""
	(cons "Article" innards))

      (if (not (keymapp gnus-summary-article-menu))
	  (easy-menu-define
	    gnus-article-commands-menu gnus-article-mode-map ""
	    (cons "Commands" innards))
	;; Don't share the menu.
	(setq gnus-article-commands-menu
	      (copy-keymap gnus-summary-article-menu))
	(define-key gnus-article-mode-map [menu-bar commands]
	  (cons "Commands" gnus-article-commands-menu))))

    (easy-menu-define
      gnus-summary-thread-menu gnus-summary-mode-map ""
      '("Threads"
	["Find all messages in thread" gnus-summary-refer-thread t]
	["Toggle threading" gnus-summary-toggle-threads t]
	["Hide threads" gnus-summary-hide-all-threads t]
	["Show threads" gnus-summary-show-all-threads t]
	["Hide thread" gnus-summary-hide-thread t]
	["Show thread" gnus-summary-show-thread t]
	["Go to next thread" gnus-summary-next-thread t]
	["Go to previous thread" gnus-summary-prev-thread t]
	["Go down thread" gnus-summary-down-thread t]
	["Go up thread" gnus-summary-up-thread t]
	["Top of thread" gnus-summary-top-thread t]
	["Mark thread as read" gnus-summary-kill-thread t]
	["Mark thread as expired" gnus-summary-expire-thread t]
	["Lower thread score" gnus-summary-lower-thread t]
	["Raise thread score" gnus-summary-raise-thread t]
	["Rethread current" gnus-summary-rethread-current t]))

    (easy-menu-define
      gnus-summary-post-menu gnus-summary-mode-map ""
      '("Post"
	["Send a message (mail or news)" gnus-summary-post-news
	 :help "Compose a new message (mail or news)"]
	["Followup" gnus-summary-followup
	 :help "Post followup to this article"]
	["Followup and yank" gnus-summary-followup-with-original
	 :help "Post followup to this article, quoting its contents"]
	["Supersede article" gnus-summary-supersede-article t]
	["Cancel article" gnus-summary-cancel-article
	 :help "Cancel an article you posted"]
	["Reply" gnus-summary-reply t]
	["Reply and yank" gnus-summary-reply-with-original t]
	["Wide reply" gnus-summary-wide-reply t]
	["Wide reply and yank" gnus-summary-wide-reply-with-original
	 :help "Mail a reply, quoting this article"]
	["Very wide reply" gnus-summary-very-wide-reply t]
	["Very wide reply and yank" gnus-summary-very-wide-reply-with-original
	 :help "Mail a very wide reply, quoting this article"]
	["Mail forward" gnus-summary-mail-forward t]
	["Post forward" gnus-summary-post-forward t]
	["Digest and mail" gnus-uu-digest-mail-forward t]
	["Digest and post" gnus-uu-digest-post-forward t]
	["Resend message" gnus-summary-resend-message t]
	["Resend message edit" gnus-summary-resend-message-edit t]
	["Send bounced mail" gnus-summary-resend-bounced-mail t]
	["Send a mail" gnus-summary-mail-other-window t]
	["Attach article to outgoing message" gnus-summary-attach-article t]
	["Create a local message" gnus-summary-news-other-window t]
	["Uuencode and post" gnus-uu-post-news
	 :help "Post a uuencoded article"]
	["Followup via news" gnus-summary-followup-to-mail t]
	["Followup via news and yank"
	 gnus-summary-followup-to-mail-with-original t]
	["Strip signature on reply"
	 (lambda ()
	   (interactive)
	   (setq message-cite-function
		 (if (eq message-cite-function
			 #'message-cite-original-without-signature)
		     #'message-cite-original
		   #'message-cite-original-without-signature)))
	 :visible (memq message-cite-function
			'(message-cite-original-without-signature
			  message-cite-original))
	 :style toggle
	 :selected (eq message-cite-function
		       #'message-cite-original-without-signature)
	 :help "Strip signature from cited article when replying."]))

    (cond
     ((not (keymapp gnus-summary-post-menu))
      (setq gnus-article-post-menu gnus-summary-post-menu))
     ((not gnus-article-post-menu)
      ;; Don't share post menu.
      (setq gnus-article-post-menu
	    (copy-keymap gnus-summary-post-menu))))
    (define-key gnus-article-mode-map [menu-bar post]
      (cons "Post" gnus-article-post-menu))

    (easy-menu-define
      gnus-summary-misc-menu gnus-summary-mode-map ""
      '("Gnus"
	("Mark Read"
	 ["Mark as read" gnus-summary-mark-as-read-forward t]
	 ["Mark same subject and select"
	  gnus-summary-kill-same-subject-and-select t]
	 ["Mark same subject" gnus-summary-kill-same-subject t]
	 ["Catchup" gnus-summary-catchup
	  :help "Mark unread articles in this group as read"]
	 ["Catchup all" gnus-summary-catchup-all t]
	 ["Catchup to here" gnus-summary-catchup-to-here t]
	 ["Catchup from here" gnus-summary-catchup-from-here t]
	 ["Catchup region" gnus-summary-mark-region-as-read mark-active]
	 ["Mark excluded" gnus-summary-limit-mark-excluded-as-read t])
	("Mark Various"
	 ["Tick" gnus-summary-tick-article-forward t]
	 ["Mark as dormant" gnus-summary-mark-as-dormant t]
	 ["Remove marks" gnus-summary-clear-mark-forward t]
	 ["Set expirable mark" gnus-summary-mark-as-expirable t]
	 ["Set bookmark" gnus-summary-set-bookmark t]
	 ["Remove bookmark" gnus-summary-remove-bookmark t])
	("Limit to"
	 ["Marks..." gnus-summary-limit-to-marks t]
	 ["Subject..." gnus-summary-limit-to-subject t]
	 ["Author..." gnus-summary-limit-to-author t]
	 ["Recipient..." gnus-summary-limit-to-recipient t]
	 ["Address..." gnus-summary-limit-to-address t]
	 ["Age..." gnus-summary-limit-to-age t]
	 ["Extra..." gnus-summary-limit-to-extra t]
	 ["Score..." gnus-summary-limit-to-score t]
	 ["Display Predicate" gnus-summary-limit-to-display-predicate t]
	 ["Unread" gnus-summary-limit-to-unread t]
	 ["Unseen" gnus-summary-limit-to-unseen t]
	 ["Singletons" gnus-summary-limit-to-singletons t]
	 ["Replied" gnus-summary-limit-to-replied t]
	 ["Non-dormant" gnus-summary-limit-exclude-dormant t]
	 ["Next or process marked articles" gnus-summary-limit-to-articles t]
	 ["Pop limit" gnus-summary-pop-limit t]
	 ["Show dormant" gnus-summary-limit-include-dormant t]
	 ["Hide childless dormant"
	  gnus-summary-limit-exclude-childless-dormant t]
	 ;;["Hide thread" gnus-summary-limit-exclude-thread t]
	 ["Hide marked" gnus-summary-limit-exclude-marks t]
	 ["Show expunged" gnus-summary-limit-include-expunged t])
	("Process Mark"
	 ["Toggle/Set mark" gnus-summary-mark-as-processable t]
	 ["Remove mark" gnus-summary-unmark-as-processable t]
	 ["Remove all marks" gnus-summary-unmark-all-processable t]
	 ["Invert marks" gnus-uu-invert-processable t]
	 ["Mark above" gnus-uu-mark-over t]
	 ["Mark series" gnus-uu-mark-series t]
	 ["Mark region" gnus-uu-mark-region mark-active]
	 ["Unmark region" gnus-uu-unmark-region mark-active]
	 ["Mark by regexp..." gnus-uu-mark-by-regexp t]
	 ["Unmark by regexp..." gnus-uu-unmark-by-regexp t]
	 ["Mark all" gnus-uu-mark-all t]
	 ["Mark buffer" gnus-uu-mark-buffer t]
	 ["Mark sparse" gnus-uu-mark-sparse t]
	 ["Mark thread" gnus-uu-mark-thread t]
	 ["Unmark thread" gnus-uu-unmark-thread t]
	 ("Process Mark Sets"
	  ["Kill" gnus-summary-kill-process-mark t]
	  ["Yank" gnus-summary-yank-process-mark
	   gnus-newsgroup-process-stack]
	  ["Save" gnus-summary-save-process-mark t]
	  ["Run command on marked..." gnus-summary-universal-argument t]))
	("Registry Marks")
	("Scroll article"
	 ["Page forward" gnus-summary-next-page
	  :help "Show next page of article"]
	 ["Page backward" gnus-summary-prev-page
	  :help "Show previous page of article"]
	 ["Line forward" gnus-summary-scroll-up t])
	("Move"
	 ["Next unread article" gnus-summary-next-unread-article t]
	 ["Previous unread article" gnus-summary-prev-unread-article t]
	 ["Next article" gnus-summary-next-article t]
	 ["Previous article" gnus-summary-prev-article t]
	 ["Next unread subject" gnus-summary-next-unread-subject t]
	 ["Previous unread subject" gnus-summary-prev-unread-subject t]
	 ["Next article same subject" gnus-summary-next-same-subject t]
	 ["Previous article same subject" gnus-summary-prev-same-subject t]
	 ["First unread article" gnus-summary-first-unread-article t]
	 ["Best unread article" gnus-summary-best-unread-article t]
	 ["Next unseen article" gnus-summary-next-unseen-article t]
	 ["Prev unseen article" gnus-summary-prev-unseen-article t]
	 ["Go to subject number..." gnus-summary-goto-subject t]
	 ["Go to article number..." gnus-summary-goto-article t]
	 ["Go to the last article" gnus-summary-goto-last-article t]
	 ["Pop article off history" gnus-summary-pop-article t])
	("Sort"
	 ["Sort by number" gnus-summary-sort-by-number t]
	 ["Sort by most recent number" gnus-summary-sort-by-most-recent-number t]
	 ["Sort by author" gnus-summary-sort-by-author t]
	 ["Sort by recipient" gnus-summary-sort-by-recipient t]
	 ["Sort by subject" gnus-summary-sort-by-subject t]
	 ["Sort by date" gnus-summary-sort-by-date t]
	 ["Sort by most recent date" gnus-summary-sort-by-most-recent-date t]
	 ["Sort by score" gnus-summary-sort-by-score t]
	 ["Sort by lines" gnus-summary-sort-by-lines t]
	 ["Sort by characters" gnus-summary-sort-by-chars t]
	 ["Sort by marks" gnus-summary-sort-by-marks t]
	 ["Sort by newsgroup" gnus-summary-sort-by-newsgroups t]
	 ["Sort by extra" gnus-summary-sort-by-extra t]
	 ["Randomize" gnus-summary-sort-by-random t]
	 ["Original sort" gnus-summary-sort-by-original t])
	("Help"
	 ["Describe group" gnus-summary-describe-group t]
	 ["Read manual" gnus-info-find-node t])
	("Modes"
	 ["Pick and read" gnus-pick-mode t]
	 ["Binary" gnus-binary-mode t])
	("Regeneration"
	 ["Regenerate" gnus-summary-prepare t]
	 ["Insert cached articles" gnus-summary-insert-cached-articles t]
	 ["Insert dormant articles" gnus-summary-insert-dormant-articles t]
	 ["Insert ticked articles" gnus-summary-insert-ticked-articles t]
	 ["Toggle threading" gnus-summary-toggle-threads t])
	["See old articles" gnus-summary-insert-old-articles t]
	["See new articles" gnus-summary-insert-new-articles t]
	["Filter articles..." gnus-summary-execute-command t]
	["Run command on articles..." gnus-summary-universal-argument t]
	["Search articles forward..." gnus-summary-search-article-forward t]
	["Search articles backward..." gnus-summary-search-article-backward t]
	["Toggle line truncation" toggle-truncate-lines t]
	["Expand window" gnus-summary-expand-window t]
	["Expire expirable articles" gnus-summary-expire-articles
	 (gnus-check-backend-function
	  'request-expire-articles gnus-newsgroup-name)]
	["Edit local kill file" gnus-summary-edit-local-kill t]
	["Edit main kill file" gnus-summary-edit-global-kill t]
	["Edit group parameters" gnus-summary-edit-parameters t]
	["Customize group parameters" gnus-summary-customize-parameters t]
	["Send a bug report" gnus-bug t]
	("Exit"
	 ["Catchup and exit" gnus-summary-catchup-and-exit
	  :help "Mark unread articles in this group as read, then exit"]
	 ["Catchup all and exit" gnus-summary-catchup-all-and-exit t]
	 ["Catchup and goto next" gnus-summary-catchup-and-goto-next-group t]
	 ["Catchup and goto prev" gnus-summary-catchup-and-goto-prev-group t]
	 ["Exit group" gnus-summary-exit
	  :help "Exit current group, return to group selection mode"]
	 ["Exit group without updating" gnus-summary-exit-no-update t]
	 ["Exit and goto next group" gnus-summary-next-group t]
	 ["Exit and goto prev group" gnus-summary-prev-group t]
	 ["Reselect group" gnus-summary-reselect-current-group t]
	 ["Rescan group" gnus-summary-rescan-group t]
	 ["Update dribble" gnus-summary-save-newsrc t])))

    (gnus-run-hooks 'gnus-summary-menu-hook)))

(defvar gnus-summary-tool-bar-map nil)

;; Note: The :set function in the `gnus-summary-tool-bar*' variables will only
;; affect _new_ message buffers.  We might add a function that walks thru all
;; summary-mode buffers and force the update.
(defun gnus-summary-tool-bar-update (&optional symbol value)
  "Update summary mode toolbar.
Setter function for custom variables."
  (setq-default gnus-summary-tool-bar-map nil)
  (when symbol
    ;; When used as ":set" function:
    (set-default symbol value))
  (when (gnus-buffer-live-p gnus-summary-buffer)
    (with-current-buffer gnus-summary-buffer
      (gnus-summary-make-tool-bar))))

(defcustom gnus-summary-tool-bar (if (eq gmm-tool-bar-style 'gnome)
				     'gnus-summary-tool-bar-gnome
				   'gnus-summary-tool-bar-retro)
  "Specifies the Gnus summary tool bar.

It can be either a list or a symbol referring to a list.  See
`gmm-tool-bar-from-list' for the format of the list.  The
default key map is `gnus-summary-mode-map'.

Pre-defined symbols include `gnus-summary-tool-bar-gnome' and
`gnus-summary-tool-bar-retro'."
  :type '(choice (const :tag "GNOME style" gnus-summary-tool-bar-gnome)
		 (const :tag "Retro look"  gnus-summary-tool-bar-retro)
		 (repeat :tag "User defined list" gmm-tool-bar-item)
		 (symbol))
  :version "23.1" ;; No Gnus
  :initialize 'custom-initialize-default
  :set 'gnus-summary-tool-bar-update
  :group 'gnus-summary)

(defcustom gnus-summary-tool-bar-gnome
  '((gnus-summary-post-news "mail/compose" nil)
    (gnus-summary-insert-new-articles "mail/inbox" nil
				      :visible (or (not gnus-agent)
						   gnus-plugged))
    (gnus-summary-reply-with-original "mail/reply")
    (gnus-summary-reply "mail/reply" nil :visible nil)
    (gnus-summary-followup-with-original "mail/reply-all")
    (gnus-summary-followup "mail/reply-all" nil :visible nil)
    (gnus-summary-mail-forward "mail/forward")
    (gnus-summary-save-article "mail/save")
    (gnus-summary-search-article-forward "search" nil :visible nil)
    (gnus-summary-print-article "print")
    (gnus-summary-tick-article-forward "flag-followup" nil :visible nil)
    ;; Some new commands that may need more suitable icons:
    (gnus-summary-save-newsrc "save" nil :visible nil)
    ;; (gnus-summary-show-article "stock_message-display" nil :visible nil)
    (gnus-summary-prev-article "left-arrow")
    (gnus-summary-next-article "right-arrow")
    (gnus-summary-next-page "next-page")
    ;; (gnus-summary-enter-digest-group "right_arrow" nil :visible nil)
    ;;
    ;; Maybe some sort-by-... could be added:
    ;; (gnus-summary-sort-by-author "sort-a-z" nil :visible nil)
    ;; (gnus-summary-sort-by-date "sort-1-9" nil :visible nil)
    (gnus-summary-mark-as-expirable
     "delete" nil
     :visible (gnus-check-backend-function 'request-expire-articles
					   gnus-newsgroup-name))
    (gnus-summary-mark-as-spam
     "mail/spam" t
     :visible (and (fboundp 'spam-group-ham-contents-p)
		   (spam-group-ham-contents-p gnus-newsgroup-name))
     :help "Mark as spam")
    (gnus-summary-mark-as-read-forward
     "mail/not-spam" nil
     :visible (and (fboundp 'spam-group-spam-contents-p)
		   (spam-group-spam-contents-p gnus-newsgroup-name)))
    ;;
    (gnus-summary-exit "exit")
    (gmm-customize-mode "preferences" t :help "Edit mode preferences")
    (gnus-info-find-node "help"))
  "List of functions for the summary tool bar (GNOME style).

See `gmm-tool-bar-from-list' for the format of the list."
  :type '(repeat gmm-tool-bar-item)
  :version "23.1" ;; No Gnus
  :initialize 'custom-initialize-default
  :set 'gnus-summary-tool-bar-update
  :group 'gnus-summary)

(defcustom gnus-summary-tool-bar-retro
  '((gnus-summary-prev-unread-article "gnus/prev-ur")
    (gnus-summary-next-unread-article "gnus/next-ur")
    (gnus-summary-post-news "gnus/post")
    (gnus-summary-followup-with-original "gnus/fuwo")
    (gnus-summary-followup "gnus/followup")
    (gnus-summary-reply-with-original "gnus/reply-wo")
    (gnus-summary-reply "gnus/reply")
    (gnus-summary-caesar-message "gnus/rot13")
    (gnus-uu-decode-uu "gnus/uu-decode")
    (gnus-summary-save-article-file "gnus/save-aif")
    (gnus-summary-save-article "gnus/save-art")
    (gnus-uu-post-news "gnus/uu-post")
    (gnus-summary-catchup "gnus/catchup")
    (gnus-summary-catchup-and-exit "gnus/cu-exit")
    (gnus-summary-exit "gnus/exit-summ")
    ;; Some new command that may need more suitable icons:
    (gnus-summary-print-article "gnus/print" nil :visible nil)
    (gnus-summary-mark-as-expirable "gnus/close" nil :visible nil)
    (gnus-summary-save-newsrc "gnus/save" nil :visible nil)
    ;; (gnus-summary-enter-digest-group "gnus/right_arrow" nil :visible nil)
    (gnus-summary-search-article-forward "gnus/search" nil :visible nil)
    ;; (gnus-summary-insert-new-articles "gnus/paste" nil :visible nil)
    ;; (gnus-summary-toggle-threads "gnus/open" nil :visible nil)
    ;;
    (gnus-info-find-node "gnus/help" nil :visible nil))
  "List of functions for the summary tool bar (retro look).

See `gmm-tool-bar-from-list' for the format of the list."
  :type '(repeat gmm-tool-bar-item)
  :version "23.1" ;; No Gnus
  :initialize 'custom-initialize-default
  :set 'gnus-summary-tool-bar-update
  :group 'gnus-summary)

(defcustom gnus-summary-tool-bar-zap-list t
  "List of icon items from the global tool bar.
These items are not displayed in the Gnus summary mode tool bar.

See `gmm-tool-bar-from-list' for the format of the list."
  :type 'gmm-tool-bar-zap-list
  :version "23.1" ;; No Gnus
  :initialize 'custom-initialize-default
  :set 'gnus-summary-tool-bar-update
  :group 'gnus-summary)

(defvar image-load-path)
(defvar tool-bar-map)
(declare-function image-load-path-for-library "image"
		  (library image &optional path no-error))

(defun gnus-summary-make-tool-bar (&optional force)
  "Make a summary mode tool bar from `gnus-summary-tool-bar'.
When FORCE, rebuild the tool bar."
  (when (and (boundp 'tool-bar-mode)
	     tool-bar-mode
	     (or (not gnus-summary-tool-bar-map) force))
    (let* ((load-path
	    (image-load-path-for-library "gnus" "mail/save.xpm" nil t))
           (image-load-path (cons (car load-path) image-load-path))
	   (map (gmm-tool-bar-from-list gnus-summary-tool-bar
					gnus-summary-tool-bar-zap-list
					'gnus-summary-mode-map)))
      (when map
	;; Need to set `gnus-summary-tool-bar-map' because `gnus-article-mode'
	;; uses its value.
	(setq gnus-summary-tool-bar-map map))))
  (setq-local tool-bar-map gnus-summary-tool-bar-map))

(defun gnus-make-score-map (type)
  "Make a summary score map of type TYPE."
  (if t
      nil
    (let ((headers '(("author" "from" string)
		     ("subject" "subject" string)
		     ("article body" "body" string)
		     ("article head" "head" string)
		     ("xref" "xref" string)
		     ("extra header" "extra" string)
		     ("lines" "lines" number)
		     ("followups to author" "followup" string)))
	  (types '((number ("less than" <)
			   ("greater than" >)
			   ("equal" =))
		   (string ("substring" s)
			   ("exact string" e)
			   ("fuzzy string" f)
			   ("regexp" r))))
	  (perms '(("temporary" (current-time-string))
		   ("permanent" nil)
		   ("immediate" now)))
	  header)
      (list
       (apply
	#'nconc
	(list
	 (if (eq type 'lower)
	     "Lower score"
	   "Increase score"))
	(let (outh)
	  (while headers
	    (setq header (car headers))
	    (setq outh
		  (cons
		   (apply
		    #'nconc
		    (list (car header))
		    (let ((ts (cdr (assoc (nth 2 header) types)))
			  outt)
		      (while ts
			(setq outt
			      (cons
			       (apply
				#'nconc
				(list (caar ts))
				(let ((ps perms)
				      outp)
				  (while ps
				    (setq outp
					  (cons
					   (vector
					    (caar ps)
					    (list
					     'gnus-summary-score-entry
					     (nth 1 header)
					     (if (or (string= (nth 1 header)
							      "head")
						     (string= (nth 1 header)
							      "body"))
						 ""
					       (list 'gnus-summary-header
						     (nth 1 header)))
					     (list 'quote (nth 1 (car ts)))
					     (list 'gnus-score-delta-default
						   nil)
					     (nth 1 (car ps))
					     t)
					    t)
					   outp))
				    (setq ps (cdr ps)))
				  (list (nreverse outp))))
			       outt))
			(setq ts (cdr ts)))
		      (list (nreverse outt))))
		   outh))
	    (setq headers (cdr headers)))
	  (list (nreverse outh))))))))


(declare-function turn-on-gnus-mailing-list-mode "gnus-ml" ())
(defvar bookmark-make-record-function)

(defvar bidi-paragraph-direction)

(defvar gnus-summary-mode-group nil
  "Variable for communication with `gnus-summary-mode'.
Allows the `gnus-newsgroup-name' local variable to be set before
the summary mode hooks are run.")

(define-derived-mode gnus-summary-mode gnus-mode "Summary"
  "Major mode for reading articles.
\\<gnus-summary-mode-map>
Each line in this buffer represents one article.  To read an
article, you can, for instance, type `\\[gnus-summary-next-page]'.  To move forwards
and backwards while displaying articles, type `\\[gnus-summary-next-unread-article]' and `\\[gnus-summary-prev-unread-article]',
respectively.

You can also post articles and send mail from this buffer.  To
follow up an article, type `\\[gnus-summary-followup]'.  To mail a reply to the author
of an article, type `\\[gnus-summary-reply]'.

There are approx. one gazillion commands you can execute in this
buffer; read the Info manual for more information (`\\[gnus-info-find-node]').

The following commands are available:

\\{gnus-summary-mode-map}"
  :interactive nil
  (let ((gnus-summary-local-variables gnus-newsgroup-variables))
    (gnus-summary-make-local-variables))
  (gnus-summary-make-local-variables)
  (setq gnus-newsgroup-name gnus-summary-mode-group)
  (when (gnus-visual-p 'summary-menu 'menu)
    (gnus-summary-make-menu-bar)
    (gnus-summary-make-tool-bar))
  (gnus-make-thread-indent-array)
  (gnus-simplify-mode-line)
  (buffer-disable-undo)
  (setq show-trailing-whitespace nil
	truncate-lines t
	bidi-paragraph-direction 'left-to-right)
  (add-to-invisibility-spec '(gnus-sum . t))
  (gnus-summary-set-display-table)
  (gnus-set-default-directory)
  (make-local-variable 'gnus-summary-line-format)
  (make-local-variable 'gnus-summary-line-format-spec)
  (make-local-variable 'gnus-summary-dummy-line-format)
  (make-local-variable 'gnus-summary-dummy-line-format-spec)
  (make-local-variable 'gnus-summary-mark-positions)
  (make-local-variable 'gnus-article-buffer)
  (make-local-variable 'gnus-article-current)
  (make-local-variable 'gnus-original-article-buffer)
  (add-hook 'pre-command-hook #'gnus-set-global-variables nil t)
  (mm-enable-multibyte)
  (setq-local bookmark-make-record-function
              #'gnus-summary-bookmark-make-record))

(defun gnus-summary-make-local-variables ()
  "Make all the local summary buffer variables."
  (dolist (local gnus-summary-local-variables)
    (if (consp local)
        (let ((global (if (eq (cdr local) 'global)
                          ;; Copy the global value of the variable.
                          (symbol-value (car local))
                        ;; Use the value from the list.
                        (eval (cdr local) t))))
          (set (make-local-variable (car local)) global))
      ;; Simple nil-valued local variable.
      (set (make-local-variable local) nil))))

;; Summary data functions.

(cl-defstruct (gnus-data
               (:constructor nil)
               (:constructor gnus-data-make (number mark pos header level))
               ;; In gnus-data-find-in, we rely on (car data) returning the
               ;; number, because we use `assq' on a list of gnus-data.
               (:type list))
  number mark pos header level)

(defun gnus-data-unseen-p (data)
  (memq (gnus-data-number data) gnus-newsgroup-unseen))

(define-inline gnus-data-unread-p (data)
  (inline-quote (= (gnus-data-mark ,data) gnus-unread-mark)))

(define-inline gnus-data-read-p (data)
  (inline-quote (/= (gnus-data-mark ,data) gnus-unread-mark)))

(define-inline gnus-data-pseudo-p (data)
  (inline-quote (consp (gnus-data-header ,data))))

(defalias 'gnus-data-find-in #'assq)

(define-inline gnus-data-find (number)
  (inline-quote (gnus-data-find-in ,number gnus-newsgroup-data)))

(defmacro gnus-data-find-list (number &optional data)
  `(let ((bdata ,(or data 'gnus-newsgroup-data)))
     (memq (gnus-data-find-in ,number bdata)
	   bdata)))

(defun gnus-data-enter (after-article number mark pos header level offset)
  (let ((data (gnus-data-find-list after-article)))
    (unless data
      (error "No such article: %d" after-article))
    (setcdr data (cons (gnus-data-make number mark pos header level)
		       (cdr data)))
    (setq gnus-newsgroup-data-reverse nil)
    (gnus-data-update-list (cddr data) offset)))

(defun gnus-data-enter-list (after-article list &optional offset)
  (when list
    (let ((data (and after-article (gnus-data-find-list after-article)))
	  (ilist list))
      (if (not (or data
		   after-article))
	  (let ((odata gnus-newsgroup-data))
	    (setq gnus-newsgroup-data (nconc list gnus-newsgroup-data))
	    (when offset
	      (gnus-data-update-list odata offset)))
	;; Find the last element in the list to be spliced into the main
	;; list.
	(setq list (last list))
	(if (not data)
	    (progn
	      (setcdr list gnus-newsgroup-data)
	      (setq gnus-newsgroup-data ilist)
	      (when offset
		(gnus-data-update-list (cdr list) offset)))
	  (setcdr list (cdr data))
	  (setcdr data ilist)
	  (when offset
	    (gnus-data-update-list (cdr list) offset))))
      (setq gnus-newsgroup-data-reverse nil))))

(defun gnus-data-remove (article &optional offset)
  (let ((data gnus-newsgroup-data))
    (if (= (gnus-data-number (car data)) article)
	(progn
	  (setq gnus-newsgroup-data (cdr gnus-newsgroup-data)
		gnus-newsgroup-data-reverse nil)
	  (when offset
	    (gnus-data-update-list gnus-newsgroup-data offset)))
      (while (cdr data)
	(when (= (gnus-data-number (cadr data)) article)
	  (setcdr data (cddr data))
	  (when offset
	    (gnus-data-update-list (cdr data) offset))
	  (setq data nil
		gnus-newsgroup-data-reverse nil))
	(setq data (cdr data))))))

(defmacro gnus-data-list (backward)
  `(if ,backward
       (or gnus-newsgroup-data-reverse
	   (setq gnus-newsgroup-data-reverse
		 (reverse gnus-newsgroup-data)))
     gnus-newsgroup-data))

(defun gnus-data-update-list (data offset)
  "Add OFFSET to the POS of all data entries in DATA."
  (setq gnus-newsgroup-data-reverse nil)
  (while data
    (cl-incf (gnus-data-pos (car data)) offset)
    (setq data (cdr data))))

(defun gnus-summary-article-pseudo-p (article)
  "Say whether this article is a pseudo article or not."
  (not (mail-header-p (gnus-data-header (gnus-data-find article)))))

(defmacro gnus-summary-article-sparse-p (article)
  "Say whether this article is a sparse article or not."
  `(memq ,article gnus-newsgroup-sparse))

(defmacro gnus-summary-article-ancient-p (article)
  "Say whether this article is a sparse article or not."
  `(memq ,article gnus-newsgroup-ancient))

(defun gnus-article-children (number)
  "Return a list of all children to NUMBER."
  (let* ((data (gnus-data-find-list number))
	 (level (gnus-data-level (car data)))
	 children)
    (setq data (cdr data))
    (while (and data
		(= (gnus-data-level (car data)) (1+ level)))
      (push (gnus-data-number (car data)) children)
      (setq data (cdr data)))
    children))

(defsubst gnus-summary-skip-intangible ()
  ;; FIXME: Does this really warrant a `defsubst'?
  "If the current article is intangible, then jump to a different article."
   (let ((to (get-text-property (point) 'gnus-intangible)))
     (and to (gnus-summary-goto-subject to))))

(defmacro gnus-summary-article-intangible-p ()
  "Say whether this article is intangible or not."
  '(get-text-property (point) 'gnus-intangible))

;; Some summary mode macros.

(defsubst gnus-summary-article-number ()
  "The article number of the article on the current line.
If there isn't an article number here, then we return the current
article number."
  (gnus-summary-skip-intangible)
  (or (get-text-property (point) 'gnus-number)
      (gnus-summary-last-subject)))

(define-inline gnus-summary-article-header (&optional number)
  "Return the header of article NUMBER."
  (inline-quote
   (gnus-data-header (gnus-data-find
		      ,(or number
                           (inline-quote (gnus-summary-article-number)))))))

(defsubst gnus-summary-thread-level (&optional number)
  "Return the level of thread that starts with article NUMBER."
  (if (and (eq gnus-summary-make-false-root 'dummy)
	   (get-text-property (point) 'gnus-intangible))
      0
    (gnus-data-level (gnus-data-find
		      (or number (gnus-summary-article-number))))))

(defsubst gnus-summary-article-mark (&optional number)
  "Return the mark of article NUMBER."
  (gnus-data-mark (gnus-data-find
	           (or number (gnus-summary-article-number)))))

(defmacro gnus-summary-article-pos (&optional number)
  "Return the position of the line of article NUMBER."
  `(gnus-data-pos (gnus-data-find
		   ,(or number '(gnus-summary-article-number)))))

(defalias 'gnus-summary-subject-string #'gnus-summary-article-subject)
(defsubst gnus-summary-article-subject (&optional number)
  ;; FIXME: Does this really warrant a defsubst?
  "Return current subject string or nil if nothing."
  (let ((headers
	 (gnus-data-header
          (gnus-data-find (or number
	                      (gnus-summary-article-number))))))
    (and headers
	 (mail-header-p headers)
	 (mail-header-subject headers))))

(defmacro gnus-summary-article-score (&optional number)
  "Return current article score."
  `(or (cdr (assq ,(or number '(gnus-summary-article-number))
		  gnus-newsgroup-scored))
       gnus-summary-default-score 0))

(defun gnus-summary-article-children (&optional number)
  "Return a list of article numbers that are children of article NUMBER."
  (let* ((data (gnus-data-find-list (or number (gnus-summary-article-number))))
	 (level (gnus-data-level (car data)))
	 l children)
    (while (and (setq data (cdr data))
		(> (setq l (gnus-data-level (car data))) level))
      (and (= (1+ level) l)
	   (push (gnus-data-number (car data))
		 children)))
    (nreverse children)))

(defun gnus-summary-article-parent (&optional number)
  "Return the article number of the parent of article NUMBER."
  (let* ((data (gnus-data-find-list (or number (gnus-summary-article-number))
				    (gnus-data-list t)))
	 (level (gnus-data-level (car data))))
    (if (zerop level)
	()				; This is a root.
      ;; We search until we find an article with a level less than
      ;; this one.  That function has to be the parent.
      (while (and (setq data (cdr data))
		  (not (< (gnus-data-level (car data)) level))))
      (and data (gnus-data-number (car data))))))

(defun gnus-unread-mark-p (mark)
  "Say whether MARK is the unread mark."
  (= mark gnus-unread-mark))

(defun gnus-read-mark-p (mark)
  "Say whether MARK is one of the marks that mark as read.
This is all marks except unread, ticked, dormant, and expirable."
  (not (or (= mark gnus-unread-mark)
	   (= mark gnus-ticked-mark)
	   (= mark gnus-spam-mark)
	   (= mark gnus-dormant-mark)
	   (= mark gnus-expirable-mark))))

(defmacro gnus-article-mark (number)
  "Return the MARK of article NUMBER.
This macro should only be used when computing the mark the \"first\"
time; i.e., when generating the summary lines.  After that,
`gnus-summary-article-mark' should be used to examine the
marks of articles."
  `(cond
    ((memq ,number gnus-newsgroup-unsendable) gnus-unsendable-mark)
    ((memq ,number gnus-newsgroup-downloadable) gnus-downloadable-mark)
    ((memq ,number gnus-newsgroup-unreads) gnus-unread-mark)
    ((memq ,number gnus-newsgroup-marked) gnus-ticked-mark)
    ((memq ,number gnus-newsgroup-spam-marked) gnus-spam-mark)
    ((memq ,number gnus-newsgroup-dormant) gnus-dormant-mark)
    ((memq ,number gnus-newsgroup-expirable) gnus-expirable-mark)
    (t (or (cdr (assq ,number gnus-newsgroup-reads))
	   gnus-ancient-mark))))

;; Saving hidden threads.

(defmacro gnus-save-hidden-threads (&rest forms)
  "Save hidden threads, eval FORMS, and restore the hidden threads."
  (declare (indent 0) (debug t))
  (let ((config (make-symbol "config")))
    `(let ((,config (gnus-hidden-threads-configuration)))
       (unwind-protect
	   (save-excursion
	     ,@forms)
	 (gnus-restore-hidden-threads-configuration ,config)))))

(defun gnus-data-compute-positions ()
  "Compute the positions of all articles."
  (setq gnus-newsgroup-data-reverse nil)
  (let ((data gnus-newsgroup-data))
    (save-excursion
      (gnus-save-hidden-threads
	(gnus-summary-show-all-threads)
	(goto-char (point-min))
	(while data
	  (while (get-text-property (point) 'gnus-intangible)
	    (forward-line 1))
	  (setf (gnus-data-pos (car data)) (+ (point) 3))
	  (setq data (cdr data))
	  (forward-line 1))))))

(defun gnus-hidden-threads-configuration ()
  "Return the current hidden threads configuration."
  (save-excursion
    (let (config)
      (goto-char (point-min))
      (while (not (eobp))
        (when (eq (get-char-property (point-at-eol) 'invisible) 'gnus-sum)
          (push (save-excursion (forward-line 0) (point)) config))
        (forward-line 1))
      config)))

(defun gnus-restore-hidden-threads-configuration (config)
  "Restore hidden threads configuration from CONFIG."
  (save-excursion
    (let (point (inhibit-read-only t))
      (while (setq point (pop config))
        (goto-char point)
        (gnus-summary-hide-thread)))))

;; Various summary mode internalish functions.

(defun gnus-mouse-pick-article (e)
  (interactive "e" gnus-summary-mode)
  (mouse-set-point e)
  (gnus-summary-next-page nil t))

(defun gnus-summary-set-display-table ()
  "Change the display table.
Odd characters have a tendency to mess
up nicely formatted displays - we make all possible glyphs
display only a single character."

  ;; We start from the standard display table, if any.
  (let ((table (or (copy-sequence standard-display-table)
		   (make-display-table)))
	(i 32))
    ;; Nix out all the control chars...
    (while (>= (setq i (1- i)) 0)
      (aset table i [??]))
   ;; ... but not newline and cr, of course.  (cr is necessary for the
    ;; selective display).
    (aset table ?\n nil)
    (aset table ?\r nil)
    ;; We keep TAB as well.
    (aset table ?\t nil)
    ;; We nix out any glyphs 127 through 255, or 127 through 159 in
    ;; Emacs 23 (unicode), that are not set already.
    (let ((i (if (ignore-errors (= (make-char 'latin-iso8859-1 160) 160))
		 160
	       256)))
      (while (>= (setq i (1- i)) 127)
	;; Only modify if the entry is nil.
	(unless (aref table i)
	  (aset table i [??]))))
    (setq buffer-display-table table)))

(defun gnus-summary-set-article-display-arrow (pos)
  "Update the overlay arrow to point to line at position POS."
  (when gnus-summary-display-arrow
    (make-local-variable 'overlay-arrow-position)
    (make-local-variable 'overlay-arrow-string)
    (save-excursion
      (goto-char pos)
      (beginning-of-line)
      (unless overlay-arrow-position
	(setq overlay-arrow-position (make-marker)))
      (setq overlay-arrow-string "=>"
	    overlay-arrow-position (set-marker overlay-arrow-position
					       (point)
					       (current-buffer))))))

(defun gnus-summary-setup-buffer (group)
  "Initialize summary buffer for GROUP.
This function does all setup work that relies on the specific
value of GROUP, and puts the buffer in `gnus-summary-mode'.

Returns non-nil if the setup was successful."
  (let ((buffer (gnus-summary-buffer-name group))
	(dead-name (concat "*Dead Summary " group "*")))
    ;; If a dead summary buffer exists, we kill it.
    (gnus-kill-buffer dead-name)
    (if (get-buffer buffer)
	(progn
	  (set-buffer buffer)
	  (setq gnus-summary-buffer (current-buffer))
	  (not gnus-newsgroup-prepared))
      (set-buffer (gnus-get-buffer-create buffer))
      (setq gnus-summary-buffer (current-buffer))
      (let ((gnus-summary-mode-group group))
       (gnus-summary-mode))
      (when (gnus-group-quit-config group)
        (setq-local gnus-single-article-buffer nil))
      (turn-on-gnus-mailing-list-mode)
      ;; These functions don't currently depend on GROUP, but might in
      ;; the future.
      (gnus-update-format-specifications nil 'summary 'summary-mode 'summary-dummy)
      (gnus-update-summary-mark-positions)
      ;; Set any local variables in the group parameters.
      (gnus-summary-set-local-parameters gnus-newsgroup-name)
      t)))

(defun gnus-set-global-variables ()
  "Set the global equivalents of the buffer-local variables.
They are set to the latest values they had.  These reflect the summary
buffer that was in action when the last article was fetched."
  (when (derived-mode-p 'gnus-summary-mode)
    (setq gnus-summary-buffer (current-buffer))
    (let ((name gnus-newsgroup-name)
	  (marked gnus-newsgroup-marked)
	  (spam gnus-newsgroup-spam-marked)
	  (unread gnus-newsgroup-unreads)
	  (headers gnus-current-headers)
	  (data gnus-newsgroup-data)
	  (summary gnus-summary-buffer)
	  (article-buffer gnus-article-buffer)
	  (original gnus-original-article-buffer)
	  (gac gnus-article-current)
	  (reffed gnus-reffed-article-number)
	  (score-file gnus-current-score-file)
	  (default-charset gnus-newsgroup-charset)
	  vlist)
      (dolist (local gnus-newsgroup-variables)
        (push (eval (if (consp local) (car local)
                      local)
                    t)
              vlist))
      (setq vlist (nreverse vlist))
      (with-temp-buffer
	(setq gnus-newsgroup-name name
	      gnus-newsgroup-marked marked
	      gnus-newsgroup-spam-marked spam
	      gnus-newsgroup-unreads unread
	      gnus-current-headers headers
	      gnus-newsgroup-data data
	      gnus-article-current gac
	      gnus-summary-buffer summary
	      gnus-article-buffer article-buffer
	      gnus-original-article-buffer original
	      gnus-reffed-article-number reffed
	      gnus-current-score-file score-file
	      gnus-newsgroup-charset default-charset)
	(dolist (local gnus-newsgroup-variables)
          (set (if (consp local)
                   (car local)
                 local)
               (pop vlist)))))))

(defun gnus-summary-article-unread-p (article)
  "Say whether ARTICLE is unread or not."
  (memq article gnus-newsgroup-unreads))

(defun gnus-summary-first-article-p (&optional article)
  "Return whether ARTICLE is the first article in the buffer."
  (if (not (setq article (or article (gnus-summary-article-number))))
      nil
    (eq article (gnus-data-number (car gnus-newsgroup-data)))))

(defun gnus-summary-last-article-p (&optional article)
  "Return whether ARTICLE is the last article in the buffer."
  (if (not (setq article (or article (gnus-summary-article-number))))
      ;; All non-existent numbers are the last article.  :-)
      t
    (not (cdr (gnus-data-find-list article)))))

(defconst gnus--dummy-mail-header
  (make-full-mail-header 0 "" "" "05 Apr 2001 23:33:09 +0400" "" "" 0 0 "" nil))

(defconst gnus--dummy-data-list
  (list (gnus-data-make 0 nil nil gnus--dummy-mail-header nil)))

(defun gnus-make-thread-indent-array (&optional n)
  (when (or n
	    (progn (setq n 200) nil)
	    (null gnus-thread-indent-array)
	    (/= gnus-thread-indent-level gnus-thread-indent-array-level))
    (setq gnus-thread-indent-array (make-vector (1+ n) "")
	  gnus-thread-indent-array-level gnus-thread-indent-level)
    (while (>= n 0)
      (aset gnus-thread-indent-array n
	    (make-string (* n gnus-thread-indent-level) ? ))
      (setq n (1- n)))))

(defun gnus-update-summary-mark-positions ()
  "Compute where the summary marks are to go."
  (save-excursion
    (when (gnus-buffer-live-p gnus-summary-buffer)
      (set-buffer gnus-summary-buffer))
    (let ((spec gnus-summary-line-format-spec)
	  pos)
      (save-excursion
	(gnus-set-work-buffer)
	(let ((gnus-tmp-unread ?Z)
	      (gnus-replied-mark ?Z)
	      (gnus-score-below-mark ?Z)
	      (gnus-score-over-mark ?Z)
	      (gnus-undownloaded-mark ?Z)
	      (gnus-summary-line-format-spec spec)
              ;; Make sure `gnus-data-find' finds a dummy element
              ;; so we don't call gnus-data-<field> accessors on nil.
              (gnus-newsgroup-data gnus--dummy-data-list)
	      (gnus-newsgroup-downloadable '(0))
	      (gnus-visual nil)
	      case-fold-search ignores)
	  ;; Here, all marks are bound to Z.
	  (gnus-summary-insert-line gnus--dummy-mail-header
				    0 nil t gnus-tmp-unread t nil "" nil 1)
	  (goto-char (point-min))
	  ;; Memorize the positions of the same characters as dummy marks.
	  (while (re-search-forward "[A-D]" nil t)
	    (push (point) ignores))
	  (erase-buffer)
	  ;; We use A-D as dummy marks in order to know column positions
	  ;; where marks should be inserted.
	  (setq gnus-tmp-unread ?A
		gnus-replied-mark ?B
		gnus-score-below-mark ?C
		gnus-score-over-mark ?C
		gnus-undownloaded-mark ?D)
	  (gnus-summary-insert-line gnus--dummy-mail-header
				    0 nil t gnus-tmp-unread t nil "" nil 1)
	  ;; Ignore characters which aren't dummy marks.
	  (dolist (p ignores)
	    (delete-region (goto-char (1- p)) p)
	    (insert ?Z))
	  (goto-char (point-min))
	  (setq pos (list (cons 'unread
				(and (search-forward "A" nil t)
				     (- (point) (point-min) 1)))))
	  (goto-char (point-min))
	  (push (cons 'replied (and (search-forward "B" nil t)
				    (- (point) (point-min) 1)))
		pos)
	  (goto-char (point-min))
	  (push (cons 'score (and (search-forward "C" nil t)
				  (- (point) (point-min) 1)))
		pos)
	  (goto-char (point-min))
	  (push (cons 'download (and (search-forward "D" nil t)
				     (- (point) (point-min) 1)))
		pos)))
      (setq gnus-summary-mark-positions pos))))

(defun gnus-summary-insert-dummy-line (subject number)
  "Insert a dummy root in the summary buffer."
  (beginning-of-line)
  (add-text-properties
   (point) (let ((gnus-tmp-subject subject)
                 (gnus-tmp-number number))
             (eval gnus-summary-dummy-line-format-spec t)
             (point))
   (list 'gnus-number number 'gnus-intangible number)))

(defun gnus-summary-extract-address-component (from)
  (or (car (funcall gnus-extract-address-components from))
      from))

(defun gnus-summary-from-or-to-or-newsgroups (header from)
  (let ((gnus-tmp-from from)
        (mail-parse-charset gnus-newsgroup-charset)
	;; Is it really necessary to do this next part for each summary line?
	;; Luckily, doesn't seem to slow things down much.
	(mail-parse-ignored-charsets
	 (with-current-buffer gnus-summary-buffer
	   gnus-newsgroup-ignored-charsets)))
    (or
     (and gnus-ignored-from-addresses
          (cond ((functionp gnus-ignored-from-addresses)
                 (funcall gnus-ignored-from-addresses
                          (mail-strip-quoted-names gnus-tmp-from)))
                (t (string-match (gnus-ignored-from-addresses) gnus-tmp-from)))
	  (let ((extra-headers (mail-header-extra header))
		to
		newsgroups)
	    (cond
	     ((setq to (cdr (assq 'To extra-headers)))
	      (concat gnus-summary-to-prefix
		      (inline
			(gnus-summary-extract-address-component
			 (funcall gnus-decode-encoded-address-function to)))))
	     ((setq newsgroups
		    (or
		     (cdr (assq 'Newsgroups extra-headers))
		     (and
		      (memq 'Newsgroups gnus-extra-headers)
		      (eq (car (gnus-find-method-for-group
				gnus-newsgroup-name))
                          'nntp)
		      (gnus-group-real-name gnus-newsgroup-name))))
	      (concat gnus-summary-newsgroup-prefix newsgroups)))))
     (bidi-string-mark-left-to-right
      (inline
	(gnus-summary-extract-address-component gnus-tmp-from))))))

(defcustom gnus-sum-opening-bracket "["
  "With %[ spec, used to identify normal (non-adopted) articles."
  :version "28.1"
  :type 'string
  :group 'gnus-summary-format)

(defcustom gnus-sum-closing-bracket "]"
  "With %] spec, used to identify normal (non-adopted) articles."
  :version "28.1"
  :type 'string
  :group 'gnus-summary-format)

(defcustom gnus-sum-opening-bracket-adopted "<"
  "With %[ spec, used to identify adopted articles."
  :version "28.1"
  :type 'string
  :group 'gnus-summary-format)

(defcustom gnus-sum-closing-bracket-adopted ">"
  "With %] spec, used to identify adopted articles."
  :version "28.1"
  :type 'string
  :group 'gnus-summary-format)

(defun gnus-summary-insert-line (header level current undownloaded
                                 unread replied expirable subject-or-nil
				 &optional dummy score process)
  (if (>= level (length gnus-thread-indent-array))
      (gnus-make-thread-indent-array (max (* 2 (length gnus-thread-indent-array))
					  level)))
  (let* ((gnus-tmp-header header)
         (gnus-tmp-level level)
         (gnus-tmp-current current)
         (gnus-tmp-unread unread)
         (gnus-tmp-expirable expirable)
         (gnus-tmp-subject-or-nil subject-or-nil)
         (gnus-tmp-dummy dummy)
         (gnus-tmp-process process)
         (gnus-tmp-indentation (aref gnus-thread-indent-array gnus-tmp-level))
	 (gnus-tmp-lines (mail-header-lines gnus-tmp-header))
	 (gnus-tmp-score (or score gnus-summary-default-score 0))
	 (gnus-tmp-score-char
	  (if (or (null gnus-summary-default-score)
		  (<= (abs (- gnus-tmp-score gnus-summary-default-score))
		      gnus-summary-zcore-fuzz))
	      ?                         ;Whitespace
	    (if (< gnus-tmp-score gnus-summary-default-score)
		gnus-score-below-mark gnus-score-over-mark)))
	 (gnus-tmp-number (mail-header-number gnus-tmp-header))
	 (gnus-tmp-replied
	  (cond (gnus-tmp-process gnus-process-mark)
		((memq gnus-tmp-current gnus-newsgroup-cached)
		 gnus-cached-mark)
		(replied gnus-replied-mark)
		((memq gnus-tmp-current gnus-newsgroup-forwarded)
		 gnus-forwarded-mark)
		((memq gnus-tmp-current gnus-newsgroup-saved)
		 gnus-saved-mark)
		((memq gnus-tmp-number gnus-newsgroup-unseen)
		 gnus-unseen-mark)
		(t gnus-no-mark)))
	 (gnus-tmp-downloaded
	  (cond (undownloaded
                 gnus-undownloaded-mark)
                (gnus-newsgroup-agentized
                 gnus-downloaded-mark)
                (t
                 gnus-no-mark)))
	 (gnus-tmp-from (mail-header-from gnus-tmp-header))
	 (gnus-tmp-name
	  (cond
	   ((string-match "<[^>]+> *$" gnus-tmp-from)
	    (let ((beg (match-beginning 0)))
	      (or (and (string-match "^\".+\"" gnus-tmp-from)
		       (substring gnus-tmp-from 1 (1- (match-end 0))))
		  (substring gnus-tmp-from 0 beg))))
	   ((string-match "(.+)" gnus-tmp-from)
	    (substring gnus-tmp-from
		       (1+ (match-beginning 0)) (1- (match-end 0))))
	   (t gnus-tmp-from)))
	 (gnus-tmp-subject (mail-header-subject gnus-tmp-header))
	 (gnus-tmp-opening-bracket
	  (if gnus-tmp-dummy
	      gnus-sum-opening-bracket-adopted
	    gnus-sum-opening-bracket))
	 (gnus-tmp-closing-bracket
	  (if gnus-tmp-dummy
	      gnus-sum-closing-bracket-adopted
	    gnus-sum-closing-bracket))
	 (inhibit-read-only t))
    (when (string= gnus-tmp-name "")
      (setq gnus-tmp-name gnus-tmp-from))
    (unless (numberp gnus-tmp-lines)
      (setq gnus-tmp-lines -1))
    (setq gnus-tmp-lines (if (= gnus-tmp-lines -1)
	                     "?"
                           (number-to-string gnus-tmp-lines)))
    (condition-case ()
	(put-text-property
	 (point)
	 (progn (eval gnus-summary-line-format-spec t) (point))
	 'gnus-number gnus-tmp-number)
      (error (gnus-message 5 "Error updating the summary line")))
    (when (gnus-visual-p 'summary-highlight 'highlight)
      (forward-line -1)
      (gnus-summary-highlight-line)
      (gnus-run-hooks 'gnus-summary-update-hook)
      (forward-line 1))))

(defun gnus-summary-update-line (&optional dont-update)
  "Update summary line after change."
  (when (and gnus-summary-default-score
	     (not gnus-summary-inhibit-highlight))
    (let* ((gnus-summary-inhibit-highlight t) ; Prevent recursion.
	   (article (gnus-summary-article-number))
	   (score (gnus-summary-article-score article)))
      (unless dont-update
	(if (and gnus-summary-mark-below
		 (< (gnus-summary-article-score)
		    gnus-summary-mark-below))
	    ;; This article has a low score, so we mark it as read.
	    (when (memq article gnus-newsgroup-unreads)
	      (gnus-summary-mark-article-as-read gnus-low-score-mark))
	  (when (eq (gnus-summary-article-mark) gnus-low-score-mark)
	    ;; This article was previously marked as read on account
	    ;; of a low score, but now it has risen, so we mark it as
	    ;; unread.
	    (gnus-summary-mark-article-as-unread gnus-unread-mark)))
	(gnus-summary-update-mark
	 (if (or (null gnus-summary-default-score)
		 (<= (abs (- score gnus-summary-default-score))
		     gnus-summary-zcore-fuzz))
	     ?                          ;Whitespace
	   (if (< score gnus-summary-default-score)
	       gnus-score-below-mark gnus-score-over-mark))
	 'score))
      ;; Do visual highlighting.
      (when (gnus-visual-p 'summary-highlight 'highlight)
	(gnus-summary-highlight-line)
	(gnus-run-hooks 'gnus-summary-update-hook)))))

(defvar gnus-tmp-new-adopts nil)

(defun gnus-summary-number-of-articles-in-thread (thread &optional level char)
  "Return the number of articles in THREAD.
This may be 0 in some cases -- if none of the articles in
the thread are to be displayed."
  (let* ((number
	 ;; Fix by Luc Van Eycken <Luc.VanEycken@esat.kuleuven.ac.be>.
	  (cond
	   ((not (listp thread))
	    1)
	   ((and (consp thread) (cdr thread))
	    (apply
	     #'+ 1 (mapcar
		    #'gnus-summary-number-of-articles-in-thread (cdr thread))))
	   ((null thread)
	    1)
	   ((memq (mail-header-number (car thread)) gnus-newsgroup-limit)
	    1)
	   (t 0))))
    (when (and level (zerop level) gnus-tmp-new-adopts)
      (cl-incf number
	    (apply #'+ (mapcar
		        #'gnus-summary-number-of-articles-in-thread
		        gnus-tmp-new-adopts))))
    (if char
	(if (> number 1) gnus-not-empty-thread-mark
	  gnus-empty-thread-mark)
      number)))

(defsubst gnus-summary-line-message-size (head)
  "Return pretty-printed version of message size.
This function is intended to be used in
`gnus-summary-line-format-alist'."
  (let ((c (or (mail-header-chars head) -1)))
    (cond ((< c 0) "n/a")		; chars not available
	  ((< c (* 1000 10)) (format "%1.1fk" (/ c 1024.0)))
	  ((< c (* 1000 100)) (format "%dk" (/ c 1024.0)))
	  ((< c (* 1000 10000)) (format "%1.1fM" (/ c (* 1024.0 1024))))
	  (t (format "%dM" (/ c (* 1024.0 1024)))))))

(defcustom gnus-user-date-format-alist
  '(((gnus-seconds-today) . "Today, %H:%M")
    ((+ 86400 (gnus-seconds-today)) . "Yesterday, %H:%M")
    (604800 . "%A %H:%M")               ; That's one week
    ((gnus-seconds-month) . "%A %d")
    ((gnus-seconds-year) . "%B %d")
    (t . "%b %d %Y"))                   ; This one is used when no other
                                        ; does match
  "Specifies date format depending on age of article.
This is an alist of items (AGE . FORMAT).  AGE can be a number (of
seconds) or a Lisp expression evaluating to a number.  When the age of
the article is less than this number, then use `format-time-string'
with the corresponding FORMAT for displaying the date of the article.
If AGE is not a number or a Lisp expression evaluating to a
non-number, then the corresponding FORMAT is used as a default value.

Note that the list is processed from the beginning, so it should be
sorted by ascending AGE.  Also note that items following the first
non-number AGE will be ignored.

You can use the functions `gnus-seconds-today', `gnus-seconds-month'
and `gnus-seconds-year' in the AGE spec.  They return the number of
seconds passed since the start of today, of this month, of this year,
respectively."
  :version "24.1"
  :group 'gnus-summary-format
  :type '(alist :key-type sexp :value-type string))

(defun gnus-user-date (messy-date)
  "Format the messy-date according to `gnus-user-date-format-alist'.
Returns \"  ?  \" if there's bad input or if another error occurs.
Input should look like this: \"Sun, 14 Oct 2001 13:34:39 +0200\"."
  (condition-case ()
      (let* ((messy-date (gnus-date-get-time messy-date))
	     (now (current-time))
	     ;;If we don't find something suitable we'll use this one
	     (my-format "%b %d '%y"))
	(let* ((difference (time-subtract now messy-date))
	       (templist gnus-user-date-format-alist)
	       (top (eval (caar templist) t)))
	  (while (if (numberp top) (time-less-p top difference) (not top))
	    (progn
	      (setq templist (cdr templist))
	      (setq top (eval (caar templist) t))))
	  (if (stringp (cdr (car templist)))
	      (setq my-format (cdr (car templist)))))
	(format-time-string (eval my-format t) messy-date))
    (error "  ?   ")))

(defun gnus-summary-set-local-parameters (group)
  "Go through the local params of GROUP and set all variable specs in that list."
  (let ((vars '(quit-config active)))	; Ignore things that aren't
					; really variables.
    (dolist (elem (gnus-group-find-parameter group))
      (and (consp elem)			; Has to be a cons.
	   (consp (cdr elem))		; The cdr has to be a list.
	   (symbolp (car elem))		; Has to be a symbol in there.
	   (not (memq (car elem) vars))
	   (ignore-errors
	     (push (car elem) vars)
	     ;; Variables like `gnus-show-threads' that are globally
	     ;; bound, if used as group parameters, need to get to be
	     ;; buffer-local, whereas just parameters like `gcc-self',
	     ;; `timestamp', etc. should not be bound as variables.
	     (if (boundp (car elem))
		 (set (make-local-variable (car elem)) (eval (nth 1 elem) t))
	       (eval (nth 1 elem) t)))))))

(defun gnus-summary-read-group (group &optional show-all no-article
				      kill-buffer no-display backward
				      select-articles)
  "Start reading news in newsgroup GROUP.
If SHOW-ALL is non-nil, already read articles are also listed.
If NO-ARTICLE is non-nil, no article is selected initially.
If NO-DISPLAY, don't generate the summary buffer contents.
If KILL-BUFFER, it should be a buffer that's killed once the new
summary buffer has been generated.
If BACKWARD, move point to the previous group in the group buffer
If SELECT-ARTICLES, only select those articles from GROUP."
  (let (result)
    (while (and group
		(null (setq result
			    (let ((gnus-auto-select-next nil))
			      (or (gnus-summary-read-group-1
				   group show-all no-article
				   kill-buffer no-display
				   select-articles)
				  (setq show-all nil
					select-articles nil)))))
		(eq gnus-auto-select-next 'quietly))
      (set-buffer gnus-group-buffer)
      ;; The entry function called above goes to the next
      ;; group automatically, so we go two groups back
      ;; if we are searching for the previous group.
      (when backward
	(gnus-group-prev-unread-group 2))
      (if (not (equal group (gnus-group-group-name)))
	  (setq group (gnus-group-group-name))
	(setq group nil)))
    result))

(defun gnus-summary-read-group-1 (group show-all no-article
					kill-buffer no-display
					&optional select-articles)
  "Display articles and threads in a Summary buffer for GROUP."
  ;; This function calls `gnus-summary-setup-buffer' to create the
  ;; buffer, put it in `gnus-summary-mode', and set local variables;
  ;; `gnus-select-newsgroup' to update the group's active and marks
  ;; from the server; and `gnus-summary-prepare' to actually insert
  ;; lines for articles.  The rest of the function is mostly concerned
  ;; with limiting and positioning and windowing and other visual
  ;; effects.

  ;; Killed foreign groups can't be entered.
  ;;  (when (and (not (gnus-group-native-p group))
  ;;	     (not (gethash group gnus-newsrc-hashtb)))
  ;;    (error "Dead non-native groups can't be entered"))
  (gnus-message 7 "Retrieving newsgroup: %s..." group)
  (let* ((new-group (gnus-summary-setup-buffer group))
	 (quit-config (gnus-group-quit-config group))
	 (did-select (and new-group (gnus-select-newsgroup
				     group show-all select-articles))))
    (cond
     ;; This summary buffer exists already, so we just select it.
     ((not new-group)
      (gnus-set-global-variables)
      (when kill-buffer
	(gnus-kill-or-deaden-summary kill-buffer))
      (gnus-configure-windows 'summary 'force)
      (gnus-set-mode-line 'summary)
      (gnus-summary-position-point)
      (message "")
      t)
     ;; We couldn't select this group.
     ((null did-select)
      (when (and (derived-mode-p 'gnus-summary-mode)
		 (not (equal (current-buffer) kill-buffer)))
	(kill-buffer (current-buffer))
	(if (not quit-config)
	    (progn
	      ;; Update the info -- marks might need to be removed,
	      ;; for instance.
	      (gnus-summary-update-info)
	      (set-buffer gnus-group-buffer)
	      (gnus-group-jump-to-group group)
	      (gnus-group-next-unread-group 1))
	  (gnus-handle-ephemeral-exit quit-config)))
      (if (null (gnus-list-of-unread-articles group))
	  (gnus-message 3 "Group %s contains no messages" group)
	(gnus-message 3 "Can't select group"))
      nil)
     ;; The user did a `C-g' while prompting for number of articles,
     ;; so we exit this group.
     ((eq did-select 'quit)
      (and (derived-mode-p 'gnus-summary-mode)
	   (not (equal (current-buffer) kill-buffer))
	   (kill-buffer (current-buffer)))
      (when kill-buffer
	(gnus-kill-or-deaden-summary kill-buffer))
      (if (not quit-config)
	  (progn
	    (set-buffer gnus-group-buffer)
	    (gnus-group-jump-to-group group)
	    (gnus-configure-windows 'group 'force))
	(gnus-handle-ephemeral-exit quit-config))
      ;; Finally signal the quit.
      (signal 'quit nil))
     ;; The group was successfully selected.
     (t
      (gnus-set-global-variables)
      (when (boundp 'spam-install-hooks)
	(spam-initialize))
      ;; Save the active value in effect when the group was entered.
      (setq gnus-newsgroup-active
	    (copy-tree
	     (gnus-active gnus-newsgroup-name)))
      (setq gnus-newsgroup-highest (cdr gnus-newsgroup-active))
      ;; You can change the summary buffer in some way with this hook.
      (gnus-run-hooks 'gnus-select-group-hook)
      (when (memq 'summary (gnus-update-format-specifications
			    nil 'summary 'summary-mode 'summary-dummy))
	;; The format specification for the summary line was updated,
	;; so we need to update the mark positions as well.
	(gnus-update-summary-mark-positions))
      ;; Do score processing.
      (when gnus-use-scoring
	(gnus-possibly-score-headers))
      ;; Check whether to fill in the gaps in the threads.
      (when gnus-build-sparse-threads
	(gnus-build-sparse-threads))
      ;; Find the initial limit.
      (if show-all
	  (let ((gnus-newsgroup-dormant nil))
	    (gnus-summary-initial-limit show-all))
	(gnus-summary-initial-limit show-all))
      ;; Generate the summary buffer.
      (unless no-display
	(gnus-summary-prepare))
      (when gnus-use-trees
	(gnus-tree-open)                ;Autoloaded from gnus-salt.
        (declare-function gnus-tree-highlight-article "gnus-salt" (article face))
	(setq gnus-summary-highlight-line-function
	      #'gnus-tree-highlight-article))
      ;; If the summary buffer is empty, but there are some low-scored
      ;; articles or some excluded dormants, we include these in the
      ;; buffer.
      (when (and (zerop (buffer-size))
		 (not no-display))
	(cond (gnus-newsgroup-dormant
	       (gnus-summary-limit-include-dormant))
	      ((and gnus-newsgroup-scored show-all)
	       (gnus-summary-limit-include-expunged t))))
      ;; Function `gnus-apply-kill-file' must be called in this hook.
      (gnus-run-hooks 'gnus-apply-kill-hook)
      (if (and (zerop (buffer-size))
	       (not no-display))
	  (progn
	    ;; This newsgroup is empty.
	    (gnus-summary-catchup-and-exit nil t)
	    (gnus-message 6 "No unread news")
	    (when kill-buffer
	      (gnus-kill-or-deaden-summary kill-buffer))
	    ;; Return nil from this function.
	    nil)
	;; Hide conversation thread subtrees.  We cannot do this in
	;; gnus-summary-prepare-hook since kill processing may not
	;; work with hidden articles.
	(gnus-summary-maybe-hide-threads)
	(gnus-configure-windows 'summary)
	(when kill-buffer
	  (gnus-kill-or-deaden-summary kill-buffer))
	(gnus-summary-auto-select-subject)
	;; Don't mark any articles as selected if we haven't done that.
	(when no-article
	  (setq overlay-arrow-position nil))
	;; Show first unread article if requested.
	(if (and (not no-article)
		 (not no-display)
		 gnus-newsgroup-unreads
		 gnus-auto-select-first)
	    (progn
	      (let ((art (gnus-summary-article-number)))
		(when (and art
			   gnus-plugged
			   (not (memq art gnus-newsgroup-undownloaded))
			   (not (memq art gnus-newsgroup-downloadable)))
		  (gnus-summary-goto-article art))))
	  ;; Don't select any articles.
	  (gnus-summary-position-point)
	  (gnus-configure-windows 'summary 'force)
	  (gnus-set-mode-line 'summary))
	(when (and gnus-auto-center-group
		   (get-buffer-window gnus-group-buffer t))
	  ;; Gotta use windows, because recenter does weird stuff if
	  ;; the current buffer ain't the displayed window.
	  (let ((owin (selected-window)))
	    (select-window (get-buffer-window gnus-group-buffer t))
	    (when (gnus-group-goto-group group)
	      (recenter))
	    (select-window owin)))
	;; Mark this buffer as "prepared".
	(setq gnus-newsgroup-prepared t)
	(gnus-run-hooks 'gnus-summary-prepared-hook)
	(unless (gnus-ephemeral-group-p group)
	  (gnus-group-update-group group nil t))
	t)))))

(defun gnus-summary-auto-select-subject ()
  "Select the subject line on initial group entry."
  (goto-char (point-min))
  (cond
   ((eq gnus-auto-select-subject 'best)
    (gnus-summary-best-unread-subject))
   ((eq gnus-auto-select-subject 'unread)
    (gnus-summary-first-unread-subject))
   ((eq gnus-auto-select-subject 'unseen)
    (gnus-summary-first-unseen-subject))
   ((eq gnus-auto-select-subject 'unseen-or-unread)
    (gnus-summary-first-unseen-or-unread-subject))
   ((eq gnus-auto-select-subject 'first)
    ;; Do nothing.
    )
   ((functionp gnus-auto-select-subject)
    (funcall gnus-auto-select-subject))))

(defun gnus-summary-prepare ()
  "Generate the summary buffer."
  (interactive nil gnus-summary-mode)
  (let ((inhibit-read-only t))
    (erase-buffer)
    (setq gnus-newsgroup-data nil
	  gnus-newsgroup-data-reverse nil)
    (gnus-run-hooks 'gnus-summary-generate-hook)
    ;; Generate the buffer, either with threads or without.
    (when (boundp 'gnus-pick-line-number)
      (setq gnus-pick-line-number 0))
    (when gnus-newsgroup-headers
      (gnus-summary-prepare-threads
       (if gnus-show-threads
	   (gnus-sort-gathered-threads
	    (funcall gnus-summary-thread-gathering-function
		     (gnus-sort-threads
		      (gnus-cut-threads (gnus-make-threads)))))
	 ;; Unthreaded display.
	 (gnus-sort-articles gnus-newsgroup-headers))))
    (setq gnus-newsgroup-data (nreverse gnus-newsgroup-data))
    ;; Call hooks for modifying summary buffer.
    (goto-char (point-min))
    (gnus-run-hooks 'gnus-summary-prepare-hook)))

(defsubst gnus-general-simplify-subject (subject)
  "Simplify subject by the same rules as `gnus-gather-threads-by-subject'."
  (setq subject
	(cond
	 ;; Truncate the subject.
	 (gnus-simplify-subject-functions
	  (gnus-map-function gnus-simplify-subject-functions subject))
	 ((numberp gnus-summary-gather-subject-limit)
	  (setq subject (gnus-simplify-subject-re subject))
	  (if (> (length subject) gnus-summary-gather-subject-limit)
	      (substring subject 0 gnus-summary-gather-subject-limit)
	    subject))
	 ;; Fuzzily simplify it.
	 ((eq 'fuzzy gnus-summary-gather-subject-limit)
	  (gnus-simplify-subject-fuzzy subject))
	 ;; Just remove the leading "Re:".
	 (t
	  (gnus-simplify-subject-re subject))))

  (if (and gnus-summary-gather-exclude-subject
	   (string-match gnus-summary-gather-exclude-subject subject))
      nil                         ; This article shouldn't be gathered
    subject))

(defun gnus-summary-simplify-subject-query ()
  "Query where the respool algorithm would put this article."
  (interactive nil gnus-summary-mode)
  (gnus-summary-select-article)
  (message "%s" (gnus-general-simplify-subject (gnus-summary-article-subject))))

(defun gnus-gather-threads-by-subject (threads)
  "Gather threads by looking at Subject headers."
  (if (not gnus-summary-make-false-root)
      threads
    (let ((hashtb (gnus-make-hashtable 1000))
	  (prev threads)
	  (result threads)
	  subject hthread whole-subject)
      (while threads
	(setq subject (gnus-general-simplify-subject
		       (setq whole-subject (mail-header-subject
					    (caar threads)))))
	(when subject
	  (if (setq hthread (gethash subject hashtb))
	      (progn
		;; We enter a dummy root into the thread, if we
		;; haven't done that already.
		(unless (stringp (caar hthread))
		  (setcar hthread (list whole-subject (car hthread))))
		;; We add this new gathered thread to this gathered
		;; thread.
		(setcdr (car hthread)
			(nconc (cdar hthread) (list (car threads))))
		;; Remove it from the list of threads.
		(setcdr prev (cdr threads))
		(setq threads prev))
	    ;; Enter this thread into the hash table.
	    (puthash subject
		     (if gnus-summary-make-false-root-always
			 (progn
			   ;; If you want a dummy root above all
			   ;; threads...
			   (setcar threads (list whole-subject
						 (car threads)))
			   threads)
		       threads)
		     hashtb)))
	(setq prev threads)
	(setq threads (cdr threads)))
      result)))

(defun gnus-gather-threads-by-references (threads)
  "Gather threads by looking at References headers."
  (let ((idhashtb (gnus-make-hashtable 1000))
	(thhashtb (gnus-make-hashtable 1000))
	(prev threads)
	(result threads)
	ids references id gthread gid entered ref)
    (while threads
      (when (setq references (mail-header-references (caar threads)))
	(setq id (mail-header-id (caar threads))
	      ids (inline (gnus-split-references references))
	      entered nil)
	(while (setq ref (pop ids))
	  (setq ids (delete ref ids))
	  (if (not (setq gid (gethash ref idhashtb)))
	      (progn
		(puthash ref id idhashtb)
		(puthash id threads thhashtb))
	    (setq gthread (gethash gid thhashtb))
	    (unless entered
	      ;; We enter a dummy root into the thread, if we
	      ;; haven't done that already.
	      (unless (stringp (caar gthread))
		(setcar gthread (list (mail-header-subject (caar gthread))
				      (car gthread))))
	      ;; We add this new gathered thread to this gathered
	      ;; thread.
	      (setcdr (car gthread)
		      (nconc (cdar gthread) (list (car threads)))))
	    ;; Add it into the thread hash table.
	    (puthash id gthread thhashtb)
	    (setq entered t)
	    ;; Remove it from the list of threads.
	    (setcdr prev (cdr threads))
	    (setq threads prev))))
      (setq prev threads)
      (setq threads (cdr threads)))
    result))

(defun gnus-sort-gathered-threads (threads)
  "Sort subthreads inside each gathered thread by `gnus-sort-gathered-threads-function'."
  (let ((result threads))
    (while threads
      (when (stringp (caar threads))
	(setcdr (car threads)
		(sort (cdar threads) gnus-sort-gathered-threads-function)))
      (setq threads (cdr threads)))
    result))

(defun gnus-thread-loop-p (root thread)
  "Say whether ROOT is in THREAD."
  (let ((stack (list thread))
	(infloop 0)
	th)
    (while (setq thread (pop stack))
      (setq th (cdr thread))
      (while (and th
		  (not (eq (caar th) root)))
	(pop th))
      (if th
	  ;; We have found a loop.
	  (let (ref-dep)
	    (setcdr thread (delq (car th) (cdr thread)))
	    (if (setq ref-dep (gethash "none"
				       gnus-newsgroup-dependencies))
		(setcdr ref-dep
			(nconc (cdr ref-dep)
			       (list (car th))))
	      (puthash ref-dep (list nil (car th)) gnus-newsgroup-dependencies))
	    (setq infloop 1
		  stack nil))
	;; Push all the subthreads onto the stack.
	(push (cdr thread) stack)))
    infloop))

(defun gnus-make-threads ()
  "Go through the dependency hashtb and find the roots.  Return all threads."
  (let (threads)
    (while (catch 'infloop
	     (maphash
	      (lambda (_id refs)
		;; Deal with self-referencing References loops.
		(when (and (car refs)
			   (not (zerop
				 (apply
				  #'+
				  (mapcar
				   (lambda (thread)
				     (gnus-thread-loop-p
				      (car refs) thread))
				   (cdr refs))))))
		  (setq threads nil)
		  (throw 'infloop t))
		(unless (car refs)
		  ;; These threads do not refer back to any other
		  ;; articles, so they're roots.
		  (setq threads (append (cdr refs) threads))))
	      gnus-newsgroup-dependencies)))
    threads))

;; Build the thread tree.
(defsubst gnus-dependencies-add-header (header dependencies force-new)
  "Enter HEADER into the DEPENDENCIES table if it is not already there.
If FORCE-NEW is not nil, enter HEADER into the DEPENDENCIES table even
if it was already present.

If `gnus-summary-ignore-duplicates' is non-nil then duplicate
Message-IDs will not be entered in the DEPENDENCIES table.
Otherwise duplicate Message-IDs will be renamed to a unique
Message-ID before being entered.

Returns HEADER if it was entered in the DEPENDENCIES.  Returns nil otherwise."
  (let* ((id (mail-header-id header))
	 ;; An "id-dep" is a list holding the vector headers of this
	 ;; message, plus equivalent "id-deps" for each immediate
	 ;; child message.
	 (id-dep (and id (gethash id dependencies)))
	 parent-id ref ref-dep ref-header replaced)
    ;; Enter this `header' in the `dependencies' table.
    (cond
     ((null id)
      ;; Omit this article altogether if there is no Message-ID.
      (setq header nil))
     ;; Enter a new id and `header' in the `dependencies' table.
     ((null id-dep)
      (setq id-dep (puthash id (list header) dependencies)))
     ;; A child message has already added this id, just insert the header.
     ((null (car id-dep))
      (setcar (gethash id dependencies) header)
      (setq id-dep (gethash id dependencies)))
     ;; From here the `header' was already present in the
     ;; `dependencies' table.
     (force-new
      ;; Overrides an existing entry;
      ;; just set the header part of the entry.
      (setcar (gethash id dependencies) header)
      (setq replaced t))

     ;; Renames the existing `header' to a unique Message-ID.
     ((not gnus-summary-ignore-duplicates)
      ;; An article with this Message-ID has already been seen.
      ;; We rename the Message-ID.
      (setq id-dep (puthash (setq id (nnmail-message-id))
			    (list header)
			    dependencies))
      (setf (mail-header-id header) id))

     ;; The last case ignores an existing entry, except it adds any
     ;; additional Xrefs (in case the two articles came from different
     ;; servers.
     ;; Also sets `header' to nil meaning that the `dependencies'
     ;; table was *not* modified.
     (t
      (setf (mail-header-xref (car id-dep))
            (concat (or (mail-header-xref (car id-dep))
		        "")
	            (or (mail-header-xref header) "")))
      (setq header nil)))

    (when (and header (not replaced))
      ;; First check that we are not creating a References loop.
      (setq parent-id (gnus-parent-id (mail-header-references header)))
      (setq ref parent-id)
      (while (and ref
		  (setq ref-dep (gethash ref dependencies))
		  (setq ref-header (car-safe ref-dep)))
	(if (string= id ref)
	    ;; Yuk!  This is a reference loop.  Make the article be a
	    ;; root article.
	    (progn
	      (setf (mail-header-references (car id-dep)) "none")
	      (setq ref nil)
	      (setq parent-id nil))
	  (setq ref (gnus-parent-id (mail-header-references ref-header)))))
      (setq ref (or parent-id "none")
	    ref-dep (gethash ref dependencies))
      ;; Add `header' to its parent's list of children, creating that
      ;; list if the parent isn't yet registered in the dependency
      ;; table.
      (if ref-dep
	  (setcdr (gethash ref dependencies)
		  (nconc (cdr ref-dep)
			 (list id-dep)))
	(puthash ref (list nil id-dep)
		 dependencies)))
    header))

(defun gnus-extract-message-id-from-in-reply-to (string)
  (if (string-match "<[^>]+>" string)
      (substring string (match-beginning 0) (match-end 0))
    nil))

(defun gnus-build-sparse-threads ()
  (let ((headers gnus-newsgroup-headers)
	(mail-parse-charset gnus-newsgroup-charset)
	(gnus-summary-ignore-duplicates t)
	header references generation relations
	subject child end new-child date)
    ;; First we create an alist of generations/relations, where
    ;; generations is how much we trust the relation, and the relation
    ;; is parent/child.
    (gnus-message 7 "Making sparse threads...")
    (save-excursion
      (nnheader-set-temp-buffer " *gnus sparse threads*")
      (while (setq header (pop headers))
	(when (and (setq references (mail-header-references header))
		   (not (string= references "")))
	  (insert references)
	  (setq child (mail-header-id header)
		subject (mail-header-subject header)
		date (mail-header-date header)
		generation 0)
	  (while (search-backward ">" nil t)
	    (setq end (1+ (point)))
	    (when (search-backward "<" nil t)
	      (setq new-child (buffer-substring (point) end))
	      (push (list (cl-incf generation)
			  child (setq child new-child)
			  subject date)
		    relations)))
	  (when child
	    (push (list (1+ generation) child nil subject) relations))
	  (erase-buffer)))
      (kill-buffer (current-buffer)))
    ;; Sort over trustworthiness.
    (dolist (relation (sort relations #'car-less-than-car))
      (when (gnus-dependencies-add-header
	     (make-full-mail-header
	      gnus-reffed-article-number
	      (nth 3 relation) "" (or (nth 4 relation) "")
	      (nth 1 relation)
	      (or (nth 2 relation) "") 0 0 "")
	     gnus-newsgroup-dependencies nil)
	(push gnus-reffed-article-number gnus-newsgroup-limit)
	(push gnus-reffed-article-number gnus-newsgroup-sparse)
	(push (cons gnus-reffed-article-number gnus-sparse-mark)
	      gnus-newsgroup-reads)
	(cl-decf gnus-reffed-article-number)))
    (gnus-message 7 "Making sparse threads...done")))

(defun gnus-build-old-threads ()
  ;; Look at all the articles that refer back to old articles, and
  ;; fetch the headers for the articles that aren't there.  This will
  ;; build complete threads - if the roots haven't been expired by the
  ;; server, that is.
  (let ((mail-parse-charset gnus-newsgroup-charset)
	heads)
    (maphash
     (lambda (id refs)
       (when (not (car refs))
	 (setq heads (cdr refs))
	 (while heads
	   (if (memq (mail-header-number (caar heads))
		     gnus-newsgroup-dormant)
	       (setq heads (cdr heads))
	     (while (and (setq id (gnus-build-get-header id))
			 (not (car (gnus-id-to-thread id)))))
	     (setq heads nil)))))
     gnus-newsgroup-dependencies)))

(defsubst gnus-remove-odd-characters (string)
  "Translate STRING into something that doesn't contain weird characters."
  (subst-char-in-string
   ?\r ?\-
   (subst-char-in-string ?\n ?\- string t) t))

;; This function has to be called with point after the article number
;; on the beginning of the line.
(defsubst gnus-nov-parse-line (number dependencies &optional force-new)
  (let (header)
    ;; overview: [num subject from date id refs chars lines misc]
    (unwind-protect
	(narrow-to-region (point) (point-at-eol))
      (unless (eobp)
	(forward-char))
      (setq header (nnheader-parse-nov number))
      (widen))
    (when gnus-alter-header-function
      (funcall gnus-alter-header-function header))
    (gnus-dependencies-add-header header dependencies force-new)))

(defun gnus-build-get-header (id)
  "Look through the buffer of NOV lines and find the header to ID.
Enter this line into the dependencies hash table, and return
the id of the parent article (if any)."
  (let ((deps gnus-newsgroup-dependencies)
	found header)
    (prog1
	(with-current-buffer nntp-server-buffer
	  (let ((case-fold-search nil))
	    (goto-char (point-min))
	    (while (and (not found)
			(search-forward id nil t))
	      (beginning-of-line)
	      (setq found (looking-at
			   (format "^[^\t]*\t[^\t]*\t[^\t]*\t[^\t]*\t%s"
				   (regexp-quote id))))
	      (or found (beginning-of-line 2)))
	    (when found
	      (beginning-of-line)
	      (and
	       (setq header (gnus-nov-parse-line
			     (read (current-buffer)) deps))
	       (gnus-parent-id (mail-header-references header))))))
      (when header
	(let ((number (mail-header-number header)))
	  (push number gnus-newsgroup-limit)
	  (push header gnus-newsgroup-headers)
	  (if (memq number gnus-newsgroup-unselected)
	      (progn
		(setq gnus-newsgroup-unreads
		      (gnus-add-to-sorted-list gnus-newsgroup-unreads
					       number))
		(setq gnus-newsgroup-unselected
		      (delq number gnus-newsgroup-unselected)))
	    (push number gnus-newsgroup-ancient)))))))

(defun gnus-build-all-threads ()
  "Read all the headers."
  (let ((gnus-summary-ignore-duplicates t)
	(mail-parse-charset gnus-newsgroup-charset)
	(dependencies gnus-newsgroup-dependencies)
	header article)
    (with-current-buffer nntp-server-buffer
      (let ((case-fold-search nil))
	(goto-char (point-min))
	(while (not (eobp))
	  (ignore-errors
	    (setq article (read (current-buffer))
		  header (gnus-nov-parse-line article dependencies t)))
	  (when header
	    (with-current-buffer gnus-summary-buffer
	      (push header gnus-newsgroup-headers)
	      (if (memq (setq article (mail-header-number header))
			gnus-newsgroup-unselected)
		  (progn
		    (setq gnus-newsgroup-unreads
			  (gnus-add-to-sorted-list
			   gnus-newsgroup-unreads article))
		    (setq gnus-newsgroup-unselected
			  (delq article gnus-newsgroup-unselected)))
		(push article gnus-newsgroup-ancient)))
	    (forward-line 1)))))))

(defun gnus-summary-update-article-line (article header)
  "Update the line for ARTICLE using HEADER."
  (let* ((id (mail-header-id header))
	 (thread (gnus-id-to-thread id)))
    (unless thread
      (error "Article in no thread"))
    ;; Update the thread.
    (setcar thread header)
    (gnus-summary-goto-subject article)
    (let* ((datal (gnus-data-find-list article))
	   (data (car datal))
	   (inhibit-read-only t)
	   (level (gnus-summary-thread-level)))
      (gnus-delete-line)
      (let ((inserted (- (point)
                         (progn
                           (gnus-summary-insert-line
                            header level nil
                            (memq article gnus-newsgroup-undownloaded)
                            (gnus-article-mark article)
                            (memq article gnus-newsgroup-replied)
                            (memq article gnus-newsgroup-expirable)
                            ;; Only insert the Subject string when it's different
                            ;; from the previous Subject string.
                            (if (and
                                 gnus-show-threads
                                 (gnus-subject-equal
                                  (condition-case ()
                                      (mail-header-subject
                                       (gnus-data-header
                                        (cadr
                                         (gnus-data-find-list
                                          article
                                          (gnus-data-list t)))))
                                    ;; Error on the side of excessive subjects.
                                    (error ""))
                                  (mail-header-subject header)))
                                ""
                              (mail-header-subject header))
                            nil (cdr (assq article gnus-newsgroup-scored))
                            (memq article gnus-newsgroup-processable))
                           (point)))))
        (when (cdr datal)
          (gnus-data-update-list
           (cdr datal)
           (- (gnus-data-pos data) (gnus-data-pos (cadr datal)) inserted)))))))

(defun gnus-summary-update-article (article &optional iheader)
  "Update ARTICLE in the summary buffer."
  (set-buffer gnus-summary-buffer)
  (let* ((header (gnus-summary-article-header article))
	 (id (mail-header-id header))
	 (data (gnus-data-find article))
	 (thread (gnus-id-to-thread id))
	 (references (mail-header-references header))
	 (parent
	  (gnus-id-to-thread
	   (or (gnus-parent-id
		(when (and references
			   (not (equal "" references)))
		  references))
	       "none")))
	 (inhibit-read-only t)
	 (old (car thread)))
    (when thread
      (unless iheader
	(setcar thread nil)
	(when parent
	  (delq thread parent)))
      (if (gnus-summary-insert-subject id header)
	  ;; Set the (possibly) new article number in the data structure.
	  (setf (gnus-data-number data) (gnus-id-to-article id))
	(setcar thread old)
	nil))))

(defun gnus-rebuild-thread (id &optional line)
  "Rebuild the thread containing ID.
If LINE, insert the rebuilt thread starting on line LINE."
  (let ((inhibit-read-only t)
	old-pos current thread data)
    (if (not gnus-show-threads)
	(setq thread (list (car (gnus-id-to-thread id))))
      ;; Get the thread this article is part of.
      (setq thread (gnus-remove-thread id)))
    (setq old-pos (point-at-bol))
    (setq current (save-excursion
		    (and (re-search-backward "[\r\n]" nil t)
			 (gnus-summary-article-number))))
    ;; If this is a gathered thread, we have to go some re-gathering.
    (when (stringp (car thread))
      (let ((subject (car thread))
	    roots thr)
	(setq thread (cdr thread))
	(while thread
	  (unless (memq (setq thr (gnus-id-to-thread
				   (gnus-root-id
				    (mail-header-id (caar thread)))))
			roots)
	    (push thr roots))
	  (setq thread (cdr thread)))
	;; We now have all (unique) roots.
	(setq thread (if (= (length roots) 1)
	                 ;; All the loose roots are now one solid root.
	                 (car roots)
                       (cons subject (gnus-sort-threads roots))))))
    (let (threads)
      ;; We then insert this thread into the summary buffer.
      (when line
	(goto-char (point-min))
	(forward-line (1- line)))
      (let (gnus-newsgroup-data gnus-newsgroup-threads)
	(if gnus-show-threads
	    (gnus-summary-prepare-threads (gnus-cut-threads (list thread)))
	  (gnus-summary-prepare-unthreaded thread))
        ;; FIXME: Why is this `nreverse' safe?  Don't we need `reverse' instead?
	(setq data (nreverse gnus-newsgroup-data))
	(setq threads gnus-newsgroup-threads))
      ;; We splice the new data into the data structure.
      ;;!!! This is kinda bogus.  We assume that in LINE is non-nil,
      ;;!!! then we want to insert at the beginning of the buffer.
      ;;!!! That happens to be true with Gnus now, but that may
      ;;!!! change in the future.  Perhaps.
      (gnus-data-enter-list
       (if line nil current) data (- (point) old-pos))
      (setq gnus-newsgroup-threads
	    (nconc threads gnus-newsgroup-threads))
      (gnus-data-compute-positions))))

(defun gnus-number-to-header (number)
  "Return the header for article NUMBER."
  (let ((headers gnus-newsgroup-headers))
    (while (and headers
		(not (= number (mail-header-number (car headers)))))
      (pop headers))
    (when headers
      (car headers))))

(defun gnus-parent-headers (in-headers &optional generation)
  "Return the headers of the GENERATIONth parent of HEADERS."
  (unless generation
    (setq generation 1))
  (let ((parent t)
	(headers in-headers)
	references)
    (while (and parent
		(not (zerop generation))
		(setq references (mail-header-references headers)))
      (setq headers (if (and references
			     (setq parent (gnus-parent-id references)))
			(car (gnus-id-to-thread parent))
		      nil))
      (cl-decf generation))
    (and (not (eq headers in-headers))
	 headers)))

(defun gnus-id-to-thread (id)
  "Return the (sub-)thread where ID appears."
  (when (hash-table-p gnus-newsgroup-dependencies)
    (gethash id gnus-newsgroup-dependencies)))

(defun gnus-id-to-article (id)
  "Return the article number of ID."
  (let ((thread (gnus-id-to-thread id)))
    (when (and thread
	       (car thread))
      (mail-header-number (car thread)))))

(defun gnus-id-to-header (id)
  "Return the article headers of ID."
  (car (gnus-id-to-thread id)))

(defun gnus-article-displayed-root-p (article)
  "Say whether ARTICLE is a root(ish) article."
  (let ((level (gnus-summary-thread-level article))
	(refs (mail-header-references  (gnus-summary-article-header article)))
	particle)
    (cond
     ((null level) nil)
     ((zerop level) t)
     ((null refs) t)
     ((null (gnus-parent-id refs)) t)
     ((and (= 1 level)
	   (null (setq particle (gnus-id-to-article
				 (gnus-parent-id refs))))
	   (null (gnus-summary-thread-level particle)))))))

(defun gnus-root-id (id)
  "Return the id of the root of the thread where ID appears."
  (let (last-id prev)
    (while (and id (setq prev (car (gnus-id-to-thread id))))
      (setq last-id id
	    id (gnus-parent-id (mail-header-references prev))))
    last-id))

(defun gnus-articles-in-thread (thread)
  "Return the list of articles in THREAD."
  (cons (mail-header-number (car thread))
	(mapcan #'gnus-articles-in-thread (cdr thread))))

(defun gnus-remove-thread (id &optional dont-remove)
  "Remove the thread that has ID in it."
  (let (headers thread last-id)
    ;; First go up in this thread until we find the root.
    (setq last-id (gnus-root-id id)
	  headers (flatten-tree (gnus-id-to-thread last-id)))
    ;; We have now found the real root of this thread.  It might have
    ;; been gathered into some loose thread, so we have to search
    ;; through the threads to find the thread we wanted.
    (let ((threads gnus-newsgroup-threads)
	  sub)
      (while threads
	(setq sub (car threads))
	(if (stringp (car sub))
	    ;; This is a gathered thread, so we look at the roots
	    ;; below it to find whether this article is in this
	    ;; gathered root.
	    (progn
	      (setq sub (cdr sub))
	      (while sub
		(when (member (caar sub) headers)
		  (setq thread (car threads)
			threads nil
			sub nil))
		(setq sub (cdr sub))))
	  ;; It's an ordinary thread, so we check it.
	  (when (eq (car sub) (car headers))
	    (setq thread sub
		  threads nil)))
	(setq threads (cdr threads)))
      ;; If this article is in no thread, then it's a root.
      (if thread
	  (unless dont-remove
	    (setq gnus-newsgroup-threads (delq thread gnus-newsgroup-threads)))
	(setq thread (gnus-id-to-thread last-id)))
      (when thread
	(prog1
	    thread			; We return this thread.
	  (unless dont-remove
	    (if (stringp (car thread))
		(progn
		  ;; If we use dummy roots, then we have to remove the
		  ;; dummy root as well.
		  (when (eq gnus-summary-make-false-root 'dummy)
		    ;; We go to the dummy root by going to
		    ;; the first sub-"thread", and then one line up.
		    (gnus-summary-goto-article
		     (mail-header-number (caadr thread)))
		    (forward-line -1)
		    (gnus-delete-line)
		    (gnus-data-compute-positions))
		  (setq thread (cdr thread))
		  (while thread
		    (gnus-remove-thread-1 (car thread))
		    (setq thread (cdr thread))))
	      (gnus-remove-thread-1 thread))))))))

(defun gnus-remove-thread-1 (thread)
  "Remove the thread THREAD recursively."
  (let ((number (mail-header-number (pop thread)))
	d)
    (setq thread (reverse thread))
    (while thread
      (gnus-remove-thread-1 (pop thread)))
    (when (setq d (gnus-data-find number))
      (goto-char (gnus-data-pos d))
      (gnus-summary-show-thread)
      (gnus-data-remove
       number
       (- (point-at-bol)
	  (prog1
	      (1+ (point-at-eol))
	    (gnus-delete-line)))))))

(defun gnus-sort-threads-recursive (threads func)
  ;; Responsible for sorting the root articles of threads.
  (let ((subthread-sort-func (if (eq gnus-subthread-sort-functions
				     'gnus-thread-sort-functions)
				 func
			       (gnus-make-sort-function
				gnus-subthread-sort-functions))))
    (sort (mapcar (lambda (thread)
		    (cons (car thread)
			  (and (cdr thread)
			       (gnus-sort-subthreads-recursive
				(cdr thread) subthread-sort-func))))
		  threads)
          func)))

(defun gnus-sort-subthreads-recursive (threads func)
  ;; Responsible for sorting subthreads.
  (sort (mapcar (lambda (thread)
		  (cons (car thread)
			(and (cdr thread)
			     (gnus-sort-subthreads-recursive (cdr thread) func))))
		threads)
        func))

(defun gnus-sort-threads-loop (threads func)
  (let* ((superthread (cons nil threads))
  	 (stack (list (cons superthread threads)))
  	 remaining-threads thread)
    (while stack
      (setq remaining-threads (cdr (car stack)))
      (if remaining-threads
  	  (progn (setq thread (car remaining-threads))
  		 (setcdr (car stack) (cdr remaining-threads))
  		 (if (cdr thread)
  		     (push (cons thread (cdr thread)) stack)))
  	(setq thread (caar stack))
  	(setcdr thread (sort (cdr thread) func))
  	(pop stack)))
    (cdr superthread)))

(defun gnus-sort-threads (threads)
  "Sort THREADS."
  (if (not gnus-thread-sort-functions)
      threads
    (gnus-message 8 "Sorting threads...")
    (prog1
	(condition-case nil
	    (let ((max-lisp-eval-depth (max max-lisp-eval-depth 5000))
		  (sort-func (gnus-make-sort-function gnus-thread-sort-functions)))
	      (gnus-sort-threads-recursive threads sort-func))
	  ;; Even after binding max-lisp-eval-depth, the recursive
	  ;; sorter might fail for very long threads.  In that case,
	  ;; try using a (less well-tested) non-recursive sorter.
	  (error (gnus-message 9 "Sorting threads with loop...")
		 (gnus-sort-threads-loop
		  threads (gnus-make-sort-function
			   gnus-thread-sort-functions))))
      (gnus-message 8 "Sorting threads...done"))))

(defun gnus-sort-articles (articles)
  "Sort ARTICLES."
  (when gnus-article-sort-functions
    (gnus-message 7 "Sorting articles...")
    (prog1
	(setq gnus-newsgroup-headers
	      (sort articles (gnus-make-sort-function
			      gnus-article-sort-functions)))
      (gnus-message 7 "Sorting articles...done"))))

;; Written by Hallvard B Furuseth <h.b.furuseth@usit.uio.no>.
(defmacro gnus-thread-header (thread)
  "Return header of first article in THREAD.
Note that THREAD must never, ever be anything else than a variable -
using some other form will lead to serious barfage."
  (or (symbolp thread) (signal 'wrong-type-argument '(symbolp thread)))
  ;; (8% speedup to gnus-summary-prepare, just for fun :-)
  (cond
   ((and (boundp 'lexical-binding) lexical-binding)
    ;; FIXME: This version could be a "defsubst" rather than a macro.
    `(#[257 "\211:\203\16\0\211@;\203\15\0A@@\207"
            [] 2]
      ,thread))
   (t
    ;; Not sure how XEmacs handles these things, so let's keep the old code.
    (list 'byte-code "\10\211:\203\17\0\211@;\203\16\0A@@\207"
          (vector thread) 2))))

(defsubst gnus-article-sort-by-number (h1 h2)
  "Sort articles by article number."
  (< (mail-header-number h1)
     (mail-header-number h2)))

(defun gnus-thread-sort-by-number (h1 h2)
  "Sort threads by root article number."
  (gnus-article-sort-by-number
   (gnus-thread-header h1) (gnus-thread-header h2)))

(defsubst gnus-article-sort-by-random (_h1 _h2)
  "Sort articles randomly."
  (zerop (random 2)))

(defalias 'gnus-thread-sort-by-random #'gnus-article-sort-by-random
  "Sort threads randomly.")

(defsubst gnus-article-sort-by-lines (h1 h2)
  "Sort articles by article Lines header."
  (< (mail-header-lines h1)
     (mail-header-lines h2)))

(defun gnus-thread-sort-by-lines (h1 h2)
  "Sort threads by root article Lines header."
  (gnus-article-sort-by-lines
   (gnus-thread-header h1) (gnus-thread-header h2)))

(defsubst gnus-article-sort-by-chars (h1 h2)
  "Sort articles by octet length."
  (< (mail-header-chars h1)
     (mail-header-chars h2)))

(defun gnus-thread-sort-by-chars (h1 h2)
  "Sort threads by root article octet length."
  (gnus-article-sort-by-chars
   (gnus-thread-header h1) (gnus-thread-header h2)))

(defsubst gnus-article-sort-by-marks (h1 h2)
  "Sort articles by octet length."
  (< (gnus-article-mark (mail-header-number h1))
     (gnus-article-mark (mail-header-number h2))))

(defun gnus-thread-sort-by-marks (h1 h2)
  "Sort threads by root article octet length."
  (gnus-article-sort-by-marks
   (gnus-thread-header h1) (gnus-thread-header h2)))

(defsubst gnus-article-sort-by-author (h1 h2)
  "Sort articles by root author."
  (gnus-string<
   (let ((extract (funcall
		   gnus-extract-address-components
		   (mail-header-from h1))))
     (or (car extract) (cadr extract) ""))
   (let ((extract (funcall
		   gnus-extract-address-components
		   (mail-header-from h2))))
     (or (car extract) (cadr extract) ""))))

(defun gnus-thread-sort-by-author (h1 h2)
  "Sort threads by root author."
  (gnus-article-sort-by-author
   (gnus-thread-header h1)  (gnus-thread-header h2)))

(defsubst gnus-article-sort-extract-extra (name header)
  (let ((extract
	 (funcall gnus-extract-address-components
		  (or (cdr (assq name (mail-header-extra header)))
		      ""))))
    (or (car extract) (cadr extract))))

(defsubst gnus-article-sort-by-recipient (h1 h2)
  "Sort articles by recipient."
  (let ((ex (lambda (h) (gnus-article-sort-extract-extra 'To h))))
    (gnus-string< (funcall ex h1) (funcall ex h2))))

(defun gnus-thread-sort-by-recipient (h1 h2)
  "Sort threads by root recipient."
  (gnus-article-sort-by-recipient
   (gnus-thread-header h1) (gnus-thread-header h2)))

(defsubst gnus-article-sort-by-subject (h1 h2)
  "Sort articles by root subject."
  (gnus-string<
   (downcase (gnus-simplify-subject-re (mail-header-subject h1)))
   (downcase (gnus-simplify-subject-re (mail-header-subject h2)))))

(defun gnus-thread-sort-by-subject (h1 h2)
  "Sort threads by root subject."
  (gnus-article-sort-by-subject
   (gnus-thread-header h1) (gnus-thread-header h2)))

(defsubst gnus-article-sort-by-date (h1 h2)
  "Sort articles by root article date."
  (time-less-p
   (gnus-date-get-time (mail-header-date h1))
   (gnus-date-get-time (mail-header-date h2))))

(defun gnus-thread-sort-by-date (h1 h2)
  "Sort threads by root article date."
  (gnus-article-sort-by-date
   (gnus-thread-header h1) (gnus-thread-header h2)))

(defsubst gnus-article-sort-by-rsv (h1 h2)
  "Sort articles by rsv."
  (when gnus-newsgroup-selection
    (< (nnselect-article-rsv (mail-header-number h1))
       (nnselect-article-rsv (mail-header-number h2)))))

(defun gnus-thread-sort-by-rsv (h1 h2)
  "Sort threads by root article rsv."
  (gnus-article-sort-by-rsv
   (gnus-thread-header h1) (gnus-thread-header h2)))

(defsubst gnus-article-sort-by-score (h1 h2)
  "Sort articles by root article score.
Unscored articles will be counted as having a score of zero."
  (> (or (cdr (assq (mail-header-number h1)
		    gnus-newsgroup-scored))
	 gnus-summary-default-score 0)
     (or (cdr (assq (mail-header-number h2)
		    gnus-newsgroup-scored))
	 gnus-summary-default-score 0)))

(defun gnus-thread-sort-by-score (h1 h2)
  "Sort threads by root article score."
  (gnus-article-sort-by-score
   (gnus-thread-header h1) (gnus-thread-header h2)))

(defun gnus-thread-sort-by-total-score (h1 h2)
  "Sort threads by the sum of all scores in the thread.
Unscored articles will be counted as having a score of zero."
  (> (gnus-thread-total-score h1) (gnus-thread-total-score h2)))

(defun gnus-thread-total-score (thread)
  ;; This function find the total score of THREAD.
  (cond
   ((null thread)
    0)
   ((consp thread)
    (if (stringp (car thread))
	(apply gnus-thread-score-function 0
	       (mapcar #'gnus-thread-total-score-1 (cdr thread)))
      (gnus-thread-total-score-1 thread)))
   (t
    (gnus-thread-total-score-1 (list thread)))))

(defun gnus-article-sort-by-most-recent-number (h1 h2)
  "Sort articles by number."
  (gnus-article-sort-by-number h1 h2))

(defun gnus-thread-sort-by-most-recent-number (h1 h2)
  "Sort threads such that the thread with the most recently arrived article comes first."
  (> (gnus-thread-highest-number h1) (gnus-thread-highest-number h2)))

(defun gnus-thread-highest-number (thread)
  "Return the highest article number in THREAD."
  (apply #'max (mapcar (lambda (header)
			(mail-header-number header))
		      (flatten-tree thread))))

(defun gnus-article-sort-by-most-recent-date (h1 h2)
  "Sort articles by number."
  (gnus-article-sort-by-date h1 h2))

(defun gnus-thread-sort-by-most-recent-date (h1 h2)
  "Sort threads such that the thread with the most recently dated article comes first."
  (> (gnus-thread-latest-date h1) (gnus-thread-latest-date h2)))

(defsubst gnus-article-sort-by-newsgroups (h1 h2)
  "Sort articles by newsgroups."
  (let ((ex (lambda (h) (gnus-article-sort-extract-extra 'Newsgroups h))))
    (gnus-string< (funcall ex h1) (funcall ex h2))))

(defun gnus-thread-sort-by-newsgroups (h1 h2)
  "Sort threads by root newsgroups."
  (gnus-article-sort-by-newsgroups
   (gnus-thread-header h1) (gnus-thread-header h2)))

; Since this is called not only to sort the top-level threads, but
; also in recursive sorts to order the articles within a thread, each
; article will be processed many times.  Thus it speeds things up
; quite a bit to use gnus-date-get-time, which caches the time value.
(defun gnus-thread-latest-date (thread)
  "Return the highest article date in THREAD."
  (apply #'max
	 (mapcar (lambda (header) (float-time
				   (gnus-date-get-time
				    (mail-header-date header))))
		 (flatten-tree thread))))

(defun gnus-thread-total-score-1 (root)
  ;; This function find the total score of the thread below ROOT.
  (setq root (car root))
  (apply gnus-thread-score-function
	 (or (append
	      (mapcar #'gnus-thread-total-score
		      (cdr (gnus-id-to-thread (mail-header-id root))))
	      (when (> (mail-header-number root) 0)
		(list (or (cdr (assq (mail-header-number root)
				     gnus-newsgroup-scored))
			  gnus-summary-default-score 0))))
	     (list gnus-summary-default-score)
	     '(0))))

;; Added by Per Abrahamsen <amanda@iesd.auc.dk>.
(defvar gnus-tmp-prev-subject nil)
(defvar gnus-tmp-false-parent nil)
(defvar gnus-tmp-root-expunged nil)
(defvar gnus-tmp-dummy-line nil)

(defun gnus-extra-header (type &optional header)
  "Return the extra header of TYPE."
  (or (cdr (assq type (mail-header-extra (or header gnus-tmp-header))))
      ""))

(defvar gnus-tmp-thread-tree-header-string "")

(defcustom gnus-sum-thread-tree-root "> "
  "With %B spec, used for the root of a thread.
If nil, use subject instead."
  :version "22.1"
  :type '(radio (const :format "%v  " nil) string)
  :group 'gnus-thread)

(defcustom gnus-sum-thread-tree-false-root "> "
  "With %B spec, used for a false root of a thread.
If nil, use subject instead."
  :version "22.1"
  :type '(radio (const :format "%v  " nil) string)
  :group 'gnus-thread)

(defcustom gnus-sum-thread-tree-single-indent ""
  "With %B spec, used for a thread with just one message.
If nil, use subject instead."
  :version "22.1"
  :type '(radio (const :format "%v  " nil) string)
  :group 'gnus-thread)

(defcustom gnus-sum-thread-tree-vertical "| "
  "With %B spec, used for drawing a vertical line."
  :version "22.1"
  :type 'string
  :group 'gnus-thread)

(defcustom gnus-sum-thread-tree-indent "  "
  "With %B spec, used for indenting."
  :version "22.1"
  :type 'string
  :group 'gnus-thread)

(defcustom gnus-sum-thread-tree-leaf-with-other "+-> "
  "With %B spec, used for a leaf with brothers."
  :version "22.1"
  :type 'string
  :group 'gnus-thread)

(defcustom gnus-sum-thread-tree-single-leaf "\\-> "
  "With %B spec, used for a leaf without brothers."
  :version "22.1"
  :type 'string
  :group 'gnus-thread)

(defcustom gnus-summary-display-while-building nil
  "If non-nil, show and update the summary buffer as it's being built.
If the value is t, update the buffer after every line is inserted.  If
the value is an integer (N), update the display every N lines."
  :version "22.1"
  :group 'gnus-thread
  :type '(choice (const :tag "off" nil)
		 number
		 (const :tag "frequently" t)))

(defun gnus-summary-prepare-threads (threads)
  "Prepare summary buffer from THREADS and indentation LEVEL.
THREADS is either a list of `(PARENT [(CHILD1 [(GRANDCHILD ...]...) ...])'
or a straight list of headers."
  (gnus-message 7 "Generating summary...")

  (setq gnus-newsgroup-threads threads)
  (beginning-of-line)

  (let ((gnus-tmp-level 0)
	(default-score (or gnus-summary-default-score 0))
	(gnus-visual-p (gnus-visual-p 'summary-highlight 'highlight))
	(building-line-count gnus-summary-display-while-building)
	(building-count (integerp gnus-summary-display-while-building))
	thread number subject stack state gnus-tmp-gathered beg-match
	new-roots gnus-tmp-new-adopts thread-end simp-subject
	gnus-tmp-header gnus-tmp-unread gnus-tmp-downloaded
	gnus-tmp-replied gnus-tmp-subject-or-nil
	gnus-tmp-dummy gnus-tmp-indentation gnus-tmp-lines gnus-tmp-score
	gnus-tmp-score-char gnus-tmp-from gnus-tmp-name gnus-tmp-thread
	gnus-tmp-number gnus-tmp-opening-bracket gnus-tmp-closing-bracket
	tree-stack)

    (setq gnus-tmp-prev-subject nil
          gnus-tmp-thread-tree-header-string "")

    (if (vectorp (car threads))
	;; If this is a straight (sic) list of headers, then a
	;; threaded summary display isn't required, so we just create
	;; an unthreaded one.
	(gnus-summary-prepare-unthreaded threads)

      ;; Do the threaded display.

      (if gnus-summary-display-while-building
	  (switch-to-buffer (buffer-name)))
      (while (or threads stack gnus-tmp-new-adopts new-roots)

	(if (and (= gnus-tmp-level 0)
		 (or (not stack)
		     (= (caar stack) 0))
		 (not gnus-tmp-false-parent)
		 (or gnus-tmp-new-adopts new-roots))
	    (if gnus-tmp-new-adopts
		(setq gnus-tmp-level (if gnus-tmp-root-expunged 0 1)
		      thread (list (car gnus-tmp-new-adopts))
		      gnus-tmp-header (caar thread)
		      gnus-tmp-new-adopts (cdr gnus-tmp-new-adopts))
	      (when new-roots
		(setq thread (list (car new-roots))
		      gnus-tmp-header (caar thread)
		      new-roots (cdr new-roots))))

	  (if threads
	      ;; If there are some threads, we do them before the
	      ;; threads on the stack.
	      (setq thread threads
		    gnus-tmp-header (caar thread))
	    ;; There were no current threads, so we pop something off
	    ;; the stack.
	    (setq state (car stack)
		  gnus-tmp-level (car state)
		  tree-stack (cadr state)
		  thread (caddr state)
		  stack (cdr stack)
		  gnus-tmp-header (caar thread))))

	(setq gnus-tmp-false-parent nil)
	(setq gnus-tmp-root-expunged nil)
	(setq thread-end nil)

	(if (stringp gnus-tmp-header)
	    ;; The header is a dummy root.
	    (cond
	     ((eq gnus-summary-make-false-root 'adopt)
	      ;; We let the first article adopt the rest.
	      (setq gnus-tmp-new-adopts (nconc gnus-tmp-new-adopts
					       (cddar thread)))
	      (setq gnus-tmp-gathered
		    (nconc (mapcar
			    (lambda (h) (mail-header-number (car h)))
			    (cddar thread))
			   gnus-tmp-gathered))
	      (setq thread (cons (list (caar thread)
				       (cadar thread))
				 (cdr thread)))
	      (setq gnus-tmp-level -1
		    gnus-tmp-false-parent t))
	     ((eq gnus-summary-make-false-root 'empty)
	      ;; We print adopted articles with empty subject fields.
	      (setq gnus-tmp-gathered
		    (nconc (mapcar
			    (lambda (h) (mail-header-number (car h)))
			    (cddar thread))
			   gnus-tmp-gathered))
	      (setq gnus-tmp-level -1))
	     ((eq gnus-summary-make-false-root 'dummy)
	      ;; We remember that we probably want to output a dummy
	      ;; root.
	      (setq gnus-tmp-dummy-line gnus-tmp-header)
	      (setq gnus-tmp-prev-subject
		    (gnus-simplify-subject-fully gnus-tmp-header)))
	     (t
	      ;; We do not make a root for the gathered
	      ;; sub-threads at all.
	      (setq gnus-tmp-level -1)))

	  (setq number (mail-header-number gnus-tmp-header)
		subject (mail-header-subject gnus-tmp-header)
		simp-subject (gnus-simplify-subject-fully subject))

	  (cond
	   ;; If the thread has changed subject, we might want to make
	   ;; this subthread into a root.
	   ((and (null gnus-thread-ignore-subject)
		 (not (zerop gnus-tmp-level))
		 gnus-tmp-prev-subject
		 (not (string= gnus-tmp-prev-subject simp-subject)))
	    (setq new-roots (nconc new-roots (list (car thread)))
		  thread-end t
		  gnus-tmp-header nil))
	   ;; If the article lies outside the current limit,
	   ;; then we do not display it.
	   ((not (memq number gnus-newsgroup-limit))
	    (setq gnus-tmp-gathered
		  (nconc (mapcar
			  (lambda (h) (mail-header-number (car h)))
			  (cdar thread))
			 gnus-tmp-gathered))
	    (setq gnus-tmp-new-adopts (if (cdar thread)
					  (append gnus-tmp-new-adopts
						  (cdar thread))
					gnus-tmp-new-adopts)
		  thread-end t
		  gnus-tmp-header nil)
	    (when (zerop gnus-tmp-level)
	      (setq gnus-tmp-root-expunged t)))
	   ;; Perhaps this article is to be marked as read?
	   ((and gnus-summary-mark-below
		 (< (or (cdr (assq number gnus-newsgroup-scored))
			default-score)
		    gnus-summary-mark-below)
		 ;; Don't touch sparse articles.
		 (not (gnus-summary-article-sparse-p number))
		 (not (gnus-summary-article-ancient-p number)))
	    (setq gnus-newsgroup-unreads
		  (delq number gnus-newsgroup-unreads))
	    (if gnus-newsgroup-auto-expire
		(setq gnus-newsgroup-expirable
		      (gnus-add-to-sorted-list
		       gnus-newsgroup-expirable number))
	      (push (cons number gnus-low-score-mark)
		    gnus-newsgroup-reads))))

	  (when gnus-tmp-header
	    ;; We may have an old dummy line to output before this
	    ;; article.
	    (when (and gnus-tmp-dummy-line
		       (gnus-subject-equal
			gnus-tmp-dummy-line
			(mail-header-subject gnus-tmp-header)))
	      (gnus-summary-insert-dummy-line
	       gnus-tmp-dummy-line (mail-header-number gnus-tmp-header))
	      (setq gnus-tmp-dummy-line nil))

	    ;; Compute the mark.
	    (setq gnus-tmp-unread (gnus-article-mark number))

	    (push (gnus-data-make number gnus-tmp-unread (1+ (point))
				  gnus-tmp-header gnus-tmp-level)
		  gnus-newsgroup-data)

	    ;; Actually insert the line.
	    (setq
	     gnus-tmp-subject-or-nil
	     (cond
	      ((and gnus-thread-ignore-subject
		    gnus-tmp-prev-subject
		    (not (string= gnus-tmp-prev-subject simp-subject)))
	       subject)
	      ((zerop gnus-tmp-level)
	       (if (and (eq gnus-summary-make-false-root 'empty)
			(memq number gnus-tmp-gathered)
			gnus-tmp-prev-subject
			(string= gnus-tmp-prev-subject simp-subject))
		   gnus-summary-same-subject
		 subject))
	      (t gnus-summary-same-subject)))
	    (if (and (eq gnus-summary-make-false-root 'adopt)
		     (= gnus-tmp-level 1)
		     (memq number gnus-tmp-gathered))
		(setq gnus-tmp-opening-bracket gnus-sum-opening-bracket-adopted
		      gnus-tmp-closing-bracket gnus-sum-closing-bracket-adopted)
	      (setq gnus-tmp-opening-bracket gnus-sum-opening-bracket
		    gnus-tmp-closing-bracket gnus-sum-closing-bracket))
	    (if (>= gnus-tmp-level (length gnus-thread-indent-array))
		(gnus-make-thread-indent-array
		 (max (* 2 (length gnus-thread-indent-array))
		      gnus-tmp-level)))
	    (setq
	     gnus-tmp-indentation
	     (aref gnus-thread-indent-array gnus-tmp-level)
	     gnus-tmp-lines (mail-header-lines gnus-tmp-header)
	     gnus-tmp-score (or (cdr (assq number gnus-newsgroup-scored))
				gnus-summary-default-score 0)
	     gnus-tmp-score-char
	     (if (or (null gnus-summary-default-score)
		     (<= (abs (- gnus-tmp-score gnus-summary-default-score))
			 gnus-summary-zcore-fuzz))
		 ?                      ;Whitespace
	       (if (< gnus-tmp-score gnus-summary-default-score)
		   gnus-score-below-mark gnus-score-over-mark))
	     gnus-tmp-replied
	     (cond ((memq number gnus-newsgroup-processable)
		    gnus-process-mark)
		   ((memq number gnus-newsgroup-cached)
		    gnus-cached-mark)
		   ((memq number gnus-newsgroup-replied)
		    gnus-replied-mark)
		   ((memq number gnus-newsgroup-forwarded)
		    gnus-forwarded-mark)
		   ((memq number gnus-newsgroup-saved)
		    gnus-saved-mark)
		   ((memq number gnus-newsgroup-unseen)
		    gnus-unseen-mark)
		   (t gnus-no-mark))
	     gnus-tmp-downloaded
             (cond ((memq number gnus-newsgroup-undownloaded)
                    gnus-undownloaded-mark)
                   (gnus-newsgroup-agentized
                    gnus-downloaded-mark)
                   (t
                    gnus-no-mark))
	     gnus-tmp-from (mail-header-from gnus-tmp-header)
	     gnus-tmp-name
	     (cond
	      ((string-match "<[^>]+> *$" gnus-tmp-from)
	       (setq beg-match (match-beginning 0))
	       (or (and (string-match "^\".+\"" gnus-tmp-from)
			(substring gnus-tmp-from 1 (1- (match-end 0))))
		   (substring gnus-tmp-from 0 beg-match)))
	      ((string-match "(.+)" gnus-tmp-from)
	       (substring gnus-tmp-from
			  (1+ (match-beginning 0)) (1- (match-end 0))))
	      (t gnus-tmp-from))

	     ;; Do the %B string
	     gnus-tmp-thread-tree-header-string
	     (cond
	      ((not gnus-show-threads) "")
	      ((zerop gnus-tmp-level)
	       (cond ((cdar thread)
		      (or gnus-sum-thread-tree-root subject))
		     (gnus-tmp-new-adopts
		      (or gnus-sum-thread-tree-false-root subject))
		     (t
		      (or gnus-sum-thread-tree-single-indent subject))))
	      (t
	       (concat (apply #'concat
			      (mapcar (lambda (item)
					(if (= item 1)
					    gnus-sum-thread-tree-vertical
					  gnus-sum-thread-tree-indent))
				      (cdr (reverse tree-stack))))
		       (if (nth 1 thread)
			   gnus-sum-thread-tree-leaf-with-other
			 gnus-sum-thread-tree-single-leaf)))))
	    (when (string= gnus-tmp-name "")
	      (setq gnus-tmp-name gnus-tmp-from))
	    (unless (numberp gnus-tmp-lines)
	      (setq gnus-tmp-lines -1))
	    (setq gnus-tmp-lines (if (= gnus-tmp-lines -1)
		                     "?"
                                   (number-to-string gnus-tmp-lines)))
            (setq gnus-tmp-thread thread)
	    (put-text-property
	     (point)
	     (progn (eval gnus-summary-line-format-spec t) (point))
	     'gnus-number number)
	    (when gnus-visual-p
	      (forward-line -1)
	      (gnus-summary-highlight-line)
	      (when gnus-summary-update-hook
		(gnus-run-hooks 'gnus-summary-update-hook))
	      (forward-line 1))

	    (setq gnus-tmp-prev-subject simp-subject)))

	(when (nth 1 thread)
	  (push (list (max 0 gnus-tmp-level)
		      (copy-sequence tree-stack)
		      (nthcdr 1 thread))
		stack))
	(push (if (nth 1 thread) 1 0) tree-stack)
	(cl-incf gnus-tmp-level)
	(setq threads (if thread-end nil (cdar thread)))
	(if gnus-summary-display-while-building
	    (if building-count
		(progn
		  ;; use a set frequency
		  (setq building-line-count (1- building-line-count))
		  (when (= building-line-count 0)
		    (sit-for 0)
		    (setq building-line-count
			  gnus-summary-display-while-building)))
	      ;; always
	      (sit-for 0)))
	(unless threads
	  (setq gnus-tmp-level 0)))))
  (gnus-message 7 "Generating summary...done"))

(defun gnus-summary-prepare-unthreaded (headers)
  "Generate an unthreaded summary buffer based on HEADERS."
  (let (header number mark)

    (beginning-of-line)

    (while headers
      ;; We may have to root out some bad articles...
      (when (memq (setq number (mail-header-number
				(setq header (pop headers))))
		  gnus-newsgroup-limit)
	;; Mark article as read when it has a low score.
	(when (and gnus-summary-mark-below
		   (< (or (cdr (assq number gnus-newsgroup-scored))
			  gnus-summary-default-score 0)
		      gnus-summary-mark-below)
		   (not (gnus-summary-article-ancient-p number)))
	  (setq gnus-newsgroup-unreads
		(delq number gnus-newsgroup-unreads))
	  (if gnus-newsgroup-auto-expire
	      (push number gnus-newsgroup-expirable)
	    (push (cons number gnus-low-score-mark)
		  gnus-newsgroup-reads)))

	(setq mark (gnus-article-mark number))
	(push (gnus-data-make number mark (1+ (point)) header 0)
	      gnus-newsgroup-data)
	(gnus-summary-insert-line
	 header 0 number
	 (memq number gnus-newsgroup-undownloaded)
	 mark (memq number gnus-newsgroup-replied)
	 (memq number gnus-newsgroup-expirable)
	 (mail-header-subject header) nil
	 (cdr (assq number gnus-newsgroup-scored))
	 (memq number gnus-newsgroup-processable))))))

(declare-function gnus-parameter-list-identifier "gnus-art" (name) t)

(defun gnus-group-get-list-identifiers (group)
  "Get list identifier regexp for GROUP."
  (or (gnus-parameter-list-identifier group)
      (if (consp gnus-list-identifiers)
          (mapconcat #'identity gnus-list-identifiers " *\\|")
        gnus-list-identifiers)))

(defun gnus-summary-remove-list-identifiers ()
  "Remove list identifiers in `gnus-list-identifiers' from articles in the current group."
  (let ((regexp (gnus-group-get-list-identifiers gnus-newsgroup-name))
        changed subject)
    (when regexp
      (setq regexp (concat "^\\(?:R[Ee]: +\\)*\\(" regexp " *\\)"))
      (dolist (header gnus-newsgroup-headers)
	(setq subject (mail-header-subject header)
	      changed nil)
	(while (string-match regexp subject)
	  (setq subject
		(concat (substring subject 0 (match-beginning 1))
			(substring subject (match-end 0)))
		changed t))
	(when changed
	  (when (string-match "^\\(\\(?:R[Ee]: +\\)+\\)R[Ee]: +" subject)
	    (setq subject
		  (concat (substring subject 0 (match-beginning 1))
			  (substring subject (match-end 1)))))
	  (setf (mail-header-subject header) subject))))))

(defun gnus-fetch-headers (articles &optional limit force-new dependencies)
  "Fetch headers of ARTICLES."
  (gnus-message 7 "Fetching headers for %s..." gnus-newsgroup-name)
  (prog1
      (pcase (setq gnus-headers-retrieved-by
		   (gnus-retrieve-headers
		    articles gnus-newsgroup-name
		    (or limit
			;; We might want to fetch old headers, but
			;; not if there is only 1 article.
			(and (or (and
				  (not (eq gnus-fetch-old-headers 'some))
				  (not (numberp gnus-fetch-old-headers)))
				 (> (length articles) 1))
			     gnus-fetch-old-headers))))
    ('nov
     (gnus-get-newsgroup-headers-xover
      articles force-new dependencies gnus-newsgroup-name t))
    ('headers
     (gnus-get-newsgroup-headers dependencies force-new))
    ((pred listp)
     (let ((dependencies
	    (or dependencies
		(with-current-buffer gnus-summary-buffer
		  gnus-newsgroup-dependencies))))
       (delq nil (mapcar (lambda (header)
                           (gnus-dependencies-add-header
                            header dependencies force-new))
			 gnus-headers-retrieved-by)))))
  (gnus-message 7 "Fetching headers for %s...done" gnus-newsgroup-name)))

(defun gnus-select-newsgroup (group &optional read-all select-articles)
  "Select newsgroup GROUP.
If READ-ALL is non-nil, all articles in the group are selected.
If SELECT-ARTICLES, only select those articles from GROUP."
  (let* ((entry (gnus-group-entry group))
	 ;;!!! Dirty hack; should be removed.
	 (gnus-summary-ignore-duplicates
	  (if (eq (car (gnus-find-method-for-group group)) 'nnvirtual)
	      t
	    gnus-summary-ignore-duplicates))
	 (info (nth 1 entry))
	 articles fetched-articles cached)

    (unless (gnus-check-server
             (setq-local gnus-current-select-method
                         (gnus-find-method-for-group group)))
      (error "Couldn't open server"))

    (or (and entry (not (eq (car entry) t))) ; Either it's active...
	(gnus-activate-group group)	; Or we can activate it...
	(progn				; Or we bug out.
	  (when (derived-mode-p 'gnus-summary-mode)
	    (gnus-kill-buffer (current-buffer)))
	  (error
	   "Couldn't activate group %s: %s" group (gnus-status-message group))))

    (unless (gnus-request-group group t nil info)
      (when (derived-mode-p 'gnus-summary-mode)
	(gnus-kill-buffer (current-buffer)))
      (error "Couldn't request group %s: %s" group (gnus-status-message group)))

    (when (and gnus-agent
	       (gnus-active group))
      (gnus-agent-possibly-alter-active group (gnus-active group) info)

      (setq gnus-summary-use-undownloaded-faces
	    (gnus-agent-find-parameter
	     group
	     'agent-enable-undownloaded-faces)))

    (setq gnus-newsgroup-name group
	  gnus-newsgroup-unselected nil
	  gnus-newsgroup-unreads (gnus-list-of-unread-articles group))

    (let ((display (gnus-group-find-parameter group 'display)))
      (setq gnus-newsgroup-display
	    (cond
	     ((not (zerop (or (car-safe read-all) 0)))
	      ;; The user entered the group with C-u SPC/RET, let's show
	      ;; all articles.
	      #'gnus-not-ignore)
	     ((eq display 'all)
	      #'gnus-not-ignore)
	     ((arrayp display)
	      (gnus-summary-display-make-predicate (mapcar #'identity display)))
	     ((numberp display)
	      ;; The following is probably the "correct" solution, but
	      ;; it makes Gnus fetch all headers and then limit the
	      ;; articles (which is slow), so instead we hack the
	      ;; select-articles parameter instead. -- Simon Josefsson
	      ;; <jas@kth.se>
	      ;;
	      ;;  (let ((n (cdr (gnus-active group))))
	      ;;    (lambda () (> number (- n display))))
	      (setq select-articles
		    (gnus-uncompress-range
		     (cons (let ((tmp (- (cdr (gnus-active group)) display)))
			     (if (> tmp 0)
				 tmp
			       1))
			   (cdr (gnus-active group)))))
	      nil)
	     (t
	      nil))))

    (gnus-summary-setup-default-charset)

    ;; Kludge to avoid having cached articles nixed out in virtual groups.
    (when (gnus-virtual-group-p group)
      (setq cached gnus-newsgroup-cached))

    (setq gnus-newsgroup-unreads
	  (gnus-sorted-ndifference
	   (gnus-sorted-ndifference gnus-newsgroup-unreads
				    gnus-newsgroup-marked)
	   gnus-newsgroup-dormant))

    (setq gnus-newsgroup-processable nil)

    (gnus-update-read-articles group gnus-newsgroup-unreads t)

    ;; Adjust and set lists of article marks.
    (when info
      (gnus-adjust-marked-articles info))
    (if (setq articles select-articles)
	(setq gnus-newsgroup-unselected
	      (gnus-sorted-difference gnus-newsgroup-unreads articles))
      (setq articles (gnus-articles-to-read group read-all)))

    (cond
     ((null articles)
      ;;(gnus-message 3 "Couldn't select newsgroup -- no articles to display")
      'quit)
     ((eq articles 0) nil)
     (t
      ;; Init the dependencies hash table.
      (setq gnus-newsgroup-dependencies
	    (gnus-make-hashtable (length articles)))
      (if (gnus-buffer-live-p gnus-group-buffer)
	  (gnus-set-global-variables)
	(set-default 'gnus-newsgroup-name gnus-newsgroup-name))
      ;; Retrieve the headers and read them in.

      (setq gnus-newsgroup-headers (gnus-fetch-headers articles))

      ;; Kludge to avoid having cached articles nixed out in virtual groups.
      (when cached
	(setq gnus-newsgroup-cached cached))

      ;; Suppress duplicates?
      (when gnus-suppress-duplicates
	(gnus-dup-suppress-articles))

      ;; Set the initial limit.
      (setq gnus-newsgroup-limit (copy-sequence articles))
      ;; Remove canceled articles from the list of unread articles.
      (setq fetched-articles
	    (mapcar #'mail-header-number gnus-newsgroup-headers))
      (setq gnus-newsgroup-articles fetched-articles)
      (setq gnus-newsgroup-unreads
	    (gnus-sorted-nintersection
	     gnus-newsgroup-unreads fetched-articles))
      (gnus-compute-unseen-list)

      ;; Removed marked articles that do not exist.
      (gnus-update-missing-marks
       (gnus-sorted-difference articles fetched-articles))
      ;; We might want to build some more threads first.
      (when (and gnus-fetch-old-headers
		 (eq gnus-headers-retrieved-by 'nov))
	(if (eq gnus-fetch-old-headers 'invisible)
	    (gnus-build-all-threads)
	  (gnus-build-old-threads)))
      ;; Let the Gnus agent mark articles as read.
      (when gnus-agent
	(gnus-agent-get-undownloaded-list))
      ;; Remove list identifiers from subject
      (gnus-summary-remove-list-identifiers)
      ;; Check whether auto-expire is to be done in this group.
      (setq gnus-newsgroup-auto-expire
	    (and (gnus-group-auto-expirable-p group)
		 (not (gnus-group-read-only-p group))))
      ;; Set up the article buffer now, if necessary.
      (unless (and gnus-single-article-buffer
		   (equal gnus-article-buffer "*Article*"))
	(gnus-article-setup-buffer))
      ;; First and last article in this newsgroup.
      (when gnus-newsgroup-headers
	(setq gnus-newsgroup-begin
	      (mail-header-number (car gnus-newsgroup-headers))
	      gnus-newsgroup-end
	      (mail-header-number
	       (car (last gnus-newsgroup-headers)))))
      ;; GROUP is successfully selected.
      (or gnus-newsgroup-headers t)))))

(defun gnus-compute-unseen-list ()
  ;; The `seen' marks are treated specially.
  (if (not gnus-newsgroup-seen)
      (setq gnus-newsgroup-unseen gnus-newsgroup-articles)
    (setq gnus-newsgroup-unseen
	  (gnus-inverse-list-range-intersection
	   gnus-newsgroup-articles gnus-newsgroup-seen))))

(declare-function gnus-get-predicate "gnus-agent" (predicate))

(defun gnus-summary-display-make-predicate (display)
  (require 'gnus-agent)
  (when (= (length display) 1)
    (setq display (car display)))
  (unless gnus-summary-display-cache
    (dolist (elem (append '((unread . unread)
			    (read . read)
			    (unseen . unseen))
			  gnus-article-mark-lists))
      (push (cons (cdr elem)
                  (let ((x (cdr elem)))
		    (lambda () (gnus-article-marked-p x))))
	    gnus-summary-display-cache)))
  (let ((gnus-category-predicate-alist gnus-summary-display-cache)
	(gnus-category-predicate-cache gnus-summary-display-cache))
    (gnus-get-predicate display)))

;; Uses the dynamically bound `gnus-number' variable.
(defvar gnus-number)
(defun gnus-article-marked-p (type &optional article)
  (let ((article (or article gnus-number)))
    (cond
     ((eq type 'tick)
      (memq article gnus-newsgroup-marked))
     ((eq type 'spam)
      (memq article gnus-newsgroup-spam-marked))
     ((eq type 'unsend)
      (memq article gnus-newsgroup-unsendable))
     ((eq type 'undownload)
      (memq article gnus-newsgroup-undownloaded))
     ((eq type 'download)
      (memq article gnus-newsgroup-downloadable))
     ((eq type 'unread)
      (memq article gnus-newsgroup-unreads))
     ((eq type 'read)
      (memq article gnus-newsgroup-reads))
     ((eq type 'dormant)
      (memq article gnus-newsgroup-dormant) )
     ((eq type 'expire)
      (memq article gnus-newsgroup-expirable))
     ((eq type 'reply)
      (memq article gnus-newsgroup-replied))
     ((eq type 'killed)
      (memq article gnus-newsgroup-killed))
     ((eq type 'bookmark)
      (assq article gnus-newsgroup-bookmarks))
     ((eq type 'score)
      (assq article gnus-newsgroup-scored))
     ((eq type 'save)
      (memq article gnus-newsgroup-saved))
     ((eq type 'cache)
      (memq article gnus-newsgroup-cached))
     ((eq type 'forward)
      (memq article gnus-newsgroup-forwarded))
     ((eq type 'seen)
      (not (memq article gnus-newsgroup-unseen)))
     (t t))))

(defun gnus-articles-to-read (group &optional read-all)
  "Find out what articles the user wants to read."
  (let* ((only-read-p t)
	 (articles
	  (gnus-list-range-difference
	  ;; Select all articles if `read-all' is non-nil, or if there
	  ;; are no unread articles.
	  (if (or read-all
		  (and (zerop (length gnus-newsgroup-marked))
		       (zerop (length gnus-newsgroup-unreads)))
		  ;; Fetch all if the predicate is non-nil.
		  gnus-newsgroup-display)
	      ;; We want to select the headers for all the articles in
	      ;; the group, so we select either all the active
	      ;; articles in the group, or (if that's nil), the
	      ;; articles in the cache.
	      (or
	       (if gnus-newsgroup-maximum-articles
		   (let ((active (gnus-active group)))
		     (gnus-uncompress-range
		      (cons (max (car active)
				 (- (cdr active)
				    gnus-newsgroup-maximum-articles
				    -1))
			    (cdr active))))
		 (gnus-uncompress-range (gnus-active group)))
	       (gnus-cache-articles-in-group group))
	    ;; Select only the "normal" subset of articles.
	    (setq only-read-p nil)
	    (gnus-sorted-nunion
	     (gnus-sorted-union gnus-newsgroup-dormant gnus-newsgroup-marked)
	     gnus-newsgroup-unreads))
	  (cdr (assq 'unexist (gnus-info-marks (gnus-get-info group))))))
	 (scored-list (gnus-killed-articles gnus-newsgroup-killed articles))
	 (scored (length scored-list))
	 (number (length articles))
	 (marked (+ (length gnus-newsgroup-marked)
		    (length gnus-newsgroup-dormant)))
	 (select
	  (cond
	   ((numberp read-all)
	    read-all)
	   ((numberp gnus-newsgroup-display)
	    gnus-newsgroup-display)
	   (t
	    (condition-case ()
		(cond
		 ((and (or (<= scored marked) (= scored number))
		       (numberp gnus-large-newsgroup)
		       (> number gnus-large-newsgroup))
		  (let* ((cursor-in-echo-area nil)
			 (initial (gnus-parameter-large-newsgroup-initial
				   gnus-newsgroup-name))
			 (default (if only-read-p
				      (if (eq initial 'all)
					  nil
					(or initial gnus-large-newsgroup))
				    number))
			 (input
			  (read-string
			   (if only-read-p
			       (format-prompt
				    "How many articles from %s (available %d)"
				    default
				    (gnus-group-real-name gnus-newsgroup-name)
				    number)
			     (format-prompt
			      "How many articles from %s"
			      default
			      (gnus-group-real-name gnus-newsgroup-name)))
			   nil
			   nil
			   (number-to-string default))))
		    (if (string-match "^[ \t]*$" input) number input)))
		 ((and (> scored marked) (< scored number)
		       (> (- scored number) 20))
		  (let ((input
			 (read-string
			  (format "%s %s (%d scored, %d total): "
				  "How many articles from"
				  (gnus-group-real-name gnus-newsgroup-name)
				  scored number))))
		    (if (string-match "^[ \t]*$" input)
			number input)))
		 (t number))
	      (quit
	       (message "Quit getting the articles to read")
	       nil))))))
    (setq select (if (stringp select) (string-to-number select) select))
    (if (or (null select) (zerop select))
	select
      (if (and (not (zerop scored)) (<= (abs select) scored))
	  (progn
	    (setq articles (sort scored-list #'<))
	    (setq number (length articles)))
	(setq articles (copy-sequence articles)))

      (when (< (abs select) number)
	(if (< select 0)
	    ;; Select the N oldest articles.
	    (setcdr (nthcdr (1- (abs select)) articles) nil)
	  ;; Select the N most recent articles.
	  (setq articles (nthcdr (- number select) articles))))
      (setq gnus-newsgroup-unselected
	    (gnus-sorted-difference gnus-newsgroup-unreads articles))
      (when (functionp gnus-alter-articles-to-read-function)
	(setq articles
	      (sort
	       (funcall gnus-alter-articles-to-read-function
			gnus-newsgroup-name articles)
	       #'<)))
      articles)))

(defun gnus-killed-articles (killed articles)
  (let (out)
    (while articles
      (when (inline (gnus-member-of-range (car articles) killed))
	(push (car articles) out))
      (setq articles (cdr articles)))
    out))

(defun gnus-article-mark-to-type (mark)
  "Return the type of MARK."
  (or (cadr (assq mark gnus-article-special-mark-lists))
      'list))

(defun gnus-article-unpropagatable-p (mark)
  "Return whether MARK should be propagated to back end."
  (memq mark gnus-article-unpropagated-mark-lists))

(defun gnus-adjust-marked-articles (info)
  "Set all article lists and remove all marks that are no longer valid."
  (let* ((marked-lists (gnus-info-marks info))
	 (active (gnus-active (gnus-info-group info)))
	 (min (car active))
	 (max (cdr active))
	 (types gnus-article-mark-lists)
         var articles article mark mark-type
         bgn end)
    ;; Hack to avoid adjusting marks for imap.
    (when (eq (car (gnus-find-method-for-group (gnus-info-group info)))
	      'nnimap)
      (setq min 1))

    (dolist (marks marked-lists)
      (setq mark (car marks)
	    mark-type (gnus-article-mark-to-type mark)
	    var (intern (format "gnus-newsgroup-%s" (car (rassq mark types)))))
      ;; We set the variable according to the type of the marks list,
      ;; and then adjust the marks to a subset of the active articles.
      (cond
       ;; Adjust "simple" lists - compressed yet unsorted
       ((eq mark-type 'list)
        ;; Simultaneously uncompress and clip to active range
        ;; See gnus-uncompress-range for a description of possible marks
        (let (l lh)
          (if (not (cadr marks))
              (set var nil)
            (setq articles (if (numberp (cddr marks))
                               (list (cdr marks))
                             (cdr marks))
                  lh (cons nil nil)
                  l lh)

            (while (setq article (pop articles))
              (cond ((consp article)
                     (setq bgn (max (car article) min)
                           end (min (cdr article) max))
                     (while (<= bgn end)
                       (setq l (setcdr l (cons bgn nil))
                             bgn (1+ bgn))))
                    ((and (<= min article)
                          (>= max article))
                     (setq l (setcdr l (cons article nil))))))
            (set var (cdr lh)))))
       ;; Adjust assocs.
       ((eq mark-type 'tuple)
	(set var (setq articles (cdr marks)))
	(when (not (listp (cdr (symbol-value var))))
	  (set var (list (symbol-value var))))
	(when (not (listp (cdr articles)))
	  (setq articles (list articles)))
	(while articles
	  (when (or (not (consp (setq article (pop articles))))
		    (< (car article) min)
		    (> (car article) max))
	    (set var (delq article (symbol-value var))))))
       ;; Adjust ranges (sloppily).
       ((eq mark-type 'range)
	(cond
	 ((eq mark 'seen)
	  ;; Fix the record for `seen' if it looks like (seen NUM1 . NUM2).
	  ;; It should be (seen (NUM1 . NUM2)).
	  (when (numberp (cddr marks))
	    (setcdr marks (list (cdr marks))))
	  (setq articles (cdr marks))
	  (while (and articles
		      (or (and (consp (car articles))
			       (> min (cdar articles)))
			  (and (numberp (car articles))
			       (> min (car articles)))))
	    (pop articles))
	  (set var articles))
	 ((eq mark 'unexist)
	  (set var (cdr marks)))))))))

(defun gnus-update-missing-marks (missing)
  "Go through the list of MISSING articles and remove them from the mark lists."
  (when missing
    (let (var m)
      ;; Go through all types.
      (dolist (elem gnus-article-mark-lists)
	(when (eq (gnus-article-mark-to-type (cdr elem)) 'list)
	  (setq var (intern (format "gnus-newsgroup-%s" (car elem))))
	  (when (symbol-value var)
	    ;; This list has articles.  So we delete all missing
	    ;; articles from it.
	    (setq m missing)
	    (while m
	      (set var (delq (pop m) (symbol-value var))))))))))

(defun gnus-update-marks ()
  "Enter the various lists of marked articles into the newsgroup info list."
  (let ((types gnus-article-mark-lists)
	(info (gnus-get-info gnus-newsgroup-name))
	type list newmarked symbol delta-marks)
    (when info
      ;; Add all marks lists to the list of marks lists.
      (while (setq type (pop types))
	(setq list (symbol-value
		    (setq symbol
			  (intern (format "gnus-newsgroup-%s" (car type))))))

	(when list
	  ;; Get rid of the entries of the articles that have the
	  ;; default score.
	  (when (and (eq (cdr type) 'score)
		     gnus-save-score
		     list)
	    (let* ((arts list)
		   (prev (cons nil list))
		   (all prev))
	      (while arts
		(if (or (not (consp (car arts)))
			(= (cdar arts) gnus-summary-default-score))
		    (setcdr prev (cdr arts))
		  (setq prev arts))
		(setq arts (cdr arts)))
	      (setq list (cdr all)))))

	;; When exiting the group, everything that's previously been
	;; unseen is now seen.
	(when (eq (cdr type) 'seen)
	  (setq list (gnus-range-add list gnus-newsgroup-unseen)))

	(when (eq (gnus-article-mark-to-type (cdr type)) 'list)
	  (setq list (gnus-compress-sequence (set symbol (sort list #'<)) t)))

	(when (and (gnus-check-backend-function
		    'request-set-mark gnus-newsgroup-name)
		   (not (gnus-article-unpropagatable-p (cdr type))))
	  (let* ((old (cdr (assq (cdr type) (gnus-info-marks info))))
		 ;; Don't do anything about marks for articles we
		 ;; didn't actually get any headers for.
		 (del
		  (gnus-list-range-intersection
		   gnus-newsgroup-articles
		   (gnus-remove-from-range (copy-tree old) list)))
		 (add
		  (gnus-list-range-intersection
		   gnus-newsgroup-articles
		   (gnus-remove-from-range
		    (copy-tree list) old))))
	    (when add
	      (push (list add 'add (list (cdr type))) delta-marks))
	    (when del
	      ;; Don't delete marks from outside the active range.
	      ;; This shouldn't happen, but is a sanity check.
	      (setq del (gnus-sorted-range-intersection
			 (gnus-active gnus-newsgroup-name) del))
	      (push (list del 'del (list (cdr type))) delta-marks))))

	(when (or list
		  (eq (cdr type) 'unexist))
	  (push (cons (cdr type) list) newmarked)))

      (when delta-marks
	(unless (gnus-check-group gnus-newsgroup-name)
	  (error "Can't open server for %s" gnus-newsgroup-name))
	(gnus-request-set-mark gnus-newsgroup-name delta-marks))

      ;; Enter these new marks into the info of the group.
      (if (nthcdr 3 info)
	  (setcar (nthcdr 3 info) newmarked)
	;; Add the marks lists to the end of the info.
	(when newmarked
	  (setcdr (nthcdr 2 info) (list newmarked))))

      ;; Cut off the end of the info if there's nothing else there.
      (let ((i 5))
	(while (and (> i 2)
		    (not (nth i info)))
	  (when (nthcdr (cl-decf i) info)
	    (setcdr (nthcdr i info) nil)))))))

(defun gnus-set-mode-line (where)
  "Set the mode line of the article or summary buffers.
If WHERE is `summary', the summary mode line format will be used."
  ;; Is this mode line one we keep updated?
  (when (and (memq where gnus-updated-mode-lines)
	     (symbol-value
	      (intern (format "gnus-%s-mode-line-format-spec" where))))
    (let (mode-string)
      ;; We evaluate this in the summary buffer since these
      ;; variables are buffer-local to that buffer.
      (with-current-buffer gnus-summary-buffer
        ;; We bind all these variables that are used in the `eval' form
	;; below.
	(let* ((mformat (symbol-value
			 (intern
			  (format "gnus-%s-mode-line-format-spec" where))))
	       (gnus-tmp-group-name (gnus-mode-string-quote
				     gnus-newsgroup-name))
	       (gnus-tmp-article-number (or gnus-current-article 0))
	       (gnus-tmp-unread gnus-newsgroup-unreads)
	       (gnus-tmp-unread-and-unticked (length gnus-newsgroup-unreads))
	       (gnus-tmp-unselected (length gnus-newsgroup-unselected))
	       (gnus-tmp-unread-and-unselected
		(cond ((and (zerop gnus-tmp-unread-and-unticked)
			    (zerop gnus-tmp-unselected))
		       "")
		      ((zerop gnus-tmp-unselected)
		       (format "{%d more}" gnus-tmp-unread-and-unticked))
		      (t (format "{%d(+%d) more}"
				 gnus-tmp-unread-and-unticked
				 gnus-tmp-unselected))))
	       (gnus-tmp-subject
		(if (and gnus-current-headers
			 (mail-header-p gnus-current-headers))
		    (gnus-mode-string-quote
		     (mail-header-subject gnus-current-headers))
		  ""))
	       bufname-length max-len
	       gnus-tmp-header)	;; passed as argument to any user-format-funcs
	  (setq mode-string (eval mformat t))
	  (setq bufname-length (if (string-match "%b" mode-string)
				   (- (length
				       (buffer-name
					(if (eq where 'summary)
					    nil
					  (get-buffer gnus-article-buffer))))
				      2)
				 0))
	  (setq max-len (max 4 (if gnus-mode-non-string-length
				   (- (window-width)
				      gnus-mode-non-string-length
				      bufname-length)
				 (length mode-string))))
	  ;; We might have to chop a bit of the string off...
	  (when (> (length mode-string) max-len)
	    (setq mode-string
		  (truncate-string-to-width
		   mode-string (- max-len 3) nil nil t)))))
      ;; Update the mode line.
      (setq mode-line-buffer-identification
	    (gnus-mode-line-buffer-identification
	     (list (propertize mode-string
			       'face 'mode-line-buffer-id))))
      (set-buffer-modified-p t))))

(defun gnus-create-xref-hashtb (from-newsgroup headers unreads)
  "Go through the HEADERS list and add all Xrefs to a hash table.
The resulting hash table is returned, or nil if no Xrefs were found."
  (let* ((virtual (gnus-virtual-group-p from-newsgroup))
	 (prefix (if virtual "" (gnus-group-real-prefix from-newsgroup)))
	 (xref-hashtb (gnus-make-hashtable))
	 start group entry number xrefs header)
    (while headers
      (setq header (pop headers))
      (when (and (setq xrefs (mail-header-xref header))
		 (not (memq (setq number (mail-header-number header))
			    unreads)))
	(setq start 0)
	(while (string-match "\\([^ ]+\\)[:/]\\([0-9]+\\)" xrefs start)
	  (setq start (match-end 0))
	  (setq group (if prefix
			  (concat prefix (substring xrefs (match-beginning 1)
						    (match-end 1)))
			(substring xrefs (match-beginning 1) (match-end 1))))
	  (setq number
		(string-to-number (substring xrefs (match-beginning 2)
					  (match-end 2))))
	  (if (setq entry (gethash group xref-hashtb))
	      (setcdr entry (cons number (cdr entry)))
	    (puthash group (cons number nil) xref-hashtb)))))
    (and start xref-hashtb)))

(defun gnus-mark-xrefs-as-read (from-newsgroup headers unreads)
  "Look through all the headers and mark the Xrefs as read."
  (let ((virtual (gnus-virtual-group-p from-newsgroup))
	info xref-hashtb method nth4)
    (with-current-buffer gnus-group-buffer
      (when (setq xref-hashtb
		  (gnus-create-xref-hashtb from-newsgroup headers unreads))
	(maphash
	 (lambda (group idlist)
	   (unless (string= from-newsgroup group)
	     ;; Dead groups are not updated.
	     (and (prog1
		      (setq info (gnus-get-info group))
		    (when (stringp (setq nth4 (gnus-info-method info)))
		      (setq nth4 (gnus-server-to-method nth4))))
		  ;; Only do the xrefs if the group has the same
		  ;; select method as the group we have just read.
		  (or (gnus-methods-equal-p
		       nth4 (gnus-find-method-for-group from-newsgroup))
		      virtual
		      (equal nth4 (setq method (gnus-find-method-for-group
						from-newsgroup)))
		      (and (equal (car nth4) (car method))
			   (equal (nth 1 nth4) (nth 1 method))))
		  gnus-use-cross-reference
		  (or (not (eq gnus-use-cross-reference t))
		      virtual
		      ;; Only do cross-references on subscribed
		      ;; groups, if that is what is wanted.
		      (<= (gnus-info-level info) gnus-level-subscribed))
		  (gnus-group-make-articles-read group idlist))))
	 xref-hashtb)))))

(defun gnus-compute-read-articles (group articles)
  (let* ((entry (gnus-group-entry group))
	 (info (nth 1 entry))
	 (active (gnus-active group))
	 ninfo)
    (when entry
      ;; First peel off all invalid article numbers.
      (when active
	(let ((ids articles)
	      id) ;; first
	  (while (setq id (pop ids))
	    (when nil ;; (and first (> id (cdr active)))
	      ;; We'll end up in this situation in one particular
	      ;; obscure situation.  If you re-scan a group and get
	      ;; a new article that is cross-posted to a different
	      ;; group that has not been re-scanned, you might get
	      ;; crossposted article that has a higher number than
	      ;; Gnus believes possible.  So we re-activate this
	      ;; group as well.  This might mean doing the
	      ;; crossposting thingy will *increase* the number
	      ;; of articles in some groups.  Tsk, tsk.
	      (setq active (or (gnus-activate-group group) active)))
	    (when (or (> id (cdr active))
		      (< id (car active)))
	      (setq articles (delq id articles))))))
      ;; If the read list is nil, we init it.
      (if (and active
	       (null (gnus-info-read info))
	       (> (car active) 1))
	  (setq ninfo (cons 1 (1- (car active))))
	(setq ninfo (gnus-info-read info)))
      ;; Then we add the read articles to the range.
      (gnus-add-to-range
       ninfo (setq articles (sort articles #'<))))))

(defun gnus-group-make-articles-read (group articles)
  "Update the info of GROUP to say that ARTICLES are read."
  (let* ((num 0)
	 (entry (gnus-group-entry group))
	 (info (nth 1 entry))
	 (active (gnus-active group))
	 (set-marks
	  (gnus-method-option-p
	   (gnus-find-method-for-group group)
	   'server-marks))
	 range)
    (if (not entry)
	;; Group that Gnus doesn't know exists, but still allow the
	;; backend to set marks.
	(when set-marks
	  (gnus-request-set-mark
	   group (list (list (gnus-compress-sequence (sort articles #'<))
			     'add '(read)))))
      ;; Normal, subscribed groups.
      (setq range (gnus-compute-read-articles group articles))
      (with-current-buffer gnus-group-buffer
	(gnus-undo-register
	  `(progn
	     (gnus-info-set-marks ',info ',(gnus-info-marks info) t)
	     (setf (gnus-info-read ',info) ',(gnus-info-read info))
	     (gnus-get-unread-articles-in-group ',info (gnus-active ,group))
	     (when ,set-marks
	       (gnus-request-set-mark
		,group (list (list ',range 'del '(read)))))
	     (gnus-group-jump-to-group ,group)
	     (gnus-group-update-group ,group t))))
      ;; Add the read articles to the range.
      (setf (gnus-info-read info) range)
      (when set-marks
	(gnus-request-set-mark group (list (list range 'add '(read)))))
      ;; Then we have to re-compute how many unread
      ;; articles there are in this group.
      (when active
	(cond
	 ((not range)
	  (setq num (- (1+ (cdr active)) (car active))))
	 ((not (listp (cdr range)))
	  (setq num (- (cdr active) (- (1+ (cdr range))
				       (car range)))))
	 (t
	  (while range
	    (if (numberp (car range))
		(setq num (1+ num))
	      (setq num (+ num (- (1+ (cdar range)) (caar range)))))
	    (setq range (cdr range)))
	  (setq num (- (cdr active) num))))
	;; Update the number of unread articles.
	(setcar entry num)
	;; Update the group buffer.
	(unless (gnus-ephemeral-group-p group)
	  (gnus-group-update-group group t))))))

(defun gnus-get-newsgroup-headers (&optional dependencies force-new)
  (let ((dependencies
	 (or dependencies
	     (with-current-buffer gnus-summary-buffer
	       gnus-newsgroup-dependencies)))
	headers
	(mail-parse-charset gnus-newsgroup-charset)
	(mail-parse-ignored-charsets
	 (save-current-buffer (condition-case nil
                                  (set-buffer gnus-summary-buffer)
                                (error))
                              gnus-newsgroup-ignored-charsets)))
    (with-current-buffer nntp-server-buffer
      (gnus-run-hooks 'gnus-parse-headers-hook)
      (let ((nnmail-extra-headers gnus-extra-headers)
	    header)
	(goto-char (point-min))
	(while (setq header (nnheader-parse-head))
	  (when (setq header
		      (gnus-dependencies-add-header
		       header dependencies force-new))
	    (push header headers)))
	(nreverse headers)))))

;; Goes through the xover lines and returns a list of vectors
(defun gnus-get-newsgroup-headers-xover (sequence &optional
						  force-new dependencies
						  group also-fetch-heads)
  "Parse the news overview data in the server buffer.
Return a list of headers that match SEQUENCE (see
`nntp-retrieve-headers')."
  ;; Get the Xref when the users reads the articles since most/some
  ;; NNTP servers do not include Xrefs when using XOVER.
  (setq gnus-article-internal-prepare-hook (list #'gnus-article-get-xrefs))
  (let ((mail-parse-charset gnus-newsgroup-charset)
	(mail-parse-ignored-charsets gnus-newsgroup-ignored-charsets)
	(cur nntp-server-buffer)
	(dependencies (or dependencies gnus-newsgroup-dependencies))
	(allp (cond
	       ((eq gnus-read-all-available-headers t)
		t)
	       ((and (stringp gnus-read-all-available-headers)
		     group)
		(string-match gnus-read-all-available-headers group))
	       (t
		nil)))
	number headers header)
    (with-current-buffer nntp-server-buffer
      (subst-char-in-region (point-min) (point-max) ?\r ?  t)
      ;; Allow the user to mangle the headers before parsing them.
      (gnus-run-hooks 'gnus-parse-headers-hook)
      (goto-char (point-min))
      (gnus-parse-without-error
	(while (and (or sequence allp)
		    (not (eobp)))
	  (setq number (read cur))
	  (when (not allp)
	    (while (and sequence
			(< (car sequence) number))
	      (setq sequence (cdr sequence))))
	  (when (and (or allp
			 (and sequence
			      (eq number (car sequence))))
		     (progn
		       (setq sequence (cdr sequence))
		       (setq header (inline
				      (gnus-nov-parse-line
				       number dependencies force-new)))))
	    (push header headers))
	  (forward-line 1)))
      ;; A common bug in inn is that if you have posted an article and
      ;; then retrieves the active file, it will answer correctly --
      ;; the new article is included.  However, a NOV entry for the
      ;; article may not have been generated yet, so this may fail.
      ;; We work around this problem by retrieving the last few
      ;; headers using HEAD.
      (if (or (not also-fetch-heads)
	      (not sequence))
	  ;; We (probably) got all the headers.
	  (nreverse headers)
	(let ((gnus-nov-is-evil t))
	  (nconc
	   (nreverse headers)
	   (when (eq (gnus-retrieve-headers sequence group) 'headers)
	     (gnus-get-newsgroup-headers))))))))

(defun gnus-article-get-xrefs ()
  "Fill in the Xref value in `gnus-current-headers', if necessary.
This is meant to be called in `gnus-article-internal-prepare-hook'."
  (let ((headers (with-current-buffer gnus-summary-buffer
		   gnus-current-headers)))
    (or (not gnus-use-cross-reference)
	(not headers)
	(and (mail-header-xref headers)
	     (not (string= (mail-header-xref headers) "")))
	(let ((case-fold-search t)
	      xref)
	  (save-restriction
	    (nnheader-narrow-to-headers)
	    (goto-char (point-min))
	    (when (or (and (not (eobp))
			   (eq (downcase (char-after)) ?x)
			   (looking-at "Xref:"))
		      (search-forward "\nXref:" nil t))
	      (goto-char (1+ (match-end 0)))
	      (setq xref (buffer-substring (point) (point-at-eol)))
	      (setf (mail-header-xref headers) xref)))))))

(defun gnus-summary-insert-subject (id &optional old-header use-old-header)
  "Find article ID and insert the summary line for that article.
OLD-HEADER can either be a header or a line number to insert
the subject line on.
If USE-OLD-HEADER is non-nil, then OLD-HEADER should be a header,
and OLD-HEADER will be used when the summary line is inserted,
too, instead of trying to fetch new headers."
  (let* ((line (and (numberp old-header) old-header))
	 (old-header (and (mail-header-p old-header) old-header))
	 (header (cond ((and old-header use-old-header)
			old-header)
		       ((and (numberp id)
			     (gnus-number-to-header id))
			(gnus-number-to-header id))
		       (t
			(gnus-read-header id))))
	 (number (and (numberp id) id))
	 d)
    (when header
      ;; Rebuild the thread that this article is part of and go to the
      ;; article we have fetched.
      (when (and (not gnus-show-threads)
		 old-header)
	(when (and number
		   (setq d (gnus-data-find (mail-header-number old-header))))
	  (goto-char (gnus-data-pos d))
	  (gnus-data-remove
	   number
	   (- (point-at-bol)
	      (prog1
		  (1+ (point-at-eol))
		(gnus-delete-line))))))
      ;; Remove list identifiers from subject.
      (let ((gnus-newsgroup-headers (list header)))
        (gnus-summary-remove-list-identifiers))
      (when old-header
	(setf (mail-header-number header) (mail-header-number old-header)))
      (setq gnus-newsgroup-sparse
	    (delq (setq number (mail-header-number header))
		  gnus-newsgroup-sparse))
      (setq gnus-newsgroup-ancient (delq number gnus-newsgroup-ancient))
      (push number gnus-newsgroup-limit)
      (gnus-rebuild-thread (mail-header-id header) line)
      (gnus-summary-goto-subject number nil t))
    (when (and (numberp number)
	       (> number 0))
      ;; We have to update the boundaries even if we can't fetch the
      ;; article if ID is a number -- so that the next `P' or `N'
      ;; command will fetch the previous (or next) article even
      ;; if the one we tried to fetch this time has been canceled.
      (unless (and gnus-newsgroup-end (< number gnus-newsgroup-end))
	(setq gnus-newsgroup-end number))
      (unless (and gnus-newsgroup-begin (> number gnus-newsgroup-begin))
	(setq gnus-newsgroup-begin number))
      (setq gnus-newsgroup-unselected
	    (delq number gnus-newsgroup-unselected)))
    ;; Report back a success?
    (and header (mail-header-number header))))

;;; Process/prefix in the summary buffer

(defun gnus-summary-work-articles (n)
  "Return a list of articles to be worked upon.
The prefix argument, the list of process marked articles, and the
current article will be taken into consideration."
  (with-current-buffer gnus-summary-buffer
    (cond
     (n
      ;; A numerical prefix has been given.
      (setq n (prefix-numeric-value n))
      (let ((backward (< n 0))
	    (n (abs (prefix-numeric-value n)))
	    articles article)
	(save-excursion
	  (while
	      (and (> n 0)
		   (push (setq article (gnus-summary-article-number))
			 articles)
		   (if backward
		       (gnus-summary-find-prev nil article)
		     (gnus-summary-find-next nil article)))
	    (cl-decf n)))
	(nreverse articles)))
     ((and (and transient-mark-mode mark-active) (mark))
      (message "region active")
      ;; Work on the region between point and mark.
      (let ((max (max (point) (mark)))
	    articles article)
	(save-excursion
	  (goto-char (min (point) (mark)))
	  (while
	      (and
	       (push (setq article (gnus-summary-article-number)) articles)
	       (gnus-summary-find-next nil article)
	       (< (point) max)))
	  (nreverse articles))))
     (gnus-newsgroup-processable
      ;; There are process-marked articles present.
      ;; Save current state.
      (gnus-summary-save-process-mark)
      ;; Return the list.
      (reverse gnus-newsgroup-processable))
     (t
      ;; Just return the current article.
      (list (gnus-summary-article-number))))))

(defmacro gnus-summary-iterate (arg &rest forms)
  "Iterate over the process/prefixed articles and do FORMS.
ARG is the interactive prefix given to the command.  FORMS will be
executed with point over the summary line of the articles."
  (declare (indent 1) (debug t))
  (let ((articles (make-symbol "gnus-summary-iterate-articles")))
    `(let ((,articles (gnus-summary-work-articles ,arg)))
       (while ,articles
	 (gnus-summary-goto-subject (car ,articles))
	 ,@forms
	 (pop ,articles)))))

(defun gnus-summary-save-process-mark ()
  "Push the current set of process marked articles on the stack."
  (interactive nil gnus-summary-mode)
  (push (copy-sequence gnus-newsgroup-processable)
	gnus-newsgroup-process-stack))

(defun gnus-summary-kill-process-mark ()
  "Push the current set of process marked articles on the stack and unmark."
  (interactive nil gnus-summary-mode)
  (gnus-summary-save-process-mark)
  (gnus-summary-unmark-all-processable))

(defun gnus-summary-yank-process-mark ()
  "Pop the last process mark state off the stack and restore it."
  (interactive nil gnus-summary-mode)
  (unless gnus-newsgroup-process-stack
    (error "Empty mark stack"))
  (gnus-summary-process-mark-set (pop gnus-newsgroup-process-stack)))

(defun gnus-summary-process-mark-set (set)
  "Make SET into the current process marked articles."
  (gnus-summary-unmark-all-processable)
  (mapc #'gnus-summary-set-process-mark set))

;;; Searching and stuff

(defun gnus-summary-search-group (&optional backward use-level)
  "Search for next unread newsgroup.
If optional argument BACKWARD is non-nil, search backward instead."
  (with-current-buffer gnus-group-buffer
    (when (gnus-group-search-forward
	   backward nil (if use-level (gnus-group-group-level) nil))
      (gnus-group-group-name))))

(defun gnus-summary-best-group (&optional exclude-group)
  "Find the name of the best unread group.
If EXCLUDE-GROUP, do not go to this group."
  (with-current-buffer gnus-group-buffer
    (save-excursion
      (gnus-group-best-unread-group exclude-group))))

(defun gnus-summary-find-next (&optional unread article backward)
  (if backward
      (gnus-summary-find-prev unread article)
    (let* ((dummy (gnus-summary-article-intangible-p))
	   (article (or article (gnus-summary-article-number)))
	   (data (gnus-data-find-list article))
	   result)
      (when (and (not dummy)
		 (or (not gnus-summary-check-current)
		     (not unread)
		     (not (gnus-data-unread-p (car data)))))
	(setq data (cdr data)))
      (when (setq result
		  (if unread
		      (progn
			(while data
                          (unless (memq (gnus-data-number (car data))
                                        (cond
					 ((eq gnus-auto-goto-ignores
					      'always-undownloaded)
					  gnus-newsgroup-undownloaded)
					 (gnus-plugged
					  nil)
					 ((eq gnus-auto-goto-ignores
					      'unfetched)
					  gnus-newsgroup-unfetched)
					 ((eq gnus-auto-goto-ignores
					      'undownloaded)
					  gnus-newsgroup-undownloaded)))
                            (when (gnus-data-unread-p (car data))
                              (setq result (car data)
                                    data nil)))
			  (setq data (cdr data)))
			result)
		    (car data)))
	(goto-char (gnus-data-pos result))
	(gnus-data-number result)))))

(defun gnus-summary-find-prev (&optional unread article)
  (let* ((eobp (eobp))
	 (article (or article (gnus-summary-article-number)))
	 (data (gnus-data-find-list article (gnus-data-list 'rev)))
	 result)
    (when (and (not eobp)
	       (or (not gnus-summary-check-current)
		   (not unread)
		   (not (gnus-data-unread-p (car data)))))
      (setq data (cdr data)))
    (when (setq result
		(if unread
		    (progn
		      (while data
                        (unless (memq (gnus-data-number (car data))
                                      (cond
				       ((eq gnus-auto-goto-ignores
					    'always-undownloaded)
					gnus-newsgroup-undownloaded)
				       (gnus-plugged
					nil)
				       ((eq gnus-auto-goto-ignores
					    'unfetched)
					gnus-newsgroup-unfetched)
				       ((eq gnus-auto-goto-ignores
					    'undownloaded)
					gnus-newsgroup-undownloaded)))
                          (when (gnus-data-unread-p (car data))
                            (setq result (car data)
                                  data nil)))
			(setq data (cdr data)))
		      result)
		  (car data)))
      (goto-char (gnus-data-pos result))
      (gnus-data-number result))))

(defun gnus-summary-find-subject (subject &optional unread backward article)
  (let* ((simp-subject (gnus-simplify-subject-fully subject))
	 (article (or article (gnus-summary-article-number)))
	 (articles (gnus-data-list backward))
	 (arts (gnus-data-find-list article articles))
	 result)
    (when (or (not gnus-summary-check-current)
	      (not unread)
	      (not (gnus-data-unread-p (car arts))))
      (setq arts (cdr arts)))
    (while arts
      (and (or (not unread)
	       (gnus-data-unread-p (car arts)))
	   (mail-header-p (gnus-data-header (car arts)))
	   (gnus-subject-equal
	    simp-subject (mail-header-subject (gnus-data-header (car arts))) t)
	   (setq result (car arts)
		 arts nil))
      (setq arts (cdr arts)))
    (and result
	 (goto-char (gnus-data-pos result))
	 (gnus-data-number result))))

(defun gnus-summary-search-forward (&optional unread subject backward)
  "Search forward for an article.
If UNREAD, look for unread articles.  If SUBJECT, look for
articles with that subject.  If BACKWARD, search backward instead."
  (cond (subject (gnus-summary-find-subject subject unread backward))
	(backward (gnus-summary-find-prev unread))
	(t (gnus-summary-find-next unread))))

(defun gnus-recenter (&optional n)
  "Center point in window and redisplay frame.
Also do horizontal recentering."
  (interactive "P" gnus-summary-mode)
  (when (and gnus-auto-center-summary
	     (not (eq gnus-auto-center-summary 'vertical)))
    (gnus-horizontal-recenter))
  (recenter-top-bottom n))

(put 'gnus-recenter 'isearch-scroll t)

(defun gnus-forward-line-ignore-invisible (n)
  "Move N lines forward (backward if N is negative).
Like forward-line, but skip over (and don't count) invisible lines."
  (let (done)
    (while (and (> n 0) (not done))
      ;; If the following character is currently invisible,
      ;; skip all characters with that same `invisible' property value.
      (while (invisible-p (point))
	(goto-char (next-char-property-change (point))))
      (forward-line 1)
      (if (eobp)
	  (setq done t)
	(setq n (1- n))))
    (while (and (< n 0) (not done))
      (forward-line -1)
      (if (bobp) (setq done t)
	(setq n (1+ n))
	(while (and (not (bobp)) (invisible-p (1- (point))))
	  (goto-char (previous-char-property-change (point))))))))

(defun gnus-summary-recenter ()
  "Center point in the summary window.
If `gnus-auto-center-summary' is nil, or the article buffer isn't
displayed, no centering will be performed."
  ;; Suggested by earle@mahendo.JPL.NASA.GOV (Greg Earle).
  ;; Recenter only when requested.  Suggested by popovich@park.cs.columbia.edu.
  (interactive nil gnus-summary-mode)
  ;; The user has to want it.
  (when gnus-auto-center-summary
    (let* ((top (cond ((< (window-height) 4) 0)
		      ((< (window-height) 7) 1)
		      (t (if (numberp gnus-auto-center-summary)
			     gnus-auto-center-summary
                           (/ (1- (window-height)) 2)))))
	   (height (1- (window-height)))
	   (bottom (save-excursion
		     (goto-char (point-max))
		     (gnus-forward-line-ignore-invisible (- height))
		     (point)))
	   (window (get-buffer-window (current-buffer))))
      (when (get-buffer-window gnus-article-buffer)
	;; Only do recentering when the article buffer is displayed,
	;; Set the window start to either `bottom', which is the biggest
	;; possible valid number, or the second line from the top,
	;; whichever is the least.
	(let ((top-pos (save-excursion
			 (gnus-forward-line-ignore-invisible (- top))
			 (point))))
	  (if (> bottom top-pos)
	      ;; Keep the second line from the top visible
	      (set-window-start window top-pos)
	    ;; Try to keep the bottom line visible; if it's partially
	    ;; obscured, either scroll one more line to make it fully
	    ;; visible, or revert to using TOP-POS.
	    (save-excursion
	      (goto-char (point-max))
	      (gnus-forward-line-ignore-invisible -1)
	      (let ((last-line-start (point)))
		(goto-char bottom)
		(set-window-start window (point) t)
		(when (not (pos-visible-in-window-p last-line-start window))
		  (gnus-forward-line-ignore-invisible 1)
		  (set-window-start window (min (point) top-pos) t)))))))
      ;; Do horizontal recentering while we're at it.
      (when (and (get-buffer-window (current-buffer) t)
		 (not (eq gnus-auto-center-summary 'vertical)))
	(let ((selected (selected-window)))
	  (select-window (get-buffer-window (current-buffer) t))
	  (gnus-summary-position-point)
	  (gnus-horizontal-recenter)
	  (select-window selected))))))

(defun gnus-summary-jump-to-group (newsgroup)
  "Move point to NEWSGROUP in group mode buffer."
  ;; Keep update point of group mode buffer if visible.
  (if (eq (current-buffer) (get-buffer gnus-group-buffer))
      (save-window-excursion
	;; Take care of tree window mode.
	(when (get-buffer-window gnus-group-buffer)
	  (pop-to-buffer gnus-group-buffer))
	(gnus-group-jump-to-group newsgroup))
    (save-excursion
      ;; Take care of tree window mode.
      (if (get-buffer-window gnus-group-buffer 0)
	  (pop-to-buffer gnus-group-buffer t)
	(set-buffer gnus-group-buffer))
      (gnus-group-jump-to-group newsgroup))))

;; This function returns a list of article numbers based on the
;; difference between the ranges of read articles in this group and
;; the range of active articles.
(defun gnus-list-of-unread-articles (group)
  (let* ((read (gnus-info-read (gnus-get-info group)))
	 (active (or (gnus-active group) (gnus-activate-group group)))
	 (last (or (cdr active)
		   (error "Group %s couldn't be activated " group)))
	 (bottom (if gnus-newsgroup-maximum-articles
		     (max (car active)
			  (- last gnus-newsgroup-maximum-articles -1))
		   (car active)))
	 first nlast unread)
    ;; If none are read, then all are unread.
    (if (not read)
	(setq first bottom)
      ;; If the range of read articles is a single range, then the
      ;; first unread article is the article after the last read
      ;; article.  Sounds logical, doesn't it?
      (if (and (not (listp (cdr read)))
	       (or (< (car read) bottom)
		   (progn (setq read (list read))
			  nil)))
	  (setq first (max bottom (1+ (cdr read))))
	;; `read' is a list of ranges.
	(when (/= (setq nlast (or (and (numberp (car read)) (car read))
				  (caar read)))
		  1)
	  (setq first bottom))
	(while read
	  (when first
	    (while (< first nlast)
	      (setq unread (cons first unread)
                    first (1+ first))))
	  (setq first (1+ (if (atom (car read)) (car read) (cdar read))))
	  (setq nlast (if (atom (cadr read)) (cadr read) (caadr read)))
	  (setq read (cdr read)))))
    ;; And add the last unread articles.
    (while (<= first last)
      (setq unread (cons first unread)
            first (1+ first)))
    ;; Return the list of unread articles.
    (delq 0 (nreverse unread))))

(defun gnus-list-of-read-articles (group)
  "Return a list of unread, unticked and non-dormant articles."
  (let* ((info (gnus-get-info group))
	 (marked (gnus-info-marks info))
	 (active (gnus-active group)))
    (and info active
	 (gnus-list-range-difference
	  (gnus-list-range-difference
	   (gnus-sorted-complement
	    (gnus-uncompress-range
	     (if gnus-newsgroup-maximum-articles
		 (cons (max (car active)
			    (- (cdr active)
			       gnus-newsgroup-maximum-articles
			       -1))
		       (cdr active))
	       active))
	    (gnus-list-of-unread-articles group))
	   (cdr (assq 'dormant marked)))
	  (cdr (assq 'tick marked))))))

;; This function returns a sequence of article numbers based on the
;; difference between the ranges of read articles in this group and
;; the range of active articles.
(defun gnus-sequence-of-unread-articles (group)
  (let* ((read (gnus-info-read (gnus-get-info group)))
	 (active (or (gnus-active group) (gnus-activate-group group)))
	 (last (cdr active))
	 (bottom (if gnus-newsgroup-maximum-articles
		     (max (car active)
			  (- last gnus-newsgroup-maximum-articles -1))
		   (car active)))
	 first nlast unread)
    ;; If none are read, then all are unread.
    (if (not read)
	(setq first bottom)
      ;; If the range of read articles is a single range, then the
      ;; first unread article is the article after the last read
      ;; article.  Sounds logical, doesn't it?
      (if (and (not (listp (cdr read)))
	       (or (< (car read) bottom)
		   (progn (setq read (list read))
			  nil)))
	  (setq first (max bottom (1+ (cdr read))))
	;; `read' is a list of ranges.
	(when (/= (setq nlast (or (and (numberp (car read)) (car read))
				  (caar read)))
		  1)
	  (setq first bottom))
	(while read
	  (when first
            (push (cons first nlast) unread))
	  (setq first (1+ (if (atom (car read)) (car read) (cdar read))))
	  (setq nlast (if (atom (cadr read)) (cadr read) (caadr read)))
	  (setq read (cdr read)))))
    ;; And add the last unread articles.
    (cond ((not (and first last))
	   nil)
	  ((< first last)
	   (push (cons first last) unread))
	  ((= first last)
	   (push first unread)))
    ;; Return the sequence of unread articles.
    (delq 0 (nreverse unread))))

;; Various summary commands

(defun gnus-summary-select-article-buffer ()
  "Reconfigure windows to show the article buffer.
If `gnus-widen-article-window' is set, show only the article
buffer."
  (interactive nil gnus-summary-mode)
  (if (not (gnus-buffer-live-p gnus-article-buffer))
      (error "There is no article buffer for this summary buffer")
    (or (get-buffer-window gnus-article-buffer)
	(eq gnus-current-article (gnus-summary-article-number))
	(gnus-summary-show-article))
    (let ((point (with-current-buffer gnus-article-buffer
		   (point))))
      (gnus-configure-windows
       (if gnus-widen-article-window
	   'only-article
	 'article)
       t)
      (select-window (get-buffer-window gnus-article-buffer))
      ;; If we've just selected the message, place point at the start of
      ;; the body because that's probably where we want to be.
      (if (not (= point (point-min)))
	  (goto-char point)
	(article-goto-body)
	(forward-char -1)))))

(defun gnus-summary-universal-argument (arg)
  "Perform any operation on all articles that are process/prefixed."
  (interactive "P" gnus-summary-mode)
  (let ((articles (gnus-summary-work-articles arg))
	func article)
    (if (eq
	 (setq
	  func
	  (key-binding
	   (read-key-sequence
	    (substitute-command-keys
	     "\\<gnus-summary-mode-map>\\[gnus-summary-universal-argument]"))))
	 'undefined)
	(gnus-error 1 "Undefined key")
      (save-excursion
	(while articles
	  (gnus-summary-goto-subject (setq article (pop articles)))
	  (let (gnus-newsgroup-processable)
	    (command-execute func))
	  (gnus-summary-remove-process-mark article)))))
  (gnus-summary-position-point))

(define-obsolete-function-alias
  'gnus-summary-toggle-truncation #'toggle-truncate-lines "26.1")

(defun gnus-summary-find-for-reselect ()
  "Return the number of an article to stay on across a reselect.
The current article is considered, then following articles, then previous
articles.  An article is sought which is not canceled and isn't a temporary
insertion from another group.  If there's no such then return a dummy 0."
  (let (found)
    (dolist (rev '(nil t))
      (unless found      ; don't demand the reverse list if we don't need it
        (let ((data (gnus-data-find-list
                     (gnus-summary-article-number) (gnus-data-list rev))))
          (while (and data (not found))
            (if (and (< 0 (gnus-data-number (car data)))
                     (not (eq gnus-canceled-mark (gnus-data-mark (car data)))))
                (setq found (gnus-data-number (car data))))
            (setq data (cdr data))))))
    (or found 0)))

(defun gnus-summary-reselect-current-group (&optional all rescan)
  "Exit and then reselect the current newsgroup.
The prefix argument ALL means to select all articles."
  (interactive "P" gnus-summary-mode)
  (when (gnus-ephemeral-group-p gnus-newsgroup-name)
    (error "Ephemeral groups can't be reselected"))
  (let ((current-subject (gnus-summary-find-for-reselect))
	(group gnus-newsgroup-name))
    (setq gnus-newsgroup-begin nil)
    (gnus-summary-exit nil 'leave-hidden)
    ;; We have to adjust the point of group mode buffer because
    ;; point was moved to the next unread newsgroup by exiting.
    (gnus-summary-jump-to-group group)
    (when rescan
      (save-excursion
	(gnus-group-get-new-news-this-group 1)))
    (gnus-group-read-group all t)
    (gnus-summary-goto-subject current-subject nil t)))

(defun gnus-summary-rescan-group (&optional all)
  "Exit the newsgroup, ask for new articles, and select the newsgroup."
  (interactive "P" gnus-summary-mode)
  (let ((config gnus-current-window-configuration))
    (gnus-summary-reselect-current-group all t)
    (gnus-configure-windows config)
    (when (eq config 'article)
      (gnus-summary-select-article))))

(defun gnus-summary-update-info (&optional non-destructive)
  (save-excursion
    (let ((group gnus-newsgroup-name))
      (when group
	(when gnus-newsgroup-kill-headers
	  (setq gnus-newsgroup-killed
		(gnus-compress-sequence
		 (gnus-sorted-union
		  (gnus-list-range-intersection
		   gnus-newsgroup-unselected gnus-newsgroup-killed)
		  gnus-newsgroup-unreads)
		 t)))
	(unless (listp (cdr gnus-newsgroup-killed))
	  (setq gnus-newsgroup-killed (list gnus-newsgroup-killed)))
	(let ((headers gnus-newsgroup-headers)
	      (ephemeral-p (gnus-ephemeral-group-p group))
	      info)
	  (unless ephemeral-p
	    (setq info (copy-sequence (gnus-get-info group))
		  info (delq (gnus-info-params info) info)))
	  ;; Set the new ranges of read articles.
	  (with-current-buffer gnus-group-buffer
	    (gnus-undo-force-boundary))
	  (gnus-update-read-articles
	   group (gnus-sorted-union
		  gnus-newsgroup-unreads gnus-newsgroup-unselected))
	  ;; Set the current article marks.
	  (let ((gnus-newsgroup-scored
		 (if (and (not gnus-save-score)
			  (not non-destructive))
		     nil
		   gnus-newsgroup-scored)))
	    (save-excursion
	      (gnus-update-marks)))
	  ;; Do the cross-ref thing.
	  (when gnus-use-cross-reference
	    (gnus-mark-xrefs-as-read group headers gnus-newsgroup-unreads))
	  ;; Do not switch windows but change the buffer to work.
	  (set-buffer gnus-group-buffer)
	  (unless ephemeral-p
	    (gnus-group-update-group
	     group nil
	     (equal info
		    (setq info (copy-sequence (gnus-get-info group))
			  info (delq (gnus-info-params info) info))))))))))

(defun gnus-summary-make-group-from-search ()
  "Make a persistent group from the current ephemeral search group."
  (interactive nil gnus-summary-mode)
  (if (not (gnus-nnselect-group-p gnus-newsgroup-name))
      (gnus-message 3 "%s is not a search group" gnus-newsgroup-name)
    (let ((name (gnus-read-group "Group name: ")))
      (with-current-buffer gnus-group-buffer
	(gnus-group-make-group
	 name
	 (list 'nnselect "nnselect")
	 nil
	 (list (cons 'nnselect-specs
		     (gnus-group-get-parameter gnus-newsgroup-name
					       'nnselect-specs t))))))))

(defun gnus-summary-save-newsrc (&optional force)
  "Save the current number of read/marked articles in the dribble buffer.
The dribble buffer will then be saved.
If FORCE (the prefix), also save the .newsrc file(s)."
  (interactive "P" gnus-summary-mode)
  (gnus-summary-update-info t)
  (if force
      (gnus-save-newsrc-file)
    (gnus-dribble-save)))

(declare-function gnus-cache-write-active "gnus-cache" (&optional force))
(declare-function gnus-article-stop-animations "gnus-art" ())

(defun gnus-summary-exit (&optional temporary leave-hidden)
  "Exit reading current newsgroup, and then return to group selection mode.
`gnus-exit-group-hook' is called with no arguments if that value is non-nil."
  (interactive nil gnus-summary-mode)
  (gnus-set-global-variables)
  (when (gnus-buffer-live-p gnus-article-buffer)
    (with-current-buffer gnus-article-buffer
      (mm-destroy-parts gnus-article-mime-handles)
      ;; Set it to nil for safety reason.
      (setq gnus-article-mime-handle-alist nil)
      (setq gnus-article-mime-handles nil)))
  (gnus-kill-save-kill-buffer)
  (gnus-async-halt-prefetch)
  (let* ((group gnus-newsgroup-name)
	 (quit-config (gnus-group-quit-config gnus-newsgroup-name))
	 (gnus-group-is-exiting-p t)
	 (article-buffer gnus-article-buffer)
	 (original-article-buffer gnus-original-article-buffer)
	 (mode major-mode)
	 (group-point nil)
	 (buf (current-buffer))
	 ;; `gnus-single-article-buffer' is nil buffer-locally in
	 ;; ephemeral group of which summary buffer will be killed,
	 ;; but the global value may be non-nil.
	 (single-article-buffer gnus-single-article-buffer))
    (unless quit-config
      ;; Do adaptive scoring, and possibly save score files.
      (when gnus-newsgroup-adaptive
	(gnus-score-adaptive))
      (when gnus-use-scoring
	(gnus-score-save)))
    (when gnus-use-cache
      (gnus-cache-possibly-remove-articles)
      (gnus-cache-save-buffers))
    (gnus-async-prefetch-remove-group group)
    (when gnus-suppress-duplicates
      (gnus-dup-enter-articles))
    (when gnus-use-trees
      (gnus-tree-close))
    (when gnus-use-cache
      (gnus-cache-write-active))
    ;; Remove entries for this group.
    (nnmail-purge-split-history group)
    ;; Make all changes in this group permanent.
    (unless quit-config
      (gnus-run-hooks 'gnus-exit-group-hook)
      (gnus-summary-update-info))
    (gnus-run-hooks 'gnus-summary-prepare-exit-hook)
    (gnus-close-group group)
    ;; Make sure where we were, and go to next newsgroup.
    (when (gnus-buffer-live-p gnus-group-buffer)
      (set-buffer gnus-group-buffer))
    (unless quit-config
      (gnus-group-jump-to-group group))
    (gnus-run-hooks 'gnus-summary-exit-hook)
    (unless (or quit-config
		(not gnus-summary-next-group-on-exit)
		;; If this group has disappeared from the summary
		;; buffer, don't skip forwards.
		(not (string= group (gnus-group-group-name))))
      (gnus-group-next-unread-group 1))
    (setq group-point (point))
    (gnus-article-stop-animations)
    (unless leave-hidden
      (gnus-configure-windows 'group 'force))
    (if temporary
	nil				;Nothing to do.
      (set-buffer buf)
      (if (not gnus-kill-summary-on-exit)
	  (progn
	    (gnus-deaden-summary)
	    (setq mode nil))
	(when (get-buffer gnus-article-buffer)
	  (bury-buffer gnus-article-buffer))
	;; Return to group mode buffer.
	(when (eq mode 'gnus-summary-mode)
	  (gnus-kill-buffer buf)))

      (setq gnus-current-select-method gnus-select-method)
      (when (gnus-buffer-live-p gnus-group-buffer)
	(set-buffer gnus-group-buffer))
      (if quit-config
	  (gnus-handle-ephemeral-exit quit-config)
	(goto-char group-point)
	;; If gnus-group-buffer is already displayed, make sure we also move
	;; the cursor in the window that displays it.
	(let ((win (get-buffer-window (current-buffer) 0)))
	  (goto-char group-point)
	  (if win (set-window-point win (point)))))

      ;; If we have several article buffers, we kill them at exit.
      (unless single-article-buffer
	(when (gnus-buffer-live-p article-buffer)
	  (with-current-buffer article-buffer
	    ;; Don't kill sticky article buffers
	    (unless (eq major-mode 'gnus-sticky-article-mode)
	      (gnus-kill-buffer article-buffer)
	      (setq gnus-article-current nil))))
	(gnus-kill-buffer original-article-buffer))

      ;; Clear the current group name.
      (unless quit-config
	(setq gnus-newsgroup-name nil)))))

(declare-function gnus-stop-downloads "gnus-art" ())

(defalias 'gnus-summary-quit 'gnus-summary-exit-no-update)
(defun gnus-summary-exit-no-update (&optional no-questions)
  "Quit reading current newsgroup without updating read article info."
  (interactive nil gnus-summary-mode)
  (let* ((group gnus-newsgroup-name)
	 (gnus-group-is-exiting-p t)
	 (gnus-group-is-exiting-without-update-p t)
	 (quit-config (gnus-group-quit-config group)))
    (when (or no-questions
	      (gnus-ephemeral-group-p group)
	      gnus-expert-user
	      (gnus-y-or-n-p "Discard changes to this group and exit? "))
      (gnus-async-halt-prefetch)
      (run-hooks 'gnus-summary-prepare-exit-hook)
      (when (gnus-buffer-live-p gnus-article-buffer)
	(with-current-buffer gnus-article-buffer
	  (gnus-article-stop-animations)
	  (gnus-stop-downloads)
	  (mm-destroy-parts gnus-article-mime-handles)
	  ;; Set it to nil for safety reason.
	  (setq gnus-article-mime-handle-alist nil)
	  (setq gnus-article-mime-handles nil)))
      ;; If we have several article buffers, we kill them at exit.
      (unless gnus-single-article-buffer
	(gnus-kill-buffer gnus-article-buffer)
	(gnus-kill-buffer gnus-original-article-buffer)
	(setq gnus-article-current nil))
      ;; Return to the group buffer.
      (if (not gnus-kill-summary-on-exit)
	  (progn
	    (gnus-deaden-summary)
	    (gnus-configure-windows 'group 'force))
	(gnus-configure-windows 'group 'force)
	(gnus-close-group group)
	(gnus-kill-buffer gnus-summary-buffer))
      (unless gnus-single-article-buffer
	(setq gnus-article-current nil))
      (when gnus-use-trees
	(gnus-tree-close))
      (gnus-async-prefetch-remove-group group)
      (when (get-buffer gnus-article-buffer)
	(bury-buffer gnus-article-buffer))
      ;; Clear the current group name.
      (setq gnus-newsgroup-name nil)
      (unless (gnus-ephemeral-group-p group)
	(gnus-group-update-group group nil t))
      (when (gnus-group-goto-group group)
	(gnus-group-next-unread-group 1))
      (gnus-article-stop-animations)
      (when quit-config
	(gnus-handle-ephemeral-exit quit-config)))))

(defun gnus-handle-ephemeral-exit (quit-config)
  "Handle movement when leaving an ephemeral group.
The state which existed when entering the ephemeral is reset."
  (if (not (buffer-live-p (car quit-config)))
      (when (gnus-buffer-live-p gnus-group-buffer)
	(gnus-configure-windows 'group 'force))
    (set-buffer (car quit-config))
    (unless (eq (cdr quit-config) 'group)
      (setq gnus-current-select-method
	    (gnus-find-method-for-group gnus-newsgroup-name)))
    (cond ((derived-mode-p 'gnus-summary-mode)
	   (gnus-set-global-variables))
	  ((derived-mode-p 'gnus-article-mode)
	   (save-current-buffer
	     ;; The `gnus-summary-buffer' variable may point
	     ;; to the old summary buffer when using a single
	     ;; article buffer.
	     (unless (gnus-buffer-live-p gnus-summary-buffer)
	       (set-buffer gnus-group-buffer))
	     (set-buffer gnus-summary-buffer)
	     (gnus-set-global-variables))))
    (if (or (eq (cdr quit-config) 'article)
	    (eq (cdr quit-config) 'pick))
	(if (and (boundp 'gnus-pick-mode) (symbol-value 'gnus-pick-mode))
	    (gnus-configure-windows 'pick 'force)
	  (gnus-configure-windows (cdr quit-config) 'force))
      (gnus-configure-windows (cdr quit-config) 'force))
    (when (derived-mode-p 'gnus-summary-mode)
      (if (memq gnus-auto-select-on-ephemeral-exit '(next-noselect
						     next-unread-noselect))
	  (when (zerop (cond ((eq gnus-auto-select-on-ephemeral-exit
				  'next-noselect)
			      (gnus-summary-next-subject 1 nil t))
			     ((eq gnus-auto-select-on-ephemeral-exit
				  'next-unread-noselect)
			      (gnus-summary-next-subject 1 t t))))
	    ;; Hide the article buffer which displays the article different
	    ;; from the one that the cursor points to in the summary buffer.
	    (gnus-configure-windows 'summary 'force))
	(cond ((eq gnus-auto-select-on-ephemeral-exit 'next)
	       (gnus-summary-next-subject 1))
	      ((eq gnus-auto-select-on-ephemeral-exit 'next-unread)
	       (gnus-summary-next-subject 1 t))))
      (gnus-summary-recenter)
      (gnus-summary-position-point))))

;;; Dead summaries.

(defvar gnus-dead-summary-mode-map
  (let ((map (make-keymap)))
    (suppress-keymap map)
    (substitute-key-definition 'undefined 'gnus-summary-wake-up-the-dead map)
    (dolist (key '("\C-d" "\r" "\177" [delete]))
      (define-key map key 'gnus-summary-wake-up-the-dead))
    (dolist (key '("q" "Q"))
      (define-key map key 'bury-buffer))
    map))

(define-minor-mode gnus-dead-summary-mode
  "Minor mode for Gnus summary buffers."
  :lighter " Dead" :keymap gnus-dead-summary-mode-map
  (unless (derived-mode-p 'gnus-summary-mode)
    (setq gnus-dead-summary-mode nil)))

(defun gnus-deaden-summary ()
  "Make the current summary buffer into a dead summary buffer."
  ;; Kill any previous dead summary buffer.
  (when (buffer-live-p gnus-dead-summary)
    (with-current-buffer gnus-dead-summary
      (when gnus-dead-summary-mode
	(kill-buffer (current-buffer)))))
  ;; Make this the current dead summary.
  (setq gnus-dead-summary (current-buffer))
  (gnus-dead-summary-mode 1)
  (let ((name (buffer-name)))
    (when (string-match "Summary" name)
      (rename-buffer
       (concat (substring name 0 (match-beginning 0)) "Dead "
	       (substring name (match-beginning 0)))
       t)
      (bury-buffer))))

(defun gnus-kill-or-deaden-summary (buffer)
  "Kill or deaden the summary BUFFER."
  (save-excursion
    (when (and (buffer-live-p buffer)
	       (not gnus-single-article-buffer))
      (with-current-buffer buffer
	(gnus-kill-buffer gnus-article-buffer)
	(gnus-kill-buffer gnus-original-article-buffer)))
    (cond
     ;; Kill the buffer.
     (gnus-kill-summary-on-exit
      (when (and gnus-use-trees
                 (gnus-buffer-live-p buffer))
	(with-current-buffer buffer
	  (gnus-tree-close)))
      (gnus-kill-buffer buffer))
     ;; Deaden the buffer.
     ((gnus-buffer-live-p buffer)
      (with-current-buffer buffer
	(gnus-deaden-summary))))))

(defun gnus-summary-wake-up-the-dead (&rest _)
  "Wake up the dead summary buffer."
  (interactive nil gnus-summary-mode)
  (gnus-dead-summary-mode -1)
  (let ((name (buffer-name)))
    (when (string-match "Dead " name)
      (rename-buffer
       (concat (substring name 0 (match-beginning 0))
	       (substring name (match-end 0)))
       t)))
  (gnus-message 3 "This dead summary is now alive again"))

;; Suggested by Per Abrahamsen <amanda@iesd.auc.dk>.
(defun gnus-summary-describe-group (&optional force)
  "Describe the current newsgroup."
  (interactive "P" gnus-summary-mode)
  (gnus-group-describe-group force gnus-newsgroup-name))

(defun gnus-summary-describe-briefly ()
  "Describe summary mode commands briefly."
  (interactive nil gnus-summary-mode)
  (gnus-message 6 "%s" (substitute-command-keys "\\<gnus-summary-mode-map>\\[gnus-summary-next-page]:Select  \\[gnus-summary-next-unread-article]:Forward  \\[gnus-summary-prev-unread-article]:Backward  \\[gnus-summary-exit]:Exit  \\[gnus-info-find-node]:Run Info	 \\[gnus-summary-describe-briefly]:This help")))

;; Walking around group mode buffer from summary mode.

(defun gnus-summary-next-group (&optional no-article target-group backward)
  "Exit current newsgroup and then select next unread newsgroup.
If prefix argument NO-ARTICLE is non-nil, no article is selected
initially.  If TARGET-GROUP, go to this group.  If BACKWARD, go to
previous group instead."
  (interactive "P" gnus-summary-mode)
  ;; Stop pre-fetching.
  (gnus-async-halt-prefetch)
  (let ((current-group gnus-newsgroup-name)
	(current-buffer (current-buffer))
	entered)
    ;; First we semi-exit this group to update Xrefs and all variables.
    ;; We can't do a real exit, because the window conf must remain
    ;; the same in case the user is prompted for info, and we don't
    ;; want the window conf to change before that...
    (gnus-summary-exit t)
    (while (not entered)
      ;; Then we find what group we are supposed to enter.
      (set-buffer gnus-group-buffer)
      (gnus-group-jump-to-group current-group)
      (setq target-group
	    (or target-group
		(if (eq gnus-keep-same-level 'best)
		    (gnus-summary-best-group gnus-newsgroup-name)
		  (gnus-summary-search-group backward gnus-keep-same-level))))
      (if (not target-group)
	  ;; There are no further groups, so we return to the group
	  ;; buffer.
	  (progn
	    (gnus-message 5 "Returning to the group buffer")
	    (setq entered t)
	    (when (gnus-buffer-live-p current-buffer)
	      (set-buffer current-buffer)
	      (gnus-summary-exit))
	    (gnus-run-hooks 'gnus-group-no-more-groups-hook))
	;; We try to enter the target group.
	(gnus-group-jump-to-group target-group)
	(let ((unreads (gnus-group-group-unread)))
	  (if (and (or (eq t unreads)
		       (and unreads (not (zerop unreads))))
 		   (gnus-summary-read-group
 		    target-group nil no-article
                    (and (buffer-live-p current-buffer) current-buffer)
 		    nil backward))
	      (setq entered t)
	    (setq current-group target-group
		  target-group nil)))))))

(defun gnus-summary-prev-group (&optional no-article)
  "Exit current newsgroup and then select previous unread newsgroup.
If prefix argument NO-ARTICLE is non-nil, no article is selected initially."
  (interactive "P" gnus-summary-mode)
  (gnus-summary-next-group no-article nil t))

;; Walking around summary lines.

(defun gnus-summary-first-subject (&optional unread undownloaded unseen)
  "Go to the first subject satisfying any non-nil constraint.
If UNREAD is non-nil, the article should be unread.
If UNDOWNLOADED is non-nil, the article should be undownloaded.
If UNSEEN is non-nil, the article should be unseen as well as unread.
Returns the article selected or nil if there are no matching articles."
  (interactive "P" gnus-summary-mode)
  (cond
   ;; Empty summary.
   ((null gnus-newsgroup-data)
    (gnus-message 3 "No articles in the group")
    nil)
   ;; Pick the first article.
   ((not (or unread undownloaded unseen))
    (goto-char (gnus-data-pos (car gnus-newsgroup-data)))
    (gnus-data-number (car gnus-newsgroup-data)))
   ;; Find the first unread article.
   (t
    (let ((data gnus-newsgroup-data))
      (while (and data
                  (let ((num (gnus-data-number (car data))))
                    (or (memq num gnus-newsgroup-unfetched)
                        (not (or (and unread
                                      (memq num gnus-newsgroup-unreads))
                                 (and undownloaded
                                      (memq num gnus-newsgroup-undownloaded))
                                 (and unseen
                                      (memq num gnus-newsgroup-unseen)
				      (memq num gnus-newsgroup-unreads)))))))
        (setq data (cdr data)))
      (prog1
          (if data
              (progn
                (goto-char (gnus-data-pos (car data)))
                (gnus-data-number (car data)))
            (gnus-message 3 "No more%s articles"
                          (let* ((r (when unread " unread"))
                                 (d (when undownloaded " undownloaded"))
                                 (s (when unseen " unseen"))
                                 (l (delq nil (list r d s))))
                            (cond ((= 3 (length l))
                                   (concat r "," d ", or" s))
                                  ((= 2 (length l))
                                   (concat (car l) ", or" (cadr l)))
                                  ((= 1 (length l))
                                   (car l))
                                  (t
                                   ""))))
            nil
            )
        (gnus-summary-position-point))))))

(defun gnus-summary-next-subject (n &optional unread dont-display)
  "Go to next N'th summary line.
If N is negative, go to the previous N'th subject line.
If UNREAD is non-nil, only unread articles are selected.
The difference between N and the actual number of steps taken is
returned."
  (interactive "p" gnus-summary-mode)
  (let ((backward (< n 0))
	(n (abs n)))
    (while (and (> n 0)
		(if backward
		    (gnus-summary-find-prev unread)
		  (gnus-summary-find-next unread)))
      (unless (zerop (setq n (1- n)))
	(gnus-summary-show-thread)))
    (when (/= 0 n)
      (gnus-message 7 "No more%s articles"
		    (if unread " unread" "")))
    (unless dont-display
      (gnus-summary-recenter)
      (gnus-summary-position-point))
    n))

(defun gnus-summary-next-unread-subject (n)
  "Go to next N'th unread summary line."
  (interactive "p" gnus-summary-mode)
  (gnus-summary-next-subject n t))

(defun gnus-summary-prev-subject (n &optional unread)
  "Go to previous N'th summary line.
If optional argument UNREAD is non-nil, only unread article is selected."
  (interactive "p" gnus-summary-mode)
  (gnus-summary-next-subject (- n) unread))

(defun gnus-summary-prev-unread-subject (n)
  "Go to previous N'th unread summary line."
  (interactive "p" gnus-summary-mode)
  (gnus-summary-next-subject (- n) t))

(defun gnus-summary-goto-subjects (articles)
  "Insert the subject header for ARTICLES in the current buffer."
  (save-excursion
    (dolist (article articles)
      (gnus-summary-goto-subject article t)))
  (gnus-summary-limit (append articles gnus-newsgroup-limit))
  (gnus-summary-position-point))

(defun gnus-summary-goto-subject (article &optional force silent)
  "Go to the subject line of ARTICLE.
If FORCE, also allow jumping to articles not currently shown."
  (interactive "nArticle number: " gnus-summary-mode)
  (unless (numberp article)
    (error "Article %s is not a number" article))
  (let ((b (point))
	(data (gnus-data-find article)))
    ;; We read in the article if we have to.
    (and (not data)
	 force
	 (gnus-summary-insert-subject
	  article
	  (if (or (numberp force) (mail-header-p force)) force)
	  t)
	 (setq data (gnus-data-find article)))
    (goto-char b)
    (if (not data)
	(progn
	  (unless silent
	    (gnus-message 3 "Can't find article %d" article))
	  nil)
      (let ((pt (gnus-data-pos data)))
	(goto-char pt)
	(gnus-summary-set-article-display-arrow pt))
      (gnus-summary-position-point)
      article)))

;; Walking around summary lines with displaying articles.

(defun gnus-summary-expand-window (&optional arg)
  "Make the summary buffer take up the entire Emacs frame.
Given a prefix, will force an `article' buffer configuration."
  (interactive "P" gnus-summary-mode)
  (if arg
      (gnus-configure-windows 'article 'force)
    (gnus-configure-windows 'summary 'force)))

(defun gnus-summary-display-article (article &optional all-header)
  "Display ARTICLE in article buffer."
  (unless (and (gnus-buffer-live-p gnus-article-buffer)
	       (with-current-buffer gnus-article-buffer
		 (derived-mode-p 'gnus-article-mode)))
    (gnus-article-setup-buffer))
  (gnus-set-global-variables)
  (with-current-buffer gnus-article-buffer
    ;; The buffer may be non-empty and even narrowed, so go back to
    ;; a sane state.
    (widen)
    ;; We're going to erase the buffer anyway so do it now: it can save us from
    ;; uselessly performing multibyte-conversion of the current content.
    (let ((inhibit-read-only t)) (erase-buffer))
    (setq gnus-article-charset gnus-newsgroup-charset)
    (setq gnus-article-ignored-charsets gnus-newsgroup-ignored-charsets)
    (mm-enable-multibyte))
  (if (null article)
      nil
    (prog1
	(funcall (or gnus-summary-display-article-function
                     #'gnus-article-prepare)
                 article all-header)
      (gnus-run-hooks 'gnus-select-article-hook)
      (when (and gnus-current-article
		 (not (zerop gnus-current-article)))
	(gnus-summary-goto-subject gnus-current-article))
      (gnus-summary-recenter)
      (when (and gnus-use-trees gnus-show-threads)
	(gnus-possibly-generate-tree article)
	(gnus-highlight-selected-tree article))
      ;; Successfully display article.
      (gnus-article-set-window-start
       (cdr (assq article gnus-newsgroup-bookmarks))))))

(defun gnus-summary-select-article (&optional all-headers force pseudo article)
  "Select the current article.
If ALL-HEADERS is non-nil, show all header fields.  If FORCE is
non-nil, the article will be re-fetched even if it already present in
the article buffer.  If PSEUDO is non-nil, pseudo-articles will also
be displayed."
  ;; Make sure we are in the summary buffer to work around bbdb bug.
  (unless (derived-mode-p 'gnus-summary-mode)
    (set-buffer gnus-summary-buffer))
  (let ((article (or article (gnus-summary-article-number)))
        (all-headers (and all-headers t)) ; Must be t or nil.
	gnus-summary-display-article-function)
    (and (not pseudo)
	 (gnus-summary-article-pseudo-p article)
	 (error "This is a pseudo-article"))
    (with-current-buffer gnus-summary-buffer
      (if (or (and gnus-single-article-buffer
		   (or (null gnus-current-article)
		       (null gnus-article-current)
		       (null (get-buffer gnus-article-buffer))
		       (not (eq article (cdr gnus-article-current)))
		       (not (equal (car gnus-article-current)
				   gnus-newsgroup-name))
		       (not (get-buffer gnus-original-article-buffer))))
	      (and (not gnus-single-article-buffer)
		   (or (null gnus-current-article)
		       (not (get-buffer gnus-original-article-buffer))
		       (not (eq gnus-current-article article))))
	      force)
	  ;; The requested article is different from the current article.
	  (progn
	    (gnus-summary-display-article article all-headers)
	    (when (gnus-buffer-live-p gnus-article-buffer)
	      (with-current-buffer gnus-article-buffer
		(if (not gnus-article-decoded-p) ;; a local variable
		    (mm-disable-multibyte))))
	    (gnus-article-set-window-start
	     (cdr (assq article gnus-newsgroup-bookmarks)))
	    article)
	'old))))

(defun gnus-summary-force-verify-and-decrypt ()
  "Display buttons for signed/encrypted parts and verify/decrypt them."
  (interactive nil gnus-summary-mode)
  (let ((mm-verify-option 'known)
	(mm-decrypt-option 'known)
	(gnus-article-emulate-mime t)
	(gnus-buttonized-mime-types (append (list "multipart/signed"
						  "multipart/encrypted")
					    gnus-buttonized-mime-types)))
    (gnus-summary-select-article nil 'force)))

(defun gnus-summary-next-article (&optional unread subject backward push)
  "Select the next article.
If UNREAD, only unread articles are selected.
If SUBJECT, only articles with SUBJECT are selected.
If BACKWARD, the previous article is selected instead of the next."
  (interactive "P" gnus-summary-mode)
  ;; Make sure we are in the summary buffer.
  (unless (derived-mode-p 'gnus-summary-mode)
    (set-buffer gnus-summary-buffer))
  (cond
   ;; Is there such an article?
   ((and (gnus-summary-search-forward unread subject backward)
	 (or (gnus-summary-display-article (gnus-summary-article-number))
	     (eq (gnus-summary-article-mark) gnus-canceled-mark)))
    (gnus-summary-position-point))
   ;; If not, we try the first unread, if that is wanted.
   ((and subject
	 gnus-auto-select-same
	 (gnus-summary-first-unread-article))
    (gnus-summary-position-point)
    (gnus-message 6 "Wrapped"))
   ;; Try to get next/previous article not displayed in this group.
   ((and gnus-auto-extend-newsgroup
	 (not unread) (not subject))
    (gnus-summary-goto-article
     (if backward (1- gnus-newsgroup-begin) (1+ gnus-newsgroup-end))
     nil (count-lines (point-min) (point))))
   ;; Go to next/previous group.
   (t
    (unless (gnus-ephemeral-group-p gnus-newsgroup-name)
      (gnus-summary-jump-to-group gnus-newsgroup-name))
    (let ((cmd last-command-event)
	  (point
	   (with-current-buffer gnus-group-buffer
	     (point)))
	  (current-summary (current-buffer))
	  (group
	   (if (eq gnus-keep-same-level 'best)
	       (gnus-summary-best-group gnus-newsgroup-name)
	     (gnus-summary-search-group backward gnus-keep-same-level))))
      ;; Select next unread newsgroup automagically.
      (cond
       ((or (not gnus-auto-select-next)
	    (not cmd))
	(unless (eq gnus-auto-select-next 'quietly)
	  (gnus-message 6 "No more%s articles" (if unread " unread" ""))))
       ((or (eq gnus-auto-select-next 'quietly)
	    (and (eq gnus-auto-select-next 'slightly-quietly)
		 push)
	    (and (eq gnus-auto-select-next 'almost-quietly)
		 (gnus-summary-last-article-p)))
	;; Select quietly.
	(if (gnus-ephemeral-group-p gnus-newsgroup-name)
	    (gnus-summary-exit)
	  (unless (eq gnus-auto-select-next 'quietly)
	    (gnus-message 6 "No more%s articles (%s)..."
			  (if unread " unread" "")
			  (if group (concat "selecting " group)
			    "exiting")))
	  (gnus-summary-next-group nil group backward)))
       (t
	(when (numberp last-input-event)
	  ;; Somehow or other, we may now have selected a different
	  ;; window.  Make point go back to the summary buffer.
	  (when (eq current-summary (current-buffer))
            ;; FIXME: This burps when get-buffer-window returns nil.
	    (select-window (get-buffer-window current-summary 0)))
	  (gnus-summary-walk-group-buffer
	   gnus-newsgroup-name cmd unread backward point))))))))

(defun gnus-summary-walk-group-buffer (_from-group cmd unread backward start)
  (let ((keystrokes '((?\C-n (gnus-group-next-unread-group 1))
		      (?\C-p (gnus-group-prev-unread-group 1))))
	(cursor-in-echo-area t)
	keve key group ended prompt)
    (with-current-buffer gnus-group-buffer
      (goto-char start)
      (setq group
	    (if (eq gnus-keep-same-level 'best)
		(gnus-summary-best-group gnus-newsgroup-name)
	      (gnus-summary-search-group backward gnus-keep-same-level))))
    (while (not ended)
      (setq prompt
	    (format
	     "No more%s articles%s " (if unread " unread" "")
	     (if (and group
		      (not (gnus-ephemeral-group-p gnus-newsgroup-name)))
		 (format " (Type %s for %s [%s])"
			 (single-key-description cmd)
			 group
			 (gnus-group-unread group))
	       (format " (Type %s to exit %s)"
		       (single-key-description cmd)
		       gnus-newsgroup-name))))
      ;; Confirm auto selection.
      (setq key (car (setq keve (gnus-read-event-char prompt)))
	    ended t)
      (cond
       ((assq key keystrokes)
	(let ((obuf (current-buffer)))
	  (switch-to-buffer gnus-group-buffer)
	  (when group
	    (gnus-group-jump-to-group group))
	  (eval (cadr (assq key keystrokes)) t)
	  (setq group (gnus-group-group-name))
	  (switch-to-buffer obuf))
	(setq ended nil))
       ((equal key cmd)
	(if (or (not group)
		(gnus-ephemeral-group-p gnus-newsgroup-name))
	    (gnus-summary-exit)
	  (gnus-summary-next-group nil group backward)))
       (t
	(push (cdr keve) unread-command-events))))))

(defun gnus-summary-next-unread-article ()
  "Select unread article after current one."
  (interactive nil gnus-summary-mode)
  (gnus-summary-next-article
   (or (not (eq gnus-summary-goto-unread 'never))
       (gnus-summary-last-article-p (gnus-summary-article-number)))
   (and gnus-auto-select-same
	(gnus-summary-article-subject))))

(defun gnus-summary-prev-article (&optional unread subject)
  "Select the article before the current one.
If UNREAD is non-nil, only unread articles are selected."
  (interactive "P" gnus-summary-mode)
  (gnus-summary-next-article unread subject t))

(defun gnus-summary-prev-unread-article ()
  "Select unread article before current one."
  (interactive nil gnus-summary-mode)
  (gnus-summary-prev-article
   (or (not (eq gnus-summary-goto-unread 'never))
       (gnus-summary-first-article-p (gnus-summary-article-number)))
   (and gnus-auto-select-same
	(gnus-summary-article-subject))))

(declare-function gnus-article-only-boring-p "gnus-art" ())

(defun gnus-summary-next-page (&optional lines circular stop)
  "Show next page of the selected article.
If at the end of the current article, select the next article.
LINES says how many lines should be scrolled up.

If CIRCULAR is non-nil, go to the start of the article instead of
selecting the next article when reaching the end of the current
article.

If STOP is non-nil, just stop when reaching the end of the message.

Also see the variable `gnus-article-skip-boring'."
  (interactive "P" gnus-summary-mode)
  (gnus-set-global-variables)
  (let ((article (gnus-summary-article-number))
	(article-window (get-buffer-window gnus-article-buffer t))
	endp)
    ;; If the buffer is empty, we have no article.
    (unless article
      (error "No article to select"))
    (gnus-configure-windows 'article)
    (if (eq (cdr (assq article gnus-newsgroup-reads)) gnus-canceled-mark)
	(if (and (eq gnus-summary-goto-unread 'never)
		 (not (gnus-summary-last-article-p article)))
	    (gnus-summary-next-article)
	  (gnus-summary-next-unread-article))
      (if (or (null gnus-current-article)
	      (null gnus-article-current)
	      (/= article (cdr gnus-article-current))
	      (not (equal (car gnus-article-current) gnus-newsgroup-name)))
	  ;; Selected subject is different from current article's.
	  (gnus-summary-display-article article)
	(when article-window
	  (gnus-eval-in-buffer-window gnus-article-buffer
	    (setq endp (or (gnus-article-next-page lines)
			   (gnus-article-only-boring-p))))
	  (when endp
	    (cond ((or stop gnus-summary-stop-at-end-of-message)
		   (gnus-message 3 "End of message"))
		  (circular
		   (gnus-summary-beginning-of-article))
		  ((or lines
		       (not gnus-paging-select-next))
		   (gnus-message 3 "End of message"))
		  ((null lines)
		   (if (and (eq gnus-summary-goto-unread 'never)
			    (not (gnus-summary-last-article-p article)))
		       (gnus-summary-next-article)
		     (gnus-summary-next-unread-article))))))))
    (gnus-summary-recenter)
    (gnus-summary-position-point)))

(defun gnus-summary-prev-page (&optional lines move)
  "Show previous page of selected article.
Argument LINES specifies lines to be scrolled down.
If MOVE, move to the previous unread article if point is at
the beginning of the buffer."
  (interactive "P" gnus-summary-mode)
  (let ((article (gnus-summary-article-number))
	(article-window (get-buffer-window gnus-article-buffer t))
	endp)
    (gnus-configure-windows 'article)
    (if (or (null gnus-current-article)
	    (null gnus-article-current)
	    (/= article (cdr gnus-article-current))
	    (not (equal (car gnus-article-current) gnus-newsgroup-name)))
	;; Selected subject is different from current article's.
	(gnus-summary-display-article article)
      (gnus-summary-recenter)
      (when article-window
	(gnus-eval-in-buffer-window gnus-article-buffer
	  (setq endp (gnus-article-prev-page lines)))
	(when (and move endp)
	  (cond ((or lines
		     (not gnus-paging-select-next))
		 (gnus-message 3 "Beginning of message"))
		((null lines)
		 (if (and (eq gnus-summary-goto-unread 'never)
			  (not (gnus-summary-first-article-p article)))
		     (gnus-summary-prev-article)
		   (gnus-summary-prev-unread-article))))))))
  (gnus-summary-position-point))

(defun gnus-summary-prev-page-or-article (&optional lines)
  "Show previous page of selected article.
Argument LINES specifies lines to be scrolled down.
If at the beginning of the article, go to the next article."
  (interactive "P" gnus-summary-mode)
  (gnus-summary-prev-page lines t))

(defun gnus-summary-scroll-up (lines)
  "Scroll up (or down) one line current article.
Argument LINES specifies lines to be scrolled up (or down if negative).
If no article is selected, then the current article will be selected first."
  (interactive "p" gnus-summary-mode)
  (gnus-configure-windows 'article)
  (gnus-summary-show-thread)
  (when (eq (gnus-summary-select-article nil nil 'pseudo) 'old)
    (gnus-eval-in-buffer-window gnus-article-buffer
      (cond ((> lines 0)
	     (when (gnus-article-next-page lines)
	       (gnus-message 3 "End of message")))
	    ((< lines 0)
	     (gnus-article-prev-page (- lines))))))
  (gnus-summary-recenter)
  (gnus-summary-position-point))

(defun gnus-summary-scroll-down (lines)
  "Scroll down (or up) one line current article.
Argument LINES specifies lines to be scrolled down (or up if negative).
If no article is selected, then the current article will be selected first."
  (interactive "p" gnus-summary-mode)
  (gnus-summary-scroll-up (- lines)))

(defun gnus-summary-next-same-subject ()
  "Select next article which has the same subject as current one."
  (interactive nil gnus-summary-mode)
  (gnus-summary-next-article nil (gnus-summary-article-subject)))

(defun gnus-summary-prev-same-subject ()
  "Select previous article which has the same subject as current one."
  (interactive nil gnus-summary-mode)
  (gnus-summary-prev-article nil (gnus-summary-article-subject)))

(defun gnus-summary-next-unread-same-subject ()
  "Select next unread article which has the same subject as current one."
  (interactive nil gnus-summary-mode)
  (gnus-summary-next-article t (gnus-summary-article-subject)))

(defun gnus-summary-prev-unread-same-subject ()
  "Select previous unread article which has the same subject as current one."
  (interactive nil gnus-summary-mode)
  (gnus-summary-prev-article t (gnus-summary-article-subject)))

(defun gnus-summary-first-unread-article ()
  "Select the first unread article.
Return nil if there are no unread articles."
  (interactive nil gnus-summary-mode)
  (prog1
      (when (gnus-summary-first-subject t)
	(gnus-summary-show-thread)
	(gnus-summary-first-subject t)
	(gnus-summary-display-article (gnus-summary-article-number)))
    (gnus-summary-position-point)))

(defun gnus-summary-first-unread-subject ()
  "Place the point on the subject line of the first unread article.
Return nil if there are no unread articles."
  (interactive nil gnus-summary-mode)
  (prog1
      (when (gnus-summary-first-subject t)
	(gnus-summary-show-thread)
	(gnus-summary-first-subject t))
    (gnus-summary-position-point)))

(defun gnus-summary-next-unseen-article (&optional backward)
  "Select the next unseen article."
  (interactive nil gnus-summary-mode)
  (let* ((article (gnus-summary-article-number))
	 (articles (gnus-data-find-list article (gnus-data-list backward))))
    (when (or (not gnus-summary-check-current)
	      (not (gnus-data-unseen-p (car articles)))
	      (not (gnus-data-unread-p (car articles))))
      (setq articles (cdr articles)))
    (while (and articles
		(or (not (gnus-data-unseen-p (car articles)))
		    (not (gnus-data-unread-p (car articles)))))
      (setq articles (cdr articles)))
    (if (not articles)
	(if backward
	    (message "No previous unseen article")
	  (message "No next unseen article"))
      (goto-char (gnus-data-pos (car articles)))
      (gnus-summary-select-article)
      (gnus-data-number (car articles)))))

(defun gnus-summary-prev-unseen-article ()
  "Select the previous unseen article."
  (interactive nil gnus-summary-mode)
  (gnus-summary-next-unseen-article t))

(defun gnus-summary-first-unseen-subject ()
  "Place the point on the subject line of the first unseen article.
Return nil if there are no unseen articles."
  (interactive nil gnus-summary-mode)
  (prog1
      (when (gnus-summary-first-subject nil nil t)
	(gnus-summary-show-thread)
	(gnus-summary-first-subject nil nil t))
    (gnus-summary-position-point)))

(defun gnus-summary-first-unseen-or-unread-subject ()
  "Place the point on the subject line of the first unseen and unread article.
If all articles have been seen, on the subject line of the first unread
article."
  (interactive nil gnus-summary-mode)
  (prog1
      (unless (when (gnus-summary-first-subject nil nil t)
		(gnus-summary-show-thread)
		(gnus-summary-first-subject nil nil t))
	(when (gnus-summary-first-subject t)
	  (gnus-summary-show-thread)
	  (gnus-summary-first-subject t)))
    (gnus-summary-position-point)))

(defun gnus-summary-first-article ()
  "Select the first article.
Return nil if there are no articles."
  (interactive nil gnus-summary-mode)
  (prog1
      (when (gnus-summary-first-subject)
	(gnus-summary-show-thread)
	(gnus-summary-first-subject)
	(gnus-summary-display-article (gnus-summary-article-number)))
    (gnus-summary-position-point)))

(defun gnus-summary-best-unread-article (&optional arg)
  "Select the unread article with the highest score.
If given a prefix argument, select the next unread article that has a
score higher than the default score."
  (interactive "P" gnus-summary-mode)
  (let ((article (if arg
		     (gnus-summary-better-unread-subject)
		   (gnus-summary-best-unread-subject))))
    (if article
	(gnus-summary-goto-article article)
      (error "No unread articles"))))

(defun gnus-summary-best-unread-subject ()
  "Select the unread subject with the highest score."
  (interactive nil gnus-summary-mode)
  (let ((best -1000000)
	(data gnus-newsgroup-data)
	article score)
    (while data
      (and (gnus-data-unread-p (car data))
	   (> (setq score
		    (gnus-summary-article-score (gnus-data-number (car data))))
	      best)
	   (setq best score
		 article (gnus-data-number (car data))))
      (setq data (cdr data)))
    (when article
      (gnus-summary-goto-subject article))
    (gnus-summary-position-point)
    article))

(defun gnus-summary-better-unread-subject ()
  "Select the first unread subject that has a score over the default score."
  (interactive nil gnus-summary-mode)
  (let ((data gnus-newsgroup-data)
	article)
    (while (and (setq article (gnus-data-number (car data)))
		(or (gnus-data-read-p (car data))
		    (not (> (gnus-summary-article-score article)
			    gnus-summary-default-score))))
      (setq data (cdr data)))
    (when article
      (gnus-summary-goto-subject article))
    (gnus-summary-position-point)
    article))

(defun gnus-summary-last-subject ()
  "Go to the last displayed subject line in the group."
  (let ((article (gnus-data-number (car (gnus-data-list t)))))
    (when article
      (gnus-summary-goto-subject article))))

(defun gnus-summary-goto-article (article &optional all-headers force)
  "Fetch ARTICLE (article number or Message-ID) and display it if it exists.
If ALL-HEADERS is non-nil, no header lines are hidden.
If FORCE, go to the article even if it isn't displayed.  If FORCE
is a number, it is the line the article is to be displayed on."
  (interactive
   (list
    (gnus-completing-read "Article number or Message-ID"
			  (mapcar #'int-to-string gnus-newsgroup-limit))
    current-prefix-arg t)
   gnus-summary-mode)
  (prog1
      (if (and (stringp article)
	       (string-match "@\\|%40" article))
	  (gnus-summary-refer-article article)
	(when (stringp article)
	  (setq article (string-to-number article)))
	(if (gnus-summary-goto-subject article force)
	    (gnus-summary-display-article article all-headers)
	  (gnus-message 4 "Couldn't go to article %s" article) nil))
    (gnus-summary-position-point)))

(defun gnus-summary-goto-last-article ()
  "Go to the previously read article."
  (interactive nil gnus-summary-mode)
  (prog1
      (when gnus-last-article
	(gnus-summary-goto-article gnus-last-article nil t))
    (gnus-summary-position-point)))

(defun gnus-summary-pop-article (number)
  "Pop one article off the history and go to the previous.
NUMBER articles will be popped off."
  (interactive "p" gnus-summary-mode)
  (let (to)
    (setq gnus-newsgroup-history
	  (cdr (setq to (nthcdr number gnus-newsgroup-history))))
    (if to
	(gnus-summary-goto-article (car to) nil t)
      (error "Article history empty")))
  (gnus-summary-position-point))

;; Summary commands and functions for limiting the summary buffer.

(defun gnus-summary-limit-to-articles (n)
  "Limit the summary buffer to the next N articles.
If not given a prefix, use the process marked articles instead."
  (interactive "P" gnus-summary-mode)
  (prog1
      (let ((articles (gnus-summary-work-articles n)))
	(setq gnus-newsgroup-processable nil)
	(gnus-summary-limit articles))
    (gnus-summary-position-point)))

(defun gnus-summary-pop-limit (&optional total)
  "Restore the previous limit.
If given a prefix, remove all limits."
  (interactive "P" gnus-summary-mode)
  (when total
    (setq gnus-newsgroup-limits
	  (list (mapcar #'mail-header-number gnus-newsgroup-headers))))
  (unless gnus-newsgroup-limits
    (error "No limit to pop"))
  (prog1
      (gnus-summary-limit nil 'pop)
    (gnus-summary-position-point)))

(defun gnus-summary-limit-to-subject (subject &optional header not-matching)
  "Limit the summary buffer to articles that have subjects that match a regexp.
If NOT-MATCHING, excluding articles that have subjects that match a regexp."
  (interactive
   (list
    (read-string
     (if current-prefix-arg "Exclude subject (regexp): " "Limit to subject (regexp): "))
    nil current-prefix-arg)
   gnus-summary-mode)
  (unless header
    (setq header "subject"))
  (when (not (equal "" subject))
    (prog1
	(let ((articles (gnus-summary-find-matching
			 (or header "subject") subject 'all nil nil
			 not-matching)))
	  (unless (or articles not-matching)
	    (error "Found no matches for \"%s\"" subject))
	  (gnus-summary-limit articles))
      (gnus-summary-position-point))))

(defun gnus-summary-limit-to-author (from &optional not-matching)
  "Limit the summary buffer to articles that have authors that match a regexp.
If NOT-MATCHING, excluding articles that have authors that match a regexp."
  (interactive
   (list
    (let*
	((header
	  (gnus-summary-article-header))
	 (default
	   (and header
		(car
		 (mail-header-parse-address
		  (mail-header-from header))))))
      (read-string
       (concat
	(if current-prefix-arg
	    "Exclude author (regexp" "Limit to author (regexp")
	(if default
	    (concat ", default \"" default "\"): ")
	  "): "))
       nil nil default))
    current-prefix-arg)
   gnus-summary-mode)
  (gnus-summary-limit-to-subject from "from" not-matching))

(defun gnus-summary-limit-to-recipient (recipient &optional not-matching)
  "Limit the summary buffer to articles with the given RECIPIENT.

If NOT-MATCHING, exclude RECIPIENT.

To and Cc headers are checked.  You need to include them in
`nnmail-extra-headers'."
  ;; Unlike `rmail-summary-by-recipients', doesn't include From.
  (interactive
   (list
    (read-string
     (format "%s recipient (regexp): "
	     (if current-prefix-arg "Exclude" "Limit to")))
    current-prefix-arg)
   gnus-summary-mode)
  (when (not (equal "" recipient))
    (prog1 (let* ((to
		   (if (memq 'To nnmail-extra-headers)
		       (gnus-summary-find-matching
			(cons 'extra 'To) recipient 'all nil nil
			not-matching)
		     (gnus-message
		      1 "`To' isn't present in `nnmail-extra-headers'")
		     (sit-for 1)
		     nil))
		  (cc
		   (if (memq 'Cc nnmail-extra-headers)
		       (gnus-summary-find-matching
			(cons 'extra 'Cc) recipient 'all nil nil
			not-matching)
		     (gnus-message
		      1 "`Cc' isn't present in `nnmail-extra-headers'")
		     (sit-for 1)
		     nil))
		  (articles
		   (if not-matching
		       ;; We need the numbers that are in both lists:
		       (mapcar (lambda (a)
				 (and (memq a to) a))
			       cc)
		     (nconc to cc))))
	     (unless (or articles not-matching)
	       (error "Found no matches for \"%s\"" recipient))
	     (gnus-summary-limit articles))
      (gnus-summary-position-point))))

(defun gnus-summary-limit-to-address (address &optional not-matching)
  "Limit the summary buffer to articles with the given ADDRESS.

If NOT-MATCHING, exclude ADDRESS.

To, Cc and From headers are checked.  You need to include `To' and `Cc'
in `nnmail-extra-headers'."
  (interactive
   (list
    (read-string
     (format "%s address (regexp): "
	     (if current-prefix-arg "Exclude" "Limit to")))
    current-prefix-arg)
   gnus-summary-mode)
  (when (not (equal "" address))
    (prog1 (let* ((to
		   (if (memq 'To nnmail-extra-headers)
		       (gnus-summary-find-matching
			(cons 'extra 'To) address 'all nil nil
			not-matching)
		     (gnus-message
		      1 "`To' isn't present in `nnmail-extra-headers'")
		     (sit-for 1)
		     t))
		  (cc
		   (if (memq 'Cc nnmail-extra-headers)
		       (gnus-summary-find-matching
			(cons 'extra 'Cc) address 'all nil nil
			not-matching)
		     (gnus-message
		      1 "`Cc' isn't present in `nnmail-extra-headers'")
		     (sit-for 1)
		     t))
		  (from
		   (gnus-summary-find-matching "from" address
					       'all nil nil not-matching))
		  (articles
		   (if not-matching
		       ;; We need the numbers that are in all lists:
		       (if (eq cc t)
			   (if (eq to t)
			       from
			     (mapcar (lambda (a) (car (memq a from))) to))
			 (mapcar (lambda (a) (car (memq a from)))
                                 (if (eq to t)
			             cc
				   (mapcar (lambda (a) (car (memq a to)))
					   cc))))
		     (nconc (if (eq to t) nil to)
			    (if (eq cc t) nil cc)
			    from))))
	     (unless (or articles not-matching)
	       (error "Found no matches for \"%s\"" address))
	     (gnus-summary-limit articles))
      (gnus-summary-position-point))))

(defun gnus-summary-limit-strange-charsets-predicate (header)
  (let ((string (concat (mail-header-subject header)
			(mail-header-from header)))
	charset found)
    (dotimes (i (1- (length string)))
      (setq charset (format "%s" (char-charset (aref string (1+ i)))))
      (when (string-match "unicode\\|big\\|japanese" charset)
	(setq found t)))
    found))

(defun gnus-summary-limit-to-predicate (predicate)
  "Limit to articles where PREDICATE returns non-nil.
PREDICATE will be called with the header structures of the
articles."
  (let ((articles nil)
	(case-fold-search t))
    (dolist (header gnus-newsgroup-headers)
      (when (funcall predicate header)
	(push (mail-header-number header) articles)))
    (gnus-summary-limit (nreverse articles))))

(defun gnus-summary-limit-to-age (age &optional younger-p)
  "Limit the summary buffer to articles that are older than (or equal) AGE days.
If YOUNGER-P (the prefix) is non-nil, limit the summary buffer to
articles that are younger than AGE days."
  (interactive
   (let ((younger current-prefix-arg)
	 (days-got nil)
	 days)
     (while (not days-got)
       (setq days (if younger
		      (read-string "Limit to articles younger than (in days, older when negative): ")
		    (read-string
		     "Limit to articles older than (in days, younger when negative): ")))
       (when (> (length days) 0)
	 (setq days (read days)))
       (if (numberp days)
	   (progn
	     (setq days-got t)
	     (when (< days 0)
	       (setq younger (not younger))
	       (setq days (* days -1))))
	 (message "Please enter a number.")
	 (sleep-for 1)))
     (list days younger))
   gnus-summary-mode)
  (prog1
      (let ((data gnus-newsgroup-data)
	    (cutoff (days-to-time age))
	    articles d date is-younger)
	(while (setq d (pop data))
	  (when (and (mail-header-p (gnus-data-header d))
		     (setq date (mail-header-date (gnus-data-header d))))
	    (setq is-younger (time-less-p
			      (time-since (gnus-date-get-time date))
			      cutoff))
	    (when (if younger-p
		      is-younger
		    (not is-younger))
	      (push (gnus-data-number d) articles))))
	(gnus-summary-limit (nreverse articles)))
    (gnus-summary-position-point)))

(defun gnus-summary-limit-to-extra (header regexp &optional not-matching)
  "Limit the summary buffer to articles that match an `extra' header."
  (interactive
   (let ((header
	  (intern
	   (gnus-completing-read
	    (if current-prefix-arg "Exclude extra header" "Limit extra header")
	    (mapcar #'symbol-name gnus-extra-headers)
	    t nil nil
	    (symbol-name
	     (car gnus-extra-headers))))))
     (list header
	   (read-string
	    (format "%s header %s (regexp): "
		    (if current-prefix-arg "Exclude" "Limit to")
		    header))
	   current-prefix-arg))
   gnus-summary-mode)
  (when (not (equal "" regexp))
    (prog1
	(let ((articles (gnus-summary-find-matching
			 (cons 'extra header) regexp 'all nil nil
			 not-matching)))
	  (unless (or articles not-matching)
	    (error "Found no matches for \"%s\"" regexp))
	  (gnus-summary-limit articles))
      (gnus-summary-position-point))))

(defun gnus-summary-limit-to-display-predicate ()
  "Limit the summary buffer to the predicated in the `display' group parameter."
  (interactive nil gnus-summary-mode)
  (unless gnus-newsgroup-display
    (error "There is no `display' group parameter"))
  (let (articles)
    (dolist (gnus-number gnus-newsgroup-articles)
      (when (funcall gnus-newsgroup-display)
	(push gnus-number articles)))
    (gnus-summary-limit articles))
  (gnus-summary-position-point))

(defun gnus-summary-limit-to-unread (&optional all)
  "Limit the summary buffer to articles that are not marked as read.
If ALL is non-nil, limit strictly to unread articles."
  (interactive "P" gnus-summary-mode)
  (if all
      (gnus-summary-limit-to-marks (char-to-string gnus-unread-mark))
    (gnus-summary-limit-to-marks
     ;; Concat all the marks that say that an article is read and have
     ;; those removed.
     (list gnus-del-mark gnus-read-mark gnus-ancient-mark
	   gnus-killed-mark gnus-spam-mark gnus-kill-file-mark
	   gnus-low-score-mark gnus-expirable-mark
	   gnus-canceled-mark gnus-catchup-mark gnus-sparse-mark
	   gnus-duplicate-mark)
     'reverse)))

(defun gnus-summary-limit-to-headers (match &optional reverse)
  "Limit the summary buffer to articles that have headers that match MATCH.
If REVERSE (the prefix), limit to articles that don't match."
  (interactive "sMatch headers (regexp): \nP" gnus-summary-mode)
  (gnus-summary-limit-to-bodies match reverse t))

(declare-function article-goto-body "gnus-art" ())

(defun gnus-summary-limit-to-bodies (match &optional reverse headersp)
  "Limit the summary buffer to articles that have bodies that match MATCH.
If REVERSE (the prefix), limit to articles that don't match."
  (interactive "sMatch body (regexp): \nP" gnus-summary-mode)
  (let ((articles nil)
	(gnus-select-article-hook nil)	;Disable hook.
	(gnus-article-prepare-hook nil)
	(gnus-use-article-prefetch nil)
	(gnus-keep-backlog nil)
	(gnus-break-pages nil)
	(gnus-summary-display-arrow nil)
	(gnus-updated-mode-lines nil)
	(gnus-auto-center-summary nil)
	(gnus-display-mime-function nil))
    (dolist (data gnus-newsgroup-data)
      (let (gnus-mark-article-hook)
	(gnus-summary-select-article t t nil (gnus-data-number data)))
      (with-current-buffer gnus-article-buffer
	(article-goto-body)
	(let* ((case-fold-search t)
	       (found (if headersp
			  (re-search-backward match nil t)
			(re-search-forward match nil t))))
	  (when (or (and found
			 (not reverse))
		    (and (not found)
			 reverse))
	    (push (gnus-data-number data) articles)))))
    (if (not articles)
	(message "No messages matched")
      (gnus-summary-limit articles)))
  (gnus-summary-position-point))

(defun gnus-summary-limit-to-singletons (&optional threadsp)
  "Limit the summary buffer to articles that aren't part on any thread.
If THREADSP (the prefix), limit to articles that are in threads."
  (interactive "P" gnus-summary-mode)
  (let ((articles nil)
	thread-articles
	threads)
    (dolist (thread gnus-newsgroup-threads)
      (if (stringp (car thread))
	  (dolist (thread (cdr thread))
	    (push thread threads))
	(push thread threads)))
    (dolist (thread threads)
      (setq thread-articles (gnus-articles-in-thread thread))
      (when (or (and threadsp
		     (> (length thread-articles) 1))
		(and (not threadsp)
		     (= (length thread-articles) 1)))
	(setq articles (nconc thread-articles articles))))
    (if (not articles)
	(message "No messages matched")
      (gnus-summary-limit articles))
    (gnus-summary-position-point)))

(defun gnus-summary-limit-to-replied (&optional unreplied)
  "Limit the summary buffer to replied articles.
If UNREPLIED (the prefix), limit to unreplied articles."
  (interactive "P" gnus-summary-mode)
  (if unreplied
      (gnus-summary-limit
       (seq-difference gnus-newsgroup-articles
                       gnus-newsgroup-replied
                       #'eq))
    (gnus-summary-limit gnus-newsgroup-replied))
  (gnus-summary-position-point))

(defun gnus-summary-limit-exclude-marks (marks &optional _reverse)
  "Exclude articles that are marked with MARKS (e.g. \"DK\").
If REVERSE, limit the summary buffer to articles that are marked
with MARKS.  MARKS can either be a string of marks or a list of marks.
Returns how many articles were removed."
  (interactive "sMarks: " gnus-summary-mode)
  (gnus-summary-limit-to-marks marks t))

(defun gnus-summary-limit-to-marks (marks &optional reverse)
  "Limit the summary buffer to articles that are marked with MARKS (e.g. \"DK\").
If REVERSE (the prefix), limit the summary buffer to articles that are
not marked with MARKS.  MARKS can either be a string of marks or a
list of marks.
Returns how many articles were removed."
  (interactive "sMarks: \nP" gnus-summary-mode)
  (prog1
      (let ((data gnus-newsgroup-data)
	    (marks (if (listp marks) marks
		     (append marks nil))) ; Transform to list.
	    articles)
	(while data
	  (when (if reverse (not (memq (gnus-data-mark (car data)) marks))
		  (memq (gnus-data-mark (car data)) marks))
	    (push (gnus-data-number (car data)) articles))
	  (setq data (cdr data)))
	(gnus-summary-limit articles))
    (gnus-summary-position-point)))

(defun gnus-summary-limit-to-score (score &optional below)
  "Limit to articles with score at or above SCORE.

With a prefix argument, limit to articles with score at or below
SCORE."
  (interactive
   (list
    (string-to-number
     (read-string
      (format "Limit to articles with score of at %s: "
	      (if current-prefix-arg "most" "least")))))
   gnus-summary-mode)
  (let ((data gnus-newsgroup-data)
        (compare (if (or below current-prefix-arg) #'<= #'>=))
        articles)
    (while data
      (when (funcall compare (gnus-summary-article-score
                              (gnus-data-number (car data)))
                     score)
	(push (gnus-data-number (car data)) articles))
      (setq data (cdr data)))
    (prog1
	(gnus-summary-limit articles)
      (gnus-summary-position-point))))

(defun gnus-summary-limit-to-unseen ()
  "Limit to unseen articles."
  (interactive nil gnus-summary-mode)
  (prog1
      (gnus-summary-limit gnus-newsgroup-unseen)
    (gnus-summary-position-point)))

(defun gnus-summary-limit-include-thread (id &optional thread-only)
  "Display all hidden articles belonging to thread ID.
When called interactively, ID is the Message-ID of the current
article.  If thread-only is non-nil limit the summary buffer to
these articles."
  (interactive
   (list
    (mail-header-id
     (gnus-summary-article-header))
    current-prefix-arg)
   gnus-summary-mode)
  (let ((articles (gnus-articles-in-thread
		   (gnus-id-to-thread (gnus-root-id id))))
	;;we REALLY want the whole thread---this prevents cut-threads
	;;from removing the thread we want to include.
	(gnus-fetch-old-headers nil)
	(gnus-build-sparse-threads nil))
    (prog1
	(gnus-summary-limit (if thread-only articles
			      (nconc articles gnus-newsgroup-limit)))
      (gnus-summary-limit-include-matching-articles
       "subject"
       (regexp-quote (gnus-general-simplify-subject
		      (mail-header-subject (gnus-id-to-header id)))))
      ;; the previous two calls each push a limit onto the limit
      ;; stack. the first pop remove the articles that match the
      ;; subject, while the second pop gets us back to the state
      ;; before we started to deal with the thread. presumably we want
      ;; to think of the thread and its associated subject matches as
      ;; a single thing so that we need to pop only once to get back
      ;; to the original view.
      (pop gnus-newsgroup-limits)
      (gnus-summary-position-point))))

(defun gnus-summary-limit-include-matching-articles (header regexp)
  "Display all the hidden articles that have HEADERs that match REGEXP."
  (interactive
   (list
    (read-string "Match on header: ")
    (read-string "Regexp: "))
   gnus-summary-mode)
  (let ((articles (gnus-find-matching-articles header regexp)))
    (prog1
	(gnus-summary-limit (nconc articles gnus-newsgroup-limit))
      (gnus-summary-position-point))))

(defun gnus-summary-insert-dormant-articles ()
  "Insert all the dormant articles for this group into the current buffer."
  (interactive nil gnus-summary-mode)
  (let ((gnus-verbose (max 6 gnus-verbose)))
    (if (not gnus-newsgroup-dormant)
	(gnus-message 3 "No dormant articles for this group")
      (gnus-summary-goto-subjects gnus-newsgroup-dormant))))

(defun gnus-summary-insert-ticked-articles ()
  "Insert ticked articles for this group into the current buffer."
  (interactive nil gnus-summary-mode)
  (let ((gnus-verbose (max 6 gnus-verbose)))
    (if (not gnus-newsgroup-marked)
	(gnus-message 3 "No ticked articles for this group")
      (gnus-summary-goto-subjects gnus-newsgroup-marked))))

(defun gnus-summary-limit-include-dormant ()
  "Display all the hidden articles that are marked as dormant.
Note that this command only works on a subset of the articles currently
fetched for this group."
  (interactive nil gnus-summary-mode)
  (unless gnus-newsgroup-dormant
    (error "There are no dormant articles in this group"))
  (prog1
      (gnus-summary-limit (append gnus-newsgroup-dormant gnus-newsgroup-limit))
    (gnus-summary-position-point)))

(defun gnus-summary-include-articles (articles)
  "Fetch the headers for ARTICLES and then display the summary lines."
  (let ((gnus-inhibit-demon t)
	(gnus-agent nil)
	(gnus-read-all-available-headers t))
    (setq gnus-newsgroup-headers
	  (cl-merge
	   'list gnus-newsgroup-headers
	   (gnus-fetch-headers articles nil t)
	   'gnus-article-sort-by-number))
    (setq gnus-newsgroup-articles
	  (gnus-sorted-nunion gnus-newsgroup-articles articles))
    (gnus-summary-limit (append articles gnus-newsgroup-limit))))

(defun gnus-summary-limit-exclude-dormant ()
  "Hide all dormant articles."
  (interactive nil gnus-summary-mode)
  (prog1
      (gnus-summary-limit-to-marks (list gnus-dormant-mark) 'reverse)
    (gnus-summary-position-point)))

(defun gnus-summary-limit-exclude-childless-dormant ()
  "Hide all dormant articles that have no children."
  (interactive nil gnus-summary-mode)
  (let ((data (gnus-data-list t))
	articles d children)
    ;; Find all articles that are either not dormant or have
    ;; children.
    (while (setq d (pop data))
      (when (or (not (= (gnus-data-mark d) gnus-dormant-mark))
		(and (setq children
			   (gnus-article-children (gnus-data-number d)))
		     (let (found)
		       (while children
			 (when (memq (car children) articles)
			   (setq children nil
				 found t))
			 (pop children))
		       found)))
	(push (gnus-data-number d) articles)))
    ;; Do the limiting.
    (prog1
	(gnus-summary-limit articles)
      (gnus-summary-position-point))))

(defun gnus-summary-limit-mark-excluded-as-read (&optional all)
  "Mark all unread excluded articles as read.
If ALL, mark even excluded ticked and dormants as read."
  (interactive "P" gnus-summary-mode)
  (setq gnus-newsgroup-limit (sort gnus-newsgroup-limit #'<))
  (let ((articles (gnus-sorted-ndifference
		   (sort
		    (mapcar #'mail-header-number gnus-newsgroup-headers)
		    #'<)
		   gnus-newsgroup-limit))
	article)
    (setq gnus-newsgroup-unreads
	  (gnus-sorted-intersection gnus-newsgroup-unreads
				    gnus-newsgroup-limit))
    (if all
	(setq gnus-newsgroup-dormant nil
	      gnus-newsgroup-marked nil
	      gnus-newsgroup-reads
	      (nconc
	       (mapcar (lambda (n) (cons n gnus-catchup-mark)) articles)
	       gnus-newsgroup-reads))
      (while (setq article (pop articles))
	(unless (or (memq article gnus-newsgroup-dormant)
		    (memq article gnus-newsgroup-marked))
	  (push (cons article gnus-catchup-mark) gnus-newsgroup-reads))))))

(defun gnus-summary-limit (articles &optional pop)
  (if pop
      ;; We pop the previous limit off the stack and use that.
      (setq articles (car gnus-newsgroup-limits)
	    gnus-newsgroup-limits (cdr gnus-newsgroup-limits))
    ;; We use the new limit, so we push the old limit on the stack.
    (push gnus-newsgroup-limit gnus-newsgroup-limits))
  ;; Set the limit.
  (setq gnus-newsgroup-limit articles)
  (let ((total (length gnus-newsgroup-data))
	(data (gnus-data-find-list (gnus-summary-article-number)))
	(gnus-summary-mark-below nil)	; Inhibit this.
	found)
    ;; This will do all the work of generating the new summary buffer
    ;; according to the new limit.
    (gnus-summary-prepare)
    ;; Hide any threads, possibly.
    (gnus-summary-maybe-hide-threads)
    ;; Try to return to the article you were at, or one in the
    ;; neighborhood.
    (when data
      ;; We try to find some article after the current one.
      (while data
	(when (gnus-summary-goto-subject (gnus-data-number (car data)) nil t)
	  (setq data nil
		found t))
	(setq data (cdr data))))
    (unless found
      ;; If there is no data, that means that we were after the last
      ;; article.  The same goes when we can't find any articles
      ;; after the current one.
      (goto-char (point-max))
      (gnus-summary-find-prev))
    (gnus-set-mode-line 'summary)
    ;; We return how many articles were removed from the summary
    ;; buffer as a result of the new limit.
    (- total (length gnus-newsgroup-data))))

(defsubst gnus-invisible-cut-children (threads)
  (let ((num 0))
    (while threads
      (when (memq (mail-header-number (caar threads)) gnus-newsgroup-limit)
	(cl-incf num))
      (pop threads))
    (< num 2)))

(defsubst gnus-cut-thread (thread)
  "Go forwards in the thread until we find an article that we want to display."
  (when (or (eq gnus-fetch-old-headers 'some)
	    (eq gnus-fetch-old-headers 'invisible)
	    (numberp gnus-fetch-old-headers)
	    (eq gnus-build-sparse-threads 'some)
	    (eq gnus-build-sparse-threads 'more))
    ;; Deal with old-fetched headers and sparse threads.
    (while (and
	    thread
	    (or
	     (gnus-summary-article-sparse-p (mail-header-number (car thread)))
	     (gnus-summary-article-ancient-p
	      (mail-header-number (car thread))))
	    (if (or (<= (length (cdr thread)) 1)
		    (eq gnus-fetch-old-headers 'invisible))
		(setq gnus-newsgroup-limit
		      (delq (mail-header-number (car thread))
			    gnus-newsgroup-limit)
		      thread (cadr thread))
	      (when (gnus-invisible-cut-children (cdr thread))
		(let ((th (cdr thread)))
		  (while th
		    (if (memq (mail-header-number (caar th))
			      gnus-newsgroup-limit)
			(setq thread (car th)
			      th nil)
		      (setq th (cdr th))))))))))
  thread)

(defun gnus-cut-threads (threads)
  "Cut off all uninteresting articles from the beginning of THREADS."
  (when (or (eq gnus-fetch-old-headers 'some)
	    (eq gnus-fetch-old-headers 'invisible)
	    (numberp gnus-fetch-old-headers)
	    (eq gnus-build-sparse-threads 'some)
	    (eq gnus-build-sparse-threads 'more))
    (let ((th threads))
      (while th
	(setcar th (gnus-cut-thread (car th)))
	(setq th (cdr th)))))
  ;; Remove nixed out threads.
  (delq nil threads))

(defun gnus-summary-initial-limit (&optional show-if-empty)
  "Figure out what the initial limit is supposed to be on group entry.
This entails weeding out unwanted dormants, low-scored articles,
fetch-old-headers verbiage, and so on."
  ;; Most groups have nothing to remove.
  (unless (or gnus-inhibit-limiting
	      (and (null gnus-newsgroup-dormant)
		   (eq gnus-newsgroup-display #'gnus-not-ignore)
		   (not (eq gnus-fetch-old-headers 'some))
		   (not (numberp gnus-fetch-old-headers))
		   (not (eq gnus-fetch-old-headers 'invisible))
		   (null gnus-summary-expunge-below)
		   (not (eq gnus-build-sparse-threads 'some))
		   (not (eq gnus-build-sparse-threads 'more))
		   (null gnus-thread-expunge-below)))
    (push gnus-newsgroup-limit gnus-newsgroup-limits)
    (setq gnus-newsgroup-limit nil)
    (maphash
     (lambda (_id deps)
       (unless (car deps)
	 ;; These threads have no parents -- they are roots.
	 (let ((nodes (cdr deps))
	       thread)
	   (while nodes
	     (if (and gnus-thread-expunge-below
		      (< (gnus-thread-total-score (car nodes))
			 gnus-thread-expunge-below))
		 (gnus-expunge-thread (pop nodes))
	       (setq thread (pop nodes))
	       (gnus-summary-limit-children thread))))))
     gnus-newsgroup-dependencies)
    ;; If this limitation resulted in an empty group, we might
    ;; pop the previous limit and use it instead.
    (when (and (not gnus-newsgroup-limit)
	       show-if-empty)
      (setq gnus-newsgroup-limit (pop gnus-newsgroup-limits)))
    gnus-newsgroup-limit))

(defun gnus-summary-limit-children (thread)
  "Return 1 if this subthread is visible and 0 if it is not."
  ;; First we get the number of visible children to this thread.  This
  ;; is done by recursing down the thread using this function, so this
  ;; will really go down to a leaf article first, before slowly
  ;; working its way up towards the root.
  (when thread
    (let* ((max-lisp-eval-depth (max 5000 max-lisp-eval-depth))
	   (children
	   (if (cdr thread)
	       (apply #'+ (mapcar #'gnus-summary-limit-children
				 (cdr thread)))
	     0))
	   (number (mail-header-number (car thread)))
	   score)
      (if (and
	   (not (memq number gnus-newsgroup-marked))
	   (or
	    ;; If this article is dormant and has absolutely no visible
	    ;; children, then this article isn't visible.
	    (and (memq number gnus-newsgroup-dormant)
		 (zerop children))
	    ;; If this is "fetch-old-headered" and there is no
	    ;; visible children, then we don't want this article.
	    (and (or (eq gnus-fetch-old-headers 'some)
		     (numberp gnus-fetch-old-headers))
		 (gnus-summary-article-ancient-p number)
		 (zerop children))
	    ;; If this is "fetch-old-headered" and `invisible', then
	    ;; we don't want this article.
	    (and (eq gnus-fetch-old-headers 'invisible)
		 (gnus-summary-article-ancient-p number))
	    ;; If this is a sparsely inserted article with no children,
	    ;; we don't want it.
	    (and (eq gnus-build-sparse-threads 'some)
		 (gnus-summary-article-sparse-p number)
		 (zerop children))
	    ;; If we use expunging, and this article is really
	    ;; low-scored, then we don't want this article.
	    (when (and gnus-summary-expunge-below
		       (< (setq score
				(or (cdr (assq number gnus-newsgroup-scored))
				    gnus-summary-default-score))
			  gnus-summary-expunge-below))
	      ;; We increase the expunge-tally here, but that has
	      ;; nothing to do with the limits, really.
	      (cl-incf gnus-newsgroup-expunged-tally)
	      ;; We also mark as read here, if that's wanted.
	      (when (and gnus-summary-mark-below
			 (< score gnus-summary-mark-below))
		(setq gnus-newsgroup-unreads
		      (delq number gnus-newsgroup-unreads))
		(if gnus-newsgroup-auto-expire
		    (push number gnus-newsgroup-expirable)
		  (push (cons number gnus-low-score-mark)
			gnus-newsgroup-reads)))
	      t)
	    ;; Do the `display' group parameter.
	    (and gnus-newsgroup-display
		 (let ((gnus-number number))
		   (not (funcall gnus-newsgroup-display))))))
	  ;; Nope, invisible article.
	  0
	;; Ok, this article is to be visible, so we add it to the limit
	;; and return 1.
	(push number gnus-newsgroup-limit)
	1))))

(defun gnus-expunge-thread (thread)
  "Mark all articles in THREAD as read."
  (let* ((number (mail-header-number (car thread))))
    (cl-incf gnus-newsgroup-expunged-tally)
    ;; We also mark as read here, if that's wanted.
    (setq gnus-newsgroup-unreads
	  (delq number gnus-newsgroup-unreads))
    (if gnus-newsgroup-auto-expire
	(push number gnus-newsgroup-expirable)
      (push (cons number gnus-low-score-mark)
	    gnus-newsgroup-reads)))
  ;; Go recursively through all subthreads.
  (mapcar #'gnus-expunge-thread (cdr thread)))

;; Summary article oriented commands

(defun gnus-summary-refer-parent-article (n)
  "Refer parent article N times.
If N is negative, go to ancestor -N instead.
The difference between N and the number of articles fetched is returned."
  (interactive "p" gnus-summary-mode)
  (let ((skip 1)
	error header ref)
    (when (not (natnump n))
      (setq skip (abs n)
	    n 1))
    (while (and (> n 0)
		(not error))
      (setq header (gnus-summary-article-header))
      (if (and (eq (mail-header-number header)
		   (cdr gnus-article-current))
	       (equal gnus-newsgroup-name
		      (car gnus-article-current)))
	  ;; If we try to find the parent of the currently
	  ;; displayed article, then we take a look at the actual
	  ;; References header, since this is slightly more
	  ;; reliable than the References field we got from the
	  ;; server.
	  (with-current-buffer gnus-original-article-buffer
	    (nnheader-narrow-to-headers)
	    (unless (setq ref (message-fetch-field "references"))
	      (when (setq ref (message-fetch-field "in-reply-to"))
		(setq ref (gnus-extract-message-id-from-in-reply-to ref))))
	    (widen))
	(setq ref
	      ;; It's not the current article, so we take a bet on
	      ;; the value we got from the server.
	      (mail-header-references header)))
      (if (and ref
	       (not (equal ref "")))
	  (unless (gnus-summary-refer-article (gnus-parent-id ref skip))
	    (gnus-message 1 "Couldn't find parent"))
	(gnus-message 1 "No references in article %d"
		      (gnus-summary-article-number))
	(setq error t))
      (cl-decf n))
    (gnus-summary-position-point)
    n))

(defun gnus-summary-refer-references ()
  "Fetch all articles mentioned in the References header.
Return the number of articles fetched."
  (interactive nil gnus-summary-mode)
  (let ((ref (mail-header-references (gnus-summary-article-header)))
	(current (gnus-summary-article-number))
	(n 0))
    (if (or (not ref)
	    (equal ref ""))
	(error "No References in the current article")
      ;; For each Message-ID in the References header...
      (while (string-match "<[^>]*>" ref)
	(cl-incf n)
	;; ... fetch that article.
	(gnus-summary-refer-article
	 (prog1 (match-string 0 ref)
	   (setq ref (substring ref (match-end 0))))))
      (gnus-summary-goto-subject current)
      (gnus-summary-position-point)
      n)))

(defun gnus-delete-duplicate-headers (headers)
  ;; First remove leading duplicates.
  (while (and (> (length headers) 1)
	      (= (mail-header-number (car headers))
		 (mail-header-number (cadr headers))))
    (pop headers))
  ;; Then the rest.
  (let ((result headers))
    (while (> (length headers) 1)
      (if (= (mail-header-number (car headers))
	     (mail-header-number (cadr headers)))
	  (setcdr headers (cddr headers))
	(pop headers)))
    result))

(defun gnus-summary-refer-thread (&optional limit)
  "Fetch all articles in the current thread.
For backends that know how to search for threads (currently only
`nnimap') a non-numeric prefix arg will search the entire server;
without a prefix arg only the current group is searched.  If the
variable `gnus-refer-thread-use-search' is non-nil the prefix arg
has the reverse meaning.  If no backend-specific `request-thread'
function is available fetch LIMIT (the numerical prefix) old
headers.  If LIMIT is non-numeric or nil fetch the number
specified by the `gnus-refer-thread-limit' variable."
  (interactive "P" gnus-summary-mode)
  (let* ((header (gnus-summary-article-header))
	 (id (mail-header-id header))
	 (gnus-inhibit-demon t)
	 (gnus-summary-ignore-duplicates t)
	 (gnus-read-all-available-headers t)
	 (gnus-refer-thread-use-search
	  (if (and (not (null limit)) (listp limit))
	      (not gnus-refer-thread-use-search) gnus-refer-thread-use-search))
	 (new-headers
	  (if (gnus-check-backend-function
	       'request-thread gnus-newsgroup-name)
	      (gnus-request-thread header gnus-newsgroup-name)
	    (let* ((limit (if (numberp limit) (prefix-numeric-value limit)
			    gnus-refer-thread-limit))
		   (last (if (numberp limit)
			     (min (+ (mail-header-number header)
				     limit)
				  gnus-newsgroup-highest)
			   gnus-newsgroup-highest))
		   (subject (gnus-simplify-subject
			     (mail-header-subject header)))
		   (refs (split-string (or (mail-header-references header)
					   "")))
		   (gnus-parse-headers-hook
                    (let ((refs (append refs (list id subject))))
		      (lambda ()
                        (goto-char (point-min))
		        (keep-lines (regexp-opt refs))))))
	      (gnus-fetch-headers (list last) (if (numberp limit)
						  (* 2 limit) limit)
                                  t))))
	 article-ids new-unreads)
    (when (listp new-headers)
      (dolist (header new-headers)
	(push (mail-header-number header) article-ids))
      (setq article-ids (nreverse article-ids))
      (setq new-unreads
	    (gnus-sorted-intersection gnus-newsgroup-unselected article-ids))
      (setq gnus-newsgroup-unselected
	    (gnus-sorted-ndifference gnus-newsgroup-unselected new-unreads))
      (setq gnus-newsgroup-unreads
	    (gnus-sorted-nunion gnus-newsgroup-unreads new-unreads))
      (setq gnus-newsgroup-headers
            (gnus-delete-duplicate-headers
             (cl-merge
              'list gnus-newsgroup-headers new-headers
              'gnus-article-sort-by-number)))
      (setq gnus-newsgroup-articles
	    (gnus-sorted-nunion gnus-newsgroup-articles article-ids))
      (gnus-summary-limit-include-thread id gnus-refer-thread-limit-to-thread)))
  (gnus-summary-show-thread))

(defun gnus-summary-open-group-with-article (message-id)
  "Open a group containing the article with the given MESSAGE-ID."
  (interactive "sMessage-ID: " gnus-summary-mode)
  (require 'nndoc)
  (with-temp-buffer
    ;; Prepare a dummy article
    (erase-buffer)
    (insert "From nobody Tue Sep 13 22:05:34 2011\n\n")

    ;; Prepare pretty modelines for summary and article buffers
    (let ((gnus-summary-mode-line-format "Found %G")
          (gnus-article-mode-line-format
           ;; Group names just get in the way here, especially the
           ;; abbreviated ones
           (if (string-match "%[gG]" gnus-article-mode-line-format)
	       (concat (substring gnus-article-mode-line-format
				  0 (match-beginning 0))
		       (substring gnus-article-mode-line-format (match-end 0)))
	     gnus-article-mode-line-format)))

      ;; Build an ephemeral group containing the dummy article (hidden)
      (gnus-group-read-ephemeral-group
       message-id
       `(nndoc ,message-id
	       (nndoc-address ,(current-buffer))
	       (nndoc-article-type mbox))
       :activate
       (cons (current-buffer) gnus-current-window-configuration)
       (not :request-only)
       '(-1)				; :select-articles
       (not :parameters)
       0))				; :number
    ;; Fetch the desired article
    (gnus-summary-refer-article message-id)))

(defun gnus-summary-refer-article (message-id)
  "Fetch an article specified by MESSAGE-ID."
  (interactive "sMessage-ID: " gnus-summary-mode)
  (when (and (stringp message-id)
	     (not (zerop (length message-id))))
    (setq message-id (string-replace " " "" message-id))
    ;; Construct the correct Message-ID if necessary.
    ;; Suggested by tale@pawl.rpi.edu.
    (unless (string-match "^<" message-id)
      (setq message-id (concat "<" message-id)))
    (unless (string-match ">$" message-id)
      (setq message-id (concat message-id ">")))
    ;; People often post MIDs from URLs, so unhex it:
    (unless (string-search "@" message-id)
      (setq message-id (gnus-url-unhex-string message-id)))
    (let* ((header (gnus-id-to-header message-id))
	   (sparse (and header
			(gnus-summary-article-sparse-p
			 (mail-header-number header))
			(memq (mail-header-number header)
			      gnus-newsgroup-limit)))
	   number)
      (cond
       ;; If the article is present in the buffer we just go to it.
       ((and header
	     (or (not (gnus-summary-article-sparse-p
		       (mail-header-number header)))
		 sparse))
	(prog1
	    (gnus-summary-goto-article
	     (mail-header-number header) nil t)
	  (when sparse
	    (gnus-summary-update-article (mail-header-number header)))))
       (t
	;; We fetch the article.
	(catch 'found
	  (dolist (gnus-override-method (gnus-refer-article-methods))
	    (when (and (gnus-check-server gnus-override-method)
		       ;; Fetch the header,
		       (setq number (gnus-summary-insert-subject message-id)))
	      ;; and display the article.
	      (gnus-summary-select-article nil nil nil number)
	      (throw 'found t)))
	  (gnus-message 3 "Couldn't fetch article %s" message-id)))))))

(defun gnus-refer-article-methods ()
  "Return a list of referable methods."
  (cond
   ;; No method, so we default to current and native.
   ((null gnus-refer-article-method)
    (list gnus-current-select-method gnus-select-method))
   ;; Current.
   ((eq 'current gnus-refer-article-method)
    (list gnus-current-select-method))
   ;; List of select methods.
   ((not (and (symbolp (car gnus-refer-article-method))
	      (assq (car gnus-refer-article-method) nnoo-definition-alist)))
    (let (out)
      (dolist (method gnus-refer-article-method)
	(push (if (eq 'current method)
		  gnus-current-select-method
		(if (eq 'nnselect (car method))
		    (list
		     'nnselect
		     (or (cadr method)
			 (gnus-method-to-server gnus-current-select-method)))
		  method))
	      out))
      (nreverse out)))
   ;; One single select method.
   (t
    (list gnus-refer-article-method))))

(defun gnus-summary-edit-parameters ()
  "Edit the group parameters of the current group."
  (interactive nil gnus-summary-mode)
  (gnus-group-edit-group gnus-newsgroup-name 'params))

(defun gnus-summary-customize-parameters ()
  "Customize the group parameters of the current group."
  (interactive nil gnus-summary-mode)
  (gnus-group-customize gnus-newsgroup-name))

(defun gnus-summary-enter-digest-group (&optional force)
  "Enter an nndoc group based on the current article.
If FORCE, force a digest interpretation.  If not, try to guess
what the document format is.

To control what happens when you exit the group, see the
`gnus-auto-select-on-ephemeral-exit' variable."
  (interactive "P" gnus-summary-mode)
  (let ((conf gnus-current-window-configuration))
    (save-window-excursion
      (save-excursion
	(let (gnus-article-prepare-hook
	      gnus-display-mime-function
	      gnus-break-pages)
	  (gnus-summary-select-article))))
    (setq gnus-current-window-configuration conf)
    (let* ((name (format "%s-%d"
			 (gnus-group-prefixed-name
			  gnus-newsgroup-name (list 'nndoc ""))
			 (with-current-buffer gnus-summary-buffer
			   gnus-current-article)))
	   (ogroup gnus-newsgroup-name)
	   (params (append (gnus-info-params (gnus-get-info ogroup))
			   (list (cons 'to-group ogroup))
			   (list (cons 'parent-group ogroup))
			   (list (cons 'save-article-group ogroup))))
	   (case-fold-search t)
	   (buf (current-buffer))
	   dig to-address charset)
      (with-current-buffer gnus-original-article-buffer
	;; Have the digest group inherit the main mail address of
	;; the parent article.
	(when (setq to-address (or (gnus-fetch-field "reply-to")
				   (gnus-fetch-field "from")))
	  (setq params
		(append
		 params
		 (list (cons 'to-address
			     (funcall gnus-decode-encoded-address-function
				      to-address))))))
	(setq dig (nnheader-set-temp-buffer " *gnus digest buffer*"))
	(insert-buffer-substring gnus-original-article-buffer)
	(narrow-to-region
	 (goto-char (point-min))
	 (or (search-forward "\n\n" nil t) (point)))
	;; Remove lines that may lead nndoc to misinterpret the
	;; document type.
	(goto-char (point-min))
	(delete-matching-lines "^Path:\\|^From ")
	;; Parse charset, and decode content transfer encoding.
	(setq charset (mail-content-type-get
		       (mail-header-parse-content-type
			(or (gnus-fetch-field "content-type") ""))
		       'charset))
	(let ((encoding (gnus-fetch-field "content-transfer-encoding")))
	  (when encoding
	    (message-remove-header "content-transfer-encoding")
	    (goto-char (point-max))
	    (widen)
	    (narrow-to-region (point) (point-max))
	    (mm-decode-content-transfer-encoding
	     (intern (downcase (mail-header-strip-cte encoding))))))
	(widen))
      (unwind-protect
	  (if (let ((gnus-newsgroup-ephemeral-charset
		     (if charset
			 (intern (downcase (gnus-strip-whitespace charset)))
		       gnus-newsgroup-charset))
		    (gnus-newsgroup-ephemeral-ignored-charsets
		     gnus-newsgroup-ignored-charsets))
		(gnus-group-read-ephemeral-group
		 name `(nndoc ,name (nndoc-address ,(get-buffer dig))
			      (nndoc-article-type
			       ,(if force 'mbox 'guess)))
		 t nil nil nil
		 `((adapt-file . ,(gnus-score-file-name gnus-newsgroup-name
							"ADAPT")))))
	      ;; Make all postings to this group go to the parent group.
	      (nconc (gnus-info-params (gnus-get-info name))
		     params)
	    ;; Couldn't select this doc group.
	    (switch-to-buffer buf)
	    (gnus-set-global-variables)
	    (gnus-configure-windows 'summary)
	    (gnus-message 3 "Article couldn't be entered?"))
	(kill-buffer dig)))))

(defun gnus-summary-read-document (n)
  "Open a new group based on the current article(s).
This will allow you to read digests and other similar
documents as newsgroups.
Obeys the standard process/prefix convention."
  (interactive "P" gnus-summary-mode)
  (let* ((ogroup gnus-newsgroup-name)
	 (params (append (gnus-info-params (gnus-get-info ogroup))
			 (list (cons 'to-group ogroup))))
	 group egroup groups vgroup)
    (dolist (article (gnus-summary-work-articles n))
      (setq group (format "%s-%d" gnus-newsgroup-name article))
      (gnus-summary-remove-process-mark article)
      (when (gnus-summary-display-article article)
	(save-excursion ;;What for?
	  (with-temp-buffer
	    (insert-buffer-substring gnus-original-article-buffer)
	    ;; Remove some headers that may lead nndoc to make
	    ;; the wrong guess.
	    (message-narrow-to-head)
	    (goto-char (point-min))
	    (delete-matching-lines "^Path:\\|^From ")
	    (widen)
	    (if (setq egroup
		      (gnus-group-read-ephemeral-group
		       group `(nndoc ,group (nndoc-address ,(current-buffer))
				     (nndoc-article-type guess))
		       t nil t))
		(progn
                  ;; Make all postings to this group go to the parent group.
		  (nconc (gnus-info-params (gnus-get-info egroup))
			 params)
		  (push egroup groups))
	      ;; Couldn't select this doc group.
	      (gnus-error 3 "Article couldn't be entered"))))))
    ;; Now we have selected all the documents.
    (cond
     ((not groups)
      (error "None of the articles could be interpreted as documents"))
     ((gnus-group-read-ephemeral-group
       (setq vgroup (format
		     "nnvirtual:%s-%s" gnus-newsgroup-name
		     (format-time-string "%Y%m%dT%H%M%S")))
       `(nnvirtual ,vgroup (nnvirtual-component-groups ,groups))
       t
       (cons (current-buffer) 'summary)))
     (t
      (error "Couldn't select virtual nndoc group")))))

(define-obsolete-function-alias 'gnus-summary-widget-forward
  #'gnus-summary-button-forward "27.1")
(defun gnus-summary-button-forward (arg)
  "Move point to the next field or button in the article.
With optional ARG, move across that many fields."
  (interactive "p" gnus-summary-mode)
  (gnus-summary-select-article)
  (gnus-configure-windows 'article)
  (let ((win (or (gnus-get-buffer-window gnus-article-buffer t)
                 (error "No article window found"))))
    (select-window win)
    (select-frame-set-input-focus (window-frame win))
    (forward-button arg)))

(define-obsolete-function-alias 'gnus-summary-widget-backward
  #'gnus-summary-button-backward "27.1")
(defun gnus-summary-button-backward (arg)
  "Move point to the previous field or button in the article.
With optional ARG, move across that many fields."
  (interactive "p" gnus-summary-mode)
  (gnus-summary-select-article)
  (gnus-configure-windows 'article)
  (let ((win (or (gnus-get-buffer-window gnus-article-buffer t)
                 (error "No article window found"))))
    (select-window win)
    (select-frame-set-input-focus (window-frame win))
    (unless (button-at (point))
      (goto-char (point-max)))
    (backward-button arg)))

(defcustom gnus-collect-urls-primary-text "Link"
  "The button text for the default link in `gnus-summary-browse-url'."
  :version "27.1"
  :type 'string
  :group 'gnus-article-various)

(defun gnus-collect-urls ()
  "Return the list of URLs in the buffer after (point).
The 1st element is the button named by `gnus-collect-urls-primary-text'."
  (let ((pt (point)) urls primary)
    (while (forward-button 1 nil nil t)
      (setq pt (point))
      (when-let ((w (button-at pt))
                 (u (or (button-get w 'shr-url)
                        (get-text-property pt 'gnus-string))))
	(when (string-match-p "\\`[[:alpha:]]+://" u)
          (if (and gnus-collect-urls-primary-text (null primary)
                   (string= gnus-collect-urls-primary-text (button-label w)))
              (setq primary u)
	    (push u urls)))))
    (setq urls (nreverse urls))
    (when primary
      (push primary urls))
    (delete-dups urls)))

(defun gnus-shorten-url (url max)
  "Return an excerpt from URL not exceeding MAX characters."
  (if (<= (length url) max)
      url
    (let* ((parsed (url-generic-parse-url url))
           (host (url-host parsed))
           (rest (concat (url-filename parsed)
                         (when-let ((target (url-target parsed)))
                           (concat "#" target)))))
      (concat host (string-truncate-left rest (- max (length host)))))))

(defun gnus-summary-browse-url (&optional external)
  "Scan the current article body for links, and offer to browse them.

Links are opened using `browse-url' unless a prefix argument is
given: Then `browse-url-secondary-browser-function' is used instead.

If only one link is found, browse that directly, otherwise use
completion to select a link.  The first link marked in the
article text with `gnus-collect-urls-primary-text' is the
default."
  (interactive "P" gnus-summary-mode)
  (let (urls target)
    (gnus-summary-select-article)
    (gnus-with-article-buffer
      (article-goto-body)
      ;; Back up a char, in case body starts with a button.
      (backward-char)
      (setq urls (gnus-collect-urls))
      (setq target
	    (cond ((= (length urls) 1)
		   (car urls))
		  ((> (length urls) 1)
		   (completing-read
		    (format-prompt "URL to browse"
				   (gnus-shorten-url (car urls) 40))
		    urls nil t nil nil (car urls)))))
      (if target
	  (if external
	      (funcall browse-url-secondary-browser-function target)
	    (browse-url target))
	(message "No URLs found.")))))

(defun gnus-summary-isearch-article (&optional regexp-p)
  "Do incremental search forward on the current article.
If REGEXP-P (the prefix) is non-nil, do regexp isearch."
  (interactive "P" gnus-summary-mode)
  (gnus-summary-select-article)
  (gnus-configure-windows 'article)
  (gnus-eval-in-buffer-window gnus-article-buffer
    (save-restriction
      (widen)
      (isearch-forward regexp-p))))

(defun gnus-summary-repeat-search-article-forward ()
  "Repeat the previous search forwards."
  (interactive nil gnus-summary-mode)
  (unless gnus-last-search-regexp
    (error "No previous search"))
  (gnus-summary-search-article-forward gnus-last-search-regexp))

(defun gnus-summary-repeat-search-article-backward ()
  "Repeat the previous search backwards."
  (interactive nil gnus-summary-mode)
  (unless gnus-last-search-regexp
    (error "No previous search"))
  (gnus-summary-search-article-forward gnus-last-search-regexp t))

(defun gnus-summary-search-article-forward (regexp &optional backward)
  "Search for an article containing REGEXP forward.
If BACKWARD, search backward instead."
  (interactive
   (list
    (read-string
     (format-prompt "Search article %s (regexp)"
                    gnus-last-search-regexp
                    (if current-prefix-arg "backward" "forward")))
    current-prefix-arg)
   gnus-summary-mode)
  (if (string-equal regexp "")
      (setq regexp (or gnus-last-search-regexp ""))
    (setq gnus-last-search-regexp regexp)
    (setq gnus-article-before-search gnus-current-article))
  ;; Intentionally set gnus-last-article.
  (setq gnus-last-article gnus-article-before-search)
  (let ((gnus-last-article gnus-last-article))
    (if (gnus-summary-search-article regexp backward)
	(gnus-summary-show-thread)
      (signal 'search-failed (list regexp)))))

(defun gnus-summary-search-article-backward (regexp)
  "Search for an article containing REGEXP backward."
  (interactive
   (list
    (read-string
     (format-prompt "Search article backward (regexp)"
                    gnus-last-search-regexp)))
   gnus-summary-mode)
  (gnus-summary-search-article-forward regexp 'backward))

(defun gnus-summary-search-article (regexp &optional backward)
  "Search for an article containing REGEXP.
Optional argument BACKWARD means do search for backward.
`gnus-select-article-hook' is not called during the search."
  ;; We have to require this here to make sure that the following
  ;; dynamic binding isn't shadowed by autoloading.
  (require 'gnus-async)
  (require 'gnus-art)
  (let ((gnus-select-article-hook nil)	;Disable hook.
	(gnus-article-prepare-hook nil)
	(gnus-mark-article-hook nil)	;Inhibit marking as read.
	(gnus-use-article-prefetch nil)
	(gnus-use-trees nil)		;Inhibit updating tree buffer.
	(gnus-visual nil)
	(gnus-keep-backlog nil)
	(gnus-break-pages nil)
	(gnus-summary-display-arrow nil)
	(gnus-updated-mode-lines nil)
	(gnus-auto-center-summary nil)
	(sum (current-buffer))
	(gnus-display-mime-function nil)
	(found nil)
	point)
    (gnus-save-hidden-threads
      (gnus-summary-select-article)
      (set-buffer gnus-article-buffer)
      (goto-char (window-point (get-buffer-window (current-buffer))))
      (when backward
	(forward-line -1))
      (while (not found)
	(gnus-message 7 "Searching article: %d..." (cdr gnus-article-current))
	(if (if backward
		(re-search-backward regexp nil t)
	      (re-search-forward regexp nil t))
	    ;; We found the regexp.
	    (progn
	      (setq found 'found)
	      (beginning-of-line)
	      (set-window-start
	       (get-buffer-window (current-buffer))
	       (point))
	      (forward-line 1)
	      (set-window-point
	       (get-buffer-window (current-buffer))
	       (point))
	      (set-buffer sum)
	      (setq point (point)))
	  ;; We didn't find it, so we go to the next article.
	  (set-buffer sum)
	  (setq found 'not)
	  (while (eq found 'not)
	    (if (not (if backward (gnus-summary-find-prev)
		       (gnus-summary-find-next)))
		;; No more articles.
		(setq found t)
	      ;; Select the next article and adjust point.
	      (unless (gnus-summary-article-sparse-p
		       (gnus-summary-article-number))
		(setq found nil)
		(gnus-summary-select-article)
		(set-buffer gnus-article-buffer)
		(widen)
		(goto-char (if backward (point-max) (point-min))))))))
      (gnus-message 7 ""))
    ;; Return whether we found the regexp.
    (when (eq found 'found)
      (goto-char point)
      (sit-for 0) ;; Ensure that the point is visible in the summary window.
      (gnus-summary-show-thread)
      (gnus-summary-goto-subject gnus-current-article)
      (gnus-summary-position-point)
      t)))

(defun gnus-find-matching-articles (header regexp)
  "Return a list of all articles that match REGEXP on HEADER.
This search includes all articles in the current group that Gnus has
fetched headers for, whether they are displayed or not."
  (let ((articles nil)
	(func (intern (concat "mail-header-" header)))
	(case-fold-search t))
    (dolist (header gnus-newsgroup-headers)
      ;; FIXME: when called from gnus-summary-limit-include-thread via
      ;; gnus-summary-limit-include-matching-articles, `regexp' is a decoded
      ;; string whereas the header isn't decoded.
      (when (string-match regexp (funcall func header))
	(push (mail-header-number header) articles)))
    (nreverse articles)))

(defun gnus-summary-find-matching (header regexp &optional backward unread
					  not-case-fold not-matching)
  "Return a list of all articles that match REGEXP on HEADER.
The search stars on the current article and goes forwards unless
BACKWARD is non-nil.  If BACKWARD is `all', do all articles.
If UNREAD is non-nil, only unread articles will
be taken into consideration.  If NOT-CASE-FOLD, case won't be folded
in the comparisons.  If NOT-MATCHING, return a list of all articles
that not match REGEXP on HEADER."
  (let ((case-fold-search (not not-case-fold))
	articles func)
    (if (consp header)
	(if (eq (car header) 'extra)
	    (setq func
                  (let ((x (cdr header)))
		    (lambda (h)
		      (or (cdr (assq x (mail-header-extra h)))
			  ""))))
	  (error "%s is an invalid header" header))
      (unless (fboundp (intern (concat "mail-header-" header)))
	(error "%s is not a valid header" header))
      (setq func (intern (concat "mail-header-" header))))
    (dolist (d (if (eq backward 'all)
		   gnus-newsgroup-data
		 (gnus-data-find-list
		  (gnus-summary-article-number)
		  (gnus-data-list backward))))
      (when (and (or (not unread)	; We want all articles...
		     (gnus-data-unread-p d)) ; Or just unreads.
		 (mail-header-p (gnus-data-header d)) ; It's not a pseudo.
		 (if not-matching
		     (not (string-match
			   regexp
			   (funcall func (gnus-data-header d))))
		   (string-match regexp
				 (funcall func (gnus-data-header d)))))
	(push (gnus-data-number d) articles))) ; Success!
    (nreverse articles)))

(defun gnus-summary-execute-command (header regexp command &optional backward)
  "Search forward for an article whose HEADER matches REGEXP and execute COMMAND.
If HEADER is an empty string (or nil), the match is done on the entire
article.  If BACKWARD (the prefix) is non-nil, search backward instead."
  (interactive
   (list
    (let ((completion-ignore-case t))
      (gnus-completing-read
       "Header name"
       (mapcar #'symbol-name
	       (append
		'(Number Subject From Lines Date Message-ID
			 Xref References Body)
		gnus-extra-headers))
       'require-match))
    (read-string "Regexp: ")
    (read-key-sequence "Command: ")
    current-prefix-arg)
   gnus-summary-mode)
  (when (equal header "Body")
    (setq header ""))
  ;; Hidden thread subtrees must be searched as well.
  (gnus-summary-show-all-threads)
  ;; We don't want to change current point nor window configuration.
  (save-excursion
    (save-window-excursion
      (let (gnus-visual
	    gnus-treat-strip-trailing-blank-lines
	    gnus-treat-strip-leading-blank-lines
	    gnus-treat-strip-multiple-blank-lines
	    gnus-treat-hide-boring-headers
	    gnus-treat-fold-newsgroups
	    gnus-article-prepare-hook)
	(gnus-message 6 "Executing %s..." (key-description command))
	;; We'd like to execute COMMAND interactively so as to give arguments.
	(gnus-execute header regexp
		      `(call-interactively ',(key-binding command))
		      backward)
	(gnus-message 6 "Executing %s...done" (key-description command))))))

(defun gnus-summary-beginning-of-article ()
  "Scroll the article back to the beginning."
  (interactive nil gnus-summary-mode)
  (gnus-summary-select-article)
  (gnus-configure-windows 'article)
  (gnus-eval-in-buffer-window gnus-article-buffer
    (widen)
    (goto-char (point-min))
    (when gnus-break-pages
      (gnus-narrow-to-page))))

(defun gnus-summary-end-of-article ()
  "Scroll to the end of the article."
  (interactive nil gnus-summary-mode)
  (gnus-summary-select-article)
  (gnus-configure-windows 'article)
  (gnus-eval-in-buffer-window gnus-article-buffer
    (widen)
    (goto-char (point-max))
    (recenter -3)
    (when gnus-break-pages
      (gnus-narrow-to-page))))

(defun gnus-summary-print-truncate-and-quote (string &optional len)
  "Truncate to LEN and quote all \"(\"'s in STRING."
  (replace-regexp-in-string "[()]" "\\\\\\&"
			    (if (and len (> (length string) len))
				(substring string 0 len)
			      string)))

(defun gnus-summary-print-article (&optional filename n)
  "Generate and print a PostScript image of the process-marked (mail) articles.

If used interactively, print the current article if none are
process-marked.  With prefix arg, prompt the user for the name of the
file to save in.

When used from Lisp, accept two optional args FILENAME and N.  N means
to print the next N articles.  If N is negative, print the N previous
articles.  If N is nil and articles have been marked with the process
mark, print these instead.

If the optional first argument FILENAME is nil, send the image to the
printer.  If FILENAME is a string, save the PostScript image in a file with
that name.  If FILENAME is a number, prompt the user for the name of the file
to save in."
  (interactive
   (list (ps-print-preprint current-prefix-arg))
   gnus-summary-mode)
  (dolist (article (gnus-summary-work-articles n))
    (gnus-summary-select-article nil nil 'pseudo article)
    (gnus-eval-in-buffer-window gnus-article-buffer
      (gnus-print-buffer))
    (gnus-summary-remove-process-mark article))
  (ps-despool filename))

(defvar ps-right-header)
(defvar ps-left-header)
(defvar shr-ignore-cache)

(defun gnus-print-buffer ()
  (let ((ps-left-header
	 (list
	  (concat "("
		  (gnus-summary-print-truncate-and-quote
		   (mail-header-subject gnus-current-headers)
		   66) ")")
	  (concat "("
		  (gnus-summary-print-truncate-and-quote
		   (mail-header-from gnus-current-headers)
		   45) ")")))
	(ps-right-header
	 (list
	  "/pagenumberstring load"
	  (concat "("
		  (mail-header-date gnus-current-headers) ")"))))
    (gnus-run-hooks 'gnus-ps-print-hook)
    (save-excursion
      (if ps-print-color-p
	  (ps-spool-buffer-with-faces)
	(ps-spool-buffer)))))

(declare-function gnus-flush-original-article-buffer "gnus-art" ())

(defun gnus-summary-show-complete-article ()
  "Show a complete version of the current article.
This is only useful if you're looking at a partial version of the
article currently."
  (interactive nil gnus-summary-mode)
  (let ((gnus-keep-backlog nil)
	(gnus-use-cache nil)
	(gnus-agent nil)
	(variable (intern
		   (format "%s-fetch-partial-articles"
			   (car (gnus-find-method-for-group
				 gnus-newsgroup-name)))
		   obarray))
	old-val)
    (unwind-protect
	(progn
	  (setq old-val (symbol-value variable))
	  (set variable nil)
	  (gnus-flush-original-article-buffer)
	  (gnus-summary-show-article))
      (set variable old-val))))

(defun gnus-summary-show-article (&optional arg)
  "Force redisplaying of the current article.
If ARG (the prefix) is a number, show the article with the charset
defined in `gnus-summary-show-article-charset-alist', or the charset
input.
If ARG (the prefix) is non-nil and not a number, show the article,
but without running any of the article treatment functions
article.  Normally, the keystroke is `C-u g'.  When using `C-u
C-u g', show the raw article."
  (interactive "P" gnus-summary-mode)
  (cond
   ((numberp arg)
    (gnus-summary-show-article t)
    (let ((gnus-newsgroup-charset
	   (or (cdr (assq arg gnus-summary-show-article-charset-alist))
	       (read-coding-system
		"View as charset: " ;; actually it is coding system.
		(with-current-buffer gnus-article-buffer
		  (mm-detect-coding-region (point) (point-max))))))
	  (gnus-newsgroup-ignored-charsets 'gnus-all))
      (gnus-summary-select-article nil 'force)
      (let ((deps gnus-newsgroup-dependencies)
	    head header lines)
	(with-current-buffer gnus-original-article-buffer
	  (save-restriction
	    (message-narrow-to-head)
	    (setq head (buffer-string))
	    (goto-char (point-min))
	    (unless (re-search-forward "^lines:[ \t]\\([0-9]+\\)" nil t)
	      (goto-char (point-max))
	      (widen)
	      (setq lines (1- (count-lines (point) (point-max))))))
	  (with-temp-buffer
	    (insert (format "211 %d Article retrieved.\n"
			    (cdr gnus-article-current)))
	    (insert head)
	    (if lines (insert (format "Lines: %d\n" lines)))
	    (insert ".\n")
	    (let ((nntp-server-buffer (current-buffer)))
	      (setq header (car (gnus-get-newsgroup-headers deps t))))))
	(setf (gnus-data-header
	       (gnus-data-find (cdr gnus-article-current)))
	      header)
	(gnus-summary-update-article-line
	 (cdr gnus-article-current) header)
	(when (gnus-summary-goto-subject (cdr gnus-article-current) nil t)
	  (gnus-summary-update-secondary-mark (cdr gnus-article-current))))))
   ((not arg)
    ;; Select the article the normal way.
    (if (eq mm-text-html-renderer 'shr)
	(progn
	  (require 'shr)
	  (let ((shr-ignore-cache t))
	    (gnus-summary-select-article nil 'force)))
      (gnus-summary-select-article nil 'force)))
   ((equal arg '(16))
    ;; C-u C-u g
    (let ((gnus-inhibit-article-treatments t))
      (gnus-summary-select-article nil 'force)))
   (t
    ;; We have to require this here to make sure that the following
    ;; dynamic binding isn't shadowed by autoloading.
    (require 'gnus-async)
    (require 'gnus-art)
    ;; Bind the article treatment functions to nil.
    (let ((gnus-have-all-headers t)
	  gnus-article-prepare-hook
	  gnus-article-decode-hook
	  gnus-display-mime-function
	  gnus-break-pages)
      ;; Destroy any MIME parts.
      (when (gnus-buffer-live-p gnus-article-buffer)
	(with-current-buffer gnus-article-buffer
	  (gnus-article-stop-animations)
	  (gnus-stop-downloads)
	  (mm-destroy-parts gnus-article-mime-handles)
	  ;; Set it to nil for safety reason.
	  (setq gnus-article-mime-handle-alist nil)
	  (setq gnus-article-mime-handles nil)))
      (gnus-summary-select-article nil 'force))))
  (gnus-summary-goto-subject gnus-current-article)
  (gnus-summary-position-point))

(defun gnus-summary-show-raw-article ()
  "Show the raw article without any article massaging functions being run."
  (interactive nil gnus-summary-mode)
  (gnus-summary-show-article t))

(defun gnus-summary-verbose-headers (&optional arg)
  "Toggle permanent full header display.
If ARG is a positive number, turn header display on.
If ARG is a negative number, turn header display off."
  (interactive "P" gnus-summary-mode)
  (setq gnus-show-all-headers
	(cond ((or (not (numberp arg))
		   (zerop arg))
	       (not gnus-show-all-headers))
	      ((natnump arg)
	       t)))
  (gnus-summary-show-article))

(declare-function article-narrow-to-head "gnus-art" ())
(declare-function gnus-article-hidden-text-p "gnus-art" (type))
(declare-function gnus-delete-wash-type "gnus-art" (type))
(declare-function gnus-mime-buttonize-attachments-in-header
		  "gnus-art" (&optional interactive))

(defun gnus-summary-toggle-header (&optional arg)
  "Show the headers if they are hidden, or hide them if they are shown.
If ARG is a positive number, show the entire header.
If ARG is a negative number, hide the unwanted header lines."
  (interactive "P" gnus-summary-mode)
  (let ((window (and (gnus-buffer-live-p gnus-article-buffer)
		     (get-buffer-window gnus-article-buffer t))))
    (with-current-buffer gnus-article-buffer
      (widen)
      (article-narrow-to-head)
      (let* ((inhibit-read-only t)
	     (inhibit-point-motion-hooks t)
	     (hidden (if (numberp arg)
			 (>= arg 0)
		       (or
			;; The case where there's no visible header
			;; that matches `gnus-visible-headers'.
			(looking-at "\n?\\'")
			(gnus-article-hidden-text-p 'headers))))
	     s e)
	(delete-region (point-min) (point-max))
	(with-current-buffer gnus-original-article-buffer
	  (goto-char (setq s (point-min)))
	  (setq e (if (search-forward "\n\n" nil t)
		      (1- (point))
		    (point-max))))
	(insert-buffer-substring gnus-original-article-buffer s e)
	(run-hooks 'gnus-article-decode-hook)
	(if hidden
	    (let ((gnus-treat-hide-headers nil)
		  (gnus-treat-hide-boring-headers nil))
	      (gnus-delete-wash-type 'headers)
	      (gnus-treat-article 'head))
	  (gnus-treat-article 'head)
	  ;; Add attachment buttons to the header.
	  (when gnus-mime-display-attachment-buttons-in-header
	    (gnus-mime-buttonize-attachments-in-header)))
	(widen)
	(if window
	    (set-window-start window (goto-char (point-min))))
	(if gnus-break-pages
	    (gnus-narrow-to-page)
	  (when (gnus-visual-p 'page-marker)
	    (let ((inhibit-read-only t))
	      (gnus-remove-text-with-property 'gnus-prev)
	      (gnus-remove-text-with-property 'gnus-next))))
	(gnus-set-mode-line 'article)))))

(defun gnus-summary-show-all-headers ()
  "Make all header lines visible."
  (interactive nil gnus-summary-mode)
  (gnus-summary-toggle-header 1))

(defun gnus-summary-caesar-message (&optional arg)
  "Caesar rotate the current article by 13.
With a non-numerical prefix, also rotate headers.  A numerical
prefix specifies how many places to rotate each letter forward."
  (interactive "P" gnus-summary-mode)
  (gnus-summary-select-article)
  (let ((mail-header-separator ""))
    (gnus-eval-in-buffer-window gnus-article-buffer
      (save-restriction
	(widen)
	(let ((start (window-start))
	      (inhibit-read-only t))
	  (if (equal arg '(4))
	      (message-caesar-buffer-body nil t)
	    (message-caesar-buffer-body arg))
	  (set-window-start (get-buffer-window (current-buffer)) start)))))
  ;; Create buttons and stuff...
  (gnus-treat-article nil))

(defun gnus-summary-idna-message (&optional _arg)
  "Decode IDNA encoded domain names in the current articles.
IDNA encoded domain names looks like `xn--bar'.  If a string
remain unencoded after running this function, it is likely an
invalid IDNA string (`xn--bar' is invalid).

You must have GNU Libidn (URL `https://www.gnu.org/software/libidn/')
installed for this command to work."
  (interactive nil gnus-summary-mode)
  (gnus-summary-select-article)
  (let ((mail-header-separator ""))
    (gnus-eval-in-buffer-window gnus-article-buffer
      (save-restriction
	(widen)
	(let ((start (window-start))
	      buffer-read-only)
	  (while (re-search-forward "\\(xn--[-0-9a-z]+\\)" nil t)
	    (replace-match (puny-decode-domain (match-string 1))))
	  (set-window-start (get-buffer-window (current-buffer)) start))))))

(defun gnus-summary-morse-message (&optional _arg)
  "Morse decode the current article."
  (interactive nil gnus-summary-mode)
  (gnus-summary-select-article)
  (let ((mail-header-separator ""))
    (gnus-eval-in-buffer-window gnus-article-buffer
      (save-excursion
	(save-restriction
	  (widen)
	  (let ((pos (window-start))
		(inhibit-read-only t))
	    (goto-char (point-min))
	    (when (message-goto-body)
	      (gnus-narrow-to-body))
	    (goto-char (point-min))
	    (while (search-forward "·" (point-max) t)
	      (replace-match "."))
	    (unmorse-region (point-min) (point-max))
	    (widen)
	    (set-window-start (get-buffer-window (current-buffer)) pos)))))))

(defun gnus-summary-stop-page-breaking ()
  "Stop page breaking in the current article."
  (interactive nil gnus-summary-mode)
  (gnus-summary-select-article)
  (gnus-eval-in-buffer-window gnus-article-buffer
    (widen)
    (when (gnus-visual-p 'page-marker)
      (let ((inhibit-read-only t))
	(gnus-remove-text-with-property 'gnus-prev)
	(gnus-remove-text-with-property 'gnus-next))
      (setq gnus-page-broken nil))))

(defun gnus-summary-move-article (&optional n to-newsgroup
					    select-method action)
  "Move the current article to a different newsgroup.
If N is a positive number, move the N next articles.
If N is a negative number, move the N previous articles.
If N is nil and any articles have been marked with the process mark,
move those articles instead.
If TO-NEWSGROUP is string, do not prompt for a newsgroup to move to.
If SELECT-METHOD is non-nil, do not move to a specific newsgroup, but
re-spool using this method.

When called interactively with TO-NEWSGROUP being nil, the value of
the variable `gnus-move-split-methods' is used for finding a default
for the target newsgroup.

For this function to work, both the current newsgroup and the
newsgroup that you want to move to have to support the `request-move'
and `request-accept' functions.

ACTION can be either `move' (the default), `crosspost' or `copy'."
  (interactive "P" gnus-summary-mode)
  (unless action
    (setq action 'move))
  ;; Check whether the source group supports the required functions.
  (cond ((and (eq action 'move)
	      (not (gnus-check-backend-function
		    'request-move-article gnus-newsgroup-name)))
	 (user-error "The current group does not support article moving"))
	((and (eq action 'crosspost)
	      (not (gnus-check-backend-function
		    'request-replace-article gnus-newsgroup-name)))
	 (user-error "The current group does not support article editing")))
  (let ((articles (gnus-summary-work-articles n))
	(prefix (if (gnus-check-backend-function
		     'request-move-article gnus-newsgroup-name)
		    (funcall gnus-move-group-prefix-function
			     gnus-newsgroup-name)
		  ""))
	(names '((move "Move" "Moving")
		 (copy "Copy" "Copying")
		 (crosspost "Crosspost" "Crossposting")))
	(copy-buf (save-excursion
		    (nnheader-set-temp-buffer " *copy article*")))
	art-group to-method new-xref article to-groups
	articles-to-update-marks)
    (unless (assq action names)
      (error "Unknown action %s" action))
    ;; Read the newsgroup name.
    (unless (or to-newsgroup select-method)
      (if (and gnus-move-split-methods
	       (not
		(and (memq gnus-current-article articles)
		     (gnus-buffer-live-p gnus-original-article-buffer))))
	  ;; When `gnus-move-split-methods' is non-nil, we have to
	  ;; select an article to give `gnus-read-move-group-name' an
	  ;; opportunity to suggest an appropriate default.  However,
	  ;; we needn't render or mark the article.
	  (let ((gnus-display-mime-function nil)
		(gnus-article-prepare-hook nil)
		(gnus-mark-article-hook nil))
	    (gnus-summary-select-article nil nil nil (car articles))))
      (setq to-newsgroup (gnus-read-move-group-name
			  (cadr (assq action names))
			  (symbol-value
			   (intern (format "gnus-current-%s-group" action)))
			  articles prefix)
	    to-method (gnus-server-to-method (gnus-group-method to-newsgroup)))
      (set (intern (format "gnus-current-%s-group" action)) to-newsgroup))
    (unless to-method
      (setq to-method (or select-method
			  (gnus-server-to-method
			   (gnus-group-method to-newsgroup)))))
    ;; Check the method we are to move this article to...
    (unless (gnus-check-backend-function
	     'request-accept-article (car to-method))
      (error "%s does not support article copying" (car to-method)))
    (unless (gnus-check-server to-method)
      (error "Can't open server %s" (car to-method)))
    (gnus-message 6 "%s to %s: %s..."
		  (caddr (assq action names))
		  (or (car select-method)
		      to-newsgroup)
		  articles)
    ;; This `while' is not equivalent to a `dolist' (bug#33653#134).
    (while articles
      (setq article (pop articles))
      ;; Set any marks that may have changed in the summary buffer.
      (when gnus-preserve-marks
	(gnus-summary-push-marks-to-backend article))
      (setq
       art-group
       (cond
	;; Move the article.
	((eq action 'move)
         (when gnus-suppress-duplicates
           ;; Remove this article from future suppression.
           (gnus-dup-unsuppress-article article))
	 (let* ((from-method (gnus-find-method-for-group
			      gnus-newsgroup-name))
		(to-method (or select-method
			       (gnus-find-method-for-group to-newsgroup)))
		(move-is-internal (gnus-server-equal from-method to-method)))
	   (gnus-request-move-article
	    article			; Article to move
	    gnus-newsgroup-name         ; From newsgroup
	    (nth 1 (gnus-find-method-for-group
		    gnus-newsgroup-name)) ; Server
	    (list 'gnus-request-accept-article
		  to-newsgroup (list 'quote select-method)
		  (not articles) t)	; Accept form
	    (not articles)		; Only save nov last time
	    (and move-is-internal
		 to-newsgroup		; Not respooling
					; Is this move internal?
		 (gnus-group-real-name to-newsgroup)))))
	;; Copy the article.
	((eq action 'copy)
	 (with-current-buffer copy-buf
	   (when (gnus-request-article-this-buffer article
						   gnus-newsgroup-name)
	     (save-restriction
	       (nnheader-narrow-to-headers)
	       (dolist (hdr gnus-copy-article-ignored-headers)
		 (message-remove-header hdr t)))
	     (gnus-request-accept-article
	      to-newsgroup select-method (not articles) t))))
	;; Crosspost the article.
	((eq action 'crosspost)
	 (let ((xref (message-tokenize-header
		      (mail-header-xref (gnus-summary-article-header
					 article))
		      " ")))
	   (setq new-xref (concat (gnus-group-real-name gnus-newsgroup-name)
				  ":" (number-to-string article)))
	   (unless xref
	     (setq xref (list (system-name))))
	   (setq new-xref
		 (concat
		  (mapconcat #'identity
			     (delete "Xref:" (delete new-xref xref))
			     " ")
		  " " new-xref))
	   (with-current-buffer copy-buf
	     ;; First put the article in the destination group.
	     (gnus-request-article-this-buffer article gnus-newsgroup-name)
	     (when (consp (setq art-group
				(gnus-request-accept-article
				 to-newsgroup select-method (not articles)
				 t)))
	       (setq new-xref (concat new-xref " " (car art-group)
				      ":"
				      (number-to-string (cdr art-group))))
	       ;; Now we have the new Xrefs header, so we insert
	       ;; it and replace the new article.
	       (nnheader-replace-header "Xref" new-xref)
	       (gnus-request-replace-article
		(cdr art-group) to-newsgroup (current-buffer) t)
	       art-group))))))
      (cond
       ((not art-group)
	(gnus-message 1 "Couldn't %s article %s: %s"
		      (cadr (assq action names)) article
		      (nnheader-get-report (car to-method))))
       ((eq art-group 'junk)
	(when (eq action 'move)
	  (gnus-summary-mark-article article gnus-canceled-mark)
	  (gnus-message 4 "Deleted article %s" article)
	  ;; run the delete hook
	  (run-hook-with-args 'gnus-summary-article-delete-hook
			      action
			      (gnus-data-header
			       (gnus-data-find-in article (gnus-data-list nil)))
			      gnus-newsgroup-name nil
			      select-method)))
       (t
	(let* ((pto-group (gnus-group-prefixed-name
			   (car art-group) to-method))
	       (info (gnus-get-info pto-group))
	       (to-group (gnus-info-group info))
	       to-marks)
	  ;; Update the group that has been moved to.
	  (when (and info
		     (memq action '(move copy)))
	    (unless (member to-group to-groups)
	      (push to-group to-groups))

	    (when (and (not (memq article gnus-newsgroup-unreads))
		       (cdr art-group))
	      (push 'read to-marks)
	      (setf (gnus-info-read info)
		    (gnus-add-to-range (gnus-info-read info)
				       (list (cdr art-group)))))

	    ;; See whether the article is to be put in the cache.
	    (let* ((expirable (gnus-group-auto-expirable-p to-group))
		   (marks (if expirable
			      gnus-article-mark-lists
			    (delete '(expirable . expire)
				    (copy-sequence
				     gnus-article-mark-lists))))
		   (to-article (cdr art-group)))

	      ;; Enter the article into the cache in the new group,
	      ;; if that is required.
	      (when (and to-article
			 gnus-use-cache)
		(gnus-cache-possibly-enter-article
		 to-group to-article
		 (memq article gnus-newsgroup-marked)
		 (memq article gnus-newsgroup-dormant)
		 (memq article gnus-newsgroup-unreads)))

	      (when (and gnus-preserve-marks
			 to-article)
		;; Copy any marks over to the new group.
		(when (and (equal to-group gnus-newsgroup-name)
			   (not (memq article gnus-newsgroup-unreads)))
		  ;; Mark this article as read in this group.
		  (push (cons to-article gnus-read-mark)
			gnus-newsgroup-reads)
		  ;; Increase the active status of this group.
		  (setcdr (gnus-active to-group) to-article)
		  (setcdr gnus-newsgroup-active to-article))

		(while marks
		  (when (eq (gnus-article-mark-to-type (cdar marks)) 'list)
		    (when (memq article (symbol-value
					 (intern (format "gnus-newsgroup-%s"
							 (caar marks)))))
		      (push (cdar marks) to-marks)
		      ;; If the other group is the same as this group,
		      ;; then we have to add the mark to the list.
		      (when (equal to-group gnus-newsgroup-name)
			(set (intern (format "gnus-newsgroup-%s"
					     (caar marks)))
			     (cons to-article
				   (symbol-value
				    (intern (format "gnus-newsgroup-%s"
						    (caar marks)))))))
		      ;; Copy the marks to other group.
		      (gnus-add-marked-articles
		       to-group (cdar marks) (list to-article) info)))
		  (setq marks (cdr marks)))

		(when (and expirable
			   gnus-mark-copied-or-moved-articles-as-expirable
			   (not (memq 'expire to-marks)))
		  ;; Mark this article as expirable.
		  (push 'expire to-marks)
		  (when (equal to-group gnus-newsgroup-name)
		    (push to-article gnus-newsgroup-expirable))
		  ;; Copy the expirable mark to other group.
		  (gnus-add-marked-articles
		   to-group 'expire (list to-article) info))

		(when (and to-marks
			   (gnus-method-option-p
			    (gnus-find-method-for-group to-group)
			    'server-marks))
		  (gnus-request-set-mark
		   to-group (list (list (list to-article) 'add to-marks)))))

	      (gnus-dribble-enter
	       (concat "(gnus-group-set-info '"
		       (gnus-prin1-to-string (gnus-get-info to-group))
		       ")")
	       (concat "^(gnus-group-set-info '(\""
		       (regexp-quote to-group) "\""))))

	  ;; Update the Xref header in this article to point to
	  ;; the new crossposted article we have just created.
	  (when (eq action 'crosspost)
	    (with-current-buffer copy-buf
	      (gnus-request-article-this-buffer article gnus-newsgroup-name)
	      (nnheader-replace-header "Xref" new-xref)
	      (gnus-request-replace-article
	       article gnus-newsgroup-name (current-buffer) t)))

	  ;; run the move/copy/crosspost/respool hook
	  (run-hook-with-args 'gnus-summary-article-move-hook
			      action
			      (gnus-data-header (gnus-data-find article))
			      gnus-newsgroup-name
			      to-newsgroup
			      select-method))

        ;;!!!Why is this necessary?
	(set-buffer gnus-summary-buffer)

	(when (eq action 'move)
	  (save-excursion
	    (gnus-summary-goto-subject article)
	    (gnus-summary-mark-article article gnus-canceled-mark)))))
      (push article articles-to-update-marks))

    (save-excursion
      (apply #'gnus-summary-remove-process-mark articles-to-update-marks))
    ;; Re-activate all groups that have been moved to.
    (with-current-buffer gnus-group-buffer
      (let ((gnus-group-marked to-groups))
	(gnus-group-get-new-news-this-group nil t)))

    (gnus-kill-buffer copy-buf)
    (gnus-summary-position-point)
    (gnus-set-mode-line 'summary)))

(defun gnus-summary-push-marks-to-backend (article)
  (let ((set nil)
	(del nil)
	(marks gnus-article-mark-lists))
    (unless (memq article gnus-newsgroup-unreads)
      (push 'read set))
    (while marks
      (if (and (eq (gnus-article-mark-to-type (cdar marks)) 'list)
	       (memq article (symbol-value
			      (intern (format "gnus-newsgroup-%s"
					      (caar marks))))))
	  (push (cdar marks) set)
	(push (cdar marks) del))
      (pop marks))
    (gnus-request-set-mark gnus-newsgroup-name `(((,article) set ,set)
						 ((,article) del ,del)))))

(defun gnus-summary-copy-article (&optional n to-newsgroup select-method)
  "Copy the current article to some other group.
Arguments have the same meanings as in `gnus-summary-move-article'."
  (interactive "P" gnus-summary-mode)
  (gnus-summary-move-article n to-newsgroup select-method 'copy))

(defun gnus-summary-crosspost-article (&optional n)
  "Crosspost the current article to some other group.
Arguments have the same meanings as in `gnus-summary-move-article'."
  (interactive "P" gnus-summary-mode)
  (gnus-summary-move-article n nil nil 'crosspost))

(defcustom gnus-summary-respool-default-method nil
  "Default method type for respooling an article.
If nil, use to the current newsgroup method."
  :type 'symbol
  :group 'gnus-summary-mail)

(defun gnus-summary-respool-article (&optional n method)
  "Respool the current article.
The article will be squeezed through the mail spooling process again,
which means that it will be put in some mail newsgroup or other
depending on `nnmail-split-methods'.
If N is a positive number, respool the N next articles.
If N is a negative number, respool the N previous articles.
If N is nil and any articles have been marked with the process mark,
respool those articles instead.

Respooling can be done both from mail groups and \"real\" newsgroups.
In the former case, the articles in question will be moved from the
current group into whatever groups they are destined to.  In the
latter case, they will be copied into the relevant groups."
  (interactive
   (list current-prefix-arg
	 (let* ((methods (mapcar #'car (gnus-methods-using 'respool)))
		(methname
		 (symbol-name (or gnus-summary-respool-default-method
				  (car (gnus-find-method-for-group
					gnus-newsgroup-name)))))
		(method
		 (gnus-completing-read
		  "Backend to use when respooling"
		  methods t nil 'gnus-mail-method-history methname))
		ms)
	   (cond
	    ((zerop (length (setq ms (gnus-servers-using-backend
				      (intern method)))))
	     (list (intern method) ""))
	    ((= 1 (length ms))
	     (car ms))
	    (t
	     (let ((ms-alist (mapcar (lambda (m) (cons (cadr m) m)) ms)))
	       (cdr (assoc (gnus-completing-read "Server name" ms-alist t)
			   ms-alist)))))))
   gnus-summary-mode)
  (unless method
    (error "No method given for respooling"))
  (if (assoc (symbol-name
	      (car (gnus-find-method-for-group gnus-newsgroup-name)))
	     (gnus-methods-using 'respool))
      (gnus-summary-move-article n nil method)
    (gnus-summary-copy-article n nil method)))

(defun gnus-summary-import-article (file &optional edit)
  "Import an arbitrary file into a mail newsgroup."
  (interactive "fImport file: \nP" gnus-summary-mode)
  (let ((group gnus-newsgroup-name)
	atts lines group-art)
    (unless (gnus-check-backend-function 'request-accept-article group)
      (error "%s does not support article importing" group))
    (or (file-readable-p file)
	(not (file-regular-p file))
	(error "Can't read %s" file))
    (with-current-buffer (gnus-get-buffer-create " *import file*")
      (erase-buffer)
      (nnheader-insert-file-contents file)
      (goto-char (point-min))
      (if (nnheader-article-p)
	  (save-restriction
	    (goto-char (point-min))
	    (search-forward "\n\n" nil t)
	    (narrow-to-region (point-min) (1- (point)))
	    (goto-char (point-min))
	    (unless (re-search-forward "^date:" nil t)
	      (goto-char (point-max))
	      (setq atts (file-attributes file))
	      (insert "Date: " (message-make-date
				(file-attribute-modification-time atts))
		      "\n")))
       ;; This doesn't look like an article, so we fudge some headers.
	(setq atts (file-attributes file)
	      lines (count-lines (point-min) (point-max)))
	(insert "From: " (read-string "From: ") "\n"
		"Subject: " (read-string "Subject: ") "\n"
		"Date: " (message-make-date
			  (file-attribute-modification-time atts)) "\n"
		"Message-ID: " (message-make-message-id) "\n"
		"Lines: " (int-to-string lines) "\n"
		"Chars: " (int-to-string (file-attribute-size atts)) "\n\n"))
      (setq group-art (gnus-request-accept-article group nil t))
      (kill-buffer (current-buffer)))
    (setq gnus-newsgroup-active (gnus-activate-group group))
    (forward-line 1)
    (gnus-summary-goto-article (cdr group-art) nil t)
    (when edit
      (gnus-summary-edit-article))))

(defun gnus-summary-create-article ()
  "Create an article in a mail newsgroup."
  (interactive nil gnus-summary-mode)
  (let ((group gnus-newsgroup-name)
	(now (current-time))
	group-art)
    (unless (gnus-check-backend-function 'request-accept-article group)
      (error "%s does not support article importing" group))
    (with-current-buffer (gnus-get-buffer-create " *import file*")
      (erase-buffer)
      (goto-char (point-min))
      ;; This doesn't look like an article, so we fudge some headers.
      (insert "From: " (read-string "From: ") "\n"
	      "Subject: " (read-string "Subject: ") "\n"
	      "Date: " (message-make-date now) "\n"
	      "Message-ID: " (message-make-message-id) "\n")
      (setq group-art (gnus-request-accept-article group nil t))
      (kill-buffer (current-buffer)))
    (setq gnus-newsgroup-active (gnus-activate-group group))
    (forward-line 1)
    (gnus-summary-goto-article (cdr group-art) nil t)
    (gnus-summary-edit-article)))

(defun gnus-summary-article-posted-p ()
  "Say whether the current (mail) article is available from news as well.
This will be the case if the article has both been mailed and posted."
  (interactive nil gnus-summary-mode)
  (let ((id (mail-header-references (gnus-summary-article-header)))
	(gnus-override-method (car (gnus-refer-article-methods))))
    (if (gnus-request-head id "")
	(gnus-message 2 "The current message was found on %s"
		      gnus-override-method)
      (gnus-message 2 "The current message couldn't be found on %s"
		    gnus-override-method)
      nil)))

(defun gnus-summary-expire-articles (&optional now)
  "Expire all articles that are marked as expirable in the current group."
  (interactive nil gnus-summary-mode)
  (when (and (not gnus-group-is-exiting-without-update-p)
	     (gnus-check-backend-function
	      'request-expire-articles gnus-newsgroup-name))
    ;; This backend supports expiry.
    (let* ((total (gnus-group-total-expirable-p gnus-newsgroup-name))
	   (expirable
	    (gnus-list-range-difference
	     (if total
		 (progn
		   ;; We need to update the info for
		   ;; this group for `gnus-list-of-read-articles'
		   ;; to give us the right answer.
		   (gnus-run-hooks 'gnus-exit-group-hook)
		   (gnus-summary-update-info)
		   (gnus-list-of-read-articles gnus-newsgroup-name))
	       (setq gnus-newsgroup-expirable
		     (sort gnus-newsgroup-expirable #'<)))
	     gnus-newsgroup-unexist))
	   (expiry-wait (if now 'immediate
			  (gnus-group-find-parameter
			   gnus-newsgroup-name 'expiry-wait)))
	   (nnmail-expiry-target
	    (or (gnus-group-find-parameter gnus-newsgroup-name 'expiry-target)
		nnmail-expiry-target))
	   es)
      (when expirable
	;; There are expirable articles in this group, so we run them
	;; through the expiry process.
	(gnus-message 6 "Expiring articles...")
	(when (gnus-check-group gnus-newsgroup-name)
	  ;; The list of articles that weren't expired is returned.
	  (save-excursion
	    (if expiry-wait
		(let ((nnmail-expiry-wait-function nil)
		      (nnmail-expiry-wait expiry-wait))
		  (setq es (gnus-request-expire-articles
			    expirable gnus-newsgroup-name)))
	      (setq es (gnus-request-expire-articles
			expirable gnus-newsgroup-name)))
	    (unless total
	      (setq gnus-newsgroup-expirable es))
	    ;; We go through the old list of expirable, and mark all
	    ;; really expired articles as nonexistent.
	    (unless (eq es expirable) ;If nothing was expired, we don't mark.
	      (let ((gnus-use-cache nil))
		(dolist (article expirable)
		  (when (and (not (memq article es))
			     (gnus-data-find article))
		    (gnus-summary-mark-article article gnus-canceled-mark)
		    (run-hook-with-args
		     'gnus-summary-article-expire-hook
		     'delete
		     (gnus-data-header (gnus-data-find article))
		     gnus-newsgroup-name
		     (cond
		      ((stringp nnmail-expiry-target) nnmail-expiry-target)
		      ((eq nnmail-expiry-target 'delete) nil)
		      (t
		       (let ((rescall (funcall nnmail-expiry-target
					       gnus-newsgroup-name)))
			 (if (stringp rescall) rescall nil))))
		     nil)))))))
	(gnus-message 6 "Expiring articles...done")))))

(defun gnus-summary-expire-articles-now ()
  "Expunge all expirable articles in the current group.
This means that *all* articles that are marked as expirable will be
deleted forever, right now."
  (interactive nil gnus-summary-mode)
  (or gnus-expert-user
      (gnus-yes-or-no-p
       "Are you really, really sure you want to delete all expirable messages? ")
      (error "Phew!"))
  (gnus-summary-expire-articles t))

;; Suggested by Jack Vinson <vinson@unagi.cis.upenn.edu>.
(defun gnus-summary-delete-article (&optional n)
  "Delete the N next (mail) articles.
This command actually deletes articles.  This is not a marking
command.  The article will disappear forever from your life, never to
return.

If N is negative, delete backwards.
If N is nil and articles have been marked with the process mark,
delete these instead.

If `gnus-novice-user' is non-nil you will be asked for
confirmation before the articles are deleted."
  (interactive "P" gnus-summary-mode)
  (unless (gnus-check-backend-function 'request-expire-articles
				       gnus-newsgroup-name)
    (error "The current newsgroup does not support article deletion"))
  (unless (gnus-check-server (gnus-find-method-for-group gnus-newsgroup-name))
    (error "Couldn't open server"))
  ;; Compute the list of articles to delete.
  (let ((articles (sort (copy-sequence (gnus-summary-work-articles n)) #'<))
	(nnmail-expiry-target 'delete)
	not-deleted)
    (if (and gnus-novice-user
	     (not (gnus-yes-or-no-p
		   (format "Do you really want to delete %s forever? "
			   (if (> (length articles) 1)
			       (format "these %s articles" (length articles))
			     "this article")))))
	()
      ;; Delete the articles.
      (setq not-deleted (gnus-request-expire-articles
			 articles gnus-newsgroup-name 'force))
      (save-excursion
	(while articles
	  (gnus-summary-remove-process-mark (car articles))
	  ;; The backend might not have been able to delete the article
	  ;; after all.
	  (unless (memq (car articles) not-deleted)
	    (gnus-summary-mark-article (car articles) gnus-canceled-mark)
	    (let* ((article (car articles))
		   (ghead  (gnus-data-header (gnus-data-find article))))
	      (run-hook-with-args 'gnus-summary-article-delete-hook
				  'delete ghead gnus-newsgroup-name nil
				  nil)))
	  (setq articles (cdr articles))))
      (when not-deleted
	(gnus-message 4 "Couldn't delete articles %s" not-deleted)))
    (gnus-summary-position-point)
    (gnus-set-mode-line 'summary)
    not-deleted))

(defvar message-options-set-recipient)

(defun gnus-summary-edit-article (&optional arg)
  "Edit the current article.
This will have permanent effect only in mail groups.
If ARG is nil, edit the decoded articles.
If ARG is 1, edit the raw articles.
If ARG is 2, edit the raw articles even in read-only groups.
If ARG is 3, edit the articles with the current handles.
Otherwise, allow editing of articles even in read-only
groups."
  (interactive "P" gnus-summary-mode)
  (let (force raw current-handles)
    (cond
     ((null arg))
     ((eq arg 1)
      (setq raw t))
     ((eq arg 2)
      (setq raw t
	    force t))
     ((eq arg 3)
      (setq current-handles
	    (and (gnus-buffer-live-p gnus-article-buffer)
		 (with-current-buffer gnus-article-buffer
		   (prog1
		       gnus-article-mime-handles
		     (setq gnus-article-mime-handles nil))))))
     (t
      (setq force t)))
    (when (and raw (not force)
	       (member gnus-newsgroup-name '("nndraft:delayed"
					     "nndraft:drafts"
					     "nndraft:queue")))
      (error "Can't edit the raw article in group %s"
	     gnus-newsgroup-name))
    (with-current-buffer gnus-summary-buffer
      (let ((mail-parse-charset gnus-newsgroup-charset)
	    (mail-parse-ignored-charsets gnus-newsgroup-ignored-charsets))
	(gnus-set-global-variables)
	(when (and (not force)
		   (gnus-group-read-only-p))
	  (error "The current newsgroup does not support article editing"))
	(gnus-summary-show-article t)
	(when (and (not raw) (gnus-buffer-live-p gnus-article-buffer))
	  (with-current-buffer gnus-article-buffer
	    (mm-enable-multibyte)))
	(if (member gnus-newsgroup-name '("nndraft:delayed" "nndraft:drafts"))
	    (setq raw t))
	(gnus-article-edit-article
	 (if raw 'ignore
	   (lambda ()
	     (let ((mbl mml-buffer-list))
	       (setq mml-buffer-list nil)
	       (let ((rfc2047-quote-decoded-words-containing-tspecials t))
		 (mime-to-mml current-handles))
	       (let ((mbl1 mml-buffer-list))
		 (setq mml-buffer-list mbl)
                 (setq-local mml-buffer-list mbl1))
	       (add-hook 'kill-buffer-hook #'mml-destroy-buffers t t))))
	 (let ((charset gnus-newsgroup-charset)
	       (ign-cs gnus-newsgroup-ignored-charsets)
	       (hea (let ((charset (gnus-group-name-charset
				    (gnus-find-method-for-group
				     gnus-newsgroup-name)
				    gnus-newsgroup-name)))
		      (append (list (cons "Newsgroups" charset)
				    (cons "Followup-To" charset)
				    (cons "Xref" charset))
			      rfc2047-header-encoding-alist)))
	       (gch (or (mail-header-references gnus-current-headers) ""))
	       (ro (gnus-group-read-only-p))
	       (buf gnus-summary-buffer))
	   (lambda (no-highlight)
	     (let ((mail-parse-charset charset)
		   (message-options message-options)
		   (message-options-set-recipient)
		   (mail-parse-ignored-charsets ign-cs)
		   (rfc2047-header-encoding-alist hea))
	       (unless raw
		 (mml-to-mime)
		 (mml-destroy-buffers)
		 (remove-hook 'kill-buffer-hook
			      #'mml-destroy-buffers t)
		 (kill-local-variable 'mml-buffer-list))
	       (gnus-summary-edit-article-done gch ro buf no-highlight)))))))))

(defalias 'gnus-summary-edit-article-postpone 'gnus-article-edit-exit)

(defun gnus-summary-edit-article-done (&optional references read-only buffer
						 no-highlight)
  "Make edits to the current article permanent."
  (interactive nil gnus-summary-mode)
  (save-excursion
    ;; The buffer restriction contains the entire article if it exists.
    (when (article-goto-body)
      (let ((lines (count-lines (point) (point-max)))
	    (length (- (point-max) (point)))
	    (case-fold-search t)
	    (body (point-marker)))
	(goto-char (point-min))
	(when (re-search-forward "^content-length:[ \t]\\([0-9]+\\)" body t)
	  (delete-region (match-beginning 1) (match-end 1))
	  (insert (number-to-string length)))
	(goto-char (point-min))
	(when (re-search-forward
	       "^x-content-length:[ \t]\\([0-9]+\\)" body t)
	  (delete-region (match-beginning 1) (match-end 1))
	  (insert (number-to-string length)))
	(goto-char (point-min))
	(when (re-search-forward "^lines:[ \t]\\([0-9]+\\)" body t)
	  (delete-region (match-beginning 1) (match-end 1))
	  (insert (number-to-string lines))))))
  ;; Replace the article.
  (let ((buf (current-buffer))
	(article (cdr gnus-article-current))
	replace-result)
    (with-temp-buffer
      (insert-buffer-substring buf)
      (if (and (not read-only)
	       (not (setq replace-result
			  (gnus-request-replace-article
			   article (car gnus-article-current)
			   (current-buffer) t))))
	  (error "Couldn't replace article")
	;; If we got a number back, then that's the new article number
	;; for this article.  Otherwise, the article number didn't change.
	(when (numberp replace-result)
	  (with-current-buffer gnus-summary-buffer
	    (setq gnus-newsgroup-limit (delq article gnus-newsgroup-limit))
	    (gnus-summary-limit gnus-newsgroup-limit)
	    (setq article replace-result)
	    (gnus-summary-goto-subject article t)))
	;; Update the summary buffer.
	(if (and references
		 (equal (message-tokenize-header references " ")
			(message-tokenize-header
			 (or (message-fetch-field "references") "") " ")))
	    ;; We only have to update this line.
	    (save-excursion
	      (save-restriction
		(nnheader-ms-strip-cr)
		(message-narrow-to-head)
		(let ((head (buffer-substring-no-properties
			     (point-min) (point-max)))
		      header)
		  (with-temp-buffer
		    (insert (format "211 %d Article retrieved.\n" article))
		    (insert head)
		    (insert ".\n")
		    (let ((nntp-server-buffer (current-buffer)))
		      (setq header (car (gnus-get-newsgroup-headers nil t))))
		    (with-current-buffer gnus-summary-buffer
		      (setf (gnus-data-header (gnus-data-find article)) header)
		      (gnus-summary-update-article-line article header)
		      (if (gnus-summary-goto-subject article nil t)
			  (gnus-summary-update-secondary-mark article)))))))
	  ;; Update threads.
	  (set-buffer (or buffer gnus-summary-buffer))
	  (gnus-summary-update-article article)
	  (if (gnus-summary-goto-subject article nil t)
	      (gnus-summary-update-secondary-mark article)))
	;; Prettify the article buffer again.
	(unless no-highlight
	  (with-current-buffer gnus-article-buffer
	    ;;!!! Fix this -- article should be rehighlighted.
	    ;;(gnus-run-hooks 'gnus-article-display-hook)
	    (set-buffer gnus-original-article-buffer)
	    (gnus-request-article
	     article (car gnus-article-current) (current-buffer))))
	;; Prettify the summary buffer line.
	(when (gnus-visual-p 'summary-highlight 'highlight)
	  (gnus-run-hooks 'gnus-visual-mark-article-hook))))))

(defun gnus-summary-edit-wash (key)
  "Perform editing command KEY in the article buffer."
  (interactive
   (list
    (progn
      (message "%s" (concat (this-command-keys) "- "))
      (read-char)))
   gnus-summary-mode)
  (message "")
  (gnus-summary-edit-article)
  (execute-kbd-macro (concat (this-command-keys) key))
  (gnus-article-edit-done))

;;; Respooling

(defvar nnimap-split-fancy)
(defvar nnimap-split-methods)

(defun gnus-summary-respool-query (&optional silent trace)
  "Query where the respool algorithm would put this article."
  (interactive nil gnus-summary-mode)
  (let (gnus-mark-article-hook)
    (gnus-summary-select-article)
    (with-current-buffer gnus-original-article-buffer
      (let ((groups
	     (if (eq (car (gnus-find-method-for-group gnus-newsgroup-name))
		     'nnimap)
		 ;; nnimap has its own splitting variables.
		 (let ((nnmail-split-methods
			(cond
			 ((eq nnimap-split-methods 'default)
			  nnmail-split-methods)
			 (nnimap-split-methods
			  nnimap-split-methods)
			 (nnimap-split-fancy
			  'nnmail-split-fancy)))
		       (nnmail-split-fancy (or nnimap-split-fancy
					       nnmail-split-fancy)))
		   (nnmail-article-group 'identity trace))
	       (nnmail-article-group 'identity trace))))
	(unless silent
	  (if groups
	      (message "This message would go to %s"
		       (mapconcat #'car groups ", "))
	    (message "This message would go to no groups"))
	  groups)))))

(defun gnus-summary-respool-trace ()
  "Trace where the respool algorithm would put this article.
Display a buffer showing all fancy splitting patterns which matched."
  (interactive nil gnus-summary-mode)
  (gnus-summary-respool-query nil t))

;; Summary marking commands.

(defun gnus-summary-kill-same-subject-and-select (&optional unmark)
  "Mark articles which has the same subject as read, and then select the next.
If UNMARK is positive, remove any kind of mark.
If UNMARK is negative, tick articles."
  (interactive "P" gnus-summary-mode)
  (when unmark
    (setq unmark (prefix-numeric-value unmark)))
  (let ((count
	 (gnus-summary-mark-same-subject
	  (gnus-summary-article-subject) unmark)))
    ;; Select next unread article.  If auto-select-same mode, should
    ;; select the first unread article.
    (gnus-summary-next-article t (and gnus-auto-select-same
				      (gnus-summary-article-subject)))
    (gnus-message 7 "%d article%s marked as %s"
		  count (if (= count 1) " is" "s are")
		  (if unmark "unread" "read"))))

(defun gnus-summary-kill-same-subject (&optional unmark)
  "Mark articles which has the same subject as read.
If UNMARK is positive, remove any kind of mark.
If UNMARK is negative, tick articles."
  (interactive "P" gnus-summary-mode)
  (when unmark
    (setq unmark (prefix-numeric-value unmark)))
  (let ((count
	 (gnus-summary-mark-same-subject
	  (gnus-summary-article-subject) unmark)))
    ;; If marked as read, go to next unread subject.
    (when (null unmark)
      ;; Go to next unread subject.
      (gnus-summary-next-subject 1 t))
    (gnus-message 7 "%d articles are marked as %s"
		  count (if unmark "unread" "read"))))

(defun gnus-summary-mark-same-subject (subject &optional unmark)
  "Mark articles with same SUBJECT as read, and return marked number.
If optional argument UNMARK is positive, remove any kinds of marks.
If optional argument UNMARK is negative, mark articles as unread instead."
  (let ((count 1))
    (save-excursion
      (cond
       ((null unmark)			; Mark as read.
	(while (and
		(progn
		  (gnus-summary-mark-article-as-read gnus-killed-mark)
		  (gnus-summary-show-thread) t)
		(gnus-summary-find-subject subject))
	  (setq count (1+ count))))
       ((> unmark 0)			; Tick.
	(while (and
		(progn
		  (gnus-summary-mark-article-as-unread gnus-ticked-mark)
		  (gnus-summary-show-thread) t)
		(gnus-summary-find-subject subject))
	  (setq count (1+ count))))
       (t				; Mark as unread.
	(while (and
		(progn
		  (gnus-summary-mark-article-as-unread gnus-unread-mark)
		  (gnus-summary-show-thread) t)
		(gnus-summary-find-subject subject))
	  (setq count (1+ count)))))
      (gnus-set-mode-line 'summary)
      ;; Return the number of marked articles.
      count)))

(defun gnus-summary-mark-as-processable (n &optional unmark)
  "Set the process mark on the next N articles.
If N is negative, mark backward instead.  If UNMARK is non-nil, remove
the process mark instead.  The difference between N and the actual
number of articles marked is returned."
  (interactive "P" gnus-summary-mode)
  (if (and (null n) (and transient-mark-mode mark-active))
      (gnus-uu-mark-region (region-beginning) (region-end) unmark)
    (setq n (prefix-numeric-value n))
    (let ((backward (< n 0))
	  (n (abs n)))
      (while (and
	      (> n 0)
	      (let ((article (gnus-summary-article-number)))
		(if unmark
		    (gnus-summary-remove-process-mark article)
		  (if gnus-process-mark-toggle
		      (if (memq article gnus-newsgroup-processable)
			  (gnus-summary-remove-process-mark article)
			(gnus-summary-set-process-mark article))
		    (gnus-summary-set-process-mark article))))
	      (zerop (gnus-summary-next-subject (if backward -1 1) nil t)))
	(setq n (1- n)))
      (when (/= 0 n)
	(gnus-message 7 "No more articles"))
      (gnus-summary-recenter)
      (gnus-summary-position-point)
      n)))

(defun gnus-summary-unmark-as-processable (n)
  "Remove the process mark from the next N articles.
If N is negative, unmark backward instead.  The difference between N and
the actual number of articles unmarked is returned."
  (interactive "P" gnus-summary-mode)
  (gnus-summary-mark-as-processable n t))

(defun gnus-summary-unmark-all-processable ()
  "Remove the process mark from all articles."
  (interactive nil gnus-summary-mode)
  (save-excursion
    (while gnus-newsgroup-processable
      (gnus-summary-remove-process-mark (car gnus-newsgroup-processable))))
  (gnus-summary-position-point))

(defun gnus-summary-add-mark (article type)
  "Mark ARTICLE with a mark of TYPE."
  (let ((vtype (car (assq type gnus-article-mark-lists)))
	var)
    (if (not vtype)
	(error "No such mark type: %s" type)
      (setq var (intern (format "gnus-newsgroup-%s" type)))
      (set var (cons article (symbol-value var)))
      (if (memq type '(processable cached replied forwarded recent saved))
	  (gnus-summary-update-secondary-mark article)
	;; !!! This is bogus.  We should find out what primary
	;; !!! mark we want to set.
	(gnus-summary-update-mark gnus-del-mark 'unread)))))

(defun gnus-summary-mark-as-expirable (n)
  "Mark N articles forward as expirable.
If N is negative, mark backward instead.  The difference between N and
the actual number of articles marked is returned."
  (interactive "p" gnus-summary-mode)
  (gnus-summary-mark-forward n gnus-expirable-mark))

(defun gnus-summary-mark-as-spam (n)
  "Mark N articles forward as spam.
If N is negative, mark backward instead.  The difference between N and
the actual number of articles marked is returned."
  (interactive "p" gnus-summary-mode)
  (gnus-summary-mark-forward n gnus-spam-mark))

(defun gnus-summary-mark-article-as-replied (article)
  "Mark ARTICLE as replied to and update the summary line.
ARTICLE can also be a list of articles."
  (interactive (list (gnus-summary-article-number))
	       gnus-summary-mode)
  (let ((articles (if (listp article) article (list article))))
    (dolist (article articles)
      (unless (numberp article)
	(error "%s is not a number" article))
      (push article gnus-newsgroup-replied)
      (let ((inhibit-read-only t))
	(when (gnus-summary-goto-subject article nil t)
	  (gnus-summary-update-secondary-mark article))))))

(defun gnus-summary-mark-article-as-forwarded (article)
  "Mark ARTICLE as forwarded and update the summary line.
ARTICLE can also be a list of articles."
  (let ((articles (if (listp article) article (list article))))
    (dolist (article articles)
      (push article gnus-newsgroup-forwarded)
      (let ((inhibit-read-only t))
	(when (gnus-summary-goto-subject article nil t)
	  (gnus-summary-update-secondary-mark article))))))

(defun gnus-summary-set-bookmark (article)
  "Set a bookmark in current article."
  (interactive (list (gnus-summary-article-number))
	       gnus-summary-mode)
  (when (or (not (get-buffer gnus-article-buffer))
	    (not gnus-current-article)
	    (not gnus-article-current)
	    (not (equal gnus-newsgroup-name (car gnus-article-current))))
    (error "No current article selected"))
  ;; Remove old bookmark, if one exists.
  (gnus-alist-pull article gnus-newsgroup-bookmarks)
  ;; Set the new bookmark, which is on the form
  ;; (article-number . line-number-in-body).
  (push
   (cons article
	 (with-current-buffer gnus-article-buffer
	   (count-lines
	    (min (point)
		 (save-excursion
		   (article-goto-body)
		   (point)))
	    (point))))
   gnus-newsgroup-bookmarks)
  (gnus-message 6 "A bookmark has been added to the current article."))

(defun gnus-summary-remove-bookmark (article)
  "Remove the bookmark from the current article."
  (interactive (list (gnus-summary-article-number))
	       gnus-summary-mode)
  ;; Remove old bookmark, if one exists.
  (if (not (assq article gnus-newsgroup-bookmarks))
      (gnus-message 6 "No bookmark in current article.")
    (gnus-alist-pull article gnus-newsgroup-bookmarks)
    (gnus-message 6 "Removed bookmark.")))

;; Suggested by Daniel Quinlan <quinlan@best.com>.
(defun gnus-summary-mark-as-dormant (n)
  "Mark N articles forward as dormant.
If N is negative, mark backward instead.  The difference between N and
the actual number of articles marked is returned."
  (interactive "p" gnus-summary-mode)
  (gnus-summary-mark-forward n gnus-dormant-mark))

(defun gnus-summary-set-process-mark (article)
  "Set the process mark on ARTICLE and update the summary line."
  (setq gnus-newsgroup-processable
	(cons article
	      (delq article gnus-newsgroup-processable)))
  (when (gnus-summary-goto-subject article)
    (gnus-summary-show-thread)
    (gnus-summary-goto-subject article)
    (gnus-summary-update-secondary-mark article)))

(defun gnus-summary-remove-process-mark (&rest articles)
  "Remove the process mark from ARTICLES and update the summary line."
  (dolist (article articles)
    (setq gnus-newsgroup-processable (delq article gnus-newsgroup-processable))
    (when (gnus-summary-goto-subject article)
      (gnus-summary-show-thread)
      (gnus-summary-goto-subject article)
      (gnus-summary-update-secondary-mark article)))
  t)

(defun gnus-summary-set-saved-mark (article)
  "Set the process mark on ARTICLE and update the summary line."
  (push article gnus-newsgroup-saved)
  (when (gnus-summary-goto-subject article)
    (gnus-summary-update-secondary-mark article)))

(defun gnus-summary-mark-forward (n &optional mark no-expire)
  "Mark N articles as read forwards.
If N is negative, mark backwards instead.  Mark with MARK, ?r by default.
The difference between N and the actual number of articles marked is
returned.
If NO-EXPIRE, auto-expiry will be inhibited."
  (interactive "p" gnus-summary-mode)
  (gnus-summary-show-thread)
  (let ((backward (< n 0))
	(gnus-summary-goto-unread
	 (and gnus-summary-goto-unread
	      (not (eq gnus-summary-goto-unread 'never))
	      (not (memq mark (list gnus-unread-mark gnus-spam-mark
				    gnus-ticked-mark gnus-dormant-mark)))))
	(n (abs n))
	(mark (or mark gnus-del-mark)))
    (while (and (> n 0)
		(gnus-summary-mark-article nil mark no-expire)
		(zerop (gnus-summary-next-subject
			(if backward -1 1)
			(and gnus-summary-goto-unread
			     (not (eq gnus-summary-goto-unread 'never)))
			t)))
      (setq n (1- n)))
    (when (/= 0 n)
      (gnus-message 7 "No more %sarticles" (if mark "" "unread ")))
    (gnus-summary-recenter)
    (gnus-summary-position-point)
    (gnus-set-mode-line 'summary)
    n))

(defun gnus-summary-mark-article-as-read (mark)
  "Mark the current article quickly as read with MARK."
  (let ((article (gnus-summary-article-number)))
    (setq gnus-newsgroup-unreads (delq article gnus-newsgroup-unreads))
    (setq gnus-newsgroup-marked (delq article gnus-newsgroup-marked))
    (setq gnus-newsgroup-spam-marked (delq article gnus-newsgroup-spam-marked))
    (setq gnus-newsgroup-dormant (delq article gnus-newsgroup-dormant))
    (push (cons article mark) gnus-newsgroup-reads)
    ;; Possibly remove from cache, if that is used.
    (when gnus-use-cache
      (gnus-cache-enter-remove-article article))
    ;; Allow the backend to change the mark.
    (setq mark (gnus-request-update-mark gnus-newsgroup-name article mark))
    ;; Check for auto-expiry.
    (when (and gnus-newsgroup-auto-expire
	       (memq mark gnus-auto-expirable-marks))
      (setq mark gnus-expirable-mark)
      ;; Let the backend know about the mark change.
      (setq mark (gnus-request-update-mark gnus-newsgroup-name article mark))
      (push article gnus-newsgroup-expirable))
    ;; Set the mark in the buffer.
    (gnus-summary-update-mark mark 'unread)
    t))

(defun gnus-summary-mark-article-as-unread (mark)
  "Mark the current article quickly as unread with MARK."
  (let* ((article (gnus-summary-article-number))
	 (old-mark (gnus-summary-article-mark article)))
    ;; Allow the backend to change the mark.
    (setq mark (gnus-request-update-mark gnus-newsgroup-name article mark))
    (if (eq mark old-mark)
	t
      (if (<= article 0)
	  (progn
	    (gnus-error 1 "Gnus doesn't know the article number; can't mark")
	    nil)
	(setq gnus-newsgroup-marked (delq article gnus-newsgroup-marked))
	(setq gnus-newsgroup-spam-marked
	      (delq article gnus-newsgroup-spam-marked))
	(setq gnus-newsgroup-dormant (delq article gnus-newsgroup-dormant))
	(setq gnus-newsgroup-expirable (delq article gnus-newsgroup-expirable))
	(setq gnus-newsgroup-reads (delq article gnus-newsgroup-reads))
	(setq gnus-newsgroup-unreads (delq article gnus-newsgroup-unreads))
	(cond ((= mark gnus-ticked-mark)
	       (setq gnus-newsgroup-marked
		     (gnus-add-to-sorted-list gnus-newsgroup-marked
					      article)))
	      ((= mark gnus-spam-mark)
	       (setq gnus-newsgroup-spam-marked
		     (gnus-add-to-sorted-list gnus-newsgroup-spam-marked
					      article)))
	      ((= mark gnus-dormant-mark)
	       (setq gnus-newsgroup-dormant
		     (gnus-add-to-sorted-list gnus-newsgroup-dormant
					      article)))
	      (t
	       (setq gnus-newsgroup-unreads
		     (gnus-add-to-sorted-list gnus-newsgroup-unreads
					      article))))
	(gnus-alist-pull article gnus-newsgroup-reads)

	;; See whether the article is to be put in the cache.
	(and gnus-use-cache
	     (mail-header-p (gnus-summary-article-header article))
	     (save-excursion
	       (gnus-cache-possibly-enter-article
		gnus-newsgroup-name article
		(= mark gnus-ticked-mark)
		(= mark gnus-dormant-mark) (= mark gnus-unread-mark))))

	;; Fix the mark.
	(gnus-summary-update-mark mark 'unread)
	t))))

(defun gnus-summary-mark-article (&optional article mark no-expire)
  "Mark ARTICLE with MARK.  MARK can be any character.
Four MARK strings are reserved: `? ' (unread), `?!' (ticked),
`??' (dormant) and `?E' (expirable).
If MARK is nil, then the default character `?r' is used.
If ARTICLE is nil, then the article on the current line will be
marked.
If NO-EXPIRE, auto-expiry will be inhibited."
  ;; The mark might be a string.
  (when (stringp mark)
    (setq mark (aref mark 0)))
  ;; If no mark is given, then we check auto-expiring.
  (when (null mark)
    (setq mark gnus-del-mark))
  (when (and (not no-expire)
	     gnus-newsgroup-auto-expire
	     (memq mark gnus-auto-expirable-marks))
    (setq mark gnus-expirable-mark))
  (let ((article (or article (gnus-summary-article-number)))
	(old-mark (gnus-summary-article-mark article)))
    ;; Allow the backend to change the mark.
    (setq mark (gnus-request-update-mark gnus-newsgroup-name article mark))
    (if (eq mark old-mark)
	t
      (unless article
	(error "No article on current line"))
      (if (not (if (or (= mark gnus-unread-mark)
		       (= mark gnus-ticked-mark)
		       (= mark gnus-spam-mark)
		       (= mark gnus-dormant-mark))
		   (gnus-mark-article-as-unread article mark)
		 (gnus-mark-article-as-read article mark)))
	  t
	;; See whether the article is to be put in the cache.
	(and gnus-use-cache
	     (not (= mark gnus-canceled-mark))
	     (mail-header-p (gnus-summary-article-header article))
	     (save-excursion
	       (gnus-cache-possibly-enter-article
		gnus-newsgroup-name article
		(= mark gnus-ticked-mark)
		(= mark gnus-dormant-mark) (= mark gnus-unread-mark))))

	(when (gnus-summary-goto-subject article nil t)
	  (let ((inhibit-read-only t))
	    (gnus-summary-show-thread)
	    ;; Fix the mark.
	    (gnus-summary-update-mark mark 'unread)
	    t))))))

(defun gnus-summary-update-secondary-mark (article)
  "Update the secondary (read, process, cache) mark."
  (gnus-summary-update-mark
   (cond ((memq article gnus-newsgroup-processable)
	  gnus-process-mark)
	 ((memq article gnus-newsgroup-cached)
	  gnus-cached-mark)
	 ((memq article gnus-newsgroup-replied)
	  gnus-replied-mark)
	 ((memq article gnus-newsgroup-forwarded)
	  gnus-forwarded-mark)
	 ((memq article gnus-newsgroup-saved)
	  gnus-saved-mark)
	 ((memq article gnus-newsgroup-unseen)
	  gnus-unseen-mark)
	 (t gnus-no-mark))
   'replied)
  (when (gnus-visual-p 'summary-highlight 'highlight)
    (gnus-summary-highlight-line)
    (gnus-run-hooks 'gnus-summary-update-hook))
  t)

(defun gnus-summary-update-download-mark (article)
  "Update the download mark."
  (gnus-summary-update-mark
   (cond ((memq article gnus-newsgroup-undownloaded)
          gnus-undownloaded-mark)
         (gnus-newsgroup-agentized
          gnus-downloaded-mark)
         (t
          gnus-no-mark))
   'download)
  (gnus-summary-update-line t)
  t)

(defun gnus-summary-update-mark (mark type)
  (let ((forward (cdr (assq type gnus-summary-mark-positions)))
	(inhibit-read-only t))
    (re-search-backward "[\n\r]" (point-at-bol) 'move-to-limit)
    (when forward
      (when (looking-at "\r")
	(cl-incf forward))
      (when (<= (+ forward (point)) (point-max))
	;; Go to the right position on the line.
	(goto-char (+ forward (point)))
	;; Replace the old mark with the new mark.
        (let ((to-insert
               (subst-char-in-string
		(char-after) mark
		(buffer-substring (point) (1+ (point))))))
          (delete-region (point) (1+ (point)))
          (insert to-insert))
	;; Optionally update the marks by some user rule.
	(when (eq type 'unread)
	  (setf (gnus-data-mark
	         (gnus-data-find (gnus-summary-article-number)))
                mark)
	  (gnus-summary-update-line (eq mark gnus-unread-mark)))))))

(defun gnus-mark-article-as-read (article &optional mark)
  "Enter ARTICLE in the pertinent lists and remove it from others."
  ;; Make the article expirable.
  (let ((mark (or mark gnus-del-mark)))
    (setq gnus-newsgroup-expirable
	  (if (= mark gnus-expirable-mark)
	      (gnus-add-to-sorted-list gnus-newsgroup-expirable article)
	    (delq article gnus-newsgroup-expirable)))
    ;; Remove from unread and marked lists.
    (setq gnus-newsgroup-unreads (delq article gnus-newsgroup-unreads))
    (setq gnus-newsgroup-marked (delq article gnus-newsgroup-marked))
    (setq gnus-newsgroup-spam-marked (delq article gnus-newsgroup-spam-marked))
    (setq gnus-newsgroup-dormant (delq article gnus-newsgroup-dormant))
    (push (cons article mark) gnus-newsgroup-reads)
    ;; Possibly remove from cache, if that is used.
    (when gnus-use-cache
      (gnus-cache-enter-remove-article article))
    t))

(defun gnus-mark-article-as-unread (article &optional mark)
  "Enter ARTICLE in the pertinent lists and remove it from others."
  (let ((mark (or mark gnus-ticked-mark)))
    (if (<= article 0)
	(progn
	  (gnus-error 1 "Gnus doesn't know the article number; can't mark")
	  nil)
      (setq gnus-newsgroup-marked (delq article gnus-newsgroup-marked)
	    gnus-newsgroup-spam-marked (delq article gnus-newsgroup-spam-marked)
	    gnus-newsgroup-dormant (delq article gnus-newsgroup-dormant)
	    gnus-newsgroup-expirable (delq article gnus-newsgroup-expirable)
	    gnus-newsgroup-unreads (delq article gnus-newsgroup-unreads))

      ;; Unsuppress duplicates?
      (when gnus-suppress-duplicates
	(gnus-dup-unsuppress-article article))

      (cond ((= mark gnus-ticked-mark)
	     (setq gnus-newsgroup-marked
		   (gnus-add-to-sorted-list gnus-newsgroup-marked article)))
	    ((= mark gnus-spam-mark)
	     (setq gnus-newsgroup-spam-marked
		   (gnus-add-to-sorted-list gnus-newsgroup-spam-marked
					    article)))
	    ((= mark gnus-dormant-mark)
	     (setq gnus-newsgroup-dormant
		   (gnus-add-to-sorted-list gnus-newsgroup-dormant article)))
	    (t
	     (setq gnus-newsgroup-unreads
		   (gnus-add-to-sorted-list gnus-newsgroup-unreads article))))
      (gnus-alist-pull article gnus-newsgroup-reads)
      t)))

(defun gnus-summary-tick-article-forward (n)
  "Tick N articles forwards.
If N is negative, tick backwards instead.
The difference between N and the number of articles ticked is returned."
  (interactive "p" gnus-summary-mode)
  (gnus-summary-mark-forward n gnus-ticked-mark))

(defun gnus-summary-tick-article-backward (n)
  "Tick N articles backwards.
The difference between N and the number of articles ticked is returned."
  (interactive "p" gnus-summary-mode)
  (gnus-summary-mark-forward (- n) gnus-ticked-mark))

(defun gnus-summary-tick-article (&optional article clear-mark)
  "Mark current article as unread.
Optional 1st argument ARTICLE specifies article number to be marked as unread.
Optional 2nd argument CLEAR-MARK remove any kinds of mark."
  (interactive nil gnus-summary-mode)
  (gnus-summary-mark-article article (if clear-mark gnus-unread-mark
				       gnus-ticked-mark)))

(defun gnus-summary-mark-as-read-forward (n)
  "Mark N articles as read forwards.
If N is negative, mark backwards instead.
The difference between N and the actual number of articles marked is
returned."
  (interactive "p" gnus-summary-mode)
  (gnus-summary-mark-forward n gnus-del-mark gnus-inhibit-user-auto-expire))

(defun gnus-summary-mark-as-read-backward (n)
  "Mark the N articles as read backwards.
The difference between N and the actual number of articles marked is
returned."
  (interactive "p" gnus-summary-mode)
  (gnus-summary-mark-forward
   (- n) gnus-del-mark gnus-inhibit-user-auto-expire))

(defun gnus-summary-mark-as-read (&optional article mark)
  "Mark current article as read.
ARTICLE specifies the article to be marked as read.
MARK specifies a string to be inserted at the beginning of the line."
  (gnus-summary-mark-article article mark))

(defun gnus-summary-clear-mark-forward (n)
  "Clear marks from N articles forward.
If N is negative, clear backward instead.
The difference between N and the number of marks cleared is returned."
  (interactive "p" gnus-summary-mode)
  (gnus-summary-mark-forward n gnus-unread-mark))

(defun gnus-summary-clear-mark-backward (n)
  "Clear marks from N articles backward.
The difference between N and the number of marks cleared is returned."
  (interactive "p" gnus-summary-mode)
  (gnus-summary-mark-forward (- n) gnus-unread-mark))

(defun gnus-summary-mark-unread-as-read ()
  "Intended to be used by `gnus-mark-article-hook'."
  (when (memq gnus-current-article gnus-newsgroup-unreads)
    (gnus-summary-mark-article gnus-current-article gnus-read-mark)))

(defun gnus-summary-mark-read-and-unread-as-read (&optional new-mark)
  "Intended to be used by `gnus-mark-article-hook'."
  (let ((mark (gnus-summary-article-mark)))
    (when (or (gnus-unread-mark-p mark)
	      (gnus-read-mark-p mark))
      (gnus-summary-mark-article gnus-current-article
				 (or new-mark gnus-read-mark)))))

(defun gnus-summary-mark-current-read-and-unread-as-read (&optional new-mark)
  "Intended to be used by `gnus-mark-article-hook'."
  (let ((mark (gnus-summary-article-mark)))
    (when (or (gnus-unread-mark-p mark)
	      (gnus-read-mark-p mark))
      (gnus-summary-mark-article (gnus-summary-article-number)
				 (or new-mark gnus-read-mark)))))

(defun gnus-summary-mark-unread-as-ticked ()
  "Intended to be used by `gnus-mark-article-hook'."
  (when (memq gnus-current-article gnus-newsgroup-unreads)
    (gnus-summary-mark-article gnus-current-article gnus-ticked-mark)))

(defun gnus-summary-mark-region-as-read (point mark all)
  "Mark all unread articles between point and mark as read.
If given a prefix, mark all articles between point and mark as read,
even ticked and dormant ones."
  (interactive "r\nP" gnus-summary-mode)
  (save-excursion
    (let (article)
      (goto-char point)
      (beginning-of-line)
      (while (and
	      (< (point) mark)
	      (progn
		(when (or all
			  (memq (setq article (gnus-summary-article-number))
				gnus-newsgroup-unreads))
		  (gnus-summary-mark-article article gnus-del-mark))
		t)
	      (gnus-summary-find-next))))))

(defun gnus-summary-mark-below (score mark)
  "Mark articles with score less than SCORE with MARK."
  (interactive "P\ncMark: " gnus-summary-mode)
  (setq score (if score
		  (prefix-numeric-value score)
		(or gnus-summary-default-score 0)))
  (with-current-buffer gnus-summary-buffer
    (goto-char (point-min))
    (while
	(progn
	  (and (< (gnus-summary-article-score) score)
	       (gnus-summary-mark-article nil mark))
	  (gnus-summary-find-next)))))

(defun gnus-summary-kill-below (&optional score)
  "Mark articles with score below SCORE as read."
  (interactive "P" gnus-summary-mode)
  (gnus-summary-mark-below score gnus-killed-mark))

(defun gnus-summary-clear-above (&optional score)
  "Clear all marks from articles with score above SCORE."
  (interactive "P" gnus-summary-mode)
  (gnus-summary-mark-above score gnus-unread-mark))

(defun gnus-summary-tick-above (&optional score)
  "Tick all articles with score above SCORE."
  (interactive "P" gnus-summary-mode)
  (gnus-summary-mark-above score gnus-ticked-mark))

(defun gnus-summary-mark-above (score mark)
  "Mark articles with score over SCORE with MARK."
  (interactive "P\ncMark: " gnus-summary-mode)
  (setq score (if score
		  (prefix-numeric-value score)
		(or gnus-summary-default-score 0)))
  (with-current-buffer gnus-summary-buffer
    (goto-char (point-min))
    (while (and (progn
		  (when (> (gnus-summary-article-score) score)
		    (gnus-summary-mark-article nil mark))
		  t)
		(gnus-summary-find-next)))))

;; Suggested by Daniel Quinlan <quinlan@best.com>.
(defalias 'gnus-summary-show-all-expunged 'gnus-summary-limit-include-expunged)
(defun gnus-summary-limit-include-expunged (&optional no-error)
  "Display all the hidden articles that were expunged for low scores."
  (interactive nil gnus-summary-mode)
  (let ((inhibit-read-only t))
    (let ((scored gnus-newsgroup-scored)
	  headers h)
      (while scored
	(unless (gnus-summary-article-header (caar scored))
	  (and (setq h (gnus-number-to-header (caar scored)))
	       (< (cdar scored) gnus-summary-expunge-below)
	       (push h headers)))
	(setq scored (cdr scored)))
      (if (not headers)
	  (when (not no-error)
	    (error "No expunged articles hidden"))
	(goto-char (point-min))
	(push gnus-newsgroup-limit gnus-newsgroup-limits)
	(setq gnus-newsgroup-limit (copy-sequence gnus-newsgroup-limit))
	(dolist (x headers)
	  (push (mail-header-number x) gnus-newsgroup-limit))
	(gnus-summary-prepare-unthreaded (nreverse headers))
	(goto-char (point-min))
	(gnus-summary-position-point)
	t))))

(defun gnus-summary-catchup (&optional all quietly to-here not-mark reverse)
  "Mark all unread articles in this newsgroup as read.
If prefix argument ALL is non-nil, ticked and dormant articles will
also be marked as read.
If QUIETLY is non-nil, no questions will be asked.

If TO-HERE is non-nil, it should be a point in the buffer.  All
articles before (after, if REVERSE is set) this point will be marked
as read.

Note that this function will only catch up the unread article
in the current summary buffer limitation.

The number of articles marked as read is returned."
  (interactive "P" gnus-summary-mode)
  (prog1
      (save-excursion
	(when (or quietly
		  (not gnus-interactive-catchup) ;Without confirmation?
		  gnus-expert-user
		  (gnus-y-or-n-p
		   (if all
		       "Mark absolutely all articles as read? "
		     "Mark all unread articles as read? ")))
	  (if (and not-mark
		   (not gnus-newsgroup-adaptive)
		   (not gnus-newsgroup-auto-expire)
		   (not gnus-suppress-duplicates)
		   (or (not gnus-use-cache)
		       (eq gnus-use-cache 'passive)))
	      (progn
		(when all
		  (setq gnus-newsgroup-marked nil
			gnus-newsgroup-spam-marked nil
			gnus-newsgroup-dormant nil))
		(setq gnus-newsgroup-unreads
		      (gnus-sorted-nunion
                       (gnus-sorted-intersection gnus-newsgroup-unreads
						 gnus-newsgroup-downloadable)
		       (gnus-sorted-difference gnus-newsgroup-unfetched
					       gnus-newsgroup-cached))))
	    ;; We actually mark all articles as canceled, which we
	    ;; have to do when using auto-expiry or adaptive scoring.
	    (gnus-summary-show-all-threads)
	    (if (and to-here reverse)
		(progn
		  (goto-char to-here)
		  (gnus-summary-mark-current-read-and-unread-as-read
		   gnus-catchup-mark)
		  (while (gnus-summary-find-next (not all))
		    (gnus-summary-mark-article-as-read gnus-catchup-mark)))
	      (when (gnus-summary-first-subject (not all))
		(while (and
			(if to-here (< (point) to-here) t)
			(gnus-summary-mark-article-as-read gnus-catchup-mark)
			(gnus-summary-find-next (not all))))))
	    (gnus-set-mode-line 'summary))
	  t))
    (gnus-summary-position-point)))

(defun gnus-summary-catchup-to-here (&optional all)
  "Mark all unticked articles before the current one as read.
If ALL is non-nil, also mark ticked and dormant articles as read."
  (interactive "P" gnus-summary-mode)
  (save-excursion
    (gnus-save-hidden-threads
      (let ((beg (point)))
	;; We check that there are unread articles.
	(when (or all (gnus-summary-find-prev))
	  (gnus-summary-catchup all t beg)))))
  (gnus-summary-position-point))

(defun gnus-summary-catchup-from-here (&optional all)
  "Mark all unticked articles after (and including) the current one as read.
If ALL is non-nil, also mark ticked and dormant articles as read."
  (interactive "P" gnus-summary-mode)
  (save-excursion
    (gnus-save-hidden-threads
      (let ((beg (point)))
	;; We check that there are unread articles.
	(when (or all (gnus-summary-last-article-p) (gnus-summary-find-next))
	  (gnus-summary-catchup all t beg nil t)))))
  (gnus-summary-position-point))

(defun gnus-summary-catchup-all (&optional quietly)
  "Mark all articles in this newsgroup as read.
This command is dangerous.  Normally, you want \\[gnus-summary-catchup]
instead, which marks only unread articles as read."
  (interactive "P" gnus-summary-mode)
  (gnus-summary-catchup t quietly))

(defun gnus-summary-catchup-and-exit (&optional all quietly)
  "Mark all unread articles in this group as read, then exit.
If prefix argument ALL is non-nil, all articles are marked as read.
If QUIETLY is non-nil, no questions will be asked."
  (interactive "P" gnus-summary-mode)
  (when (gnus-summary-catchup all quietly nil 'fast)
    ;; Select next newsgroup or exit.
    (if (and (not (gnus-group-quit-config gnus-newsgroup-name))
	     (eq gnus-auto-select-next 'quietly))
	(gnus-summary-next-group nil)
      (gnus-summary-exit))))

(defun gnus-summary-catchup-all-and-exit (&optional quietly)
  "Mark all articles in this newsgroup as read, and then exit.
This command is dangerous.  Normally, you want \\[gnus-summary-catchup-and-exit]
instead, which marks only unread articles as read."
  (interactive "P" gnus-summary-mode)
  (gnus-summary-catchup-and-exit t quietly))

(defun gnus-summary-catchup-and-goto-next-group (&optional all)
  "Mark all articles in this group as read and select the next group.
If given a prefix, mark all articles, unread as well as ticked, as
read."
  (interactive "P" gnus-summary-mode)
  (save-excursion
    (gnus-summary-catchup all))
  (gnus-summary-next-group))

(defun gnus-summary-catchup-and-goto-prev-group (&optional all)
  "Mark all articles in this group as read and select the previous group.
If given a prefix, mark all articles, unread as well as ticked, as
read."
  (interactive "P" gnus-summary-mode)
  (save-excursion
    (gnus-summary-catchup all))
  (gnus-summary-next-group nil nil t))

;;;
;;; with article
;;;

(defmacro gnus-with-article (article &rest forms)
  "Select ARTICLE and perform FORMS in the original article buffer.
Then replace the article with the result."
  (declare (indent 1) (debug t))
  `(progn
     ;; We don't want the article to be marked as read.
     (let (gnus-mark-article-hook)
       (gnus-summary-select-article t t nil ,article))
     (set-buffer gnus-original-article-buffer)
     ,@forms
     (if (not (gnus-check-backend-function
	       'request-replace-article (car gnus-article-current)))
	 (gnus-message 5 "Read-only group; not replacing")
       (unless (gnus-request-replace-article
		,article (car gnus-article-current)
		(current-buffer) t)
	 (error "Couldn't replace article")))
     ;; The cache and backlog have to be flushed somewhat.
     (when gnus-keep-backlog
       (gnus-backlog-remove-article
	(car gnus-article-current) (cdr gnus-article-current)))
     (when gnus-use-cache
       (gnus-cache-update-article
	(car gnus-article-current) (cdr gnus-article-current)))))

;; Thread-based commands.

(defun gnus-summary-articles-in-thread (&optional article)
  "Return a list of all articles in the current thread.
If ARTICLE is non-nil, return all articles in the thread that starts
with that article."
  (let* ((article (or article (gnus-summary-article-number)))
	 (data (gnus-data-find-list article))
	 (top-level (gnus-data-level (car data)))
	 (top-subject
	  (cond ((null gnus-thread-operation-ignore-subject)
		 (gnus-simplify-subject-re
		  (mail-header-subject (gnus-data-header (car data)))))
		((eq gnus-thread-operation-ignore-subject 'fuzzy)
		 (gnus-simplify-subject-fuzzy
		  (mail-header-subject (gnus-data-header (car data)))))
		(t nil)))
	 (end-point (save-excursion
		      (goto-char (gnus-data-pos (car data)))
		      (if (gnus-summary-go-to-next-thread)
			  (point) (point-max))))
	 articles)
    (while (and data
		(< (gnus-data-pos (car data)) end-point))
      (when (or (not top-subject)
		(string= top-subject
			 (if (eq gnus-thread-operation-ignore-subject 'fuzzy)
			     (gnus-simplify-subject-fuzzy
			      (mail-header-subject
			       (gnus-data-header (car data))))
			   (gnus-simplify-subject-re
			    (mail-header-subject
			     (gnus-data-header (car data)))))))
	(push (gnus-data-number (car data)) articles))
      (unless (and (setq data (cdr data))
		   (> (gnus-data-level (car data)) top-level))
	(setq data nil)))
    ;; Return the list of articles.
    (nreverse articles)))

(defun gnus-summary-rethread-current ()
  "Rethread the thread the current article is part of."
  (interactive nil gnus-summary-mode)
  (let* ((gnus-show-threads t)
	 (article (gnus-summary-article-number))
	 (id (mail-header-id (gnus-summary-article-header)))
	 (gnus-newsgroup-threads (list (gnus-id-to-thread (gnus-root-id id)))))
    (unless id
      (error "No article on the current line"))
    (gnus-rebuild-thread id)
    (gnus-summary-goto-subject article)))

(defun gnus-summary-reparent-thread ()
  "Make the current article child of the marked (or previous) article.

Note that the re-threading will only work if `gnus-thread-ignore-subject'
is non-nil or the Subject: of both articles are the same."
  (interactive nil gnus-summary-mode)
  (unless (not (gnus-group-read-only-p))
    (error "The current newsgroup does not support article editing"))
  (unless (<= (length gnus-newsgroup-processable) 1)
    (error "No more than one article may be marked"))
  (let ((child (gnus-summary-article-number))
	;; First grab the marked article, otherwise one line up.
	(parent (if (not (null gnus-newsgroup-processable))
		    (car gnus-newsgroup-processable)
		  (save-excursion
		    (if (eq (forward-line -1) 0)
			(gnus-summary-article-number)
		      (error "Beginning of summary buffer"))))))
    (gnus-summary-reparent-children parent (list child))))

(defun gnus-summary-reparent-children (parent children)
  "Make PARENT the parent of CHILDREN.
When called interactively, PARENT is the current article and CHILDREN
are the process-marked articles."
  (interactive (list
		(gnus-summary-article-number)
		(gnus-summary-work-articles nil))
	       gnus-summary-mode)
  (dolist (child children)
    (save-window-excursion
      (let ((gnus-article-buffer " *reparent*"))
	(unless (not (eq parent child))
	  (error "An article may not be self-referential"))
	(let ((message-id (mail-header-id
			   (gnus-summary-article-header parent))))
	  (unless (and message-id (not (equal message-id "")))
	    (error "No message-id in desired parent"))
	  (gnus-with-article child
	    (save-restriction
	      (goto-char (point-min))
	      (message-narrow-to-head)
	      (if (re-search-forward "^References: " nil t)
		  (progn
		    (re-search-forward "^[^ \t]" nil t)
		    (forward-line -1)
		    (end-of-line)
		    (insert " " message-id))
		(insert "References: " message-id "\n"))))
	  (set-buffer gnus-summary-buffer)
	  (gnus-summary-unmark-all-processable)
	  (gnus-summary-update-article child)
	  (when (gnus-summary-goto-subject (cdr gnus-article-current) nil t)
	    (gnus-summary-update-secondary-mark (cdr gnus-article-current)))
	  (gnus-summary-rethread-current)
	  (gnus-message 3 "Article %d is now the child of article %d"
			child parent))))))

(defun gnus-summary-toggle-threads (&optional arg)
  "Toggle showing conversation threads.
If ARG is positive number, turn showing conversation threads on."
  (interactive "P" gnus-summary-mode)
  (let ((current (or (gnus-summary-article-number) gnus-newsgroup-end)))
    (setq gnus-show-threads
	  (if (null arg) (not gnus-show-threads)
	    (> (prefix-numeric-value arg) 0)))
    (gnus-summary-prepare)
    (gnus-summary-goto-subject current)
    (gnus-message 6 "Threading is now %s" (if gnus-show-threads "on" "off"))
    (gnus-summary-position-point)))

(defun gnus-summary-show-all-threads ()
  "Show all threads."
  (interactive nil gnus-summary-mode)
  (remove-overlays (point-min) (point-max) 'invisible 'gnus-sum)
  (gnus-summary-position-point))

(defsubst gnus-summary--inv (p)
  (and (eq (get-char-property p 'invisible) 'gnus-sum) p))

(defun gnus-summary-show-thread ()
  "Show thread subtrees.
Returns nil if no thread was there to be shown."
  (interactive nil gnus-summary-mode)
  (let* ((orig (point))
	 (end (point-at-eol))
         (end (or (gnus-summary--inv end) (gnus-summary--inv (1- end))))
	 ;; Leave point at bol
	 (beg (progn (beginning-of-line) (if (bobp) (point) (1- (point)))))
	 (eoi (and end (next-single-char-property-change end 'invisible))))
    (when eoi
      (remove-overlays beg eoi 'invisible 'gnus-sum)
      (goto-char orig)
      (gnus-summary-position-point)
      eoi)))

(defun gnus-summary-maybe-hide-threads ()
  "If requested, hide the threads that should be hidden."
  (when (and gnus-show-threads
	     gnus-thread-hide-subtree)
    (gnus-summary-hide-all-threads
     (if (or (consp gnus-thread-hide-subtree)
	     (functionp gnus-thread-hide-subtree))
	 (gnus-make-predicate gnus-thread-hide-subtree)
       nil))))

;;; Hiding predicates.

(defun gnus-article-unread-p (header)
  (memq (mail-header-number header) gnus-newsgroup-unreads))

(defun gnus-article-unseen-p (header)
  (memq (mail-header-number header) gnus-newsgroup-unseen))

(defun gnus-map-articles (predicate articles)
  "Map PREDICATE over ARTICLES and return non-nil if any predicate is non-nil."
  (apply #'gnus-or (mapcar predicate
			  (mapcar #'gnus-summary-article-header
				  articles))))

(defun gnus-summary-hide-all-threads (&optional predicate)
  "Hide all thread subtrees.
If PREDICATE is supplied, threads that satisfy this predicate
will not be hidden."
  (interactive nil gnus-summary-mode)
  (save-excursion
    (goto-char (point-min))
    (let ((end nil)
          (count 0))
      (while (not end)
        (cl-incf count)
        (when (zerop (mod count 1000))
          (message "Hiding all threads... %d" count))
	(when (or (not predicate)
		  (gnus-map-articles
		   predicate (gnus-summary-article-children)))
	    (gnus-summary-hide-thread))
	(setq end (not (zerop (gnus-summary-next-thread 1 t)))))))
  (gnus-summary-position-point))

(defun gnus-summary-hide-thread ()
  "Hide thread subtrees.
Returns nil if no threads were there to be hidden."
  (interactive nil gnus-summary-mode)
  (beginning-of-line)
  (let ((start (point))
	(starteol (line-end-position))
	(article (gnus-summary-article-number)))
    ;; Go forward until either the buffer ends or the subthread ends.
    (when (and (not (eobp))
	       (or (zerop (gnus-summary-next-thread 1 t))
		   (goto-char (point-max))))
      (if (and (> (point) start)
	       ;; FIXME: this should actually search for a non-invisible \n.
	       (search-backward "\n" start t))
	  (progn
	    (when (> (point) starteol)
	      (remove-overlays starteol (point) 'invisible 'gnus-sum)
	      (let ((ol (make-overlay starteol (point) nil t nil)))
		(overlay-put ol 'invisible 'gnus-sum)
		(overlay-put ol 'evaporate t)))
	    (gnus-summary-goto-subject article)
	    ;; We moved backward past the start point (invisible thread?)
            (when (> start (point))
              (goto-char starteol)))
	(goto-char start)
	nil))))

(defun gnus-summary-go-to-next-thread (&optional previous)
  "Go to the same level (or less) next thread.
If PREVIOUS is non-nil, go to previous thread instead.
Return the article number moved to, or nil if moving was impossible."
  (let ((level (gnus-summary-thread-level))
	(way (if previous -1 1))
	(beg (point)))
    (forward-line way)
    (while (and (not (eobp))
		(< level (gnus-summary-thread-level)))
      (forward-line way))
    (if (eobp)
	(progn
	  (goto-char beg)
	  nil)
      (setq beg (point))
      (prog1
	  (gnus-summary-article-number)
	(goto-char beg)))))

(defun gnus-summary-next-thread (n &optional silent)
  "Go to the same level next N'th thread.
If N is negative, search backward instead.
Returns the difference between N and the number of skips actually
done.

If SILENT, don't output messages."
  (interactive "p" gnus-summary-mode)
  (let ((backward (< n 0))
	(n (abs n)))
    (while (and (> n 0)
		(gnus-summary-go-to-next-thread backward))
      (cl-decf n))
    (unless silent
      (gnus-summary-position-point))
    (when (and (not silent) (/= 0 n))
      (gnus-message 7 "No more threads"))
    n))

(defun gnus-summary-prev-thread (n)
  "Go to the same level previous N'th thread.
Returns the difference between N and the number of skips actually
done."
  (interactive "p" gnus-summary-mode)
  (gnus-summary-next-thread (- n)))

(defun gnus-summary-go-down-thread ()
  "Go down one level in the current thread."
  (let ((children (gnus-summary-article-children)))
    (when children
      (gnus-summary-goto-subject (car children)))))

(defun gnus-summary-go-up-thread ()
  "Go up one level in the current thread."
  (let ((parent (gnus-summary-article-parent)))
    (when parent
      (gnus-summary-goto-subject parent))))

(defun gnus-summary-down-thread (n)
  "Go down thread N steps.
If N is negative, go up instead.
Returns the difference between N and how many steps down that were
taken."
  (interactive "p" gnus-summary-mode)
  (let ((up (< n 0))
	(n (abs n)))
    (while (and (> n 0)
		(if up (gnus-summary-go-up-thread)
		  (gnus-summary-go-down-thread)))
      (setq n (1- n)))
    (gnus-summary-position-point)
    (when (/= 0 n)
      (gnus-message 7 "Can't go further"))
    n))

(defun gnus-summary-up-thread (n)
  "Go up thread N steps.
If N is negative, go down instead.
Returns the difference between N and how many steps down that were
taken."
  (interactive "p" gnus-summary-mode)
  (gnus-summary-down-thread (- n)))

(defun gnus-summary-top-thread ()
  "Go to the top of the thread."
  (interactive nil gnus-summary-mode)
  (while (gnus-summary-go-up-thread))
  (gnus-summary-article-number))

(defun gnus-summary-expire-thread ()
  "Mark articles under current thread as expired."
  (interactive nil gnus-summary-mode)
  (gnus-summary-kill-thread 0))

(defun gnus-summary-kill-thread (&optional unmark)
  "Mark articles under current thread as read.
If the prefix argument is positive, remove any kinds of marks.
If the prefix argument is zero, mark thread as expired.
If the prefix argument is negative, tick articles instead."
  (interactive "P" gnus-summary-mode)
  (when unmark
    (setq unmark (prefix-numeric-value unmark)))
  (let ((articles (gnus-summary-articles-in-thread))
	(hide (or (null unmark) (= unmark 0))))
    (save-excursion
      ;; Expand the thread.
      (gnus-summary-show-thread)
      ;; Mark all the articles.
      (while articles
	(gnus-summary-goto-subject (car articles))
	(cond ((null unmark)
	       (gnus-summary-mark-article-as-read gnus-killed-mark))
	      ((> unmark 0)
	       (gnus-summary-mark-article-as-unread gnus-unread-mark))
	      ((= unmark 0)
	       (gnus-summary-mark-article nil gnus-expirable-mark))
	      (t
	       (gnus-summary-mark-article-as-unread gnus-ticked-mark)))
	(setq articles (cdr articles))))
    ;; Hide killed subtrees when hide is true.
    (and hide
	 gnus-thread-hide-killed
	 (gnus-summary-hide-thread))
    ;; If hide is t, go to next unread subject.
    (when hide
      ;; Go to next unread subject.
      (gnus-summary-next-subject 1 t)))
  (gnus-set-mode-line 'summary))

;; Summary sorting commands

(defun gnus-summary-sort-by-number (&optional reverse)
  "Sort the summary buffer by article number.
Argument REVERSE means reverse order."
  (interactive "P" gnus-summary-mode)
  (gnus-summary-sort 'number reverse))

(defun gnus-summary-sort-by-most-recent-number (&optional reverse)
  "Sort the summary buffer by most recent article number.
Argument REVERSE means reverse order."
  (interactive "P" gnus-summary-mode)
  (gnus-summary-sort 'most-recent-number reverse))

(defun gnus-summary-sort-by-random (&optional reverse)
  "Randomize the order in the summary buffer.
Argument REVERSE means to randomize in reverse order."
  (interactive "P" gnus-summary-mode)
  (gnus-summary-sort 'random reverse))

(defun gnus-summary-sort-by-author (&optional reverse)
  "Sort the summary buffer by author name alphabetically.
If `case-fold-search' is non-nil, case of letters is ignored.
Argument REVERSE means reverse order."
  (interactive "P" gnus-summary-mode)
  (gnus-summary-sort 'author reverse))

(defun gnus-summary-sort-by-recipient (&optional reverse)
  "Sort the summary buffer by recipient name alphabetically.
If `case-fold-search' is non-nil, case of letters is ignored.
Argument REVERSE means reverse order."
  (interactive "P" gnus-summary-mode)
  (gnus-summary-sort 'recipient reverse))

(defun gnus-summary-sort-by-subject (&optional reverse)
  "Sort the summary buffer by subject alphabetically.  `Re:'s are ignored.
If `case-fold-search' is non-nil, case of letters is ignored.
Argument REVERSE means reverse order."
  (interactive "P" gnus-summary-mode)
  (gnus-summary-sort 'subject reverse))

(defun gnus-summary-sort-by-date (&optional reverse)
  "Sort the summary buffer by date.
Argument REVERSE means reverse order."
  (interactive "P" gnus-summary-mode)
  (gnus-summary-sort 'date reverse))

(defun gnus-summary-sort-by-most-recent-date (&optional reverse)
  "Sort the summary buffer by most recent date.
Argument REVERSE means reverse order."
  (interactive "P" gnus-summary-mode)
  (gnus-summary-sort 'most-recent-date reverse))

(defun gnus-summary-sort-by-score (&optional reverse)
  "Sort the summary buffer by score.
Argument REVERSE means reverse order."
  (interactive "P" gnus-summary-mode)
  (gnus-summary-sort 'score reverse))

(defun gnus-summary-sort-by-lines (&optional reverse)
  "Sort the summary buffer by the number of lines.
Argument REVERSE means reverse order."
  (interactive "P" gnus-summary-mode)
  (gnus-summary-sort 'lines reverse))

(defun gnus-summary-sort-by-chars (&optional reverse)
  "Sort the summary buffer by article length.
Argument REVERSE means reverse order."
  (interactive "P" gnus-summary-mode)
  (gnus-summary-sort 'chars reverse))

(defun gnus-summary-sort-by-marks (&optional reverse)
  "Sort the summary buffer by article marks.
Argument REVERSE means reverse order."
  (interactive "P" gnus-summary-mode)
  (gnus-summary-sort 'marks reverse))

(defun gnus-summary-sort-by-newsgroups (&optional reverse)
  "Sort the summary buffer by newsgroups alphabetically.
Argument REVERSE means reverse order."
  (interactive "P" gnus-summary-mode)
  (gnus-summary-sort 'newsgroups reverse))

(defun gnus-summary-sort-by-original (&optional _reverse)
  "Sort the summary buffer using the default sorting method.
Argument REVERSE means reverse order."
  (interactive nil gnus-summary-mode)
  (let* ((inhibit-read-only t)
	 (gnus-summary-prepare-hook nil))
    ;; We do the sorting by regenerating the threads.
    (gnus-summary-prepare)
    ;; Hide subthreads if needed.
    (gnus-summary-maybe-hide-threads)))

(defun gnus-summary-sort-by-extra (&optional reverse)
  "Sort the summary buffer using an extra header.
Argument REVERSE means reverse order."
  (interactive "P" gnus-summary-mode)
  (let* ((extra-header
	  (gnus-completing-read "Sort by extra header"
	   (mapcar #'symbol-name gnus-extra-headers)
	   t nil nil
	   (symbol-name
	    (car gnus-extra-headers))))
	(header (downcase extra-header)))
    (if (and (fboundp (intern
		       (format "gnus-thread-sort-by-%s" header)))
	     (fboundp
	      (intern (format "gnus-article-sort-by-%s" header))))
	(gnus-summary-sort header reverse)
      (error "No sort function defined for header: %s" extra-header))))

(defun gnus-summary-sort (predicate reverse)
  "Sort summary buffer by PREDICATE.  REVERSE means reverse order."
  (let* ((current (gnus-summary-article-number))
	 (thread (intern (format "gnus-thread-sort-by-%s" predicate)))
	 (article (intern (format "gnus-article-sort-by-%s" predicate)))
	 (gnus-thread-sort-functions
	  (if (not reverse)
	      thread
	    (lambda (t1 t2)
	       (funcall thread t2 t1))))
	 (gnus-sort-gathered-threads-function
	  gnus-thread-sort-functions)
	 (gnus-article-sort-functions
	  (if (not reverse)
	      article
	    (lambda (t1 t2)
	      (funcall article t2 t1))))
	 (inhibit-read-only t)
	 (gnus-summary-prepare-hook nil))
    ;; We do the sorting by regenerating the threads.
    (gnus-summary-prepare)
    ;; Hide subthreads if needed.
    (gnus-summary-maybe-hide-threads)
    ;; Restore point.
    (gnus-summary-goto-subject current)))

;; Summary saving commands.

(defun gnus-summary-save-article (&optional n not-saved)
  "Save the current article using the default saver function.
If N is a positive number, save the N next articles.
If N is a negative number, save the N previous articles.
If N is nil and any articles have been marked with the process mark,
save those articles instead.
The variable `gnus-default-article-saver' specifies the saver function.

If the optional second argument NOT-SAVED is non-nil, articles saved
will not be marked as saved.

The `gnus-prompt-before-saving' variable says how prompting is
performed."
  (interactive "P" gnus-summary-mode)
  (require 'gnus-art)
  (let* ((articles (gnus-summary-work-articles n))
	 (save-buffer (save-excursion
			(nnheader-set-temp-buffer " *Gnus Save*")))
	 (num (length articles))
	 ;; Whether to save decoded articles or raw articles.
	 (decode (when gnus-article-save-coding-system
		   (get gnus-default-article-saver :decode)))
	 ;; When saving many articles in a single file, use the other
	 ;; function to save articles other than the first one.
	 (saver2 (get gnus-default-article-saver :function))
	 (gnus-prompt-before-saving (if saver2
					t
				      gnus-prompt-before-saving))
	 (gnus-default-article-saver gnus-default-article-saver)
	 header file)
    (dolist (article articles)
      (setq header (gnus-summary-article-header article))
      (if (not (mail-header-p header))
	  ;; This is a pseudo-article.
	  (if (assq 'name header)
	      (gnus-copy-file (cdr (assq 'name header)))
	    (gnus-message 1 "Article %d is unsavable" article))
	;; This is a real article.
	(save-window-excursion
	  (gnus-summary-select-article decode decode nil article)
	  (gnus-summary-goto-subject article))
	;; The article may have expired.
	(let ((art-buf (if decode
			   gnus-article-buffer
			 gnus-original-article-buffer)))
	  (when (zerop (buffer-size (get-buffer art-buf)))
	    (error "Couldn't select article %s" article))
	  (with-current-buffer save-buffer
	    (erase-buffer)
	    (insert-buffer-substring art-buf)))
	(setq file (gnus-article-save save-buffer file num))
	(gnus-summary-remove-process-mark article)
	(unless not-saved
	  (gnus-summary-set-saved-mark article)))
      (when saver2
	(setq gnus-default-article-saver saver2
	      saver2 nil)))
    (gnus-kill-buffer save-buffer)
    (gnus-summary-position-point)
    (gnus-set-mode-line 'summary)
    n))

(declare-function gnus-summary-save-in-pipe "gnus-art" (&optional command raw))

(defun gnus-summary-pipe-output (&optional n sym)
  "Pipe the current article to a subprocess.
If N is a positive number, pipe the N next articles.
If N is a negative number, pipe the N previous articles.
If N is nil and any articles have been marked with the process mark,
pipe those articles instead.
The default command to which articles are piped is specified by the
variable `gnus-summary-pipe-output-default-command'; if it is nil, you
will be prompted for the command.

The properties `:decode' and `:headers' that are put to the function
symbol `gnus-summary-save-in-pipe' control whether this function
decodes articles and what headers to keep (see the doc string for the
`gnus-default-article-saver' variable).  If SYM (the symbolic prefix)
is neither omitted nor the symbol `r', force including all headers
regardless of the `:headers' property.  If it is the symbol `r',
articles that are not decoded and include all headers will be piped
no matter what the properties `:decode' and `:headers' are."
  (interactive (gnus-interactive "P\ny") gnus-summary-mode)
  (require 'gnus-art)
  (let* ((articles (gnus-summary-work-articles n))
	 (result-buffer shell-command-buffer-name)
	 (all-headers (not (memq sym '(nil r))))
	 (gnus-save-all-headers (or all-headers gnus-save-all-headers))
	 (raw (eq sym 'r))
	 (headers (get 'gnus-summary-save-in-pipe :headers))
	 command result)
    (unless (numberp (car articles))
      (error "No article to pipe"))
    (setq command (read-shell-command
		   (concat "Shell command on "
			   (if (cdr articles)
			       (format "these %d articles" (length articles))
			     "this article")
			   ": ")
		   gnus-summary-pipe-output-default-command))
    (when (string-equal command "")
      (error "A command is required"))
    (when all-headers
      (put 'gnus-summary-save-in-pipe :headers nil))
    (unwind-protect
	(while articles
	  (gnus-summary-goto-subject (pop articles))
	  (save-window-excursion (gnus-summary-save-in-pipe command raw))
	  (when (and (get-buffer result-buffer)
		     (not (zerop (buffer-size (get-buffer result-buffer)))))
	    (setq result (concat result (with-current-buffer result-buffer
					  (buffer-string))))))
      (put 'gnus-summary-save-in-pipe :headers headers))
    (unless (zerop (length result))
      (if (with-current-buffer (gnus-get-buffer-create result-buffer)
	    (erase-buffer)
	    (insert result)
	    (prog1
		(and (= (count-lines (point-min) (point)) 1)
		     (progn
		       (end-of-line 0)
		       (<= (current-column)
			   (window-width (minibuffer-window)))))
	      (goto-char (point-min))))
	  (message "%s" (substring result 0 -1))
	(message nil)
	(gnus-configure-windows 'pipe)))))

(defun gnus-summary-save-article-mail (&optional arg)
  "Append the current article to a Unix mail box file.
If N is a positive number, save the N next articles.
If N is a negative number, save the N previous articles.
If N is nil and any articles have been marked with the process mark,
save those articles instead."
  (interactive "P" gnus-summary-mode)
  (require 'gnus-art)
  (let ((gnus-default-article-saver 'gnus-summary-save-in-mail))
    (gnus-summary-save-article arg)))

(defun gnus-summary-save-article-rmail (&optional arg)
  "Append the current article to an rmail file.
If N is a positive number, save the N next articles.
If N is a negative number, save the N previous articles.
If N is nil and any articles have been marked with the process mark,
save those articles instead."
  (interactive "P" gnus-summary-mode)
  (require 'gnus-art)
  (let ((gnus-default-article-saver 'gnus-summary-save-in-rmail))
    (gnus-summary-save-article arg)))

(defun gnus-summary-save-article-file (&optional arg)
  "Append the current article to a file.
If N is a positive number, save the N next articles.
If N is a negative number, save the N previous articles.
If N is nil and any articles have been marked with the process mark,
save those articles instead."
  (interactive "P" gnus-summary-mode)
  (require 'gnus-art)
  (let ((gnus-default-article-saver 'gnus-summary-save-in-file))
    (gnus-summary-save-article arg)))

(defun gnus-summary-write-article-file (&optional arg)
  "Write the current article to a file, deleting the previous file.
If N is a positive number, save the N next articles.
If N is a negative number, save the N previous articles.
If N is nil and any articles have been marked with the process mark,
save those articles instead."
  (interactive "P" gnus-summary-mode)
  (require 'gnus-art)
  (let ((gnus-default-article-saver 'gnus-summary-write-to-file))
    (gnus-summary-save-article arg)))

(defun gnus-summary-save-article-body-file (&optional arg)
  "Append the current article body to a file.
If N is a positive number, save the N next articles.
If N is a negative number, save the N previous articles.
If N is nil and any articles have been marked with the process mark,
save those articles instead."
  (interactive "P" gnus-summary-mode)
  (require 'gnus-art)
  (let ((gnus-default-article-saver 'gnus-summary-save-body-in-file))
    (gnus-summary-save-article arg)))

(defun gnus-summary-write-article-body-file (&optional arg)
  "Write the current article body to a file, deleting the previous file.
If N is a positive number, save the N next articles.
If N is a negative number, save the N previous articles.
If N is nil and any articles have been marked with the process mark,
save those articles instead."
  (interactive "P" gnus-summary-mode)
  (require 'gnus-art)
  (let ((gnus-default-article-saver 'gnus-summary-write-body-to-file))
    (gnus-summary-save-article arg)))

(defun gnus-summary-muttprint (&optional arg)
  "Print the current article using Muttprint.
If N is a positive number, save the N next articles.
If N is a negative number, save the N previous articles.
If N is nil and any articles have been marked with the process mark,
save those articles instead."
  (interactive "P" gnus-summary-mode)
  (require 'gnus-art)
  (let ((gnus-default-article-saver 'gnus-summary-pipe-to-muttprint))
    (gnus-summary-save-article arg t)))

(defun gnus-summary-pipe-message (program)
  "Pipe the current article through PROGRAM."
  (interactive "sProgram: " gnus-summary-mode)
  (gnus-summary-select-article)
  (let ((mail-header-separator ""))
    (gnus-eval-in-buffer-window gnus-article-buffer
      (save-restriction
	(widen)
	(let ((start (window-start))
	      (inhibit-read-only t))
	  (message-pipe-buffer-body program)
	  (set-window-start (get-buffer-window (current-buffer)) start))))))

(defun gnus-get-split-value (methods)
  "Return a value based on the split METHODS."
  (let (split-name method result match)
    (when methods
      (with-current-buffer gnus-original-article-buffer
	(save-restriction
	  (nnheader-narrow-to-headers)
	  (while (and methods (not split-name))
	    (goto-char (point-min))
	    (setq method (pop methods))
	    (setq match (car method))
	    (when (cond
		   ((stringp match)
		    ;; Regular expression.
		    (ignore-errors
		      (re-search-forward match nil t)))
		   ((functionp match)
		    ;; Function.
		    (save-restriction
		      (widen)
		      (setq result (funcall match gnus-newsgroup-name))))
		   ((consp match)
		    ;; Form.
		    (save-restriction
		      (widen)
		      (setq result (eval match t)))))
	      (setq split-name (cdr method))
	      (cond ((stringp result)
		     (push (expand-file-name
			    result gnus-article-save-directory)
			   split-name))
		    ((consp result)
		     (setq split-name (append result split-name)))))))))
    (nreverse split-name)))

(defun gnus-valid-move-group-p (group)
  (when (and (stringp group)
	     (null (string-empty-p group)))
    (gnus-get-function (gnus-find-method-for-group
			group)
		       'request-accept-article t)))

(defun gnus-read-move-group-name (prompt default articles prefix)
  "Read a group name."
  (let* ((split-name (gnus-get-split-value gnus-move-split-methods))
	 (prom
	  (format "%s %s to"
		  prompt
		  (if (> (length articles) 1)
		      (format "these %d articles" (length articles))
		    "this article")))
	 (valid-names
	  (seq-filter #'gnus-valid-move-group-p
		      (hash-table-keys gnus-active-hashtb)))
	 (to-newsgroup
          (cond
           ((null split-name)
            (gnus-group-completing-read
             prom
	     valid-names
             nil prefix nil default))
           ((= 1 (length split-name))
            (gnus-group-completing-read
             prom
	     valid-names
             nil prefix 'gnus-group-history (car split-name)))
           (t
            (gnus-completing-read
             prom (nreverse split-name) nil nil 'gnus-group-history))))
         (to-method (gnus-server-to-method (gnus-group-method to-newsgroup))))
    (when to-newsgroup
      (if (or (string= to-newsgroup "")
	      (string= to-newsgroup prefix))
	  (setq to-newsgroup default))
      (unless to-newsgroup
	(error "No group name entered"))
      (or (gnus-active to-newsgroup)
	  (gnus-activate-group to-newsgroup nil nil to-method)
	  (if (gnus-y-or-n-p (format "No such group: %s.  Create it? "
				     to-newsgroup))
	      (or (and (gnus-request-create-group to-newsgroup to-method)
		       (gnus-activate-group to-newsgroup nil nil to-method)
		       (gnus-subscribe-group to-newsgroup))
		  (error "Couldn't create group %s" to-newsgroup)))
	  (user-error "No such group: %s" to-newsgroup))
      to-newsgroup)))

(defvar gnus-summary-save-parts-counter)
(declare-function mm-uu-dissect "mm-uu" (&optional noheader mime-type))

(defun gnus-summary-save-parts (type dir n &optional reverse)
  "Save parts matching TYPE to DIR.
If REVERSE, save parts that do not match TYPE."
  (interactive
   (list (completing-read "Save parts of type: "
			  (progn
			    (gnus-summary-select-article nil t)
			    (gnus-eval-in-buffer-window gnus-article-buffer
			      (delete-dups
			       (mapcar (lambda (h)
					 (mm-handle-media-type (cdr h)))
				       gnus-article-mime-handle-alist))))
			  nil nil nil 'gnus-summary-save-parts-type-history)
	 (setq gnus-summary-save-parts-last-directory
	       (read-directory-name "Save to directory: "
                                    gnus-summary-save-parts-last-directory
                                    nil t))
	 current-prefix-arg)
   gnus-summary-mode)
  (gnus-summary-iterate n
    (let ((gnus-display-mime-function nil)
	  gnus-article-prepare-hook
	  gnus-article-decode-hook
	  gnus-display-mime-function
	  gnus-break-pages
	  (gnus-inhibit-treatment t))
      (gnus-summary-select-article))
    (with-current-buffer gnus-article-buffer
      (let ((handles (or gnus-article-mime-handles
			 (mm-dissect-buffer nil gnus-article-loose-mime)
			 (and gnus-article-emulate-mime
			      (mm-uu-dissect))))
	    (gnus-summary-save-parts-counter 1))
	(when handles
	  (gnus-summary-save-parts-1 type dir handles reverse)
	  (unless gnus-article-mime-handles ;; Don't destroy this case.
	    (mm-destroy-parts handles)))))))

(defun gnus-summary-save-parts-1 (type dir handle reverse)
  (if (stringp (car handle))
      (mapcar (lambda (h) (gnus-summary-save-parts-1 type dir h reverse))
	      (cdr handle))
    (when (if reverse
	      (not (string-match type (mm-handle-media-type handle)))
	    (string-match type (mm-handle-media-type handle)))
      (let ((file (expand-file-name
		   (gnus-map-function
		    mm-file-name-rewrite-functions
		    (file-name-nondirectory
		     (or
                      (mm-handle-filename handle)
		      (format "%s.%d.%d" gnus-newsgroup-name
			      (cdr gnus-article-current)
			      gnus-summary-save-parts-counter))))
		   dir)))
	(cl-incf gnus-summary-save-parts-counter)
	(unless (file-exists-p file)
	  (mm-save-part-to-file handle file))))))

;; Summary extract commands

(defun gnus-summary-insert-pseudos (pslist &optional not-view)
  (let ((inhibit-read-only t)
	(article (gnus-summary-article-number))
	after-article b e)
    (unless (gnus-summary-goto-subject article)
      (error "No such article: %d" article))
    (gnus-summary-position-point)
    ;; If all commands are to be bunched up on one line, we collect
    ;; them here.
    (unless gnus-view-pseudos-separately
      (let ((ps (setq pslist (sort pslist #'gnus-pseudos<)))
	    files action)
	(while ps
	  (setq action (cdr (assq 'action (car ps))))
	  (setq files (list (cdr (assq 'name (car ps)))))
	  (while (and ps (cdr ps)
		      (string= (or action "1")
			       (or (cdr (assq 'action (cadr ps))) "2")))
	    (push (cdr (assq 'name (cadr ps))) files)
	    (setcdr ps (cddr ps)))
	  (when files
	    (when (not (string-match "%s" action))
	      (push " " files))
	    (push " " files)
	    (when (assq 'execute (car ps))
	      (setcdr (assq 'execute (car ps))
		      (funcall (if (string-match "%s" action)
				   #'format #'concat)
			       action
			       (mapconcat
				(lambda (f)
				  (if (equal f " ")
				      f
				    (shell-quote-argument f)))
				files " ")))))
	  (setq ps (cdr ps)))))
    (if (and gnus-view-pseudos (not not-view))
	(while pslist
	  (when (assq 'execute (car pslist))
	    (gnus-execute-command (cdr (assq 'execute (car pslist)))
				  (eq gnus-view-pseudos 'not-confirm)))
	  (setq pslist (cdr pslist)))
      (save-excursion
	(while pslist
	  (setq after-article (or (cdr (assq 'article (car pslist)))
				  (gnus-summary-article-number)))
	  (gnus-summary-goto-subject after-article)
	  (forward-line 1)
	  (setq b (point))
	  (insert "    " (file-name-nondirectory
			  (cdr (assq 'name (car pslist))))
		  ": " (or (cdr (assq 'execute (car pslist))) "") "\n")
	  (setq e (point))
	  (forward-line -1)		; back to `b'
	  (add-text-properties
	   b (1- e) (list 'gnus-number gnus-reffed-article-number
			  'mouse-face gnus-mouse-face))
	  (gnus-data-enter
	   after-article gnus-reffed-article-number
	   gnus-unread-mark b (car pslist) 0 (- e b))
	  (setq gnus-newsgroup-unreads
		(gnus-add-to-sorted-list gnus-newsgroup-unreads
					 gnus-reffed-article-number))
	  (setq gnus-reffed-article-number (1- gnus-reffed-article-number))
	  (setq pslist (cdr pslist)))))))

(defun gnus-pseudos< (p1 p2)
  (let ((c1 (cdr (assq 'action p1)))
	(c2 (cdr (assq 'action p2))))
    (and c1 c2 (string< c1 c2))))

(defun gnus-request-pseudo-article (props)
  (cond ((assq 'execute props)
	 (gnus-execute-command (cdr (assq 'execute props)))))
  (let ((gnus-current-article (gnus-summary-article-number)))
    (gnus-run-hooks 'gnus-mark-article-hook)))

(defun gnus-execute-command (command &optional automatic)
  (save-excursion
    (gnus-article-setup-buffer)
    (set-buffer gnus-article-buffer)
    (setq buffer-read-only nil)
    (let ((command (if automatic command
		     (read-string "Command: " (cons command 0)))))
      (erase-buffer)
      (insert "$ " command "\n\n")
      (if gnus-view-pseudo-asynchronously
	  (start-process "gnus-execute" (current-buffer) shell-file-name
			 shell-command-switch command)
	(call-process shell-file-name nil t nil
		      shell-command-switch command)))))

;; Summary kill commands.

(defun gnus-summary-edit-global-kill (article)
  "Edit the \"global\" kill file."
  (interactive (list (gnus-summary-article-number)) gnus-summary-mode)
  (gnus-group-edit-global-kill article))

(defun gnus-summary-edit-local-kill ()
  "Edit a local kill file applied to the current newsgroup."
  (interactive nil gnus-summary-mode)
  (setq gnus-current-headers (gnus-summary-article-header))
  (gnus-group-edit-local-kill
   (gnus-summary-article-number) gnus-newsgroup-name))

;;; Header reading.

(defun gnus-read-header (id &optional header)
  "Read the headers of article ID and enter them into the Gnus system."
  (let ((group gnus-newsgroup-name)
	(gnus-override-method
	 (or
	  gnus-override-method
	  (and (gnus-news-group-p gnus-newsgroup-name)
	       (car (gnus-refer-article-methods)))))
	where)
    ;; First we check to see whether the header in question is already
    ;; fetched.
    (if (stringp id)
	;; This is a Message-ID.
	(setq header (or header (gnus-id-to-header id)))
      ;; This is an article number.
      (setq header (or header (gnus-summary-article-header id))))
    (if (and header
	     (not (gnus-summary-article-sparse-p (mail-header-number header))))
	;; We have found the header.
	header
      ;; We have to really fetch the header to this article.
      (with-current-buffer nntp-server-buffer
	(when (setq where (gnus-request-head id group))
	  (nnheader-fold-continuation-lines)
	  (goto-char (point-max))
	  (insert ".\n")
	  (goto-char (point-min))
	  (insert "211 ")
	  (princ (cond
		  ((numberp id) id)
		  ((cdr where) (cdr where))
		  (header (mail-header-number header))
		  (t gnus-reffed-article-number))
		 (current-buffer))
	  (insert " Article retrieved.\n"))
	(if (or (not where)
		(not (setq header (car (gnus-get-newsgroup-headers nil t)))))
	    ()				; Malformed head.
	  (unless (gnus-summary-article-sparse-p (mail-header-number header))
            (when (and (bound-and-true-p gnus-registry-enabled)
                       (not (gnus-ephemeral-group-p (car where))))
              (gnus-registry-handle-action
               (mail-header-id header) nil
               (gnus-group-prefixed-name
		(car where)
		(or gnus-override-method (gnus-find-method-for-group group)))
               (mail-header-subject header)
               (mail-header-from header)))
	    (when (and (stringp id)
		       (or
			(not (string= (gnus-group-real-name group)
				      (car where)))
			(not (gnus-server-equal gnus-override-method
						(gnus-group-method group)))))
	      ;; If we fetched by Message-ID and the article came from
	      ;; a different group (or server), we fudge some bogus
	      ;; article numbers for this article.
	      (setf (mail-header-number header) gnus-reffed-article-number))
	    (with-current-buffer gnus-summary-buffer
	      (cl-decf gnus-reffed-article-number)
	      (gnus-remove-header (mail-header-number header))
	      (push header gnus-newsgroup-headers)
	      (setq gnus-current-headers header)
	      (push (mail-header-number header) gnus-newsgroup-limit)))
	  header)))))

(defun gnus-remove-header (number)
  "Remove header NUMBER from `gnus-newsgroup-headers'."
  (if (and gnus-newsgroup-headers
	   (= number (mail-header-number (car gnus-newsgroup-headers))))
      (pop gnus-newsgroup-headers)
    (let ((headers gnus-newsgroup-headers))
      (while (and (cdr headers)
		  (not (= number (mail-header-number (cadr headers)))))
	(pop headers))
      (when (cdr headers)
	(setcdr headers (cddr headers))))))

;;;
;;; summary highlights
;;;

(defun gnus-highlight-selected-summary ()
  "Highlight selected article in summary buffer."
  ;; Added by Per Abrahamsen <amanda@iesd.auc.dk>.
  (when gnus-summary-selected-face
    (save-excursion
      (let* ((beg (point-at-bol))
	     (end (point-at-eol))
	     ;; Fix by Mike Dugan <dugan@bucrf16.bu.edu>.
	     (from (if (get-text-property beg 'mouse-face)
		       beg
		     (or (next-single-property-change
			  beg 'mouse-face nil end)
			 beg)))
	     (to
	      (if (= from end)
		  (- from 2)
		(or (next-single-property-change
		     from 'mouse-face nil end)
		    end))))
	;; If no mouse-face prop on line we will have to = from = end,
	;; so we highlight the entire line instead.
	(when (= (+ to 2) from)
	  (setq from beg)
	  (setq to (1+ end)))
	(if gnus-newsgroup-selected-overlay
	    ;; Move old overlay.
	    (move-overlay
	     gnus-newsgroup-selected-overlay from to (current-buffer))
	  ;; Create new overlay.
	  (overlay-put
	   (setq gnus-newsgroup-selected-overlay (make-overlay from to))
	   'face gnus-summary-selected-face))))))

(defvar gnus-summary-highlight-line-cached nil)
(defvar gnus-summary-highlight-line-trigger nil)

(defun gnus-summary-highlight-line-0 ()
  (if (and (eq gnus-summary-highlight-line-trigger
               gnus-summary-highlight)
           gnus-summary-highlight-line-cached)
      gnus-summary-highlight-line-cached
    (setq gnus-summary-highlight-line-trigger gnus-summary-highlight
          gnus-summary-highlight-line-cached
          (let* ((cond (list 'cond))
                 (c cond)
                 (list gnus-summary-highlight))
            (while list
              (setcdr c `((,(caar list) ',(cdar list))))
              (setq c (cdr c)
                    list (cdr list)))
            (gnus-byte-compile
             `(lambda ()
                (with-no-warnings     ;See docstring of gnus-summary-highlight.
                  (defvar score) (defvar default) (defvar default-high)
                  (defvar default-low) (defvar mark) (defvar uncached))
                ,cond))))))

(defun gnus-summary-highlight-line ()
  "Highlight current line according to `gnus-summary-highlight'."
  (with-no-warnings                   ;See docstring of gnus-summary-highlight.
    (defvar score) (defvar default) (defvar default-high) (defvar default-low)
    (defvar mark) (defvar uncached))
  (let* ((beg (point-at-bol))
	 (article (or (gnus-summary-article-number) gnus-current-article))
	 (score (or (cdr (assq article
			       gnus-newsgroup-scored))
		    gnus-summary-default-score 0))
	 (mark (or (gnus-summary-article-mark) gnus-unread-mark))
	 (inhibit-read-only t)
	 (default gnus-summary-default-score)
	 (default-high gnus-summary-default-high-score)
	 (default-low gnus-summary-default-low-score)
	 (uncached (and gnus-summary-use-undownloaded-faces
                        (memq article gnus-newsgroup-undownloaded)
                        (not (memq article gnus-newsgroup-cached)))))
    (let ((face (funcall (gnus-summary-highlight-line-0))))
      (unless (eq face (gnus-get-text-property-excluding-characters-with-faces beg 'face))
	(gnus-put-text-property-excluding-characters-with-faces
	 beg (1+ (point-at-eol)) 'face
	 (setq face (if (boundp face) (symbol-value face) face)))
	(when gnus-summary-highlight-line-function
	  (funcall gnus-summary-highlight-line-function article face))))))

(defun gnus-update-read-articles (group unread &optional compute)
  "Update the list of read articles in GROUP.
UNREAD is a sorted list."
  (let ((active (or gnus-newsgroup-active (gnus-active group)))
	(info (gnus-get-info group))
	(prev 1)
	read)
    (if (or (not info) (not active))
	;; There is no info on this group if it was, in fact,
	;; killed.  Gnus stores no information on killed groups, so
	;; there's nothing to be done.
	;; One could store the information somewhere temporarily,
	;; perhaps...  Hmmm...
	()
      ;; Remove any negative articles numbers.
      (while (and unread (< (car unread) 0))
	(setq unread (cdr unread)))
      ;; Remove any expired article numbers
      (while (and unread (< (car unread) (car active)))
	(setq unread (cdr unread)))
      ;; Compute the ranges of read articles by looking at the list of
      ;; unread articles.
      (while unread
	(when (/= (car unread) prev)
	  (push (if (= prev (1- (car unread))) prev
		  (cons prev (1- (car unread))))
		read))
	(setq prev (1+ (car unread)))
	(setq unread (cdr unread)))
      (when (<= prev (cdr active))
	(push (cons prev (cdr active)) read))
      (setq read (if (> (length read) 1) (nreverse read) read))
      (if compute
	  read
	(save-excursion
	  (let (setmarkundo)
	    ;; Propagate the read marks to the backend.
	    (when (and (gnus-method-option-p
			(gnus-find-method-for-group group)
			'server-marks)
		       (gnus-check-backend-function 'request-set-mark group))
	      (let ((del (gnus-remove-from-range (gnus-info-read info) read))
		    (add (gnus-remove-from-range read (gnus-info-read info))))
		(when (or add del)
		  (unless (gnus-check-group group)
		    (error "Can't open server for %s" group))
		  (gnus-request-set-mark
		   group (delq nil (list (if add (list add 'add '(read)))
					 (if del (list del 'del '(read))))))
		  (setq setmarkundo
			`(gnus-request-set-mark
			  ,group
			  ',(delq nil (list
				       (if del (list del 'add '(read)))
				       (if add (list add 'del '(read))))))))))
	    (set-buffer gnus-group-buffer)
	    (gnus-undo-register
	      `(progn
		 (gnus-info-set-marks ',info ',(gnus-info-marks info) t)
		 (setf (gnus-info-read ',info) ',(gnus-info-read info))
		 (gnus-group-jump-to-group ,group)
		 (gnus-get-unread-articles-in-group ',info
						    (gnus-active ,group))
		 (gnus-group-update-group ,group t)
		 ,setmarkundo))))
	;; Enter this list into the group info.
	(setf (gnus-info-read info) read)
	;; Set the number of unread articles in gnus-newsrc-hashtb.
	(gnus-get-unread-articles-in-group info (gnus-active group))
	t))))

(defun gnus-offer-save-summaries ()
  "Offer to save all active summary buffers."
  (let (buffers)
    ;; Go through all buffers and find all summaries.
    (dolist (buffer (buffer-list))
      (when (and (setq buffer (buffer-name buffer))
		 (string-match "Summary" buffer)
		 (with-current-buffer buffer
		   ;; We check that this is, indeed, a summary buffer.
		   (and (derived-mode-p 'gnus-summary-mode)
			;; Also make sure this isn't bogus.
			gnus-newsgroup-prepared
			;; Also make sure that this isn't a
			;; dead summary buffer.
			(not gnus-dead-summary-mode))))
	(push buffer buffers)))
    ;; Go through all these summary buffers and offer to save them.
    (when buffers
      (save-excursion
	(if (eq gnus-interactive-exit 'quiet)
	    (dolist (buffer buffers)
	      (switch-to-buffer buffer)
	      (gnus-summary-exit))
	  (map-y-or-n-p
	   "Update summary buffer %s? "
	   (lambda (buf)
	     (switch-to-buffer buf)
	     (gnus-summary-exit))
	   buffers))))))

(defun gnus-summary-setup-default-charset ()
  "Setup newsgroup default charset."
  (if (member gnus-newsgroup-name '("nndraft:delayed" "nndraft:drafts"))
      (setq gnus-newsgroup-charset nil)
    (let* ((ignored-charsets
	    (or gnus-newsgroup-ephemeral-ignored-charsets
		(append
		 (and gnus-newsgroup-name
		      (gnus-parameter-ignored-charsets gnus-newsgroup-name))
		 gnus-newsgroup-ignored-charsets))))
      (setq gnus-newsgroup-charset
	    (or gnus-newsgroup-ephemeral-charset
		(and gnus-newsgroup-name
		     (gnus-parameter-charset gnus-newsgroup-name))
		gnus-default-charset))
      (setq-local gnus-newsgroup-ignored-charsets ignored-charsets))))

;;;
;;; Mime Commands
;;;

(defun gnus-summary-display-buttonized (&optional show-all-parts)
  "Display the current article buffer fully MIME-buttonized.
If SHOW-ALL-PARTS (the prefix) is non-nil, all multipart/* parts are
treated as multipart/mixed."
  (interactive "P" gnus-summary-mode)
  (require 'gnus-art)
  (let ((gnus-unbuttonized-mime-types nil)
	(gnus-mime-display-multipart-as-mixed show-all-parts))
    (gnus-summary-show-article)))

(defun gnus-summary-repair-multipart (article)
  "Add a Content-Type header to a multipart article without one."
  (interactive (list (gnus-summary-article-number)) gnus-summary-mode)
  (gnus-with-article article
    (message-narrow-to-head)
    (message-remove-header "Mime-Version")
    (goto-char (point-max))
    (insert "Mime-Version: 1.0\n")
    (widen)
    (when (search-forward "\n--" nil t)
      (let ((separator (buffer-substring (point) (point-at-eol))))
	(message-narrow-to-head)
	(message-remove-header "Content-Type")
	(goto-char (point-max))
	(insert (format "Content-Type: multipart/mixed; boundary=\"%s\"\n"
			separator))
	(widen))))
  (let (gnus-mark-article-hook)
    (gnus-summary-select-article t t nil article)))

(defun gnus-summary-toggle-display-buttonized ()
  "Toggle the buttonizing of the article buffer."
  (interactive nil gnus-summary-mode)
  (require 'gnus-art)
  (if (setq gnus-inhibit-mime-unbuttonizing
	    (not gnus-inhibit-mime-unbuttonizing))
      (let ((gnus-unbuttonized-mime-types nil))
	(gnus-summary-show-article))
    (gnus-summary-show-article)))

;;;
;;; Generic summary marking commands
;;;

(defvar gnus-summary-marking-alist
  '((read gnus-del-mark "d")
    (unread gnus-unread-mark "u")
    (ticked gnus-ticked-mark "!")
    (dormant gnus-dormant-mark "?")
    (expirable gnus-expirable-mark "e"))
  "An alist of names/marks/keystrokes.")

(defvar gnus-summary-generic-mark-map (make-sparse-keymap))
(defvar gnus-summary-mark-map)

(defun gnus-summary-make-all-marking-commands ()
  (define-key gnus-summary-mark-map "M" gnus-summary-generic-mark-map)
  (dolist (elem gnus-summary-marking-alist)
    (apply #'gnus-summary-make-marking-command elem)))

(defun gnus-summary-make-marking-command (name mark keystroke)
  (let ((map (make-sparse-keymap)))
    (define-key gnus-summary-generic-mark-map keystroke map)
    (dolist (lway `((next "next" next nil "n")
		    (next-unread "next unread" next t "N")
		    (prev "previous" prev nil "p")
		    (prev-unread "previous unread" prev t "P")
		    (nomove "" nil nil ,keystroke)))
      (let ((func (gnus-summary-make-marking-command-1
		   mark (car lway) lway name)))
	(setq func (eval func t))
	(define-key map (nth 4 lway) func)))))

(defun gnus-summary-make-marking-command-1 (mark way lway name)
  `(defun ,(intern
	    (format "gnus-summary-put-mark-as-%s%s"
		    name (if (eq way 'nomove)
			     ""
			   (concat "-" (symbol-name way)))))
     (n)
     ,(format
       "Mark the current article as %s%s.
If N, the prefix, then repeat N times.
If N is negative, move in reverse order.
The difference between N and the actual number of articles marked is
returned."
       name (cadr lway))
     (interactive "p" gnus-summary-mode)
     (gnus-summary-generic-mark n ,mark ',(nth 2 lway) ,(nth 3 lway))))

(defun gnus-summary-generic-mark (n mark move unread)
  "Mark N articles with MARK."
  (unless (derived-mode-p 'gnus-summary-mode)
    (error "This command can only be used in the summary buffer"))
  (gnus-summary-show-thread)
  (let ((nummove
	 (cond
	  ((eq move 'next) 1)
	  ((eq move 'prev) -1)
	  (t 0))))
    (if (zerop nummove)
	(setq n 1)
      (when (< n 0)
	(setq n (abs n)
	      nummove (* -1 nummove))))
    (while (and (> n 0)
		(gnus-summary-mark-article nil mark)
		(zerop (gnus-summary-next-subject nummove unread t)))
      (setq n (1- n)))
    (when (/= 0 n)
      (gnus-message 7 "No more %sarticles" (if mark "" "unread ")))
    (gnus-summary-recenter)
    (gnus-summary-position-point)
    (gnus-set-mode-line 'summary)
    n))

(defun gnus-summary-insert-articles (articles)
  (when (setq articles
	      (gnus-sorted-difference articles
				      (mapcar (lambda (h)
						(mail-header-number h))
					      gnus-newsgroup-headers)))
    (setq gnus-newsgroup-headers
	  (cl-merge 'list
		    gnus-newsgroup-headers
		    (gnus-fetch-headers articles nil t)
		    'gnus-article-sort-by-number))
    (setq gnus-newsgroup-articles
	  (gnus-sorted-nunion gnus-newsgroup-articles articles))
    ;; Suppress duplicates?
    (when gnus-suppress-duplicates
      (gnus-dup-suppress-articles))

    (if (and gnus-fetch-old-headers
	     (eq gnus-headers-retrieved-by 'nov))
	;; We might want to build some more threads first.
	(if (eq gnus-fetch-old-headers 'invisible)
	    (gnus-build-all-threads)
	  (gnus-build-old-threads))
      ;; Mark the inserted articles that are unread as unread.
      (setq gnus-newsgroup-unreads
	    (gnus-sorted-nunion
	     gnus-newsgroup-unreads
	     (gnus-sorted-nintersection
	      (gnus-list-of-unread-articles gnus-newsgroup-name)
	      articles)))
      ;; Mark the inserted articles as selected so that the information
      ;; of the marks having been changed by a user may be updated when
      ;; exiting this group.  See `gnus-summary-update-info'.
      (dolist (art articles)
	(setq gnus-newsgroup-unselected (delq art gnus-newsgroup-unselected))))
    ;; Let the Gnus agent mark articles as read.
    (when gnus-agent
      (gnus-agent-get-undownloaded-list))
    ;; Remove list identifiers from subject
    (gnus-summary-remove-list-identifiers)
    ;; First and last article in this newsgroup.
    (when gnus-newsgroup-headers
      (setq gnus-newsgroup-begin
	    (mail-header-number (car gnus-newsgroup-headers))
	    gnus-newsgroup-end
	    (mail-header-number
	     (car (last gnus-newsgroup-headers)))))
    (when gnus-use-scoring
      (gnus-possibly-score-headers))))

(defun gnus-summary-insert-old-articles (&optional all)
  "Insert all old articles in this group.
If ALL is non-nil, already read articles become readable.
If ALL is a number, fetch this number of articles."
  (interactive "P" gnus-summary-mode)
  (prog1
      (let ((old (sort (mapcar #'gnus-data-number gnus-newsgroup-data) #'<))
	    older len)
	(setq older
	      ;; Some nntp servers lie about their active range.  When
	      ;; this happens, the active range can be in the millions.
	      ;; Use a compressed range to avoid creating a huge list.
	      (gnus-range-difference
	       (gnus-range-difference (list gnus-newsgroup-active) old)
	       gnus-newsgroup-unexist))
	(setq len (gnus-range-length older))
	(cond
	 ((null older) nil)
	 ((numberp all)
	  (if (< all len)
	      (let ((older-range (nreverse older)))
		(setq older nil)

		(while (> all 0)
		  (let* ((r (pop older-range))
			 (min (if (numberp r) r (car r)))
			 (max (if (numberp r) r (cdr r))))
		    (while (and (<= min max)
				(> all 0))
		      (push max older)
		      (setq all (1- all)
			    max (1- max))))))
	    (setq older (gnus-uncompress-range older))))
	 (all
	  (setq older (gnus-uncompress-range older)))
	 (t
	  (when (and (numberp gnus-large-newsgroup)
		   (> len gnus-large-newsgroup))
	      (let ((cursor-in-echo-area nil)
		    (initial (gnus-parameter-large-newsgroup-initial
			      gnus-newsgroup-name))
		    input)
		(when (eq initial 'all)
		  (setq initial len))
		(setq input
		      (read-string
		       (format
			"How many articles from %s (%s %d): "
			gnus-newsgroup-name
			(if initial "max" "default")
			len)
		       nil nil
		       (and initial
			    (number-to-string initial))))
		(unless (string-match "^[ \t]*$" input)
		  (setq all (string-to-number input))
		  (if (< all len)
		      (let ((older-range (nreverse older)))
			(setq older nil)

			(while (> all 0)
			  (let* ((r (pop older-range))
				 (min (if (numberp r) r (car r)))
				 (max (if (numberp r) r (cdr r))))
			    (while (and (<= min max)
					(> all 0))
			      (push max older)
			      (setq all (1- all)
				    max (1- max))))))))))
	  (setq older (gnus-uncompress-range older))))
	(if (not older)
	    (message "No old news.")
	  (gnus-summary-insert-articles older)
	  (gnus-summary-limit (gnus-sorted-nunion old older))))
    (gnus-summary-position-point)))

(defun gnus-summary-insert-new-articles ()
  "Insert all new articles in this group."
  (interactive nil gnus-summary-mode)
  (let ((old (sort (mapcar #'gnus-data-number gnus-newsgroup-data) #'<))
	(old-high gnus-newsgroup-highest)
	(nnmail-fetched-sources (list t))
	(new-active (gnus-activate-group gnus-newsgroup-name 'scan))
	i new)
    (unless new-active
      (error "Couldn't fetch new data"))
    (setq gnus-newsgroup-active (copy-tree new-active))
    (setq i (cdr gnus-newsgroup-active)
	  gnus-newsgroup-highest i)
    (while (> i old-high)
      (push i new)
      (cl-decf i))
    (if (not new)
	(message "No gnus is bad news")
      (gnus-summary-insert-articles new)
      (setq gnus-newsgroup-unreads
	    (gnus-sorted-nunion gnus-newsgroup-unreads new))
      (gnus-summary-limit (gnus-sorted-nunion old new))))
  (gnus-summary-position-point))

;;; Bookmark support for Gnus.
(declare-function gnus-article-show-summary "gnus-art" ())
(declare-function bookmark-make-record-default
                  "bookmark" (&optional no-file no-context posn))
(declare-function bookmark-prop-get "bookmark" (bookmark prop))
(declare-function bookmark-default-handler "bookmark" (bmk))
(declare-function bookmark-get-bookmark-record "bookmark" (bmk))
(defvar bookmark-yank-point)
(defvar bookmark-current-buffer)

(defun gnus-summary-bookmark-make-record ()
  "Make a bookmark entry for a Gnus summary buffer."
  (let (pos buf)
    (unless (and (derived-mode-p 'gnus-summary-mode) gnus-article-current)
      (save-restriction              ; FIXME is it necessary to widen?
        (widen) (setq pos (point))) ; Set position in gnus-article buffer.
      (setq buf "art") ; We are recording bookmark from article buffer.
      (setq bookmark-yank-point (point))
      (setq bookmark-current-buffer (current-buffer))
      (gnus-article-show-summary))      ; Go back in summary buffer.
    ;; We are now recording bookmark from summary buffer.
    (unless buf (setq buf "sum"))
    (let* ((subject (elt (gnus-summary-article-header) 1))
           (grp     (car gnus-article-current))
           (art     (cdr gnus-article-current))
           (head    (gnus-summary-article-header art))
           (id      (mail-header-id head)))
      `(,subject
	,@(condition-case nil
	      (bookmark-make-record-default 'no-file 'no-context pos)
	    (wrong-number-of-arguments
	     (bookmark-make-record-default 'point-only)))
        (location . ,(format "Gnus-%s %s:%d:%s" buf grp art id))
        (group . ,grp) (article . ,art)
        (message-id . ,id) (handler . gnus-summary-bookmark-jump)))))

;;;###autoload
(defun gnus-summary-bookmark-jump (bookmark)
  "Handler function for record returned by `gnus-summary-bookmark-make-record'.
BOOKMARK is a bookmark name or a bookmark record."
  (let ((group    (bookmark-prop-get bookmark 'group))
        (article  (bookmark-prop-get bookmark 'article))
        (id       (bookmark-prop-get bookmark 'message-id))
        (buf      (car (split-string (bookmark-prop-get bookmark 'location)))))
    (gnus-fetch-group group (list article))
    (gnus-summary-insert-cached-articles)
    (gnus-summary-goto-article id nil 'force)
    ;; FIXME we have to wait article buffer is ready (only large buffer)
    ;; Is there a better solution to know that?
    ;; If we don't wait `bookmark-default-handler' will have no chance
    ;; to set position. However there is no error, just wrong pos.
    (sit-for 1)
    (when (string= buf "Gnus-art")
      (other-window 1))
    (bookmark-default-handler
     `(""
       (buffer . ,(current-buffer))
       . ,(bookmark-get-bookmark-record bookmark)))))

(gnus-summary-make-all-marking-commands)

(provide 'gnus-sum)

(run-hooks 'gnus-sum-load-hook)

;; Local Variables:
;; coding: utf-8
;; End:

;;; gnus-sum.el ends here