summaryrefslogtreecommitdiff
path: root/.emacs.d/init.el
blob: 5b5698ebec7198b0b21d49e5747f822d7e997d2e (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
;;; init.el --- Sean's Emacs init  -*- lexical-binding:t;no-byte-compile:t -*-

;; Except for parts marked as authored by others, this file is
;;
;; Copyright (C) 2010-2023  Sean Whitton <spwhitton@spwhitton.name>
;;
;; and 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.
;;
;; This file 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 this file.  If not, see <https://www.gnu.org/licenses/>.

;;; Commentary:

;; We use a prefix "spw/" for functions and variables defined in files
;; matching ~/.emacs.d/*.el, since the "spw-" and "spw--" prefixes would be
;; for a file called "spw.el" with a defined API, providing an `spw' feature.
;;
;; Prefer using the customise interface for variables, faces and enabling and
;; disabling global minor modes, except when we want to associate an extended
;; comment to a number of settings (typically we use the customise interface's
;; facility for adding comments for only short comments).
;;
;; Aim for compatibility with the version of Emacs included in Debian stable.
;;
;; Bind only key sequences reserved for users or which are already bound to
;; commands I don't use often, where those bindings are well-established and
;; thus (i) not likely to be rebound by upstream to commands that I do use
;; often; and (ii) not likely to be bound by third party packages.
;; For example, we resettle `kill-region' to C-x C-d.  C-x g was tacitly
;; reserved by upstream to Magit, so that's available.  But not M-o or C-M-z.
;;
;; Rough convention to use C-c LETTER for global personal bindings and
;; sequences beginning C-z for mode-specific personal bindings.  One exception
;; is some prefix maps under C-z, like C-z 4 and C-z 5, which are meant to
;; mirror the corresponding prefix maps under C-x.  Use <F5> through <F9> for
;; mode-specific bindings or leave free for temporary keyboard macro bindings.

;;; Code:

;; libs in ~/.emacs.d/site-lisp can override system packages.
;; This is for my personal, possibly-patched versions of libraries.
(add-to-list 'load-path
	     (directory-file-name
	      (expand-file-name "site-lisp/" user-emacs-directory)))

;; libs in ~/.emacs.d/initlibs are overridden by system packages.
;; This is for fallback copies of libraries I don't want to be without.
(add-to-list 'load-path
	     (directory-file-name
	      (expand-file-name "initlibs/" user-emacs-directory))
	     t)

;; gdbmacs loads Gnus out of ~/src/emacs/primary/, if it's there.
(when (string= (daemonp) "gdbmacs")
  (let ((gnus-primary (expand-file-name "~/src/emacs/primary/lisp/gnus/")))
    (when (file-directory-p gnus-primary)
      (when-let* ((gnus-lib (locate-library "gnus"))
		  (gnus-lib-dir (file-name-directory gnus-lib))
		  (gnus-lib-cons
		   (or (member (directory-file-name gnus-lib-dir) load-path)
		       (member gnus-lib-dir load-path))))
	(rplaca gnus-lib-cons (directory-file-name gnus-primary))))))

(require 'cl-lib)
(require 'subr-x)
(require 'diminish)
(require 'paredit)
(require 'ws-butler)
(require 'mode-local)
(require 'transient-cycles)

;;;; Customisation & appearance

(custom-set-faces
 ;; custom-set-faces was added by Custom.
 ;; If you edit it by hand, you could mess it up, so be careful.
 ;; Your init file should contain only one such instance.
 ;; If there is more than one, they won't work right.
 '(default ((t (:weight medium :height 105 :foundry "SRC" :family "Hack"))))
 '(comint-highlight-prompt ((t (:inherit minibuffer-prompt :weight bold))))
 '(fill-column-indicator ((t (:background "light gray"))))
 '(fixed-pitch ((t (:foundry "SRC" :family "Hack"))))
 '(org-code ((t (:inherit (shadow fixed-pitch)))))
 '(org-date ((t (:inherit fixed-pitch :foreground "Purple" :underline t))))
 '(org-verbatim ((t (:inherit (shadow fixed-pitch)))))
 '(region ((t (:extend t :background "#EECD82"))) nil "Colour is from the Lucid build.")
 '(variable-pitch ((t (:weight regular :height 120 :foundry "bitstream" :family "Bitstream Charter"))))
 '(variable-pitch-text ((t (:inherit variable-pitch))) nil "Handled by `spw/maybe-scale-basic-faces' instead."))

;; Set background colour but don't touch text terminals.
(dolist (ws '(x pgtk w32 ns))
  (add-to-list
   'window-system-default-frame-alist
   ;; If we were not started with --daemon or by 'emacsclient -a ""', then
   ;; we're probably a shortlived instance of Emacs just to test something.
   ;; Set a different background colour to more easily distinguish frames
   ;; belonging to shortlived instances from those belonging to main instance.
   `(,ws
     . ((background-color
	 . ,(pcase (daemonp)
	      ('nil "honeydew") ("gdbmacs" "linen") (_ "#FFFFF6")))))))

(defun spw/maybe-scale-basic-faces (frame)
  "Entry for `window-size-change-functions' to increase font sizes
from those set by `custom-set-faces' for frames on wide monitors,
except where doing so would itself prevent fitting two 80-column
windows side-by-side in the frame."
  (let ((wide-monitor-p
	 (> (cadddr (assoc 'geometry (frame-monitor-attributes frame))) 1635)))
    (when (or wide-monitor-p
	      ;; Check whether a previous call made any changes we might need
	      ;; to undo if FRAME has moved to a smaller display.
	      (not (eq scroll-bar-mode
		       (frame-parameter frame 'vertical-scroll-bars)))
	      (= (face-attribute 'default :height frame) 120)
	      (= (face-attribute 'variable-pitch :height frame) 151))
      (let* (;; Above 1635 you can scale up and still fit two 80-col windows.
	     ;; Below 1315 you can't fit the two windows even w/o scaling up.
	     (medium-p (> 1635 (frame-pixel-width frame) 1315))
	     (scale-up-p (and wide-monitor-p (not medium-p))))
	(modify-frame-parameters
	 frame
	 `(;; Can fit two 80-col windows only if we disable scroll bars.
	   (vertical-scroll-bars . ,(and (not (and wide-monitor-p medium-p))
					 scroll-bar-mode))))
	;; Check Emacs found the relevant font on this window system, else our
	;; height values might be invalid.
	(when (find-font (font-spec :foundry "SRC" :family "Hack") frame)
	  (set-face-attribute 'default frame :height (if scale-up-p 120 105)))
	(when (find-font (font-spec :foundry "bitstream"
				    :family "Bitstream Charter")
			 frame)
	  (set-face-attribute 'variable-pitch frame
			      :height (if scale-up-p 151 120)))))))
(add-to-list 'window-size-change-functions #'spw/maybe-scale-basic-faces)

;;; `frame--current-backround-mode' assumes that TERM=screen-256color means a
;;; dark background.  But if we're in tmux then I can always have a light
;;; background by typing C-\ W (see ~/.tmux.conf).

;; Handle 'emacs -nw' initial frames.
(when (and (framep terminal-frame)
	   (cl-find-if
	    (apply-partially #'string-prefix-p "TMUX=") initial-environment))
  (set-terminal-parameter terminal-frame 'background-mode 'light))

;; Handle 'emacsclient -tc' frames.
;; Require that TMUX is set in the frame's own environment parameter.
;; The hook is run with the new tty frame selected.
(defun spw/set-tmux-background-mode ()
  (when (and (frame-parameter nil 'environment)	; check it has one
	     (getenv "TMUX" (selected-frame)))
    (set-terminal-parameter nil 'background-mode 'light)))
(add-hook 'tty-setup-hook #'spw/set-tmux-background-mode)

(custom-set-variables
 ;; custom-set-variables was added by Custom.
 ;; If you edit it by hand, you could mess it up, so be careful.
 ;; Your init file should contain only one such instance.
 ;; If there is more than one, they won't work right.
 '(after-save-hook '(executable-make-buffer-file-executable-if-script-p))
 '(appt-display-diary nil)
 '(appt-display-interval 6)
 '(async-shell-command-buffer 'rename-buffer)
 '(auth-source-save-behavior nil)
 '(backup-by-copying-when-linked t)
 '(bongo-default-directory "~/annex/music/")
 '(bongo-insert-album-covers t)
 '(bongo-insert-whole-directory-trees t)
 '(bongo-mode-line-indicator-mode nil)
 '(bongo-prefer-library-buffers nil)
 '(c-default-style "linux")
 '(calc-kill-line-numbering nil)
 '(calendar-date-display-form
   '((format "%s-%.2d-%.2d %.3s" year
	     (string-to-number month)
	     (string-to-number day)
	     dayname)))
 '(calendar-date-style 'iso)
 '(calendar-week-start-day 1)
 '(column-number-mode t)
 '(comint-prompt-read-only t)
 '(compilation-scroll-output 'first-error)
 '(completion-auto-help 'lazy)
 '(completion-styles '(flex))
 '(confirm-kill-emacs 'y-or-n-p)
 '(copy-region-blink-delay 0)
 '(copyright-names-regexp "Sean Whitton")
 '(copyright-year-ranges t)
 '(cperl-close-paren-offset -4 nil nil "See `cperl-indent-parens-as-block'.")
 '(cperl-indent-level 4)
 '(cperl-indent-parens-as-block t nil nil "Makes it easier to use longer names for subroutines.")
 '(cperl-lineup-step 1)
 '(cursor-type 'box)
 '(cycle-spacing-actions '(just-one-space) nil nil "Restore Emacs 28 behaviour of M-SPC.")
 '(dabbrev-case-fold-search t)
 '(diary-file "~/doc/emacs-diary")
 '(diary-list-entries-hook '(diary-include-other-diary-files diary-sort-entries))
 '(diary-mark-entries-hook '(diary-mark-included-diary-files))
 '(dired-clean-up-buffers-too nil)
 '(dired-dwim-target t)
 '(dired-free-space 'separate)
 '(dired-isearch-filenames t)
 '(dired-listing-switches "--group-directories-first -alh")
 '(dired-omit-files "\\`[.]?#\\|\\`[.][.]?\\'\\|\\`\\.git\\'")
 '(dired-recursive-copies 'always)
 '(display-fill-column-indicator-character 32)
 '(emacs-lisp-docstring-fill-column 75)
 '(enable-recursive-minibuffers t)
 '(eshell-cmpl-cycle-completions nil nil nil "This makes Eshell completions a bit more like bash's.")
 '(eshell-history-size 5000)
 '(eshell-visual-commands
   '("vi" "screen" "tmux" "top" "htop" "less" "more" "mutt" "locmaint"))
 '(fill-column 78)
 '(font-lock-maximum-decoration '((lisp-mode . 1) (consfigurator-lisp-mode . 1) (t . t)))
 '(gc-cons-threshold 16777216)
 '(gdb-many-windows t)
 '(gdb-show-main t nil nil "This is helpful when gdb-many-windows is turned off.")
 '(global-so-long-mode t)
 '(gnus-article-skip-boring t)
 '(gnus-auto-center-summary nil)
 '(gnus-auto-select-next 'slightly-quietly)
 '(gnus-buttonized-mime-types
   '("text/x-\\(?:diff\\|patch\\)" "multipart/\\(?:alternative\\|signed\\)"))
 '(gnus-directory "~/local/News/")
 '(gnus-extra-headers '(To Cc List-Id))
 '(gnus-gcc-mark-as-read t)
 '(gnus-global-score-files '("~/doc/News/"))
 '(gnus-interactive-exit 'quiet)
 '(gnus-kill-files-directory "~/src/athpriv/News/")
 '(gnus-kill-summary-on-exit t nil nil "Would prefer nil but t seems advisable for notmuch groups.")
 '(gnus-large-ephemeral-newsgroup 8000)
 '(gnus-large-newsgroup 8000)
 '(gnus-mark-article-hook '(spw/gnus-mark-article-hook))
 '(gnus-message-archive-group "sent")
 '(gnus-message-archive-method '(nnmaildir "fmail" (directory "~/.fmail/")))
 '(gnus-permanently-visible-groups "^nnmaildir\\+fmail:\\(?:notes\\|sent\\)$")
 '(gnus-read-newsrc-file nil)
 '(gnus-save-killed-list
   "^\\(?:[^n]\\|n[^n]\\|nn[^s]\\|nns[^e]\\|nnse[^l]\\|nnsel[^e]\\|nnsele[^c]\\|nnselec[^t]\\|nnselect[^:]\\)")
 '(gnus-save-newsrc-file nil)
 '(gnus-search-default-engines '((nnmaildir . notmuch)))
 '(gnus-search-notmuch-remove-prefix "~/.fmail/")
 '(gnus-secondary-select-methods '((nnmaildir "fmail" (directory "~/.fmail/"))))
 '(gnus-sum-thread-tree-false-root "")
 '(gnus-sum-thread-tree-indent " ")
 '(gnus-sum-thread-tree-leaf-with-other "├► ")
 '(gnus-sum-thread-tree-root "")
 '(gnus-sum-thread-tree-single-leaf "╰► ")
 '(gnus-sum-thread-tree-vertical "│")
 '(gnus-summary-line-format "%U%R%z %(%12&user-date;  %*%-23,23f%)  %B%s\12")
 '(gnus-summary-thread-gathering-function 'gnus-gather-threads-by-references)
 '(gnus-suppress-duplicates t)
 '(gnus-thread-sort-functions
   '(gnus-thread-sort-by-number gnus-thread-sort-by-total-score))
 '(gnus-topic-display-empty-topics nil)
 '(gnus-update-message-archive-method t)
 '(gnus-user-date-format-alist
   '((32042 . "%2l:%M%#p")
     (118823 . "Yest %2l:%M%#p")
     (604800 . "%a %2l:%M%#p")
     (16102447 . "%d %B")
     (t . "%Y-%b-%d")))
 '(haskell-indentation-layout-offset 4)
 '(haskell-indentation-left-offset 4)
 '(holiday-bahai-holidays nil)
 '(holiday-hebrew-holidays nil)
 '(holiday-islamic-holidays nil)
 '(howm-directory "~/doc/howm/")
 '(howm-file-name-format "%Y/%Y-%m-%d-%H%M.org")
 '(howm-keyword-file "~/doc/howm/.howm-keys")
 '(howm-view-use-grep t)
 '(icomplete-hide-common-prefix nil)
 '(icomplete-in-buffer t)
 '(icomplete-mode t)
 '(icomplete-show-matches-on-no-input t)
 '(icomplete-tidy-shadowed-file-names t t)
 '(imenu-auto-rescan t)
 '(initial-major-mode 'spw/scratch-lisp-interaction-mode)
 '(kill-read-only-ok t)
 '(log-edit-hook
   '(log-edit-insert-message-template log-edit-insert-cvs-template log-edit-insert-changelog spw/log-edit-show-diff) nil nil "Drop log-edit-show-files to avoid its window becoming most recently used for C-x o.")
 '(magit-define-global-key-bindings nil)
 '(magit-diff-refine-hunk 'all)
 '(magit-save-repository-buffers nil)
 '(mail-envelope-from 'header nil nil "Bypass MTA rewriting user@localhost.")
 '(mail-specify-envelope-from t nil nil "Bypass MTA rewriting user@localhost.")
 '(mail-user-agent 'gnus-user-agent)
 '(mailscripts-detach-head-from-existing-branch 'ask)
 '(mailscripts-extract-patches-branch-prefix "mail/")
 '(mailscripts-project-library 'project)
 '(major-mode-remap-alist '((perl-mode . cperl-mode)) nil nil "cperl-mode doesn't try to indent lines within a POD, and usefully font locks scalars that are members of hashes and arrays.")
 '(make-pointer-invisible t nil nil "Works only for self-insert chars and undone by changes in window manager focus, but less annoying than `mouse-avoidance-mode'.")
 '(message-auto-save-directory "~/tmp/" nil nil "So locmaint will catch them.")
 '(message-citation-line-format "On %a %d %b %Y at %I:%M%p %Z, %N wrote:\12")
 '(message-citation-line-function 'message-insert-formatted-citation-line)
 '(message-forward-as-mime nil nil nil "For compatibility.")
 '(message-forward-before-signature nil nil nil "For compatibility.")
 '(message-forward-included-headers
   '("^From:" "^Subject:" "^Date:" "^To:" "^Cc:" "^Message-ID:") nil nil "For compatibility.")
 '(message-ignored-resent-headers
   "^Return-receipt\\|^X-Gnus\\|^Gnus-Warning:\\|^>?From \\|^Delivered-To:\\|^\\(?:X-\\)?Content-Length:\\|^X-UIDL:\\|^X-TUID:\\|^\\(?:X-\\)?Status:\\|^Lines:")
 '(message-make-forward-subject-function '(message-forward-subject-fwd) nil nil "For compatibility.")
 '(message-sendmail-envelope-from 'header nil nil "Bypass MTA rewriting user@localhost.")
 '(message-wash-forwarded-subjects t)
 '(minibuffer-follows-selected-frame nil)
 '(mm-default-directory "~/tmp/")
 '(mm-file-name-rewrite-functions
   '(mm-file-name-delete-control mm-file-name-delete-gotchas mm-file-name-trim-whitespace mm-file-name-collapse-whitespace mm-file-name-replace-whitespace))
 '(mml-secure-openpgp-encrypt-to-self t nil nil "So I can read copies in my sent mail directory.")
 '(mml-secure-openpgp-sign-with-sender t)
 '(mode-line-compact 'long)
 '(mouse-drag-copy-region t nil nil "X primary selection-like behaviour within Emacs even when not available outside.")
 '(mouse-highlight 1 nil nil "See `make-pointer-invisible'.")
 '(mouse-yank-at-point t)
 '(native-comp-async-jobs-number 1)
 '(native-comp-async-report-warnings-errors 'silent)
 '(nnmail-extra-headers '(To Cc List-Id))
 '(notmuch-address-use-company nil)
 '(nov-text-width 78)
 '(org-adapt-indentation t nil nil "Sometimes set to nil in .dir-locals.el, e.g. in ~/doc/newpapers.")
 '(org-agenda-entry-text-maxlines 3)
 '(org-agenda-files "~/doc/emacs-org-agenda-files")
 '(org-agenda-persistent-filter t)
 '(org-agenda-remove-times-when-in-prefix 'beg)
 '(org-agenda-restore-windows-after-quit nil nil nil "Interacts badly with `tab-bar-history-mode'.")
 '(org-agenda-skip-deadline-if-done t)
 '(org-agenda-skip-deadline-prewarning-if-scheduled 3)
 '(org-agenda-skip-scheduled-if-deadline-is-shown 'not-today)
 '(org-agenda-skip-scheduled-if-done t)
 '(org-agenda-skip-timestamp-if-done t)
 '(org-agenda-start-on-weekday nil)
 '(org-agenda-sticky t)
 '(org-agenda-timegrid-use-ampm t)
 '(org-agenda-todo-ignore-scheduled 'future)
 '(org-agenda-window-setup 'current-window)
 '(org-archive-location "~/doc/archive/howm/archive.org::* From %s")
 '(org-archive-save-context-info '(time file olpath))
 '(org-archive-subtree-save-file-p t)
 '(org-blank-before-new-entry '((heading . t) (plain-list-item . auto)))
 '(org-bookmark-names-plist nil nil nil "Turn off to avoid git merge conflicts.")
 '(org-catch-invisible-edits 'show)
 '(org-cycle-separator-lines 0)
 '(org-deadline-warning-days 60)
 '(org-default-notes-file "~/doc/howm/refile.org")
 '(org-directory "~/doc/howm/")
 '(org-enforce-todo-checkbox-dependencies t)
 '(org-enforce-todo-dependencies t)
 '(org-footnote-section "Notes")
 '(org-imenu-depth 4)
 '(org-list-allow-alphabetical nil nil nil "So I can start lines with \"P. 211 - \" to refer to p. 211 not start a list.")
 '(org-list-demote-modify-bullet
   '(("-" . "+")
     ("+" . "*")
     ("*" . "-")
     ("1." . "-")
     ("1)" . "-")))
 '(org-list-use-circular-motion t)
 '(org-log-done 'time)
 '(org-log-into-drawer t)
 '(org-log-repeat nil nil nil "Cluttering, and information probably in git.")
 '(org-log-states-order-reversed nil)
 '(org-outline-path-complete-in-steps nil nil nil "Desirable with `icomplete-mode'.")
 '(org-read-date-prefer-future 'time)
 '(org-refile-allow-creating-parent-nodes 'confirm)
 '(org-refile-targets '((org-agenda-files :maxlevel . 5) (nil :maxlevel . 5)))
 '(org-refile-use-outline-path 'file)
 '(org-show-context-detail
   '((agenda . local)
     (bookmark-jump . lineage)
     (isearch . lineage)
     (default . ancestors-full)))
 '(org-special-ctrl-a/e t)
 '(org-special-ctrl-k t)
 '(org-startup-folded nil)
 '(org-startup-indented nil nil nil "Ensures buffer text doesn't go beyond 80 columns.")
 '(org-tags-match-list-sublevels 'indented)
 '(org-todo-keyword-faces
   '(("SOMEDAY" :foreground "#0000FF" :weight bold)
     ("NEXT" :foreground "#DD0000" :weight bold)))
 '(org-todo-keywords
   '((sequence "TODO(t)" "NEXT(n)" "|" "DONE(d)")
     (sequence "WAITING(w@)" "SOMEDAY(s)" "|" "CANCELLED(c)")))
 '(org-treat-S-cursor-todo-selection-as-state-change nil)
 '(org-treat-insert-todo-heading-as-state-change t)
 '(org-use-fast-todo-selection 'expert)
 '(org-yank-folded-subtrees nil)
 '(proced-enable-color-flag t)
 '(proced-show-remote-processes t)
 '(project-switch-commands
   '((project-find-file "Find file")
     (project-find-regexp "Find regexp")
     (project-find-dir "Find directory")
     (project-dired "Root Dired" "C-x C-j")
     (project-vc-dir "VC-Dir")
     (spw/project-vc-root-diff "VC-Diff" "D")
     (spw/project-vc-print-root-log "VC-Log" "L")
     (transient-cycles-cmd-spw/project-eshell "Eshell")))
 '(project-switch-use-entire-map t)
 '(rcirc-default-full-name "Sean Whitton [spwhitton@spwhitton.name]")
 '(rcirc-default-nick "spwhitton")
 '(rcirc-default-user-name "spwhitton")
 '(rcirc-display-server-buffer nil)
 '(rcirc-log-directory "~/local/irclogs")
 '(rcirc-log-filename-function 'spw/rcirc-generate-log-filename)
 '(rcirc-log-flag t)
 '(rcirc-time-format "%b/%d %H:%M ")
 '(rcirc-track-abbreviate-flag nil)
 '(rcirc-track-ignore-server-buffer-flag t)
 '(rcirc-track-minor-mode t)
 '(read-buffer-completion-ignore-case t)
 '(read-file-name-completion-ignore-case t)
 '(read-mail-command 'gnus)
 '(read-minibuffer-restore-windows nil)
 '(remember-data-file "~/local/tmp/scratch")
 '(remember-notes-buffer-name "*scratch*")
 '(require-final-newline t)
 '(save-interprogram-paste-before-kill nil nil nil "See <https://debbugs.gnu.org/53728>.")
 '(save-place-mode t nil nil "If quitting Emacs is slow, set `save-place-forget-unreadable-files' to nil.")
 '(savehist-additional-variables '(compile-history log-edit-comment-ring))
 '(savehist-mode t)
 '(select-active-regions 'only)
 '(select-enable-primary t)
 '(send-mail-function 'sendmail-send-it)
 '(shell-command-prompt-show-cwd t)
 '(show-paren-when-point-in-periphery t nil nil "Useful for C-M-d.")
 '(shr-max-width 78)
 '(slime-load-failed-fasl 'never)
 '(tab-bar-history-mode t)
 '(tab-bar-show 1)
 '(tramp-use-ssh-controlmaster-options nil nil nil "Rely on my ~/.ssh/config.")
 '(tramp-verbose 1 nil nil "Manual says this should improve performance.")
 '(transient-cycles-buffer-siblings-mode t)
 '(transient-cycles-tab-bar-mode t)
 '(transient-cycles-window-buffers-cycle-backwards-key [134217777] nil nil "M-1.")
 '(transient-cycles-window-buffers-cycle-forwards-key [134217780] nil nil "M-4.")
 '(transient-cycles-window-buffers-mode t)
 '(uniquify-buffer-name-style 'post-forward nil (uniquify))
 '(use-short-answers t)
 '(vc-find-revision-no-save t)
 '(vc-follow-symlinks t)
 '(vc-git-diff-switches '("-M" "-C") nil nil "We might also consider -B.")
 '(vc-git-print-log-follow t)
 '(view-read-only t nil nil "Rebind otherwise useless self-insert keys, and means existing C-x C-r, C-x 4 r etc. usable for getting into mode.")
 '(warning-suppress-types '((comp)))
 '(which-func-modes '(lisp-mode emacs-lisp-mode c-mode))
 '(which-function-mode t)
 '(window-combination-resize t)
 '(ws-butler-global-mode t)
 '(x-stretch-cursor t))


;;;; Configuration helpers

(defmacro spw/when-library-available (libraries &rest forms)
  "Evaluate FORMS when optional LIBRARIES is/are on the `load-path'.

Libraries, not features, since we can't know whether features are
available on the `load-path' without actually loading libraries,
which we want to avoid at Emacs startup.

Use this only after `package-initialize' has been called,
i.e. not in `early-init-file', so that places LIBRARIES might be
available are present in the `load-path'."
  (declare (indent 1))
  `(when ,(if (listp libraries)
	      `(cl-every #'locate-library ',(mapcar #'symbol-name libraries))
	    `(locate-library ,(symbol-name libraries)))
     ,@forms))

(defmacro spw/reclaim-keys-from (feature map &rest keys)
  "Unbind each of KEYS in MAP after FEATURE is loaded."
  `(with-eval-after-load ',feature
     (when (boundp ',map)	       ; handle older Emacsen/package versions
       ,@(cl-loop for key in keys collect `(define-key ,map ,key nil)))))

(defmacro spw/feature-define-keys (features &rest bindings)
  (declare (indent 1))
  (macroexp-progn
   (cl-loop
    with defns
    = (cl-loop for (k b) on bindings by #'cddr
	       if (symbolp b) collect `(,k #',b) else collect (list k b))
    for feature in (if (listp features) features (list features))
    for name = (if (listp feature) (car feature) feature)
    for map = (if (listp feature)
		  (cadr feature)
		(let ((name (symbol-name name)))
		  (intern (format (if (string-suffix-p "-mode" name)
				      "%s-map" "%s-mode-map")
				  name))))
    for form = `(when (boundp ',map)	; for older Emacsen/package versions
		  ,@(cl-loop for df in defns collect `(define-key ,map ,@df)))
    if name collect `(with-eval-after-load ',name ,form) else collect form)))

(defmacro spw/feature-add-hook (function &rest features)
  (declare (indent 1))
  (macroexp-progn
   (cl-loop
    for feature in (if (listp features) features (list features))
    for name = (if (listp feature) (car feature) feature)
    for hook = (if (listp feature)
		   (cadr feature)
		 (let ((name (symbol-name name)))
		   (intern (format (if (string-suffix-p "-mode" name)
				       "%s-hook" "%s-mode-hook")
				   name))))
    for form = `(add-hook ',hook #',function)
    if name collect `(with-eval-after-load ',name ,form) else collect form)))

(cl-defmacro spw/define-skeleton
    (command (mode &key abbrev key (file `',mode)
		   (map (intern (concat (symbol-name mode) "-map")))
		   (tbl (intern (concat (symbol-name mode) "-abbrev-table"))))
	     docstring interactor &rest rest-of-skeleton)
  "Wrapper for `define-skeleton' to make it easy to use the
skeleton with a prefix argument, to wrap several interregions or
an active region, but also easy to use with an abbrev, for when
there is nothing already typed that should be wrapped."
  (declare (indent 2))
  (let* ((inverted (gensym))
	 (key (and key map
		   `((define-key ,map ,key
				 ;; Invert the prefix argument as expect to
				 ;; use the binding to wrap interregions more
				 ;; often than to wrap words.
				 (lambda (&optional arg)
				   (interactive "*P")
				   (let ((,inverted (and arg (* -1 arg))))
				     (,command ,inverted ,inverted)))))))
	 (abbrev
	  (and abbrev tbl
	       ;; E.g. `minibuffer-mode-abbrev-table' unbound before Emacs 29.
	       `((when (boundp ',tbl)
		   (define-abbrev ,tbl ,abbrev "" #',command :system t))))))
    `(progn
       (define-skeleton ,command ,docstring ,interactor ,@rest-of-skeleton)
       ,@(and (or key abbrev)
	      (if file
		  `((with-eval-after-load ,file ,@key ,@abbrev))
		`(,@key ,@abbrev))))))

(defmacro spw/add-once-hook (hook function &optional depth local)
  "Add a hook which removes itself when called.
For something which should happen just once."
  (let ((sym (gensym)))
    `(progn (fset ',sym (lambda (&rest args)
			  (remove-hook ,hook ',sym ,local)
			  (apply ,function args)))
	    (add-hook ,hook ',sym ,depth ,local))))

(defconst spw/fqdn
  (cond ((string-prefix-p (format "%s." (system-name)) mail-host-address)
	 mail-host-address)
	((executable-find "perl")
	 (shell-command-to-string
	  "perl -mNet::Domain=hostfqdn -e'print hostfqdn'")))
  "The fully qualified domain name of the system running Emacs, if
that's something we can determine.")

(defun spw/on-host-p (host)
  ;; If HOST looks like an FQDN, require that `spw/fqdn' is non-nil and equal.
  (string= host (if (cl-find ?. host) spw/fqdn (system-name))))

(defun spw/on-host-primary-p (host)
  (and (eq (daemonp) t) (spw/on-host-p host)))

;; This is a combination of the two `transient-cycles-define-commands' forms
;; for `transient-cycles-buffer-siblings-mode'.  We could factor this out of
;; those and make it part of the library's API, but currently those two forms
;; also serve as nice usage examples for `transient-cycles-define-commands'.
(defmacro spw/transient-cycles-define-buffer-switch
    (commands &rest keyword-arguments)
  (declare (indent 0))
  (let ((window (gensym))
	(prev-buffers (gensym)))
    `(transient-cycles-define-commands (,window ,prev-buffers)
       ,(cl-loop for command in commands
		 for (original lambda . body)
		   = (if (proper-list-p command) command
		       `(,command (&rest args)
			  ,(interactive-form (cdr command))
			  (apply #',(cdr command) args)))
		 collect
		 `(,original ,lambda
		   ,@(and (listp (car body))
			  (eq (caar body) 'interactive) (list (pop body)))
		   (let ((ret-val ,(macroexp-progn body)))
		     (when (windowp ret-val) (setq ,window ret-val))
		     (setq ,prev-buffers (window-prev-buffers ,window))
		     ret-val)))
       (transient-cycles-buffer-ring-cycler
	:ring (cl-etypecase ret-val
		(buffer (transient-cycles-buffer-siblings-ring ret-val))
		(window (transient-cycles-buffer-siblings-ring
			 (window-buffer ret-val)))
		(ring ret-val))
	:action (if (windowp ret-val)
		    (with-selected-window ret-val
		      (let ((display-buffer-overriding-action
			     '((display-buffer-same-window)
			       (inhibit-same-window . nil))))
			(display-buffer buffer)))
		  (switch-to-buffer buffer t t)))
       :on-exit (if ,window
		    (progn (set-window-next-buffers ,window nil)
			   (set-window-prev-buffers ,window ,prev-buffers))
		  (switch-to-buffer (current-buffer) nil t)
		  (set-window-next-buffers nil nil)
		  (set-window-prev-buffers nil ,prev-buffers))
       . ,keyword-arguments)))

(defmacro spw/macroexp-for (lambda-list items &rest body)
  (declare (indent 2))
  (let ((macro (gensym)))
    `(cl-macrolet ((,macro ,lambda-list ,@body))
       ,@(cl-loop for item in items collect
		  (cons macro (if (listp item) item (list item)))))))


;;;; The *scratch* buffer

;; This uses `pop-to-buffer-same-window' and so obeys `display-buffer-alist'.
(global-set-key "\C-xl" #'scratch-buffer)

(defun spw/eval-print-last-sexp (orig-fun &rest args)
  (require 'pp)
  (let ((start (point-marker))
	(pp-use-max-width t)
	(pp-max-width fill-column)
	(eval-expression-print-level 20)
	(eval-expression-print-length 500))
    (skip-chars-backward "[:space:]\n")
    (delete-region (point) start)
    (apply orig-fun args)
    (save-excursion (goto-char start) (indent-pp-sexp t))
    (set-marker start nil)
    (terpri (current-buffer) t)))
(dolist (cmd '(eval-print-last-sexp
	       edebug-eval-print-last-sexp

	       ;; Not quite traditional Emacs C-j, but close enough.
	       xscheme-send-previous-expression))
  (advice-add cmd :around #'spw/eval-print-last-sexp))

;;; Persistent *scratch*, for the primary daemon only, to avoid conflicts.
;;; Unlike ~/doc/howm/refile.org and C-c c c, this does not require ~/doc/
;;; checked out.  And we get one per machine, which can be convenient.
;;;
;;; We used to have a separate *notes* without Paredit and in `text-mode'.
;;; But using one buffer for both Lisp evaluation and rough notes means that
;;; we can have a single i3/Sway binding for both purposes.
;;; If another major mode is really required, can just create a new buffer.
;;; This relies for its usability on `spw/scratch-lisp-interaction-mode'.

(defun spw/remember-notes-setup ()
  (when (zerop (buffer-size))
    ;; `after-init-hook' is early enough that `initial-scratch-message' would
    ;; be inserted for us by `command-line-1', but this is simpler given that
    ;; we have to advise `get-scratch-buffer-create' too.
    (insert (substitute-command-keys initial-scratch-message))
    (set-buffer-modified-p nil))
  (setq default-directory (expand-file-name "~/")))
(spw/feature-add-hook spw/remember-notes-setup
  (remember remember-notes-mode-hook))

(defun spw/hijack-scratch ()
  ;; Switch such that right after startup 'q' takes us to *scratch*, as usual.
  (switch-to-buffer (remember-notes)))

(unless (stringp (daemonp))
  (add-hook 'after-init-hook #'spw/hijack-scratch)
  (advice-add 'get-scratch-buffer-create :override #'remember-notes))

;;; Something like IELM's `ielm-change-working-buffer', the key feature which
;;; distinguishes IELM from both `lisp-interaction-mode' and Eshell.  Thanks
;;; to this, and Eshell, I don't ever need IELM.

(defun spw/lisp-interaction-wrap-with-buffer (buffer regionp)
  "Wrap the region or preceding form in `with-current-buffer'."
  (interactive
   (list (read-buffer
	  "Buffer to make current: "
	  (let ((candidate
		 (window-buffer
		  (spw/get-mru-window
		   (lambda (w) (minibufferp (window-buffer w)))))))
	    (cond ((and candidate (not (eq (current-buffer) candidate)))
		   candidate)
		  ((buffer-local-boundp
		    'spw/lisp-interaction-target-buffer
		    (current-buffer))
		   spw/lisp-interaction-target-buffer))))
	 (use-region-p)))
  (setq-local spw/lisp-interaction-target-buffer buffer)
  (save-excursion
    (unless regionp (forward-sexp -1))
    (insert-pair 1 ?\( ?\))
    (deactivate-mark)
    (insert (format "with-current-buffer \"%s\"" buffer))
    ;; Not a full `indent-sexp' as that might reduce readability if what we're
    ;; wrapping has just been yanked straight in from elsewhere.  But avoid
    ;; next sexp being directly under opening paren of `with-current-buffer'.
    (newline-and-indent))
  (when (or (not regionp) (> (point) (mark))) (up-list)))
(define-key lisp-interaction-mode-map
    "\C-z\C-b" #'spw/lisp-interaction-wrap-with-buffer)

(defun spw/lisp-interaction-wrap-with-buffer-and-eval (buffer)
  "Like `spw/lisp-interaction-wrap-with-buffer' followed by C-j."
  (interactive
   (list (or (and (not current-prefix-arg)
		  (buffer-local-boundp 'spw/lisp-interaction-target-buffer
				       (current-buffer))
		  spw/lisp-interaction-target-buffer)
	     (read-buffer "Buffer to make current: "))))
  (deactivate-mark)
  (spw/lisp-interaction-wrap-with-buffer buffer nil)
  (eval-print-last-sexp))
(define-key lisp-interaction-mode-map
    "\C-z\C-j" #'spw/lisp-interaction-wrap-with-buffer-and-eval)


;;;; System and files

;; Put all auto-save files under ~/.emacs.d, both local and TRAMP.  Put local
;; backups under local ~/.emacs.d and TRAMP backups under remote ~/.emacs.d.
;; E.g. when editing a file /sudo::/foo on laptop, its auto-saves will go to
;; /home/spwhitton/.emacs.d but its backups will go to /root/.emacs.d.
(let ((backups-dir (concat user-emacs-directory "backups/"))
      (auto-saves-dir (concat user-emacs-directory "auto-saves/")))
  (dolist (dir (list backups-dir auto-saves-dir))
    (make-directory dir t) (chmod dir #o700))
  (setq backup-directory-alist `(("." . ,backups-dir))
        auto-save-file-name-transforms `((".*" ,auto-saves-dir t))
        tramp-auto-save-directory auto-saves-dir
	tramp-backup-directory-alist backup-directory-alist))

;; On remote hosts in the UTC timezone, assume I'm in Arizona.  This is
;; relevant for using Org-mode, dired timestamps, etc..  Note that hosts in
;; the UK will be in GMT or BST, not UTC, so this won't affect those.
(when (and (string= "UTC" (cadr (current-time-zone)))
	   (memq system-type '(gnu gnu/linux gnu/kfreebsd)))
  (setenv "TZ" "MST")
  (set-time-zone-rule "/usr/share/zoneinfo/America/Phoenix"))

;;; Opening files in external programs
;;;
;;; For years I used the classic `openwith-mode', but it often breaks other
;;; Emacs features, and I am not keen on the hack of signalling an error to
;;; avoid the execution of things like `after-find-file'.  I think that all I
;;; actually require is that C-x C-f and RET in dired are able to open files
;;; in external programs, with a prefix argument to suppress, plus a binding
;;; to reopen the current buffer in an external program.
;;;
;;; If in fact something more like `openwith-mode' is wanted, let's try
;;; implementing it as :around advice which prepends the handler to
;;; `inhibit-file-name-handlers' only for the duration of specific commands.
;;; We could cl-letf `after-find-file' to just kill the buffer, and also bind
;;; `large-file-warning-threshold' to a large value in the advice.

(defvar spw/external-programs
  (cl-flet ((for-exts (cmd &rest exts)
	      (cl-loop for ext in exts collect (cons ext cmd))))
    (pcase system-type
      ((or 'ms-dos 'windows-nt) nil)	; reserved for later
      (_ `(("pdf" . "evince %s")
	   ,@(for-exts "vlc %s"
		       "ogg" "mp3" "flac" "caf"
		       "mkv" "webm" "avi" "mp4" "wmv" "flv" "mov")
	   ,@(for-exts "soffice %s" "doc" "docx"
		       "odt" "ods" "xls" "xlsx" "ppt" "pptx" "potx")
	   ("hwp" . "hanword %s")
	   ,@(for-exts "eog %s" "jpg" "jpeg" "png" "gif")))))
  "Association list of file extensions to shell commands with which
to open them using `spw/try-external-open'")

(defun spw/try-external-open (filename &optional interactive)
  (interactive (list (or (buffer-file-name)
			 (user-error "This buffer is not visiting a file"))
		     t))
  (cl-flet ((die (msg)
	      ;; Just return nil if we were called from Lisp.
	      (and interactive (user-error msg))))
    (let ((unixp (not (memq system-type '(ms-dos windows-nt)))))
      (if (and unixp (not (or (getenv "DISPLAY") (getenv "WAYLAND_DISPLAY"))))
	  (die "No DISPLAY")
	(if (file-remote-p filename)
	    (die "Not a local file")
	  (if (file-directory-p filename)
	      (die "Is a directory")
	    (if-let ((ext (file-name-extension filename))
		     (program
		      (cdr
		       (assoc
			(downcase ext) spw/external-programs #'string=)))
		     (cmd (format program (shell-quote-argument
					   (expand-file-name filename)))))
		(always
		 (set-process-query-on-exit-flag
		  (start-process-shell-command
		   "spw/try-external-open-process" nil
		   ;; On Unix-like, set process up to outlive Emacs.
		   (if unixp (concat "exec nohup " cmd " >/dev/null") cmd))
		  (not unixp)))
	      (die "No external program association"))))))))
(global-set-key "\C-cgf" #'spw/try-external-open)

(defun spw/find-file (filename &optional arg)
  (interactive
   (list (read-file-name
	  "Find file: " nil default-directory 'confirm-after-completion)
	 current-prefix-arg))
  (or (and (not arg) (spw/try-external-open filename))
      (find-file filename t)))
(global-set-key [remap find-file] #'spw/find-file)

(defun spw/dired-find-file (&optional arg)
  (interactive "P")
  (or (and (not arg) (spw/try-external-open (dired-get-file-for-visit)))
      (dired-find-file)))
(with-eval-after-load 'dired
  (define-key dired-mode-map [remap dired-find-file] #'spw/dired-find-file))


;;;; General editing

(define-minor-mode spw/personal-bindings-mode
  "A simple way to overcome problems overriding major mode bindings.
To be used only when it seems to be necessary."
  :init-value t :lighter nil :keymap (make-sparse-keymap) :global t)

;; Regarding `set-mark-command-repeat-pop': if this is set to t, then
;; re-setting the mark right after popping to it -- to go and edit somewhere
;; near the destination and then come back, say -- requires remembering that a
;; C-u C-u prefix is needed; that cognitive load outweighs a few extra C-u
;; when this is nil, I think.  And the cost of forgetting is high: you've lost
;; the position, and it might take quite a few keypresses to get back there.
;;
;; Further, if you pop fewer than four times and then want to set a mark, that
;; requires no fewer keystrokes with this set to t than with it set to nil.
;; There is also `repeat' to repeatedly pop.
;;
;; If we had a dedicated key for setting a deactivated mark, distinct from the
;; key used to pop marks, then these remarks would not apply, and we could set
;; `set-mark-command-repeat-pop' to t.

;; Swap C-SPC and C-SPC C-SPC in Transient Mark mode.
(defun spw/set-mark-command (orig-fun arg)
  (if (and (eq last-command 'set-mark-command)
	   (not mark-active) (eql (point) (mark t)))
      ;; Binding `last-command' and popping the mark is not necessary given
      ;; the current implementation of `set-mark-command', but we don't want
      ;; to depend on that.
      ;; The idea is that when Transient Mark mode is on, invoking the command
      ;; twice is the canonical way to set a deactivated mark, but we want
      ;; invoking the command twice to mean setting a mark and activating it.
      (let ((last-command 'ignore))
	(pop-mark)
	(cl-letf (((symbol-function 'message) #'ignore))
	  (funcall orig-fun arg))
	(message "Mark activated"))
    (let ((inhibit (or mark-active
		       (and arg (not (> (prefix-numeric-value arg) 4))))))
      (funcall orig-fun arg)
      (unless inhibit
        (setq deactivate-mark 'dont-save)))))
(advice-add 'set-mark-command :around #'spw/set-mark-command)

;; Swap C-x C-x and C-u C-x C-x in Transient Mark mode.
(defun spw/exchange-point-and-mark (args)
  (list (if (and transient-mark-mode (not mark-active))
	    (not (car args))
	  (car args))))
(advice-add 'exchange-point-and-mark
	    :filter-args #'spw/exchange-point-and-mark)

(setq disabled-command-function nil)

(defun spw/no-blink-matching-paren (orig-fun &rest args)
  (let ((blink-matching-paren nil))
    (apply orig-fun args)))
(advice-add 'paredit-move-past-close-and-newline
	    :around #'spw/no-blink-matching-paren)

;; Make C-w and <M-backspace> the same as the defaults of the UNIX tty
;; line editor and GNU readline, respectively: C-w deletes back to
;; whitespace, <M-backspace> to the nearest word boundary.  I can't
;; have my full Emacs config on arbitrary hosts, but by configuring
;; Emacs in this way, I can have consistent line editing almost everywhere,
;; and moreover, kill back to whitespace is often what's wanted, for
;; correcting typos and just for deletion, e.g. of whole e-mail addresses,
;; whole long form command line arguments in Eshell, etc.
(defun spw/unix-word-rubout (arg &optional pos neg)
  (interactive "p")
  ;; Do skip over \n because `backward-kill-word' does.
  (unless pos (setq pos "[:space:]\n"))
  (unless neg (setq neg "^[:space:]\n"))
  (undo-boundary)
  (let ((start (point)))
    ;; Go only backwards.
    (dotimes (_ (abs arg))
      (skip-chars-backward pos)
      (skip-chars-backward neg))
    ;; Skip forward over any read-only text (e.g. an Eshell or comint prompt).
    (when-let ((beg (and (get-char-property (point) 'read-only)
			 (next-single-char-property-change
			  (point) 'read-only nil start))))
      (goto-char beg))
    (kill-region start (point))))
(global-set-key "\C-w" 'spw/unix-word-rubout)
(global-set-key "\M-\d" 'backward-kill-word)

;; Resettle the previous occupant of C-w.  This has to be a key which can also
;; be bound in .inputrc, so C-z is out as that is used for shell job control.
;; (Don't need `list-directory' as always use dired, so no resettlement.)
(global-set-key "\C-x\C-d" #'kill-region)

;; Previously, I used M-- in front of C-M-u and C-M-d in both Paredit and
;; non-Paredit buffers, and reclaimed C-M-p and C-M-n from Paredit.  However,
;; the global bindings of C-M-p and C-M-n have not proved themselves useful.
(global-set-key [?\C-\M-n] #'up-list)
(global-set-key [?\C-\M-p] "\C-u-\C-\M-d")

;; C-x C-z, and just M-x, remain for getting at upstream's C-z binding.
;; If upstream make changes such that C-z and C-x C-z are different, we could
;; bind C-z C-m to upstream's C-z.
(global-set-key "\C-z" (define-prefix-command 'spw/ctl-z-map))

;; This is used to drop marks used for killing, or pushed after yanking, in
;; order to access a mark which was set for navigational purposes.  There's an
;; in-built C-x C-x so that it is easy to see whether enough non-navigational
;; marks have been popped.
;;
;; C-z C-z is easy to type repeatedly, and to follow up with a final C-x C-x,
;; because the two modified letter keys are on the same side of the keyboard.
;; Could use C-x C-SPC or C-z C-x for this, moving existing bindings under
;; (other parts of) `spw/ctl-z-map'.
;; C-x SPC and C-z C-SPC aren't easy to type repeatedly.
(defun spw/pop-mark-and-exchange ()
  (interactive)
  (if (memq last-command '(exchange-point-and-mark spw/pop-mark-and-exchange))
      (pop-to-mark-command)
    (pop-mark))
  (message "Mark popped")
  (exchange-point-and-mark))
(define-key spw/ctl-z-map "\C-z" #'spw/pop-mark-and-exchange)

;; Bind a key simply to (re-)activate the mark which does not
;; involve moving point, as `exchange-point-and-mark' does.  This is
;; useful if you use isearch to select a region but realise only after
;; you've left the intended start of the region that you need to do a
;; second isearch to extend it far enough: e.g. C-s 1st C-z C-x C-s 2nd RET
;;
;; Activating the region prevents the second isearch from resetting
;; the mark.  Having this binding removes the need to activate the
;; region before entering the first isearch, which is useful both with
;; and without `transient-mark-mode'.
;;
;; This makes C-z C-x a sort of prefix command: "execute the next command in
;; temporary Transient Mark mode / as if Transient Mark mode were turned on".
;;
;; C-z C-SPC might be another good option for this.
(defun spw/activate-mark (&rest _ignore)
  (interactive)
  (activate-mark))
(define-key spw/ctl-z-map "\C-x" #'spw/activate-mark)

;; Is a binding for `zap-up-to-char' needed in addition to one for
;; `zap-to-char'?  If you don't need to insert any text before the target
;; char, then M-z CHAR CHAR is equivalent to using `zap-up-to-char' with CHAR,
;; and is easy to type.  If you do need to insert, you can just M-z CHAR, type
;; or yank, and then type CHAR again to conclude.  By contrast, replacing use
;; of `zap-to-char' with `zap-up-to-char' is not so easy, as you might need to
;; switch from typing M-z to typing C-d, for example.
;;
;; At the very least this demonstrates that `zap-to-char' more deserves to be
;; on an easy-to-strike key than does `zap-up-to-char'.  So for now, make the
;; other command available on a less valuable key.
;;
;; Hmm, might be good to add `paredit-zap-to-char' which doesn't actually
;; delete some delimiters.
(spw/macroexp-for (keymap key def)
    (((current-global-map) [remap zap-to-char] zap-to-char)
     (spw/personal-bindings-mode-map "\M-`" zap-up-to-char))
  (let ((new (intern (concat "spw/" (symbol-name def))))
	(args (gensym)))
    `(progn (defun ,new (&rest ,args)
	      ,(interactive-form def)
	      (let (case-fold-search)
		(apply #',def ,args)))
	    (define-key ,keymap ,key #',new))))

(defun spw/before-zap (_arg char &optional interactive)
  (when (and interactive (eql char (char-after)))
    (delete-forward-char 1)))
(advice-add 'zap-to-char :before #'spw/before-zap)
(advice-add 'zap-up-to-char :before #'spw/before-zap)

(global-set-key [remap dabbrev-expand] #'hippie-expand)

;; In an emacsclient(1) frame, or a buffer spawned by an Eshell process
;; calling emacsclient(1), this is like '<ESC>ZZ' in vi.
(global-set-key "\C-cz" "\C-x\C-s\C-x#")

;; always update buffers when files change on disk -- if we want to go back to
;; the version of the file we had in Emacs, we can just hit undo
(setq auto-revert-use-notify nil)
(global-auto-revert-mode 1)
(diminish 'auto-revert-mode)

;; Work around lack of <https://github.com/magit/magit/pull/4591>.
(setq magit-auto-revert-mode nil)

;; C-x x g should not ask for confirmation.
(global-set-key "\C-xxg" (lambda ()
			   (interactive)
			   (revert-buffer (not current-prefix-arg) t)))

;; These don't work in text terminals, so unbind to avoid developing any
;; habits of using them.  Further, if the goal is to avoid having to release
;; modifier keys between typing numeric prefix arguments and commands, then in
;; most cases this will mean one-handed chording, which should be avoided.  If
;; the goal is instead to reduce the total number of keypresses, then it
;; should be sufficient to use only the M- bindings, releasing the meta key
;; after typing the first digit or minus sign.  But that's a minor benefit
;; over just starting with C-u.  Indeed, I rebind M-0..9 for other purposes.
;;
;; (M-- remains bound to `negative-argument' because it's particularly useful
;; for 'M-- M-l' and 'M-- M-u'.  So, C-u and M-- are the two keys I use to
;; supply non-negative and negative numeric prefix arguments, respectively.)
(cl-loop for i from ?0 to ?9
	 for key = (read (format "[?\\C-%c]" i))
	 do (global-unset-key key) (define-key esc-map key nil))
(global-set-key [?\C--] nil)
(global-set-key [?\C-\M--] nil)

(with-eval-after-load 'diff-mode
  (cl-loop with map = (lookup-key diff-mode-map "\e")
	   for i from ?0 to ?9
	   do (define-key map (char-to-string i) nil)))

;; Similarly, we cannot reliably distinguish <C-backspace> from <backspace>.
;; Many terminal emulators send ^? for <backspace> and ^H for <C-backspace>,
;; or the other way around, but not all of them.  Firefox binds <C-backspace>
;; to delete words backwards (apparently following some Microsoft products),
;; so there's some risk of developing a habit of using it.
(global-unset-key [C-backspace])

;; filling of comments -- we don't want to set
;; `comment-auto-fill-only-comments' always on because in Org-mode, for
;; example, we want auto fill both inside and outside of comments
(add-hook 'prog-mode-hook #'turn-on-auto-fill)
(setq-mode-local prog-mode comment-auto-fill-only-comments t)

(spw/feature-add-hook display-fill-column-indicator-mode
  prog-mode message conf-mode)

(add-hook 'text-mode-hook #'goto-address-mode)
(add-hook 'prog-mode-hook #'goto-address-prog-mode)

(global-set-key "\C-cih" #'add-file-local-variable-prop-line)

;; don't do anything with abbrevs if ~/doc is not checked out
(defvar spw/doc-abbrevs-file (expand-file-name "~/doc/emacs-abbrevs"))
(when (file-exists-p spw/doc-abbrevs-file)
  (setq abbrev-file-name spw/doc-abbrevs-file)
  (quietly-read-abbrev-file)

  (setq save-abbrevs 'silently)

  (setq-default abbrev-mode t)
  (diminish 'abbrev-mode))

;; similar
(defvar spw/doc-bookmarks-file (expand-file-name "~/doc/emacs-bookmarks"))
(when (file-exists-p spw/doc-bookmarks-file)
  (setq bookmark-default-file spw/doc-bookmarks-file
        bookmark-save-flag 1))

;; For files that must be in American English, add both these lines:
;;
;;    <!-- Local IspellDict: en_US -->
;;    <!-- Local IspellPersDict: ~/doc/aspell-en_US -->
;;
(let ((default-dictionary (expand-file-name "~/doc/aspell-en_GB")))
  (when (and (executable-find "aspell") (file-exists-p default-dictionary))
    ;; Emacs 29: use setopt
    (setq ispell-personal-dictionary default-dictionary)))

(global-set-key "\C-h\C-m" #'man)
(global-set-key "\C-cgp" #'cperl-perldoc)
(global-set-key "\C-cgk" #'save-buffers-kill-emacs)

;; Have M-c, M-l and M-u be consistent in all of them exiting Isearch -- the
;; fact that M-c doesn't keeps tripping me up.  While we're here, drop similar
;; isearch-mode-map bindings; all these commands have a binding under M-s too.
(spw/reclaim-keys-from isearch isearch-mode-map "\M-c" "\M-e" "\M-r")

;; Also replace C-w in isearch-mode-map, which also trips me up sometimes.
(defun spw/isearch-yank-word-or-char-hook ()
  (unless (eq this-command #'isearch-yank-word-or-char)
    (define-key isearch-mode-map "\C-w" nil)
    (remove-hook 'post-command-hook #'spw/isearch-yank-word-or-char-hook)))
(defun spw/isearch-yank-word-or-char ()
  (interactive)
  (setq this-command #'isearch-yank-word-or-char)
  (call-interactively #'isearch-yank-word-or-char)
  (define-key isearch-mode-map "\C-w" #'isearch-yank-word-or-char)
  (add-hook 'post-command-hook #'spw/isearch-yank-word-or-char-hook))
(define-key isearch-mode-map "\C-w" nil)
(define-key isearch-mode-map "\C-z\C-w" #'spw/isearch-yank-word-or-char)

(diminish 'eldoc-mode)

;; Invert meaning of C-u for M-= except when the region is active.
(defun spw/count-words ()
  (interactive)
  (if (or (use-region-p) (not current-prefix-arg))
      (call-interactively #'count-words)
    (setq current-prefix-arg nil)
    (call-interactively #'count-words-region)))
(global-set-key [remap count-words-region] #'spw/count-words)

;; Don't have RET try to reindent before inserting a newline, only indent
;; afterwards.  The reindentation is only occasionally helpful, I find, and
;; often it does the wrong thing.
(setq-default electric-indent-inhibit t)

;; Make it easy to use M-a to reach beginning of first sentence of a comment.
(defun spw/backward-sentence-skip-forward ()
  (interactive)
  (call-interactively #'backward-sentence) (skip-syntax-forward " <"))
(global-set-key [remap backward-sentence] #'spw/backward-sentence-skip-forward)

;; See `comint-prompt-read-only'.
(spw/feature-define-keys comint
  [remap kill-region] comint-kill-region
  [remap kill-whole-line] comint-kill-whole-line)

(spw/define-skeleton
    spw/minibuffer-cd-skel (minibuffer-mode :abbrev "cd" :file nil)
  "" (shell-quote-argument
      (expand-file-name (read-directory-name "Run command in dir: " "~/")))
  "cd " str " && " _)

(global-set-key "\C-cd" #'duplicate-line)

(setq skeleton-end-newline nil)

;;; Electric pairs when the region is active
;;;
;;; I used to have `electric-pair-mode' switched on, based on the idea that it
;;; makes non-paredit buffers a bit more like paredit buffers, and that's the
;;; least surprising way to have things, given that I'm not going to give up
;;; paredit.  However, even with `electric-pair-conservative-inhibit', I still
;;; frequently found myself with unwanted insertion.  It also makes C-w much
;;; less effective for correcting mistakes, because you end up with junk to
;;; the right of point as well as to the left.
;;;
;;; Add back a way to wrap the active region in paired delimiters; useful
;;; after hitting M-@ and/or C-M-SPC a few times.  This is the main paredit
;;; feature that I find myself expecting to work in other modes.
;;;
;;; An alternative is to deactivate `electric-pair-mode' only in `text-mode'.

(defvar spw/wrapping-pairs
  '((emacs-lisp-mode (?` . ?'))
    (org-mode (?* . ?*) (?/ . ?/) (?= . ?=))))

(defvar spw/global-wrapping-pairs
  '((?{ . ?}) (?< . ?>) (?\( . ?\)) (?\[ . ?\]) (?' . ?') (?\" . ?\"))
  "Like `spw/add-wrapping-pairs' but for all major modes.")

(defun spw/wrapping-pairs-post-self-insert-function ()
  (let ((parens-require-spaces nil)
	(match (or (cdr (assoc last-command-event spw/global-wrapping-pairs))
		   (cdr (assoc last-command-event
			       (cdr (assoc major-mode spw/wrapping-pairs)))))))
    (when (and match (use-region-p) (eq (char-before) last-command-event))
      ;; See `electric--after-char-pos' if this needs to be more complex.
      (delete-region (point) (1- (point)))
      ;; Moving point and mark to just outside the two characters we insert.
      ;; Note that this makes us inconsistent with `paredit-doublequote' etc.
      (save-excursion (insert-pair nil last-command-event match))
      (if (> (point) (mark))
	  (progn (forward-char 1) (set-mark (1- (mark))))
	(set-mark (1+ (mark))) (forward-char -1)))))
(add-hook 'post-self-insert-hook
	  #'spw/wrapping-pairs-post-self-insert-function
	  50)			     ; depth same as `electric-pair-mode' uses

;;; Icomplete

;; Possibly we could call `minibuffer-complete-word' if we know we're
;; completing the name of a Lisp symbol.
(spw/reclaim-keys-from minibuffer minibuffer-local-completion-map " " "?")

(setq completion-ignore-case t)

(defun spw/minibuffer-completing-file-name-p ()
  ;; See `icomplete--category'.
  (eq (completion-metadata-get
       (completion-metadata (minibuffer-contents)
			    minibuffer-completion-table
			    minibuffer-completion-predicate)
       'category)
      'file))

;; Most common actions are to select the top completion in the way that
;; `icomplete-fido-ret' does, and to exit with the current input.  So these
;; two get single keypresses, TAB and RET.  We tweak the former such that RET
;; is required to exit with input which has no matches.  This helps avoid
;; creating bogus buffers, file-visiting or otherwise, when I mistype.
;;
;; Choose RET for exiting with current input because then RET behaves the
;; same in `read-string' and `completing-read'.  This makes completion less
;; obtrusive given how some commands provide completion even when they are
;; mostly used to enter arbitrary strings (e.g. `notmuch-search').
;;
;; Don't resettle the previous occupant of <TAB>, `minibuffer-complete',
;; because an `icomplete-mode' user hardly uses it.

;; This is something like a reimplementation of `icomplete-fido-ret'.
(defun spw/icomplete-tab ()
  (interactive)
  (when-let* ((current (car completion-all-sorted-completions)))
    ;; For in-buffer completion it should always be fine to just call
    ;; `icomplete-force-complete', and not exit, because of how in-buffer
    ;; completion uses a transient map.  An alternative would be to guess
    ;; whether completing a file name, e.g. (string-suffix-p "/" current).
    (if (or (not (window-minibuffer-p))
	    (and (spw/minibuffer-completing-file-name-p)
		 (let ((dir (file-name-directory (minibuffer-contents))))
		   (file-directory-p
		    (if dir (expand-file-name (directory-file-name current)
					      (substitute-env-vars dir))
		      current)))))
	(icomplete-force-complete)
      (icomplete-force-complete-and-exit))))
(define-key icomplete-minibuffer-map [?\t] #'spw/icomplete-tab)

(define-key icomplete-minibuffer-map [remap minibuffer-complete-and-exit] nil)

;; This is based on `icomplete--fido-ccd'.
(defun spw/update-completion-category-overrides ()
  (pcase-dolist (`(,cat . ,props) completion-category-defaults)
    (setf (alist-get cat completion-category-overrides)
	  (or (alist-get cat completion-category-overrides)
	      (cl-loop for entry in props
		       for (prop . val) = entry
		       if (eq prop 'styles) collect
		       `(,prop . (flex . ,(remq 'flex val)))
		       else collect entry)))))
(add-hook 'icomplete-minibuffer-setup-hook
	  #'spw/update-completion-category-overrides)
(add-hook 'completion-in-region-mode-hook
	  #'spw/update-completion-category-overrides)

;; This is a bit like `icomplete-fido-backward-updir'.
(defun spw/icomplete-choose-rubout ()
  (when (and (window-minibuffer-p) (spw/minibuffer-completing-file-name-p))
    (let ((map (make-sparse-keymap)))
      (define-key
       map "\C-w"
       (lambda (arg)
	 (interactive "p")
	 (spw/unix-word-rubout arg "/:[:space:]\n" "^/:[:space:]\n")))
      (use-local-map (make-composed-keymap map (current-local-map))))))
(add-hook 'icomplete-minibuffer-setup-hook #'spw/icomplete-choose-rubout)

;; Preserve standard bindings for editing text in the minibuffer.
(define-key icomplete-minibuffer-map [?\C-j] nil)

;; Bind M-, and M-. to cycle completions; their normal bindings aren't likely
;; to be needed when completing, and unlike C-, and C-. they work in text
;; terminals.  Alternatives might be C-M-r and C-M-s.
(define-key icomplete-minibuffer-map [?\M-.] #'icomplete-forward-completions)
(define-key icomplete-minibuffer-map [?\M-,] #'icomplete-backward-completions)

(defun spw/empty-minibuffer ()
  (interactive)
  (kill-region (minibuffer-prompt-end) (point-max)))
(define-key minibuffer-mode-map "\C-l" #'spw/empty-minibuffer)


;;;; Buffers and windows

(defvar spw/arrow-keys-mode-map
  (let ((map (make-sparse-keymap)))
    (dolist (key '(up down left right
		      S-up S-down S-left S-right
		      M-up M-down M-left M-right))
      (define-key map (vector ?\C-z key) #'spw/arrow-keys-mode-passthru))
    map)
  "Keymap for `spw/arrow-keys-mode'.")

(define-minor-mode spw/arrow-keys-mode
  "Apply the bindings in `spw/arrow-keys-mode-map', but
additionally bind the sequences of C-z followed by each of the
four arrow keys to activate a transient map in which the four
arrow keys have the bindings they would have absent this mode.

Permits globally re-binding the four arrow keys without rendering
it impossible to access mode-specific bindings for those four
keys (e.g. the use of the left and right arrow keys in
`fido-mode' minibuffers)."
  ;; :init-value t
  :lighter nil :keymap spw/arrow-keys-mode-map :global t)

(defun spw/arrow-keys-mode-passthru ()
  (interactive)
  ;; Possibly we could cache the map in a buffer-local variable.  It'd get
  ;; cleared if the major mode changes, but we'd also need to figure out
  ;; clearing it (but not recomputing it until and unless this function is
  ;; called) if the minor modes change.
  (let ((map (make-sparse-keymap))
	(cell (cl-find 'spw/arrow-keys-mode minor-mode-map-alist :key #'car)))
    (cl-letf (((car cell) nil))
      (dolist (key '([up] [down] [left] [right]
		     [S-up] [S-down] [S-left] [S-right]
		     [M-up] [M-down] [M-left] [M-right]))
	(define-key map key (key-binding key))))
    (let ((key (vector last-command-event)))
      (call-interactively (lookup-key map key) t key))
    (set-transient-map map t)))

(defun spw/get-mru-window (&optional exclude)
  "Like `get-mru-window' but also consider the minibuffer, and
don't consider windows satisfying the predicate EXCLUDE."
  (let (best-window best-time time)
    (dolist (window (window-list-1) best-window)
      (setq time (window-use-time window))
      (when (and (not (and exclude (funcall exclude window)))
		 (not (eq window (selected-window)))
		 (or (not best-time) (> time best-time)))
	(setq best-time time)
	(setq best-window window)))))

(defun spw/back-and-forth (arg)
  (interactive "P")
  (if arg
      ;; if there's a prefix arg then just `other-window', so that's still
      ;; available on C-u 1 C-x o
      (call-interactively #'other-window)
    (if-let ((window (spw/get-mru-window)))
	(select-window window)
      (user-error "No other window to select"))))
(global-set-key [remap other-window] #'spw/back-and-forth)

;;; Initial motivation for `transient-cycles' work is that we want all these
;;; commands to be easily repeatable but without setting a transient map which
;;; binds self-insert chars, as might want to type those just after switching.
;;;
;;; We don't bind any modified arrow keys because there is a good chance they
;;; don't get through to text mode Emacs.  If I have to make regular use of a
;;; terminal to which *un*modified arrow keys don't get through, or arrive as
;;; sequences which already belong to other keys, one idea is to add
;;; C-c/C-z {h,j,k,l} to `input-decode-map' for the arrow keys (or bind them
;;; to commands setting `unread-command-events'), without any transient maps.
;;;
;;; Previously we used <left>/<right> for custom next- and previous-window
;;; commands with transient cycling, and didn't use any windmove commands.
;;; However, because <left>/<right> are my default transient cycling keys,
;;; this led to situations where I tried to use <left>/<right> to switch
;;; window and found myself continuing transient cycling for the previous
;;; command instead.  So, should probably avoid putting anything on unmodified
;;; <left>/<right>.  We could still put something on unmodified <down>/<up>,
;;; which I used to use for `tab-bar-history-mode' forward & back commands.
;;; (`spw/arrow-keys-mode' made it feasible to bind things to unmodified arrow
;;; keys in the global map.  That's disabled at present, as the unmodified
;;; arrow keys are not in use.)
;;;
;;; We might put one of the other sets of windmove commands, such as
;;; windmove-swap-states-* commands, on C-z M-7/8/9/0, or possibly
;;; C-c w M-7/8/9/0.  C-c <left>/<right> are also available, as they tacitly
;;; belong to `winner-mode' / `tab-bar-history-mode'.

(defvar spw/windmove-transient-map (make-sparse-keymap))

(spw/macroexp-for (key direction)
    (("\M-7" "left") ("\M-8" "down") ("\M-9" "up") ("\M-0" "right"))
  (let* ((init (intern (format "spw/windmove-%s" direction)))
	 (noselect (intern (format "spw/windmove-%s-noselect" direction)))
	 (noselect-body
	  `(cl-flet ((old-s-w (symbol-function 'select-window)))
	     (cl-letf (((symbol-function 'select-window)
			(lambda (window &rest _ignore)
			  (old-s-w window 'mark-for-redisplay))))
	       (call-interactively #',(intern
				       (format "windmove-%s" direction)))))))
    `(progn (defun ,noselect () (interactive) ,noselect-body)
	    (define-key spw/windmove-transient-map ,key #',noselect)
	    (defun ,init ()
	      (interactive)
	      ;; Don't select the windows we move through, so that the
	      ;; window where we started becomes the most recently
	      ;; selected window.  Then in the ON-EXIT function, select
	      ;; the destination window again with the NOSELECT argument
	      ;; to `select-window' nil.
	      ,noselect-body
	      (set-transient-map spw/windmove-transient-map t
				 (lambda ()
				   (select-window (selected-window)))))
	    (global-set-key ,key #',init))))

;; We might resettle `pop-global-mark' to C-z C-SPC.
(define-key ctl-x-map "\C-@" #'transient-cycles-window-buffers-back-and-forth)
(define-key ctl-x-map [?\C-\s] #'transient-cycles-window-buffers-back-and-forth)

;; Now using `tab-bar-history-mode' instead of `winner-mode' because (i) it
;; keeps history per tab; (ii) it doesn't delete windows from old window
;; configurations, which makes it faster to identify visually when you've
;; reached the target configuration; (iii) it handles multiple windows in a
;; configuration displaying the same buffer better; specifically, unlike
;; `winner-mode', `tab-bar-history-mode' does not restore just one value for
;; point for all of the windows in the configuration showing a single buffer.
(transient-cycles-define-commands ()
  (("\M-2" . tab-bar-history-back)
   ("\M-3" . tab-bar-history-forward))
  (lambda (_ignore)
    (lambda (count)
      (interactive "p")
      (if (> count 0) (tab-bar-history-forward) (tab-bar-history-back))))
  :cycle-backwards-key "\M-2" :cycle-forwards-key "\M-3")

(define-key transient-cycles-window-buffers-mode-map "\M-1" #'previous-buffer)
(define-key transient-cycles-window-buffers-mode-map "\M-4" #'next-buffer)

;; Start transient cycling among the current buffer's siblings.
;; Can be usefully prefixed with C-x 4 4 etc. to start cycling elsewhere.
(defun spw/cycle-from-here ()
  (interactive)
  (push last-command-event unread-command-events)
  (let (display-buffer-alist)
    ;; NORECORD nil because we *do* want the current buffer pushed to the
    ;; window's previous buffers.
    (pop-to-buffer-same-window (current-buffer))))
(spw/transient-cycles-define-buffer-switch
  (([?\C-x left] . spw/cycle-from-here)
   ([?\C-x right] . spw/cycle-from-here)))

(setq display-buffer-alist
      `(;; This is meant to say: for these buffers which, unusually, do not
	;; benefit from being as tall as possible, always display them in the
	;; other window (in the sense of `find-file-other-window' in stock
	;; Emacs), but if that means splitting vertically, make the window
	;; shorter than it would otherwise be, to allow more lines to the
	;; buffer on the other side of the split (in the case where displaying
	;; the buffer in the other window means splitting horizontally, we are
	;; already allowing as many lines as we can to buffer on the other
	;; side of the split).
	;;
	;; I don't think eshell and scheme would be suitable for
	;; `display-buffer-in-side-window' (at the bottom) because they are
	;; not purely informational -- they're for doing stuff in, and so
	;; should be one of the main (usually two) windows of the frame.  But
	;; not sure about this.  I might just use `spw--window-to-frame' when
	;; they are not purely informational.  How much of an advantage of
	;; side windows is the way in which they can be toggled on and off?
	("\\*\\(?:eshell\\|scratch\\|compilation\\|scheme\\|slime-repl\\|sly-mrepl\\|inferior-lisp\\)"
	 (display-buffer-pop-up-window display-buffer-same-window)
	 (window-height . 0.20)
	 (preserve-size . (nil . t))
	 (inhibit-same-window . t))

	;; We want `inhibit-same-window' t except when popping to a buffer
	;; that's already selected, e.g. hitting 'g' in a *vc-diff* buffer.
	,@(and (fboundp 'buffer-match-p) ; for Emacs 27
	       (let ((re "\\*\\(?:notes\\|vc\\(?:-reflog\\)?-diff\\)\\*"))
		 `((,(lambda (buffer _action)
		       (and (buffer-match-p re buffer)
			    (eq buffer (window-buffer (selected-window)))))
		    display-buffer-same-window)

		   (,re
		    display-buffer-pop-up-window
		    (inhibit-same-window . t)))))

	;; These SLIME windows don't benefit from a lot of height and it is
	;; useful to have them be independent of the main two windows
	;; displaying code, Magit etc.  Get going by hitting C-c C-z to bring
	;; up the REPL.
	("\\*\\(slime\\|sly\\)-\\(inspector\\|compilation\\)\\*"
	 display-buffer-in-side-window
	 (window-height . 0.30)
	 (slot . 2)
	 (side . bottom))
	("^\\*\\(sldb\\|sly-db\\)"
	 display-buffer-in-side-window
	 (window-height . 0.30)
	 (slot . 1) ;; we might have nested debuggers occupy a different slot
	 (side . bottom))

	("^\\*Calendar\\*$"
	 (display-buffer-reuse-window display-buffer-below-selected)
         (window-height . fit-window-to-buffer))

	("^\\*Annotate " display-buffer-full-frame)))

;; Ensure that C-x 4 C-o &c. do not reuse the selected window.
;;
;; `display-buffer-fallback-action' is a constant so cons once in advance.
(let ((ac `(,(car display-buffer-fallback-action) (inhibit-same-window . t))))
  (defun spw/display-buffer (orig-fun &rest args)
    (if (memq this-command
	      '(display-buffer
		project-display-buffer
		transient-cycles-cmd-display-buffer
		transient-cycles-cmd-spw/display-recent-major-mode-buffer))
	(let ((display-buffer-overriding-action ac))
	  (apply orig-fun args))
      (apply orig-fun args))))
(advice-add #'display-buffer :around #'spw/display-buffer)

(defun spw/window-toggle-side-windows ()
    "Like `window-toggle-side-windows', but (i) if the selected
window is a side window, change focus to the most recently used
non-side window first, and upon restore, attempt to restore focus
to the side window; and (ii) if there is no saved side window
state, attempt to produce some useful side window(s)."
  (interactive)
  (cond ((window-parameter nil 'window-side)
	 ;; We're in a side window.
	 (set-frame-parameter nil 'spw/window-side-focused (current-buffer))
	 (select-window (spw/get-mru-window
			 (lambda (w) (window-parameter w 'window-side)))
			'mark-for-redisplay)
	 (window-toggle-side-windows))
	((window-with-parameter 'window-side)
	 ;; There's a side window but it's not selected.
	 (set-frame-parameter nil 'spw/window-side-focused nil)
	 (window-toggle-side-windows))
	((frame-parameter nil 'spw/window-side-focused)
	 ;; We're restoring and we should attempt to restore focus.
	 (window-toggle-side-windows)
	 (when-let ((w (get-buffer-window
			(frame-parameter nil 'spw/window-side-focused))))
	   (select-window w)))
	(t
	 ;; We're restoring and we should not attempt to restore focus.
	 (if (frame-parameter nil 'window-state)
	     (window-toggle-side-windows)
	   ;; There's no saved state.  Attempt to produce useful side windows.
	   (cond ((and (project-current)
		       (directory-files
			(project-root (project-current)) nil "\\.asd\\'"))
		  (if (ignore-errors (slime-output-buffer))
		      (slime-switch-to-output-buffer)
		    (let ((default-directory (expand-file-name "~/")))
		      (slime))))
		 (t (error "No side windows state & no heuristic")))))))
;; Possibly this command should go on M-5 or M-6.
(global-set-key [remap window-toggle-side-windows]
		#'spw/window-toggle-side-windows)

(defun spw/delete-other-windows--toggle-side-windows
    (&optional window &rest _ignore)
  "Save any side window state before deleting other windows such that side
windows can be recovered using `window-toggle-side-windows'.

A limitation is that when `window-toggle-side-windows' is subsequently used
the non-side windows deleted by `delete-other-windows' will also reappear."
  (when (window-parameter window 'window-side)
    (window-toggle-side-windows (window-frame window))))
(advice-add 'delete-other-windows
	    :before #'spw/delete-other-windows--toggle-side-windows)

;; Thanks to `transient-cycles-tab-bar-mode', this makes C-x t o like my
;; (rebound) C-x o.
(define-key tab-prefix-map "o" #'tab-bar-switch-to-recent-tab)
(define-key tab-prefix-map "O" nil)	; easy to hit by accident

(define-key tab-prefix-map [left] #'tab-previous)
(define-key tab-prefix-map [right] #'tab-next)

(define-key spw/ctl-z-map "3" "\C-x1\C-x3")

(define-key ctl-x-5-map "\C-j" "\C-x55\C-x\C-j")
(define-key tab-prefix-map "\C-j" "\C-xtt\C-x\C-j")

;;; For when the buffer's name isn't much help for switching to it, as is
;;; often the case with `notmuch-show' buffers.  We select the most recent
;;; buffer but then transient cycling can take us to other buffers of the same
;;; major mode.

(defun spw/read-major-mode-recent-buffer ()
  (let ((buffers (make-hash-table)))
    (dolist (buffer (buffer-list))
      (with-current-buffer buffer
	(unless (gethash major-mode buffers)
	  (puthash major-mode buffer buffers))))
    (list
     (gethash
      (intern
       (completing-read
	"Most recent buffer of major mode: " (hash-table-keys buffers) nil t))
      buffers))))

(spw/transient-cycles-define-buffer-switch
  ((("\C-zb" . spw/switch-to-recent-major-mode-buffer) (buffer)
      (interactive (spw/read-major-mode-recent-buffer))
      (switch-to-buffer buffer t))

   (("\C-z4b" . spw/switch-to-recent-major-mode-buffer-other-window) (buffer)
      (interactive (spw/read-major-mode-recent-buffer))
      (switch-to-buffer-other-window buffer t))

   (("\C-z5b" . spw/switch-to-recent-major-mode-buffer-other-frame) (buffer)
      (interactive (spw/read-major-mode-recent-buffer))
      (switch-to-buffer-other-frame buffer t))

   (("\C-z4\C-o" . spw/display-recent-major-mode-buffer) (buffer)
      (interactive (spw/read-major-mode-recent-buffer))
      (display-buffer buffer))))


;;;; TRAMP

(with-eval-after-load 'tramp
  (add-to-list 'tramp-connection-properties
	       ;; Activate direct-async-process for all non-multihop SSH
	       ;; connections.
	       '("/ssh:" "direct-async-process" t)
	       ;; session-timeout is about dropping a connection for security
	       ;; reasons alone: never do that.
	       '(nil "session-timeout" nil))

  (add-to-list 'tramp-remote-path 'tramp-own-remote-path))

(unless (string-match			; Emacs 28: unquote and `string-search'
	 (regexp-quote tramp-file-name-regexp) vc-ignore-dir-regexp)
  (setq vc-ignore-dir-regexp
	(format "\\(?:%s\\)\\|\\(?:%s\\)"
		vc-ignore-dir-regexp tramp-file-name-regexp)))


;;;; The Emacs shell

;; This is like HISTCONTROL=ignorespace:ignoredups and 'shopt -s histappend'
;; in my ~/.bashrc: append most commands to the shared history file, but don't
;; load that file except when a fresh Eshell buffer is created.
(setq eshell-save-history-on-exit nil)
(defun spw/eshell-append-history ()
  (when (and eshell-history-file-name
	     (symbolp (file-locked-p eshell-history-file-name)))
    (unless (get-buffer " *eshell history*")
      (lock-file eshell-history-file-name)
      (with-current-buffer (get-buffer-create " *eshell history*" t)
	(when (file-exists-p eshell-history-file-name)
	  (insert-file-contents eshell-history-file-name))))
    (let ((latest (substring-no-properties (ring-ref eshell-history-ring 0))))
      (with-current-buffer (get-buffer " *eshell history*")
	(let* ((nlines (car (buffer-line-statistics)))
	       (excess (- nlines eshell-history-size))
	       (previous
		(and (cl-plusp nlines)
		     (save-excursion
		       (goto-char (1- (point-max)))
		       (buffer-substring (point-at-bol) (point-at-eol))))))
	  (unless (or (string-match "^\\s-" latest)
		      (and previous (string= previous latest)))
	    (unless (cl-minusp excess)
	      (forward-line (1+ excess))
	      (delete-region (point-min) (point)))
	    (save-excursion
	      (goto-char (point-max))
	      (let ((start (point)))
		(insert latest "\n")
		(subst-char-in-region start (1- (point)) ?\n ?\177)))
	    (write-region (point-min) (point-max) eshell-history-file-name nil
			  'silent)))))))
(with-eval-after-load 'esh-cmd
  (add-hook 'eshell-pre-command-hook #'spw/eshell-append-history))
(with-eval-after-load 'esh-mode
  (add-hook 'eshell-mode-hook
	    (lambda ()
	      (remove-hook 'eshell-exit-hook #'eshell-write-history t))))

;; We could have an optional argument to kill any input and reinsert it after
;; running the command, and even restore point within that input.  Might be
;; useful in `spw/eshell-jump' & interactively.
(defun spw/eshell-insert-and-send (&rest args)
  (delete-region eshell-last-output-end (point-max))
  (when (> eshell-last-output-end (point))
    (goto-char eshell-last-output-end))
  (apply #'insert-and-inherit args)
  (eshell-send-input))

(defun spw/eshell-cd (dir)
  (spw/eshell-insert-and-send "cd " (eshell-quote-argument dir)))

;;; Ideas behind the following two functions due to Protesilaos Stavrou.

(defun spw/eshell-cd-recent-dir (&optional arg)
  (interactive "P")
  (let ((directory (completing-read
		    (if arg
			"Dired in other window (directory): "
		      "Switch to directory: ")
		    (ring-elements eshell-last-dir-ring) nil t)))
    (if arg (dired-other-window directory) (spw/eshell-cd directory))))
(with-eval-after-load 'em-hist
  (define-key eshell-hist-mode-map "\C-zd" #'spw/eshell-cd-recent-dir))
;; With this set to nil, recent dirs are not saved to disk, such that the
;; history of recent dirs is effectively buffer-local.
(setq eshell-last-dir-ring-file-name nil)

(defun spw/eshell-cd-project-root ()
  (interactive)
  (if-let ((project (project-current)))
      (spw/eshell-cd (project-root project))
    (user-error "No current project")))
(with-eval-after-load 'esh-mode
  (define-key eshell-mode-map "\C-zp" #'spw/eshell-cd-project-root))

;; Work around Emacs bugs #54976 and #54977.
(with-eval-after-load 'esh-module
  (dolist (module '(eshell-elecslash eshell-tramp eshell-xtra))
    (when (locate-library (format "em-%s" (substring (symbol-name module) 7)))
      (add-to-list 'eshell-modules-list module))))

(spw/define-skeleton spw/eshell-libexec
    (eshell-mode :abbrev "le" :file "esh-mode")
  "" "" "~/" '(eshell-electric-forward-slash) "src/dotfiles/scripts/")

;;; prompt

;; Previously used "~/>" -- no trailing space -- where we appended the
;; additional forward slash at the end of the pwd as otherwise it is a bit too
;; short when we're directly inside HOME.  An alternative approach used before
;; that was to call `abbreviate-file-name' only when not directly inside HOME.
(setq eshell-prompt-function
      (lambda ()
	(if (zerop eshell-last-command-status)
	    (concat (abbreviate-file-name (eshell/pwd)) " % ")
	  (format "%s %s %% " eshell-last-command-status
		  (abbreviate-file-name (eshell/pwd)))))
      eshell-prompt-regexp "^[^%\n]* % ")

;;; getting to Eshell buffers

(defun spw/eshell-jump (&optional chdir busy-okay)
  "Pop to a recently-used Eshell that isn't busy, or start a fresh one.
Return a ring for transient cycling among other Eshells, in the order of most
recent use.  An Eshell is busy if there's a command running, or it's narrowed
(in the latter case, this was probably done with C-u C-c C-r).
When BUSY-OKAY is `interactive', an Eshell is additionally considered busy
when there is a partially-entered command.

Non-nil CHDIR requests an Eshell that's related to `default-directory'.
Specifically, if CHDIR is non-nil, pop to an Eshell in `default-directory',
pop to an Eshell under the current project root and change its directory to
`default-directory', or start a fresh Eshell in `default-directory'.
If CHDIR is `project', use the current project root as `default-directory'.
In `dired-mode', unless CHDIR is `strict', use the result of calling
`dired-current-directory' as `default-directory'.

Non-nil BUSY-OKAY requests ignoring whether Eshells are busy.  This makes
it easy to return to Eshells with long-running commands.
If BUSY-OKAY is `interactive', as it is interactively, ignore whether Eshells
are busy unless there is a prefix argument, and unconditionally start a fresh
Eshell if the prefix argument is 16 or greater (e.g. with C-u C-u).
If BUSY-OKAY is `fresh', unconditionally start a fresh Eshell, whether or not
an Eshell that isn't busy already exists.
Any other non-nil value means to ignore whether Eshells are busy.

If BUSY-OKAY is `interactive', `this-command' is equal to `last-command',
and there is no prefix argument, set the prefix argument to the numeric
value of the last prefix argument multiplied by 4, and also bind
`display-buffer-overriding-action' to use the selected window.
Thus, M-& M-& is equivalent to M-& C-u M-&, and M-& M-& M-& is equivalent to
M-& C-u M-& C-u C-u M-&.  This streamlines the case where this command takes
you to a buffer that's busy but you need one that isn't, but note that with
the current implementation transient cycling is restarted, so the busy buffer
will become the most recently selected buffer.

Some ideas behind these behaviours are as follows.

- Just like Lisp REPLs, we do not normally need a lot of different Eshells;
  it is fine for shell history associated with different tasks to become
  mixed together.  But we do require an easy way to start new Eshells when
  other Eshells are already busy running commands.

- Rename *eshell* to *eshell*<N>, but don't ever rename *eshell*<N> back to
  *eshell*, because that is a conventional workflow -- upstream M-&, C-h i,
  M-x ielm, M-x compile etc. always take you to the unnumbered buffer,
  possibly renaming the numbered one out of the way.

  We do nevertheless reuse Eshells, not for the sake of creating fewer, but
  just so that this command can be used to get back to the most recent few
  Eshells you were working in, to see output.

- We'll sometimes use C-x 4 1 in front of this command, and if we're
  already in an Eshell, we might use C-x 4 4 C-x <left>/<right> to cycle to
  another Eshell in another window, or a sequence like M-& C-u M-&, which
  doesn't bind `display-buffer-overriding-action'.

- It's not especially convenient to distinguish between `project-eshell'
  and `eshell' Eshells.  We just want a way to quickly obtain an Eshell in
  the project root, and bind that to C-x p e.

- Except when `this-command' is equal to `last-command', don't do anything
  special when the current buffer is the one we'd pop to, as previous
  versions of this command did.  That sort of context-dependent behavioural
  variation reduces the speed with which one can use the command because
  you have to think more about what it will do."
  (interactive '(nil interactive))
  (require 'eshell)
  (let* ((default-directory (or (and (not (eq chdir 'strict))
				     (eq major-mode 'dired-mode)
				     (dired-current-directory))
				default-directory))
	 (current-project (and (not (file-remote-p default-directory))
			       (project-current)))
	 (proj-root (and current-project (project-root current-project)))
	 (target-directory (expand-file-name
			    (or (and (eq chdir 'project) proj-root)
				default-directory)))
	 (again (and (not current-prefix-arg) (eq busy-okay 'interactive)
		     (eq this-command last-command)))
	 (display-buffer-overriding-action
	  (if again '(display-buffer-same-window (inhibit-same-window . nil))
	    display-buffer-overriding-action))
	 (orig-busy-okay busy-okay)
	 target-directory-eshells other-eshells
	 most-recent-eshell same-project-eshell target-directory-eshell)
    ;; It's important that `transient-cycles-cmd-spw/eshell-jump' never sees
    ;; this prefix argument because it has its own meanings for C-u & C-u C-u.
    ;; This means that C-u M-! and M-! M-! are different, which is desirable.
    ;;
    ;; We could multiply by 16 if `last-prefix-arg' is nil and the current
    ;; buffer is an Eshell that's not busy.  The idea would be that when M-&
    ;; takes us to a non-busy buffer, a second M-& would only take us to the
    ;; same buffer, so skip over that step and do C-u C-u M-&.
    ;; However, this simpler design has the advantage that if I know I want a
    ;; non-busy Eshell I can just hit M-& M-& without looking and I know I'll
    ;; get the most recent non-busy Eshell in the right directory.
    (when again
      (setq current-prefix-arg (* 4 (prefix-numeric-value last-prefix-arg))))
    (when (eq orig-busy-okay 'interactive)
      (setq busy-okay
	    (cond ((>= (prefix-numeric-value current-prefix-arg) 16) 'fresh)
		  ((not current-prefix-arg) t))))
    (cl-flet ((busy-p (buffer)
		(or (get-buffer-process buffer)
		    (with-current-buffer buffer
		      (or (buffer-narrowed-p)
			  (and (eq orig-busy-okay 'interactive)
			       (> (point-max) eshell-last-output-end))))))
	      (fresh-eshell ()
		(when-let ((buffer (get-buffer eshell-buffer-name)))
		  (with-current-buffer buffer (rename-uniquely)))
		(let ((default-directory
		       (if chdir target-directory (expand-file-name "~/"))))
		  (eshell))))
      (dolist (buffer (buffer-list))
	(with-current-buffer buffer
	  (when (eq major-mode 'eshell-mode)
	    (let ((in-target-p
		   (and chdir (string= default-directory target-directory))))
	      (push buffer
		    (if in-target-p target-directory-eshells other-eshells))
	      (cond ((and (not chdir) (not most-recent-eshell)
			  (or busy-okay (not (busy-p buffer))))
		     (setq most-recent-eshell buffer))
		    ((and in-target-p (not target-directory-eshell)
			  (or busy-okay (not (busy-p buffer))))
		     (setq target-directory-eshell buffer))
		    ((and chdir proj-root (not same-project-eshell)
			  ;; We'll change its directory so it mustn't be busy.
			  (not (busy-p buffer))
			  (file-in-directory-p default-directory proj-root))
		     (setq same-project-eshell buffer)))))))
      (cond ((eq busy-okay 'fresh) (fresh-eshell))
	    ((and chdir target-directory-eshell)
	     (pop-to-buffer target-directory-eshell))
	    ((and chdir same-project-eshell)
	     (pop-to-buffer same-project-eshell)
	     (spw/eshell-cd target-directory))
	    (most-recent-eshell		; CHDIR nil
	     (pop-to-buffer most-recent-eshell))
	    (t (fresh-eshell))))
    ;; In an interactive call where we specifically requested an Eshell that's
    ;; not busy, ensure it's ready for us to enter a command.
    ;; Otherwise, it's useful to be able to jump back to exactly where we were
    ;; in an Eshell, and when called from Lisp, let the caller decide what to
    ;; do about where we are in the buffer, and about any partially-entered
    ;; command (e.g. see `spw/dired-copy-filename-as-kill').
    (when (and (not busy-okay) (eq orig-busy-okay 'interactive))
      (goto-char (point-max)))
    (let* ((all (delq (current-buffer)
		      (nconc other-eshells target-directory-eshells)))
	   (ring (make-ring (1+ (length all)))))
      (dolist (buffer all)
	(ring-insert ring buffer))
      (ring-insert ring (current-buffer))
      ring)))

(spw/reclaim-keys-from dired-x dired-mode-map "\M-!")
(spw/reclaim-keys-from term term-raw-map "\M-!" "\M-&")

(spw/transient-cycles-define-buffer-switch
  ((("\M-!" . spw/eshell-jump) (arg)
      (interactive "p")
      (let ((>>> (and (> arg 1) (format " >>>#<buffer %s>" (buffer-name)))))
	(prog1 (spw/eshell-jump (> arg 4) (and (= arg 1) 'interactive))
	  (when >>>
	    (let ((there (save-excursion
			   (goto-char (point-max))
			   (skip-syntax-backward "\\s-")
			   (- (point) (length >>>)))))
	      (unless (string= >>> (buffer-substring there (point-max)))
		(save-excursion
		  (goto-char (point-max))
		  (insert >>>)
		  (backward-char (length >>>))
		  (when (> (point) eshell-last-output-end)
		    (just-one-space)))))))))
   ;; This could be on C-z C-j, like `dired-jump', w/ corresponding C-z 4 C-j
   ;; and C-z 5 C-j.  But I'd want C-z 4 C-j much more often than C-z C-j.
   (("\M-&" . spw/eshell-jump-from-here) ()
      (interactive)
      (spw/eshell-jump t 'interactive))))

(with-eval-after-load 'project
  (when (boundp 'project-prefix-map)	; for Emacs 27
    (spw/transient-cycles-define-buffer-switch
      ((("e" . spw/project-eshell) ()
	  (interactive)
	  (spw/eshell-jump 'project 'interactive)))
      ;; Bind into project-prefix-map, rather than adding a remap, so that we
      ;; have it under C-x 4 p, C-x 5 p etc. too.
      :keymap project-prefix-map)))


;;;; Miscellaneous functions & commands
;;;; This is meant to be like ~/src/dotfiles/bin & ~/src/dotfiles/scripts, not
;;;; so much about Emacs startup, except that we do want them always loaded.

;; This is an alternative way to activate the mark temporarily when
;; `transient-mark-mode' is off, and whether it's on or off, makes it
;; easier to operate on adjacent whole lines where the set of lines is
;; not surrounded by blank lines such that `mark-paragraph' can be
;; used.
(defun spw/ensure-whole-lines-mode (edge &optional set-mark)
  (interactive "p")
  (when (or set-mark (not (mark t)))
    (set-mark (point)))
  (letrec ((start) (end)
	   (hook
	    (lambda ()
	      (if mark-active
		  (unless isearch-mode
		    (let ((swap (> (point) (mark))))
		      (when swap (exchange-point-and-mark))
		      (goto-char
		       (if (cl-minusp edge)
			   (pos-eol (and (not (eolp))
					 (or (not start) (< (point) start))
					 0))
			 (pos-bol (and (eql start (pos-bol)) (> (point) start)
				       2))))
		      (setq start (point))
		      (unless (= (point) (mark))
			(exchange-point-and-mark)
			(goto-char
			 (if (cl-plusp edge)
			     (pos-bol (and (not (bolp))
					   (or (not end) (> (point) end))
					   2))
			   (pos-eol (and (eql end (pos-eol)) (< (point) end)
					 0))))
			(setq end (point))
			(unless swap (exchange-point-and-mark)))))
		(remove-hook 'post-command-hook hook t)
		(remove-hook 'isearch-mode-end-hook hook t)))))
    (activate-mark transient-mark-mode)
    (add-hook 'post-command-hook hook nil t)
    (add-hook 'isearch-mode-end-hook hook nil t)))
(define-key spw/ctl-z-map "\s" #'spw/ensure-whole-lines-mode)

;; If know the name of group might try `gnus-read-ephemeral-gmane-group' (and
;; if that works well, might want to make this function prompt for a group to
;; pass to that function, and if blank, do what function does now).
(defun spw/browse-gmane ()
  (interactive)
  (gnus-no-server)
  (gnus-group-browse-foreign-server '(nntp "news.gmane.io")))
(global-set-key "\C-cgG" #'spw/browse-gmane)

(defun spw/org-reformat-subtree ()
  (interactive)
  ;; we have to set the mark, rather than just narrowing to the subtree, or
  ;; just using `outline-back-to-heading'/`outline-next-heading', because of
  ;; how `org-fill-paragraph' works
  (save-mark-and-excursion
    ;; widen, because otherwise it is trickier to ensure just one line at end
    ;; of subtree
    (save-restriction
      (widen)
      ;; basic reformatting of the text
      (let ((transient-mark-mode t))
	(org-mark-subtree)
	(forward-line 1)
	(call-interactively 'org-fill-paragraph)
	(call-interactively 'indent-region)
	(beginning-of-line 0))
      ;; ensure a newline before headline unless first line of buffer
      (unless (or (equal (point) (point-min))
		  (looking-back "\n\n" nil))
	(open-line 1)
	(forward-line 1))
      ;; ensure no newline before metadata
      (delete-blank-lines)
      ;; ensure a single newline after all metadata
      (org-end-of-meta-data t)
      (open-line 2)
      (delete-blank-lines)
      ;; ensure a single newline at end of subtree
      (exchange-point-and-mark)
      (open-line 2)
      (delete-blank-lines))))
(global-set-key "\C-co\M-q" #'spw/org-reformat-subtree)

(defun spw/compact-blank-lines ()
  "Replace blocks of multiple blank lines with single blank lines."
  (interactive)
  (save-excursion
    (goto-char (point-min))
    (while (search-forward-regexp "\n\n\n+" nil t)
      (replace-match "\n\n"))))

(defun spw/vc-rename-visited-file ()
  (interactive)
  (if-let ((file-name (and (vc-backend buffer-file-name) buffer-file-name)))
      (vc-rename-file file-name (read-file-name "Rename to: "))
    (user-error "Buffer is not visiting any VC-controlled file")))

;; `vc-rename-file' is quite fussy, to a git user, so want
;; `rename-visited-file' even for files under version control.
(global-set-key "\C-cR"  #'rename-visited-file)
(global-set-key "\C-cvR" #'spw/vc-rename-visited-file)

;; It's sometimes useful to do C-u M-~ C-c D to temporarily delete something
;; just while running a cmd, say, knowing we'll be prompted to save it later.
;;
;; Another reason for wanting this is that `vc-delete-file' can be fussy too.
;;
;; There is also C-x C-j D but that asks for confirmation.
(defun spw/delete-visited-file (arg)
  (interactive "P")
  (if-let ((file-name (buffer-file-name)))
      ;; No need to ask for confirmation when we aren't killing the buffer.
      (progn (delete-file file-name)
	     (if arg (message "Deleted %s" file-name) (bury-buffer)))
    (user-error "Buffer is not visiting any file")))

(defun spw/vc-delete-visited-file ()
  (interactive)
  (if-let ((file-name (and (vc-backend buffer-file-name) buffer-file-name)))
      (vc-delete-file file-name)
    (user-error "Buffer is not visiting any VC-controlled file")))

(global-set-key "\C-cD"  #'spw/delete-visited-file)
(global-set-key "\C-cvD" #'spw/vc-delete-visited-file)

(defun spw/link-stat-block (start end)
  (interactive "r")
  (when-let ((region-text (buffer-substring start end)))
    (org-insert-link
     nil
     (concat "file:~/annex/gaming/5eblocks/" region-text ".png")
     region-text)))

;; Possibly this should be replaced with something like `project-find-regexp'
;;
;; Input e.g.: lisp "Emacs configuration"
(defun spw/git-grep-docs (words)
  (interactive "sSearch for words/quoted phrases in text docs: ")
  (vc-git-grep (concat "git --no-pager grep -n --color -iw "
		       (mapconcat (lambda (word)
				    (concat "-e " (shell-quote-argument word)))
				  (split-string-and-unquote words) " ")
		       " -- \"*.org\" \"*.tex\" \"*.md\" :!org/archive")
	       nil (expand-file-name "~/doc")))
(global-set-key "\C-cog" #'spw/git-grep-docs)

;; this is called by .dir-locals.el in ~/doc/{pres,papers}
(defun spw/set-pandoc-compile-command (&rest exts)
  (setq-local compile-command
              (concat "make "
                      (mapconcat
                       (lambda (ext)
			 (file-name-nondirectory
			  (concat (file-name-sans-extension
				   (buffer-file-name))
				  "."
				  ext)))
                       (or exts '("pdf"))
		       " ")))
  (local-set-key "\C-z\C-c" #'compile))

(defun spw/all-programming-projects ()
  (call-process "src-register-all")
  (let ((default-directory (expand-file-name "~/src")))
    (mapcar (lambda (line) (substring line 9))
	    (remove "" (process-lines "mr" "list")))))

(defun spw/register-programming-projects-and-switch ()
  (interactive)
  (dolist (directory (spw/all-programming-projects))
    (when-let ((project (project-current nil directory)))
      (project-remember-project project)))
  (call-interactively 'project-switch-project))
(global-set-key "\C-cp" #'spw/register-programming-projects-and-switch)

(defun spw/src-dirs-not-projects ()
  "Return dirs under ~/src which contain repos but are not themselves repos."
  (let ((projects (make-hash-table :test 'equal)))
    (dolist (project (spw/all-programming-projects))
      (puthash project t projects))
    (cl-labels ((dirs-below (dir)
			    (let ((contents
				   (cl-delete-if-not
				    (lambda (f)
				      (and (file-directory-p f)
					   (not (gethash f projects))))
				    (directory-files dir t "[^.]"))))
			      (nconc contents
				     (mapcan #'dirs-below contents)))))
      (dirs-below (expand-file-name "~/src")))))

(defmacro spw/with-project-root-dired (&rest body)
  (declare (indent 0))
  `(progn (require 'project)
	  (with-current-buffer
	      (dired-noselect (project-root (project-current t)))
	    ,@body)))

(defun spw/clone-repo ()
  (interactive)
  (let* ((method
	  (completing-read
	   "Method: "
	   '("git clone" "dgit clone" "debcheckout" "mr -fd co") nil t))
	 (mrp (string= method "mr -fd co"))
	 (destination
	  (and (not mrp)
	       (expand-file-name
		(completing-read
		 "Destination: "
		 (nconc
		  (mapcar #'abbreviate-file-name (spw/src-dirs-not-projects))
		  '("~/tmp" "~/src"))
		 nil t))))
	 (source (read-from-minibuffer "What to clone: "))
	 (buffer (get-buffer-create "*Repository Clone Output*"))
	 (default-directory (or destination (expand-file-name "~/"))))
    (make-directory
     (file-name-directory (directory-file-name (or destination source))) t)
    (with-current-buffer buffer (erase-buffer))
    (message "Cloning...")
    (if (zerop (call-process-shell-command
		(if mrp (format "mr -fd %s co" source)
		  (format "%s %s" method source))
		nil buffer))
	(let* ((right-chopped
		(progn (string-match "\\(\\.git\\)?/?\\'" source)
		       (substring source 0 (match-beginning 0))))
	       (repo-dir
		(if mrp (expand-file-name (concat "~/" source))
		  (file-name-concat
		   (file-name-as-directory destination)
		   (if (string-match "[/:][^/:]*\\'" right-chopped)
		       (substring right-chopped (1+ (match-beginning 0)))
		     right-chopped)))))
	  (bury-buffer buffer)
	  (unless mrp (call-process "src-register-all"))
	  (dired (if (file-directory-p repo-dir) repo-dir destination))
	  (when-let ((project (project-current nil)))
	    (project-remember-project project)))
      (display-buffer buffer))))
(global-set-key "\C-cvc" #'spw/clone-repo)

;; author unknown
(defun spw/toggle-frame-split ()
  "Toggle the orientation of a two-window split.

Useful after resizing the frame."
  (interactive)
  (when (= (count-windows) 2)
      (let* ((this-win-buffer (window-buffer))
             (next-win-buffer (window-buffer (next-window)))
             (this-win-edges (window-edges (selected-window)))
             (next-win-edges (window-edges (next-window)))
             (this-win-2nd (not (and (<= (car this-win-edges)
                                         (car next-win-edges))
                                     (<= (cadr this-win-edges)
                                         (cadr next-win-edges)))))
             (splitter
              (if (= (car this-win-edges)
                     (car (window-edges (next-window))))
                  'split-window-horizontally
                'split-window-vertically)))
        (delete-other-windows)
        (let ((first-win (selected-window)))
          (funcall splitter)
          (when this-win-2nd (other-window 1))
          (set-window-buffer (selected-window) this-win-buffer)
          (set-window-buffer (next-window) next-win-buffer)
          (select-window first-win)
          (when this-win-2nd (other-window 1))))))
(define-key spw/personal-bindings-mode-map "\M-5" #'spw/toggle-frame-split)

;; orig http://blog.gleitzman.com/post/35416335505/hunting-for-unicode-in-emacs
(defun spw/unicode-hunt ()
  "Destroy some special Unicode characters like smart quotes."
  (interactive)
  (let ((unicode-map '(("[\u2018\|\u2019\|\u201A\|\uFFFD]" . "'")
                       ("[\u201c\|\u201d\|\u201e]" . "\"")
                       ("[\u2013\|\u2014]" . "-")
                       ("\u2026" . "...")
                       ("\u00A9" . "(c)")
                       ("\u00AE" . "(r)")
                       ("\u2122" . "TM")
                       ("[\u02DC\|\u00A0]" . " "))))
    (save-excursion
      (cl-loop for (key . value) in unicode-map
            do
            (goto-char (point-min))
            (while (re-search-forward key nil t)
              (replace-match value))))))

(cl-defun spw/myrepos-global-action
    (action &optional (command (concat "mr -s " action)))
  (require 'term)
  (let ((buffer (get-buffer-create (format "*myrepos %s*" action))))
    (with-current-buffer buffer
      (term-mode)
      (setq-local revert-buffer-function
		  (lambda (&rest _ignore)
		    (spw/myrepos-global-action action command))
		  default-directory (expand-file-name "~/"))
      (term-exec buffer "mr" "sh" nil (list "-c" command))
      (let ((inhibit-read-only t)) (erase-buffer))
      ;; Work around Emacs bug#48716, which breaks mr's --minimal option.
      (term-char-mode))
    (display-buffer buffer)))
(global-set-key "\C-cgr" (lambda ()
			   (interactive)
			   (spw/myrepos-global-action
			    "status" "src-register-all && mr -ms status")))
(global-set-key "\C-cgs" (lambda ()
			   (interactive)
			   (spw/myrepos-global-action "sync")))

;; There are many variations on this online.  This one by Robert Bost, based
;; on work by Steve Yegge, Colin Doering and others
(defun spw/rotate-windows (arg)
  "Rotate your windows, reversing direction if ARG."
  (interactive "P")
  (if (not (> (count-windows) 1))
      (message "You can't rotate a single window!")
    (let* ((rotate-times (prefix-numeric-value arg))
           (direction (if (or (< rotate-times 0) (equal arg '(4)))
                          'reverse 'identity)))
      (dotimes (_ (abs rotate-times))
        (dotimes (i (- (count-windows) 1))
          (let* ((w1 (elt (funcall direction (window-list)) i))
                 (w2 (elt (funcall direction (window-list)) (+ i 1)))
                 (b1 (window-buffer w1))
                 (b2 (window-buffer w2))
                 (s1 (window-start w1))
                 (s2 (window-start w2))
                 (p1 (window-point w1))
                 (p2 (window-point w2)))
            (set-window-buffer-start-and-point w1 b2 s2 p2)
            (set-window-buffer-start-and-point w2 b1 s1 p1)))))))
;; This gets this key because we're likely to want to invoke it repeatedly.
(define-key spw/personal-bindings-mode-map "\M-6" #'spw/rotate-windows)

;; some influence here from Michael Stapelberg's config -- we both had a
;; function to do this, I discovered
(defun spw/recipient-first-name ()
  "Attempt to extract the first name of the recipient of a `message-mode' message.

Used in my `message-mode' yasnippets."
  (if-let ((to (save-excursion
		 (save-restriction
		   (message-narrow-to-headers-or-head)
		   (message-fetch-field "To")))))
      (let ((full-name (car (mail-extract-address-components to))))
	(if (string-match "\\([^ ]+\\)" full-name)
	    (let ((first-name (match-string 0 full-name)))
	      (cond
	       ;; some names which may be in a longer form in the From header
	       ;; but which I would never type out in full in a salutation
               ((string= first-name "Nathaniel") "Nathan")
               ((string= first-name "Thomas") "Tom")
               (t first-name)))
	  ;; no spaces -- assume whole thing is an alias and use it
	  full-name))
    ""))

(spw/define-skeleton spw/message-dear
    (message-mode :abbrev "dear" :file "message")
  ""
  (completing-read "Dear " (ignore-errors (list (spw/recipient-first-name))))
  '(when (setq v1 (looking-at ">")) (forward-line -2))
  "Dear " str "," \n \n
  '(when v1 (forward-line 2)))

(spw/define-skeleton spw/message-hello
    (message-mode :abbrev "hl" :file "message")
  ""
  (completing-read "Hello " (ignore-errors (list (spw/recipient-first-name))))
  '(when (setq v1 (looking-at ">")) (forward-line -2))
  "Hello " str '(when (zerop (length str)) (delete-backward-char 1)) "," \n \n
  '(when v1 (forward-line 2)))

(spw/define-skeleton spw/message-thanks
    (message-mode :abbrev "ty" :file "message")
  ""
  (completing-read "Dear " (ignore-errors (list (spw/recipient-first-name))))
  '(when (setq v1 (looking-at ">")) (forward-line -2))
  "Dear " str "," \n \n "Thank you for your e-mail." \n \n
  '(when v1 (forward-line 2)))

(defun spw/copy-to-annotated ()
  (interactive)
  (let* ((source (expand-file-name (dired-file-name-at-point)))
         (ext (file-name-extension source))
         (dest (replace-regexp-in-string
                (concat "\\." ext "$")
                (concat " - annotated." ext)
                source))
	 (dired-copy-dereference t))
    (when (and (file-exists-p source) (not (file-exists-p dest)))
      (dired-copy-file source dest nil)
      (revert-buffer)
      (dired-previous-line 1)
      (spw/dired-find-file))))

;; `debian-bug' is oriented towards reporting bugs against installed packages.
;; This function allows reporting against any suite or release, and doesn't
;; run package-specific reportbug scripts.
(defun spw/bts-submit (type package suite subject severity)
  (interactive
   (let ((type (completing-read "Report bug against: "
				'("Source" "Package") nil t)))
     (list type
	   (read-from-minibuffer
	    (format "%s package name: "
		    (pcase type ("Source" "Source") ("Package" "Binary"))))
	   (completing-read "Suite or codename (default unstable): "
			    '("experimental" "unstable" "testing"
			      "stable" "oldstable" "oldoldstable")
			    nil nil nil nil "unstable")
	   (read-from-minibuffer "Bug subject: ")
	   (completing-read "Severity (default normal): "
			    '("critical" "grave" "serious"
			      "important" "normal" "minor" "wishlist")
			    nil t nil nil "normal"))))
  (let* ((rmadison (shell-command-to-string
		    (format "rmadison --suite=%s %s" suite package)))
         (version (nth 1 (split-string rmadison "|" t "[[:blank:]]+"))))
    (compose-mail "Debian Bug Tracking System <submit@bugs.debian.org>"
		  (format "%s: %s" package subject))
    (insert
     (format "%s: %s\nVersion: %s%s\n\nDear maintainer,\n\n"
	     type package version (if (string= severity "normal") ""
				    (format "\nSeverity: %s" severity))))))

(defun spw/use-tabs-not-frames (&optional frame)
  "Whether to pop up new tabs instead of new frames.
Should be t when do not have a good way to handle having lots of open
frames, as I do have under i3/swaywm with its tabbed layout, which is my
default layout."
  (not (and spw/tiling-wm-p
	    (memq (framep (or frame (selected-frame))) '(x pgtk)))))

(defun spw/save-buffer-for-later ()
  (interactive)
  (if (spw/use-tabs-not-frames)
      (call-interactively #'spw/save-buffer-to-tab-for-later)
    (call-interactively #'spw/save-buffer-to-frame-for-later)))

;; possibly we want to set the window of the new frame to be dedicated to this
;; buffer, to prevent it being reused to display something else, thus sending
;; the buffer we wanted to save off down the buffer list
(defun spw/save-buffer-to-frame-for-later (buffer &optional rename)
  (interactive (list (current-buffer) current-prefix-arg))
  (let ((frame (selected-frame))
	(display-buffer-overriding-action '((display-buffer-pop-up-frame)
					    (inhibit-same-window . t))))
    (save-selected-window
      (display-buffer (spw/maybe-clone-buffer buffer rename)))
    (raise-frame frame)
    (when rename
      (switch-to-buffer (other-buffer) nil t))))

(defun spw/maybe-clone-buffer (buffer rename)
  (with-current-buffer buffer
    (cond
     ((buffer-file-name)
      ;; file-visiting buffers we don't clone, even indirectly, as that is
      ;; rarely what's wanted; should explicitly request an indirect clone
      buffer)
     (rename
      (rename-uniquely)
      buffer)
     (t
      (clone-buffer)))))

;; Clone buffer is for when we want to have two versions of the buffer with
;; different contents; using it does not imply that we want to prevent either
;; buffer's contents from being overwritten by, e.g., calling `compile' again
;; in a different source tree or navigating to a different Info node, nor that
;; we particularly want to avoid either buffer sinking down the buffer list
;; and being forgotten
;; (global-set-key "\C-cnn" #'clone-buffer)  ;; now on C-x x n

;; In this case, by contrast, we're saying that we want two versions of the
;; buffer specifically because (i) we don't want the buffer contents to be
;; overwritten by, e.g., calling `compile' again or navigating to a different
;; web page; and/or (ii) we want to be reminded to come back to (a particular
;; point in) the buffer by giving it its own frame or tab, in a way that's
;; lightweight and doesn't involve adding TODO entries
(global-set-key "\C-cS" #'spw/save-buffer-for-later)
;; (global-set-key "\C-cns" #'spw/save-buffer-for-later)

;; Finally, this is for when we just want to protect the buffer contents from
;; being overwritten and nothing more
;; (global-set-key "\C-cnr" #'rename-uniquely) ;; now on C-x x u

(defun spw/set-other-window-to-scroll (arg)
  "Set `other-window-scroll-buffer' to the most recently used window.
Single prefix argument to clear."
  ;; possibly we want to do other things with multiple C-u in the future
  (interactive "P")
  (if arg
      (kill-local-variable 'other-window-scroll-buffer)
    (setq-local other-window-scroll-buffer
		(window-buffer (spw/get-mru-window)))
    (message "C-M-v will scroll %s" (window-buffer (get-mru-window)))))
(global-set-key "\C-cV" #'spw/set-other-window-to-scroll)

(defun spw/update-environment (&rest pairs)
  "Update env vars like DISPLAY, SSH_AUTH_SOCK etc.
Called by '~/src/dotfiles/bin/emacsclient --spw/update-environment'."
  (cl-flet ((set-all ()
	      (cl-loop for (var val) on pairs by #'cddr do (setenv var val))))
    (with-current-buffer (get-buffer-create "*scratch*") (set-all))
    (let ((slime-connections (and (bound-and-true-p slime-default-connection)
				  (list slime-default-connection)))
	  (cl-form `(cl:handler-case (cl:require "ASDF")
   		      (cl:error ())
		      (:no-error (r)
		        (cl:declare (cl:ignore r))
			. ,(cl-loop for (var val) on pairs by #'cddr collect
				    `(cl:setf (uiop:getenv ,var) ,val))))))
      (dolist (buffer (buffer-list))
	(with-current-buffer buffer
	  (cond ((eq major-mode 'eshell-mode) (set-all))
		((bound-and-true-p slime-buffer-connection)
		 (cl-pushnew slime-buffer-connection slime-connections)))))
      (dolist (connection slime-connections)
	(let ((slime-dispatching-connection connection))
	  (slime-eval cl-form))))))

(defun spw/daemon-pid (&optional name)
  ;; We don't use `server-eval-at' because perhaps we are trying to attach gdb
  ;; to a wedged Emacs.
  (let ((socket (file-name-concat server-socket-dir (or name "server"))))
    (and (file-exists-p socket)
	 (cl-loop
	  with min and min-age
	  for line in (process-lines "ss" "-Hplx" "src" socket)
	  for pid = (if (string-match "pid=\\([[:digit:]]+\\)" line)
			(match-string 1 line)
		      (error "Unexpected output from ss(8)"))
	  for age = (string-to-number
		     (or (car (process-lines "ps" "h" "-o" "etimes" pid))
			 (error "Couldn't find age of process %s" pid)))
	  when (or (not min-age) (< age min-age))
	  do (setq min (string-to-number pid) min-age age)
	  finally return min))))

(defvar-local spw/gdbmacs-target-pid nil)
(defvar-local spw/gdbmacs-target-name nil)

(defun spw/gdbmacs-attach (&optional name)
  (require 'gdb-mi)
  (let (pid
	(arg (if name (concat "--fg-daemon=" name) "--fg-daemon"))
	(proc (get-buffer-process gud-comint-buffer)))
    (when (and proc (string= gdb-inferior-status "signal-received"))
      ;; Avoid wiping out useful info.
      (error "Possibly Emacs just crashed; not attaching for now"))
    ;; Don't interrupt non-gdb usage of gdbmacs just because the primary
    ;; daemon prints to stdout.  It's often just "Reverting buffer ‘foo.org’".
    (setopt gdb-display-io-nopopup t)
    (cl-flet ((run-or-continue ()
		(gdb-wait-for-pending
		 (lambda ()
		   (with-current-buffer gud-comint-buffer
		     (setq spw/gdbmacs-target-pid pid
			   spw/gdbmacs-target-name name))
		   (if pid
		       (gud-basic-call "continue")
		     (gud-basic-call "set cwd ~")
		     (gdb-wait-for-pending
		      (lambda () (gud-basic-call "run"))))))))
      (gdb-wait-for-pending
       (if (and proc
		;; Check it looks safe to re-use existing gdb process.
		(string-prefix-p "exited" gdb-inferior-status)
		(file-in-directory-p
		 (buffer-local-value 'default-directory gud-comint-buffer)
		 (expand-file-name "~/src/emacs/primary/")))
	   (lambda ()
	     (gud-basic-call (if (setq pid (spw/daemon-pid name))
				 (format "attach %d" pid)
			       (format "set args %s" arg)))
	     (run-or-continue))
	 ;; Start up a new process.
	 (lambda ()
	   (when (buffer-live-p gud-comint-buffer)
	     (when proc (set-process-query-on-exit-flag proc nil))
	     (kill-buffer gud-comint-buffer))
	   (gdb-wait-for-pending
	    (lambda ()
	      (let ((default-directory
		     (expand-file-name "~/src/emacs/primary/")))
		(gdb (if (setq pid (spw/daemon-pid name))
			 (format "gdb -i=mi --pid=%d src/emacs" pid)
		       (format "gdb -i=mi --args src/emacs %s" arg))))
	      (run-or-continue)))))))))

;; C-c C-z to attempt to return control to the debugger.
;;
;; In the --fg-daemon case, AIUI we are here working around this:
;;     <https://lwn.net/Articles/909496/>.
(defun spw/comint-stop-subjob (orig-fun)
  (if-let ((pid (or spw/gdbmacs-target-pid
		    (setq spw/gdbmacs-target-pid
			  (spw/daemon-pid spw/gdbmacs-target-name)))))
      (signal-process pid 'SIGTSTP)
    (funcall orig-fun)))
(advice-add 'comint-stop-subjob :around #'spw/comint-stop-subjob)

;; flock(1) starting daemons named the same as us so that instances of my
;; emacsclient(1) wrapper wait on us completing our exit before trying to
;; start us again.
(defun spw/daemon-lock-self ()
  (when (and (daemonp) (executable-find "flock") (executable-find "sleep"))
    (let ((file
	   (file-name-concat
	    (or (getenv "XDG_RUNTIME_DIR") (format "/run/user/%d" (user-uid)))
	    "spw_emacsclient"
	    (cl-etypecase (daemonp) (string (daemonp)) (t "server")))))
      (set-process-query-on-exit-flag
       (start-process "spw_emacsclient" nil
		      "flock" "-E" "0" "-n" file "sleep" "20")
       nil))))
(when (fboundp 'file-name-concat)	; for Emacs 27 compat
  (add-hook 'kill-emacs-hook #'spw/daemon-lock-self -99))

(defun spw/may-pass-to-gdbmacs-p ()
  (and (display-graphic-p)
       (not (string= (daemonp) "gdbmacs"))
       (spw/daemon-pid "gdbmacs")))

;; open a frame on a new workspace with only the relevant dired buffer open,
;; eval this form: (global-set-key "\C-cG" #'spw/grading-advance)
;; and then use C-c G to open the first item (will need C-c f t after just
;; this first one, and also maybe C-i =)
(defun spw/grading-advance ()
  (interactive)
  (unless (eq major-mode 'dired-mode)
    (when (eq major-mode 'org-mode)
      (ignore-errors (org-ctrl-c-ctrl-c)))
    (save-buffer)
    (other-window 1))
  (dired-display-file)
  (dired-next-line 1)
  (let ((pdf (dired-get-filename)))
    (dired-next-line 1)
    (other-window 1)
    (goto-char (point-min))

    ;; assignment-specific
    (search-forward "Grammar")
    (org-cycle)
    (set-goal-column nil)
    ;; (overwrite-mode 1)

    (start-process "pdf" "pdf" "xdg-open" pdf)
    (sleep-for 1)
    (call-process-shell-command
     (concat (if (executable-find "i3-msg") "i3-msg" "swaymsg")
	     " move right"))
    (let ((pdf-words (substring (with-temp-buffer
				  (call-process-shell-command
				   (concat "pdftotext "
					   (shell-quote-argument pdf)
					   " - | wc -w")
				   nil
				   (current-buffer))
				  (buffer-string))
				0
				-1)))
      (message (concat pdf-words " words")))))

(defun spw/untabify-project ()
  (interactive)
  (save-window-excursion
    (dolist (file (project-files
		   (project-current nil (project-prompt-project-dir))))

      (find-file file)
      (untabify (point-min) (point-max)))))

(defun spw/go-to-consfig ()
  (interactive)
  ;; (let ((repo (expand-file-name "~/src/cl/consfig")))
  ;;   (unless (file-directory-p repo)
  ;;     (user-error "Consfig git repo not found"))
  ;;   (dired repo))
  (cl-flet ((load ()
              (slime-load-system "com.silentflame.consfig")
              (spw/add-once-hook
               'slime-compilation-finished-hook
               (lambda (notes)
		 ;; see `slime-maybe-show-compilation-log'
                 (unless (memq 'slime-maybe-show-compilation-log
			       slime-compilation-finished-hook)
                   (slime-create-compilation-log notes))
                 (when (slime-compilation-result.successp
			slime-last-compilation-result)
		   (slime-change-directory (expand-file-name "~/"))
                   (slime-repl-set-package "COM.SILENTFLAME.CONSFIG"))))))
    (if (ignore-errors (slime-output-buffer))
	(progn (slime-switch-to-output-buffer)
	       (setq-local default-directory (expand-file-name "~/"))
	       (load))
      (let ((default-directory (expand-file-name "~/"))) (slime))
      (spw/add-once-hook 'slime-connected-hook #'load))))
(global-set-key "\C-cgc" #'spw/go-to-consfig)

(defun spw/go-to-cl-user ()
  (interactive)
  (if (not (ignore-errors (slime-output-buffer)))
      (let ((default-directory (expand-file-name "~/")))
	(slime))
    (slime-switch-to-output-buffer)
    (slime-repl-set-package "CL-USER")))
(global-set-key "\C-cgl" #'spw/go-to-cl-user)

;; These configure flags are for my workstation development builds.  We do not
;; have --with-native-compilation at present for the following reasons:
;;
;; - it results in laptop churning away natively compiling all installed
;;   addons when it may very well be on battery power, even if it was plugged
;;   in for the build;
;;
;; - it makes bootstrap builds very slow, though there is work going on to
;;   improve that; and
;;
;; - Emacs's Makefile rules for the .eln files are as yet somewhat flaky,
;;   meaning that they don't always get recompiled when they need to.
;;
;; The configure flags in "confmacs0" are for when I am actively debugging
;; Emacs.  The flags in "confmacsg" are for day-to-day use, where I still want
;; some debugging information available in case of an unexpected crash.  The
;; flags in "confmacs0" are recommended by etc/DEBUG, but other than
;; --enable-check-lisp-object-type, they do noticeably slow Emacs down,
;; especially Icomplete, and most of the time I'm working either on things
;; other than Emacs or on Emacs at the Lisp level.  "confmacsg" seems to be
;; acceptably fast, and using these abbrevs to reconfigue and rebuild Emacs's
;; C core back and forth is quick (the .elc stick around).
;;
;; We don't append "&& make" to the abbrev because I use 'C-x p c' to build.
;;
;; Order the flags such that ones I'm more likely to want to manually edit or
;; remove for a particular build come later in the list.  In particular, have
;; --enable-check-lisp-object-type come last in the abbrev expansions because
;; we sometimes need to quickly reconfigure without it, such that Lisp objects
;; aren't structs and can be used in break point conditions.
;;
;; Delete the cache each time because we're often changing CFLAGS.  It's still
;; worth passing -C because configure often gets rerun by the Makefile when I
;; rebase onto origin/master -- there is no --disable-maintainer-mode.
(with-eval-after-load 'esh-mode
  (dolist (conf '(("confmacs0"
		   "--with-pgtk"
		   "--enable-checking='yes,glyphs'"
		   "CFLAGS='-O0 -g3'"
		   "--enable-check-lisp-object-type")
		  ("confmacsg"
		   "--with-pgtk"
		   "--enable-checking='yes,glyphs'"
		   "CFLAGS='-Og -g3'"
		   "--enable-check-lisp-object-type")))
    (define-abbrev eshell-mode-abbrev-table (car conf)
      (string-join (cons "rm -f config.cache; ./configure -C" (cdr conf)) " ")
      nil :system t)))

(defun spw/read-athenet-lxc ()
  (let (lxcs
	(file (expand-file-name "~/src/cl/consfig/hosts.lisp")))
    (unless (file-exists-p file) (user-error "Looks like consfig not checked out"))
    (with-current-buffer (find-file-noselect file)
      (save-excursion
	(save-restriction
	  (widen)
	  (goto-char (point-min))
	  (while (re-search-forward
		  "(define-athenet-container \\([a-z0-9-.]+\\)
\\s-*\"\\([a-z0-9-.]+\\)"
		  nil t)
	    (push (list (substring-no-properties (match-string 1))
			(substring-no-properties (match-string 2)))
		  lxcs)))))
    (assoc (completing-read "LXC: " lxcs nil t) lxcs #'string=)))

(defun spw/ssh-and-lxc-attach-term (container host)
  (interactive (spw/read-athenet-lxc))
  (start-process "ssh-and-tmux" nil "foot" "ssh-and-tmux" host
		 (format "--container-name=%s" container)
"--container-cmd=lxc-unpriv-attach -n %s --keep-var TERM --clear-env -vHOME=/root"))
(global-set-key "\C-cgL" #'spw/ssh-and-lxc-attach-term)

(defun spw/proced-root ()
  (interactive)
  (require 'proced)
  (let ((default-directory "/sudo::")
	(proced-show-remote-processes t)
	(buffer (get-buffer "*Proced root*")))
    (if buffer (pop-to-buffer buffer)
      (proced)
      (rename-buffer "*Proced root*")
      (proced-filter-interactive 'all))))
(global-set-key "\C-cgt" #'proced)
(global-set-key "\C-cga" #'spw/proced-root)

(defun spw/copy-to-scratch ()
  (interactive)
  (if (char-equal (char-after) ?\()
      (let ((form (buffer-substring (point)
				    (save-excursion (forward-sexp) (point)))))
	(scratch-buffer)
	(unless (and (bolp) (eolp) (looking-back "\n\n"))
	  (goto-char (point-at-eol))
	  (newline 2))
	(insert form)
	;; Move so as to be ready for editing, rather than immediate C-x C-e.
	(down-list -1))
    (user-error "Not at beginning of a sexp")))
(define-key spw/ctl-z-map "l" #'spw/copy-to-scratch)

(defun spw/org-title ()
  (interactive)
  (goto-char (point-min))
  (if (search-forward "#+title: " nil t)
      (move-end-of-line 1)
    (unless (eolp) (open-line 1))
    (insert "#+title: ")))
(spw/feature-define-keys org "\C-z\C-t" spw/org-title)

(defun spw/check-debian-upstream-merge ()
  "Verify a sponsee's Git merge of a new upstream release."
  (interactive)
  (if-let ((merge (log-view-current-tag)))
      (cl-flet ((no-diff-p (&rest args)
		  (zerop (apply #'call-process "git" nil nil nil
				"diff" "--exit-code" args))))
	(message
	 (if (no-diff-p (format "%1$s^..%1$s" merge) "--" "debian" )
	     (if (no-diff-p (format "%1$s^2..%1$s" merge) "--"  ":!debian")
		 "Merge seems correct"
	       "Unexpected upstream changes; no packaging changes")
	   "Unexpected packaging changes; haven't checked upstream import")))
    (user-error "No commit at point")))

;; Supports only a single debugging session per Emacs instance.
;; One reason for this is that GUD doesn't expose its logic for finding the
;; GUD buffer debugging a given program, nor really for determining which
;; debugger (gdb, perldb, ..) is being run.
;;
;; Does not support hiding GUD's window(s).  Just use C-x 1 from the source
;; buffer.  Then invoke this command to bring GUD's window(s) back.
;;
;; The idea is to have a one Emacs frame/tab for source editing, from which
;; `compile' or `project-compile' is called, and one Emacs frame/tab for GUD.
(defun spw/run-or-restore-gud (arg)
  (interactive "P")
  (if (or arg (not (and (bound-and-true-p gud-comint-buffer)
			(get-buffer-process gud-comint-buffer))))
      ;; Start a new debugging session even if one already exists.
      ;; Killing `gud-comint-buffer' is the documented way to quit an
      ;; existing session.
      (let* ((cmd (cl-case major-mode
		    (c-mode 'gdb) (cperl-mode 'perldb) (python-mode 'pdb)
		    (t (intern (completing-read "GUD command: "
						'(gdb perldb pdb) nil t)))))
	     (args
	      (advice-eval-interactive-spec
	       (cadr
		(or (get cmd 'interactive-form) (interactive-form cmd))))))
	(when (buffer-live-p gud-comint-buffer)
	  (when-let ((proc (get-buffer-process gud-comint-buffer)))
	    (set-process-query-on-exit-flag proc nil))
	  (kill-buffer gud-comint-buffer))
	(gdb-wait-for-pending (lambda () (apply cmd args))))
    ;; Restore the session.
    (cl-case (buffer-local-value 'gud-minor-mode gud-comint-buffer)
      (gdbmi (gdb-restore-windows)
	     ;; Try to ensure prompt is at the bottom of its window.
	     (recenter (window-body-height)))
      (t (pop-to-buffer gud-comint-buffer)))))
(global-set-key "\C-cgd" #'spw/run-or-restore-gud)

(defun spw/fill-rest-of-paragraph ()
  (interactive)
  (let ((string (ignore-errors (cdr (bounds-of-thing-at-point 'string)))))
    (fill-region-as-paragraph
     (car (bounds-of-thing-at-point 'sentence))
     (cond (string (min string (cdr (bounds-of-thing-at-point 'paragraph))))
	   ((cl-fifth (syntax-ppss))
	    (min (cdr (bounds-of-thing-at-point 'paragraph))
		 (progn
		   ;; Move to last line of comment or first non-comment line.
		   (while (cl-fifth (syntax-ppss (pos-eol 2))))
		   (if (save-excursion
			 (and (cl-fifth (syntax-ppss (1- (point))))
			      (re-search-backward "\\w" (pos-bol) t)))
		       ;; At end of e.g. a GNU-style C comment.
		       (point)
		     ;; At the end of e.g. a Linux-style C comment, or on the
		     ;; first line after e.g. a shell script comment.
		     (pos-eol 0)))))
	   (t (cdr (bounds-of-thing-at-point 'paragraph))))))
  (when (bolp)
    (backward-char 1)
    (skip-syntax-backward "\"")))
(global-set-key "\C-cq" #'fill-region-as-paragraph)
(global-set-key "\C-ce" #'spw/fill-rest-of-paragraph)


;;;; Terminal emulation

;;; Make C-c and C-z escape chars too.  In particular, this ensures that have
;;; to hit C-c twice to actually SIGINT something, like in Eshell.  C-d still
;;; requires pressing just once because that's how it is in `term-line-mode'.

(defvar spw/term-raw-ctl-c-escape-map)
(defvar spw/term-raw-ctl-z-escape-map)

(with-eval-after-load 'term
  (term-set-escape-char ?\C-x)

  ;; Copy so as to include the other `term-raw-escape-map' bindings, e.g. M-x.

  (setq spw/term-raw-ctl-c-escape-map (copy-keymap term-raw-escape-map))
  (set-keymap-parent spw/term-raw-ctl-c-escape-map mode-specific-map)
  (define-key spw/term-raw-ctl-c-escape-map "\C-c" #'term-send-raw)
  (define-key term-raw-map "\C-c" spw/term-raw-ctl-c-escape-map)

  (setq spw/term-raw-ctl-z-escape-map (copy-keymap term-raw-escape-map))
  (set-keymap-parent spw/term-raw-ctl-z-escape-map spw/ctl-z-map)
  (define-key spw/term-raw-ctl-z-escape-map "\C-z" #'term-send-raw)
  (define-key term-raw-map "\C-z" spw/term-raw-ctl-z-escape-map))


;;;; Composing mail

(defvar spw/debian-bts-pseudoheader-regexp
  ;; "^\\([A-Za-z][a-z]+: [^ ]+\\|[cC]ontrol: .+\\)$"
  "^[A-Za-z][a-z]+: [^ ]+"
  "Regexp matching Debian BTS pseudoheaders.")
(defvar-local spw/message-normalised nil
  "Whether `spw/message-normalise' has been run in this buffer.")

(defun spw/unfinalise-message ()
  (interactive)
  (setq spw/message-normalised nil)
  (message "Message marked as not ready to send"))

(defun spw/normalise-message ()
  "Auto-format a message; to be used just prior to sending it.

The state after this function has been called is meant to be like
mutt's review view, after exiting EDITOR."
  (interactive)
  (message-templ-config-exec)
  (save-excursion
    (spw/message-goto-body)
    ;; also skip over Debian BTS pseudoheaders, which shouldn't be touched
    (when (looking-at spw/debian-bts-pseudoheader-regexp)
      (cl-loop do (forward-line 1)
	    while (looking-at spw/debian-bts-pseudoheader-regexp))
      (if (looking-at "\n")
	  (forward-line 1)
	(insert "\n")))
    (let ((body (point)))
      ;; add blank lines between quoted and unquoted text
      (while (not (eobp))
	(when (looking-at
	       "\\(^>[^\n]+\n\\{1\\}[^>\n]\\|^[^>\n][^\n]*\n>\\)")
	  (forward-line 1)
	  (open-line 1))
	(forward-line 1))
      (goto-char body)
      ;; ensure there is at least a basic salutation
      (unless (looking-at "^[A-Z].+,\n\n")
	(insert "Hello,\n\n"))
      (message-goto-signature)
      (unless (eobp) (end-of-line -1))
      ;; delete trailing whitespace in message body, when that message body
      ;; exists (this protects signature dashes and empty headers)
      (when (< body (point))
        (delete-trailing-whitespace body (point)))
      ;; make any remaining trailing whitespace visible to the user
      (setq-local show-trailing-whitespace t)
      ;; ensure there is a newline before the signature dashes
      (unless (bolp)
	(insert "\n"))))
  (spw/compact-blank-lines)
  (undo-boundary)
  ;; (when arg
  ;;   (save-excursion
  ;; 	(save-restriction
  ;;       (narrow-to-region body (point))
  ;;       (message-fill-yanked-message)))
  ;;   (message "Hit undo if the quoted message was too aggressively wrapped"))
  (setq spw/message-normalised t))

(defun spw/message-kill-and-normalise ()
  (interactive)
  (newline)
  (message-kill-to-signature)
  (spw/normalise-message))

(defun spw/message-send-and-exit ()
  (interactive)
  (when (or spw/message-normalised
	    (y-or-n-p "Send message which has not been auto-formatted?"))
    (call-interactively #'message-send-and-exit)))

(defun spw/message-maybe-sign ()
  ;; no PGP signing on athena
  (unless (spw/on-host-p "athena.silentflame.com")
    ;; avoid clobbering a 'signencrypt' tag added when replying to an
    ;; encrypted message
    (if (mml-secure-is-encrypted-p)
        (mml-secure-message-sign-encrypt)
      (mml-secure-message-sign-pgpmime))))

;; for interactive use this is more useful than `message-goto-body' (we don't
;; want to advise the latter because functions like
;; `notmuch-mua-check-no-misplaced-secure-tag' use it)
(defun spw/message-goto-body ()
  (interactive)
  (message-goto-body)
  (when (looking-at "^<#\\(secure\\|part\\) ") (forward-line 1))
  (point))

;; Michael Stapelberg points out that for most purposes
;; `mail-add-attachment' suffices and requires less typing than
;; `mml-attach-file', so use it by default, and gather attachments together
;; at the end of the message
(defun spw/message-add-attachment ()
  (interactive)
  (require 'sendmail)
  (save-excursion
    (goto-char (point-max))
    (terpri (current-buffer) t)
    (call-interactively #'mail-add-attachment)))

(defun spw/message-newline-and-reformat (arg)
  "Like `message-newline-and-reformat', but remove unneeded lines."
  (interactive "P")
  (with-undo-amalgamate
    (message-newline-and-reformat arg)
    (let ((re (concat message-cite-prefix-regexp "\\s-*$")))
      (save-excursion
	(forward-line -2)
	(while (looking-at re)
	  (delete-region (point) (1+ (line-end-position)))
	  (beginning-of-line 0)))
      (save-excursion
	(forward-line 2)
	(while (looking-at re)
	  (delete-region (point) (1+ (line-end-position))))))))

;; `message-ignored-resent-headers' removes X-TUID, but we want to remove
;; User-Agent & Date only when we're editing the message to be resent; I use
;; `gnus-summary-resend-message-edit' only for composing mail using an old
;; message as a template ("edit as new"), not actually editing and resending.
(defun spw/gnus-summary-resend-message-edit ()
  (message-remove-header "^Date:\\|^User-Agent:" t))
(advice-add 'gnus-summary-resend-message-edit
	    :after #'spw/gnus-summary-resend-message-edit)

;; Also cf. `message-reduce-to-to-cc'.
(defun spw/message-merge-To-Cc ()
  (interactive)
  (let ((new (save-excursion
	       (save-restriction
		 (message-narrow-to-headers-or-head)
		 (format "%s, %s"
			 (message-fetch-field "to")
			 (message-fetch-field "cc"))))))
    (message-replace-header "To" new)
    (message-remove-header "Cc")))

(spw/macroexp-for (cmd)
    (compose-mail compose-mail-other-window compose-mail-other-frame
		  mailscripts-git-format-patch-attach
		  bongo-playlist)
  (let ((new (intern (concat "spw/" (symbol-name cmd)))))
    `(progn (defun ,new (&rest args)
	      ,(interactive-form cmd)
	      (if (spw/may-pass-to-gdbmacs-p)
		  (ignore-error server-return-invalid-read-syntax
		    (server-eval-at
		     "gdbmacs"
		     `(let ((display-buffer-overriding-action
			     '(display-buffer-pop-up-frame
			       (pop-up-frame-parameters
				(display
				 . ,(frame-parameter nil 'display)))))
			    (default-directory ,default-directory)
			    (current-prefix-arg ',current-prefix-arg))
			(apply #',',cmd ',args))))
		(apply #',cmd args)))
	    (global-set-key [remap ,cmd] #',new))))

(with-eval-after-load 'message
  (spw/when-library-available message-templ
    (define-key message-mode-map [f7] #'spw/unfinalise-message)
    (define-key message-mode-map "\C-z\C-u"  #'spw/unfinalise-message)
    (define-key message-mode-map [f8] #'spw/normalise-message)
    (define-key message-mode-map "\C-z\C-c"  #'spw/normalise-message)
    (define-key message-mode-map [f9] #'spw/message-kill-and-normalise)
    (define-key message-mode-map "\C-z\C-v"  #'spw/message-kill-and-normalise))

  (define-key message-mode-map
      [remap message-goto-body] #'spw/message-goto-body)
  (define-key message-mode-map "\C-c\C-s" #'message-goto-subject)
  (define-key message-mode-map "\C-c\C-fm" #'spw/message-merge-To-Cc)

  (define-key message-mode-map
      [remap mml-attach-file] #'spw/message-add-attachment)

  ;; This relies on user.primary_email, user.other_email notmuch config keys.
  (spw/when-library-available notmuch-address
    (require 'notmuch-address) (notmuch-address-setup))

  (add-hook 'message-mode-hook #'footnote-mode)

  (define-key message-mode-map
      [remap message-newline-and-reformat] #'spw/message-newline-and-reformat)

  (define-key message-mode-map
	      [remap message-send-and-exit] #'spw/message-send-and-exit)

  (add-hook 'message-sent-hook #'gnus-score-followup-article))


;;;; Dired

;; this is the way you're meant to request dired-aux, not just dired-x,
;; according to (info "(dired-x) Installation")
(with-eval-after-load 'dired (require 'dired-x))

;; docs say to use:
;;     (add-hook 'dired-mode-hook (lambda () (dired-omit-mode 1)))
;; however the following ensures that inserted subdirs also get omitted:
(setq-default dired-omit-mode t)

(add-hook 'dired-mode-hook #'turn-on-gnus-dired-mode)

(spw/when-library-available git-annex
  ;; can't wrap this in a `with-eval-after-load' for dired because want it to
  ;; go ahead and advise `read-only-mode'
  (require 'git-annex))

(defun spw/dired-copy-filename-as-kill (&optional arg)
  (interactive "P")
  (let* ((subdir (dired-get-subdir))
	 (files
          ;; We treat as primary the meanings of the prefix argument to
	  ;; `dired-copy-filename-as-kill', then try to call `spw/eshell-jump'
	  ;; in a way that corresponds.  Thus, there isn't a way to express a
	  ;; prefix argument to 'M-&', but can use, e.g., C-u C-u M-& C-x o &.
	  ;; (It wouldn't make sense to pass a prefix argument to 'M-!').
	  ;;
	  ;; Invoking with '!', and no prefix argument, is a shortcut for
	  ;; copying absolute paths, and behaving more like 'M-!' than 'M-&'.
	  (cond (subdir
		 (spw/eshell-jump)
		 (ensure-list subdir))
		((if arg
		     (zerop (prefix-numeric-value arg))
		   (char-equal last-command-event ?!))
		 (prog1 (dired-get-marked-files) (spw/eshell-jump)))
                ((consp arg)
                 (prog1 (dired-get-marked-files t)
		   (spw/eshell-jump 'strict)))
                (t
                 (prog1 (dired-get-marked-files
			 'no-dir (and arg (prefix-numeric-value arg)))
		   (spw/eshell-jump t)))))
         (string
          (mapconcat (lambda (file)
                       (if (string-match-p "[ \"']" file)
                           (format "%S" file)
                         file))
                     files
                     " ")))
    (unless (string-empty-p string)
      (let ((empty-p (= eshell-last-output-end (point-max))))
	;; If we're somewhere else in the buffer, jump to the end.
	;; This means that if you want to insert the filenames into an old
	;; command you're editing, you have to C-c RET first.
	(when (> eshell-last-output-end (point))
	  (goto-char (point-max)))
	(save-restriction
	  (when (= eshell-last-output-end (point))
	    (narrow-to-region (point) (point-max)))
	  (just-one-space))
	(insert string)
	(just-one-space)
	(when empty-p
	  (goto-char eshell-last-output-end)
	  (when-let* ((default (dired-guess-default files)))
	    (if (listp default)
		(let ((completion-at-point-functions
		       (list (lambda () (list (point) (point) default)))))
		  (completion-at-point))
	      (insert default))))))))
(spw/feature-define-keys dired
  "!" #'spw/dired-copy-filename-as-kill
  "&" #'spw/dired-copy-filename-as-kill)


;;;; EWW

;; this should ensure that M-a and M-e work for most webpages
(add-hook 'eww-mode-hook (lambda ()
			   (setq-local sentence-end-double-space nil)))

;; eww bookmarks don't have short names associated to them, just page titles,
;; so for places we visit a lot the normal bookmarks system seems more
;; appropriate.  adapted from bookmark-w3m.el.

(defun spw/bookmark-eww-bookmark-make-record ()
  "Make an Emacs bookmark entry for an Eww buffer."
  `(,(plist-get eww-data :title)
    ,@(bookmark-make-record-default 'no-file)
    (url . ,(eww-current-url))
    (handler . spw/bookmark-eww-bookmark-jump)
    (defaults . (,(plist-get eww-data :title)))))

(defun spw/bookmark-eww-bookmark-jump (bookmark)
  (eww (bookmark-prop-get bookmark 'url))
  (bookmark-default-handler
   `(""
     (buffer . ,(current-buffer))
     . ,(bookmark-get-bookmark-record bookmark))))

(add-hook 'eww-mode-hook
	  (lambda ()
	    (setq-local bookmark-make-record-function
			#'spw/bookmark-eww-bookmark-make-record)))


;;;; Gnus

(with-eval-after-load 'gnus
  (cond ((spw/on-host-p "chiark.greenend.org.uk")
	 (setq gnus-select-method
	       '(nntp "chiark"
		      (nntp-address "news.chiark.greenend.org.uk")
		      (nntp-open-connection-function
		       spw/nntp-open-authinfo-kludge))))
	;; If NNTPSERVER has been configured by the local administrator,
	;; accept Gnus's defaults.  Otherwise, set the default select method
	;; to nnnil so that typing 'M-x gnus' does not hang.
	((not (gnus-getenv-nntpserver))
	 (setq gnus-select-method '(nnnil "")))))

(defmacro spw/defun-pass-to-gdbmacs (name arglist &rest body)
  (declare (indent 2))
  (let ((parsed-body (macroexp-parse-body body))
	(arglist-names
	 (cl-loop for entry in arglist
		  if (eq entry '&rest) do (error "Not implemented")
		  else unless (eq entry '&optional) collect entry)))
    `(defun ,name ,arglist
       ,@(car parsed-body)
       (if (spw/may-pass-to-gdbmacs-p)
	   ;; We'd like to just bind `display-buffer-overriding-action', but
	   ;; Gnus doesn't respect that when it starts up.
	   (ignore-error server-return-invalid-read-syntax
	     (server-eval-at
	      "gdbmacs" `(with-selected-frame
			     (make-frame
			      '((display
				 . ,(frame-parameter nil 'display))))
			   (let ((default-directory ,default-directory))
			     ,(list ',name ,@arglist-names)))))
	 ,@(cdr parsed-body)))))

(defvar gnus-always-read-dribble-file)

(defun spw/gnus-startup-wrapper (orig-fun &rest args)
  (when-let ((daemon (and (file-directory-p "~/.fmail/") (daemonp))))
    (unless (file-exists-p "~/.newsrc.eld")
      (user-error "Must use dedicated Emacs for Gnus first run"))
    (unless (or (string= "gdbmacs" daemon)
		(spw/on-host-primary-p "athena.silentflame.com"))
      (user-error "This is not the Gnusmacs you're looking for")))
  (let ((repo (expand-file-name "~/src/athpriv/")))
    (when (file-directory-p repo)
      ;; We want Gnus running on just one machine at once to avoid conflicts
      ;; in automatic updates to score files.  If there are no uncommitted
      ;; changes then it might be that Gnus is already running somewhere else.
      (unless (cl-remove-if-not
	       (apply-partially #'string-match
				"^.. \"?News/.+\\.\\(?:SCORE\\|ADAPT\\)\"?$")
	       (process-lines "mr" "-d" repo "status"))
	(if (yes-or-no-p
	     "~/src/athpriv/News/ has no changes; really start Gnus?")
	    (unless (zerop (call-process "mr" nil "*myrepos athpriv update*"
					 nil "-d" repo "update"))
	      (error "mr couldn't update ~/src/athpriv/"))
	  (user-error "Aborting")))))
  (let ((gc-cons-percentage 0.6)
	(gc-cons-threshold 402653184)
	(gnus-always-read-dribble-file (file-exists-p "~/.newsrc.eld")))
    (apply orig-fun args)))
(advice-add 'gnus :around #'spw/gnus-startup-wrapper)
(advice-add 'gnus-no-server :around #'spw/gnus-startup-wrapper)

(spw/defun-pass-to-gdbmacs spw/gnus (&optional fetch-and-inbox)
  (interactive "P")
  (require 'gnus)
  (if (not fetch-and-inbox)
      (if (gnus-alive-p) (pop-to-buffer-same-window gnus-group-buffer) (gnus))
    ;; We want to see mail that we think has just come in.  This is the only
    ;; time we call 'notmuch new' without --no-hooks from Emacs rather than
    ;; just waiting for cron, because it's slow.
    (unless (gnus-alive-p) (gnus))
    (unless (spw/on-host-p "athena.silentflame.com")
      (with-temp-message "Fetching from all accounts on athena ..."
	(call-process "ssh" nil nil nil "athena" "sh" "-lc" "movemymail")))
    (with-temp-message "Fetching & indexing mail locally ..."
      (call-process "notmuch" nil nil nil "new"))
    (let* ((group (cl-case (prefix-numeric-value current-prefix-arg)
		    (4 "nnselect:Process-Weekend")
		    (16 "nnselect:Process-Weekday")))
	   (buffer (gnus-summary-buffer-name group)))
      (if (not (get-buffer buffer))
	  (gnus-group-read-group nil t group)
	(pop-to-buffer-same-window buffer)
	(gnus-summary-rescan-group)))))
(global-set-key "\C-cgn" #'spw/gnus)

(defun spw/gnus-goto-all-articles (group article)
  (require 'gnus)
  (if (gnus-alive-p) (pop-to-buffer-same-window gnus-group-buffer) (gnus))
  (gnus-group-jump-to-group group)
  (gnus-group-get-new-news-this-group)
  (gnus-group-jump-to-group group)
  ;; `gnus-topic-read-group' won't ever select an article if none are unread.
  (gnus-topic-select-group t)
  (when (and article (derived-mode-p 'gnus-summary-mode))
    (gnus-summary-next-page)))

(spw/defun-pass-to-gdbmacs spw/gnus-goto-notes ()
  (interactive)
  (spw/gnus-goto-all-articles "nnmaildir+fmail:notes" t))
(global-set-key "\C-cgN" #'spw/gnus-goto-notes)

(spw/defun-pass-to-gdbmacs spw/gnus-goto-sent ()
  (interactive)
  (spw/gnus-goto-all-articles "nnmaildir+fmail:sent" nil))
(global-set-key "\C-cgS" #'spw/gnus-goto-sent)

(defvar spw/gnus-notmuch-history)

(spw/defun-pass-to-gdbmacs spw/gnus-notmuch-ephemeral-search
    (query &optional limit thread)
  (interactive
   (list (read-string "Query: " nil 'spw/gnus-notmuch-history)
	 (and current-prefix-arg (prefix-numeric-value current-prefix-arg))
	 ;; With (thread . t) messages not matching the search can easily
	 ;; swamp the message(s) we're looking for.
	 ;; Instead, can type 'A W' to view whole threads.
	 nil))
  (require 'gnus)
  (if (gnus-alive-p)
      (when (derived-mode-p 'gnus-article-mode 'gnus-summary-mode)
	(if (spw/use-tabs-not-frames)
	    (tab-bar-new-tab)
	  (select-frame (make-frame-command)))
	(let ((del (if (spw/use-tabs-not-frames) #'tab-close #'delete-frame)))
	  (spw/add-once-hook
	   'gnus-summary-prepared-hook
	   (lambda () (add-hook 'gnus-summary-prepare-exit-hook del nil t)))))
    (gnus))
  (gnus-group-read-ephemeral-group
   (concat "nnselect-" (message-unique-id)) (list 'nnselect "nnselect")
   nil (cons (current-buffer) gnus-current-window-configuration) nil nil
   `((score-file . "all.SCORE") (adapt-file . "all.ADAPT")
     (gnus-thread-sort-functions '(gnus-thread-sort-by-most-recent-number))
     (nnselect-specs
      . ((nnselect-function . gnus-search-run-query)
	 (nnselect-args
	  . ((search-group-spec ("nnmaildir:fmail"))
	     (search-query-spec
	      (thread . ,thread) (query . ,query) (raw . t)
	      (limit . ,(cl-case limit (0 nil) ((nil) 200) (t limit))))))))
     (nnselect-artlist . nil))))
(global-set-key "\C-cgm" #'spw/gnus-notmuch-ephemeral-search)

;; Adapted from chiark:~matthewv/.gnus and originally from
;; <http://www.greenend.org.uk/rjk/2000/08/29/authinfo.html>.
(defun spw/nntp-open-authinfo-kludge (buffer)
  "Open a connection to NNTP server using 'authinfo-kludge'."
  (prog1 (start-process "nntpd" buffer "authinfo-kludge" nntp-address)
    (set-buffer buffer)
    (nntp-wait-for-string "^\r*200")
    (beginning-of-line)
    (delete-region (point-min) (point))))

(defun spw/notmuch-connective (word)
  (let ((sep (format " %s " word))
	(f (apply-partially #'format "(%s)")))
    (lambda (&rest queries)
      (mapconcat f (flatten-tree queries) sep))))

(defalias 'spw/nm| (spw/notmuch-connective "or"))
(defalias 'spw/nm& (spw/notmuch-connective "and"))
(defalias 'spw/nm~ (apply-partially #'format "not (%s)"))

(defvar spw/personal-sources)
(defvar spw/work-sources)
(defvar spw/feed-sources)
(defvar spw/bulk-sources)
(defvar spw/other-process-groups)
(defvar spw/browse-groups)

(defvar spw/gnus-all-process-groups)

;;; We don't have "Sent" and "Flagged" saved searches because all flagged are
;;; visible at the top of nnmaildir+fmail:inbox and I used the "Sent" saved
;;; search to see only recent sent mail, which is just nnmaildir+fmail:sent.
;;;
;;; Flagging is used (i) in the short term to collect a list of messages for
;;; processing together (e.g. student questions for a review session, arriving
;;; over the course of a week); and (ii) in the medium term to indicate which
;;; messages in a thread are pertinent when returning to the thread from a
;;; link in an Org TODO.  Examples of the latter include messages with review
;;; comments I want to check are addressed by a revised series, and in a long
;;; thread, which messages actually contain information relevant to the task.
;;;
;;; It might be cool to use flagging with Gnus adaptive scoring, but we would
;;; want such flags to be automatically removed at some point so that the
;;; messages could be archived by archive-fmail-to-annex.  But then flags set
;;; for (i) and (ii) would get arbitrarily removed too.

(defun spw/sync-notmuch-nnselect-groups ()
  "Add or update all my Gnus-saved notmuch searches."
  (interactive)
  (when (file-directory-p
	 (expand-file-name "~/.local/share/notmuch/default/xapian/"))
    (let* ((process-groups
	    `(;; To process Inbox Zero-style in distinct inboxes.
	      ;;
	      ;; `spw/bulk-sources' is for excluding things like notifications
	      ;; that are addressed directly to me, e.g. from GitLab installs.
	      ("Weekday"
	       ,(spw/nm& (spw/nm| spw/personal-sources spw/work-sources)
			 (spw/nm~ (spw/nm| spw/bulk-sources))))
	      ("Weekend"
	       ,(spw/nm&
		 (spw/nm| spw/personal-sources)
		 (spw/nm~ (spw/nm| spw/bulk-sources spw/work-sources))))
	      ,@spw/other-process-groups))
	   (process-groups
	    (cl-loop with never-process
		     = (spw/nm~
			(spw/nm|
			 spw/feed-sources "folder:notes" "folder:sent"))
		     for (name . queries) in process-groups collect
		     (cons name (spw/nm& (spw/nm| queries) never-process))))
	   (browse-groups
	    (named-let recurse (accum (remaining spw/browse-groups))
	      (cond ((null remaining) (nreverse accum))
		    ((cl-every #'stringp (ensure-list (cdar remaining)))
		     (recurse (cons (car remaining) accum) (cdr remaining)))
		    (t (recurse accum (nconc (copy-sequence (cdar remaining))
					     (cdr remaining)))))))
	   (categorised (spw/nm| (mapcar #'cdr process-groups)
				 (mapcar #'cdr browse-groups)))

	   (process-groups
	    `(;; Groups/lists where I don't know how or whether I want to
	      ;; follow them; I may have subscribed just to post something.
	      ("Uncategorised other"
	       . ,(spw/nm~ (spw/nm| spw/feed-sources categorised)))
	      . ,process-groups))
	   (browse-groups
	    `(;; Content not from mailing lists and not otherwise categorised
	      ;; -- previously such items would fall into "uncategorised
	      ;; unread" but that's wrong because I've explicitly subscribed
	      ;; to each of these.
	      ("Uncategorised feeds"
	       ,(spw/nm& (spw/nm| spw/feed-sources) (spw/nm~ categorised)))
	      . ,browse-groups))

	   (groups
	    (nconc
	     (cl-loop
	      for (name . queries) in browse-groups collect
	      `(,name (thread . t) (query . ,(spw/nm| queries)) (raw . t)))
	     (cl-loop for (name . query) in process-groups collect
		      `(,(concat "Process-" name)
			(thread . nil) (query . ,query) (raw . t))))))
      (setq spw/gnus-all-process-groups
	    (spw/nm| (mapcar #'cdr process-groups)))
      (require 'gnus) (require 'nnselect)
      (unless (gnus-alive-p) (gnus-no-server))

      ;; Kill all summaries in case any of their queries have changed.
      (catch 'done
	(dolist (buffer (buffer-list))
	  (when (buffer-local-value 'gnus-dead-summary-mode buffer)
	    (throw 'done (kill-buffer buffer)))))
      (gnus-offer-save-summaries)

      (with-current-buffer gnus-group-buffer
	(gnus-topic-mode 0)
	(cl-loop
	 initially (goto-char (point-max)) for (name . alist) in groups
	 for nname = (nnselect-add-prefix name)
	 for specs = `((nnselect-function . gnus-search-run-query)
		       (nnselect-args
			. ((search-query-spec . ,alist)
			   (search-group-spec ("nnmaildir:fmail")))))
	 ;; We're only really interested in recent mail for all these saved
	 ;; searches: for older mail I do ephemeral searches.  Take advantage
	 ;; of this to limit the number of results we're ever asking Gnus to
	 ;; read.  An alternative to "not folder:annex" might be "tag:unread".
	 do (cl-callf spw/nm& (cdr (assq 'query alist)) "not folder:annex")
	 if (gnus-group-entry nname) do
	 (gnus-group-set-parameter nname 'nnselect-specs specs)
	 ;; From `gnus-group-make-search-group' (though marked "temporary"?).
	 else do (gnus-group-make-group name (list 'nnselect "nnselect")
					nil `((nnselect-specs . ,specs)
					      (nnselect-rescan . t)
					      (nnselect-artlist . nil)))
	 ;; Manual recommends keeping mail groups on levels 1 and 2.  We have
	 ;; browse groups higher for `gnus-group-best-unread-group'.  Then `.'
	 ;; to jump to the first processing group, `,' to jump to the first
	 ;; browse group.
	 do (gnus-group-set-subscription
	     nname (if (string-prefix-p "Process-" name) 2 1)))
	(gnus-group-set-subscription "nnmaildir+fmail:notes" 2)

	;; Finally, group buffer setup.  If we want to add groups other than
	;; my nnselect groups to topics, we might have starting values
	;; `spw/gnus-topic-topology' and `spw/gnus-topic-alist' in .gnus.el,
	;; upon which this code would base its work.

	(setq
	 ;; It's not necessary to alter `gnus-variable-list' like this but it
	 ;; might be less confusing not to see in .newsrc.eld values for these
	 ;; variables which will always be ignored.
	 gnus-variable-list
	 (cl-set-difference gnus-variable-list
			    '(gnus-topic-alist gnus-topic-topology))

	 gnus-topic-alist
	 (list (cl-list*
		"Inboxes"
		"nnselect:Process-Weekday"
		"nnselect:Process-Weekend"
		"nnselect:Process-Uncategorised other"
		(cl-loop for (group . _) in spw/other-process-groups collect
			 (nnselect-add-prefix (concat "Process-" group))))
	       (list "Publications" "nnselect:Uncategorised feeds"))
	 gnus-topic-topology
	 (named-let recurse ((accum
			      (copy-tree
			       '((("Inboxes" visible)) ("Gnus" visible))))
			     (remaining spw/browse-groups)
			     topic)
	   (cond ((null remaining) (nreverse accum))
		 ((cl-every #'stringp (ensure-list (cdar remaining)))
		  (push (nnselect-add-prefix (caar remaining))
			(alist-get topic gnus-topic-alist nil nil #'string=))
		  (recurse accum (cdr remaining) topic))
		 (t (let* ((new-topic (caar remaining))
			   (new-topology
			    (recurse nil (cdar remaining) new-topic)))
		      (recurse (cons (cons `(,new-topic visible) new-topology)
				     accum)
			       (cdr remaining)
			       topic))))))
	(rplacd (last gnus-topic-topology) (copy-tree '((("misc" visible)))))

	(gnus-topic-mode 1)
	(gnus-group-list-groups)
	(gnus-topic-move-matching "^\\(?:nndraft:\\|nnmaildir\\)" "misc")
	(gnus-group-sort-topic		; actually sorts in all topics
	 (lambda (info1 info2)
	   (let ((group1 (gnus-group-real-name (gnus-info-group info1)))
		 (group2 (gnus-group-real-name (gnus-info-group info2))))
	     ;; Ensure we can't move Weekend->Weekday at end of group, and
	     ;; that otherwise they are first within their group
	     (or (string= group1 "Process-Weekday")
		 (and (string= group1 "Process-Weekend")
		      (not (string= group2 "Process-Weekday")))
		 (and (not (string-prefix-p "Process-Week" group2))
		      (string< group1 group2)))))
	 nil)

	;; Any nnselect groups in the root group at this point must be old
	;; searches I've dropped from .gnus.el.
	(cl-loop for group in (cdr (assoc "Gnus" gnus-topic-alist #'string=))
		 when (string-prefix-p "nnselect:" group) do
		 (gnus-group-jump-to-group group) (gnus-topic-kill-group 1))

	;; Ensure inbox maildir group is unsubscribed because it will have
	;; unread messages whenever any nnselect group does, but we don't want
	;; to read any of them by entering it.  Do this here instead of
	;; modifying `gnus-auto-subscribed-groups' to exclude the inbox
	;; because we want to re-unsubscribe in case I subscribed to it since
	;; this function last ran.
	;;
	;; Put inbox and annex maildirs on a level >`gnus-activate-level' such
	;; that they are each activated only when entering an nnselect group
	;; with messages from that maildir.  This speeds up Gnus startup.
	(gnus-group-set-subscription "nnmaildir+fmail:inbox" 7)
	(when (gnus-group-entry "nnmaildir+fmail:annex")
	  (gnus-group-set-subscription "nnmaildir+fmail:annex" 7))

	(gnus-group-list-groups)
	(gnus-group-best-unread-group)))))
(with-eval-after-load 'gnus-start
  (add-hook 'gnus-started-hook #'spw/sync-notmuch-nnselect-groups))

;; Rescan nnmaildir+fmail:inbox too, else rescanning the nnselect group will
;; not display any new mail.
(defun spw/gnus-request-group-scan (group _info)
  (when (eq 'nnselect (car (gnus-find-method-for-group group)))
    (gnus-activate-group "nnmaildir+fmail:inbox" 'scan)))
(advice-add 'gnus-request-group-scan :before #'spw/gnus-request-group-scan)

;; This works around Emacs bug#56592 without relying on duplicate suppression.
(defun spw/gnus-summary-read-group (orig-fun group show-all &rest args)
  (let* ((nnselectp (string-prefix-p "nnselect:" group))
	 (unread-before (gnus-group-unread group))
	 (none-unread-before-p (and (numberp unread-before)
				    (zerop unread-before))))
    (when nnselectp
      (with-current-buffer gnus-group-buffer
	(save-excursion
	  (gnus-group-goto-group group)
	  (gnus-group-get-new-news-this-group 1))))
    (let ((none-unread-after-p (and nnselectp
				    (zerop (gnus-group-unread group)))))
      (cond ((and nnselectp (not show-all)
		  (not none-unread-before-p) none-unread-after-p)
	     ;; Ensure we return nil to `gnus-summary-next-group'.
	     (ignore (message "No more unread articles")))
	    ;; `gnus-group-read-group' passes SHOW-ALL t if it thinks the
	    ;; group has no unread messages.  Override that.
	    ((and nnselectp
		  (not (and current-prefix-arg
			    (memq this-command '(gnus-topic-read-group
						 gnus-topic-select-group))))
		  none-unread-before-p (not none-unread-after-p))
	     (apply orig-fun group nil args))
	    (t (apply orig-fun group show-all args))))))
(advice-add 'gnus-summary-read-group :around #'spw/gnus-summary-read-group)

(defun spw/gnus-group-nnselect-query (group)
  (when-let ((specs (gnus-group-get-parameter group 'nnselect-specs t)))
    (cdr (assq 'query
	       (cdr (assq 'search-query-spec
			  (cdr (assq 'nnselect-args specs))))))))

;; This simple scheme means that we can always tell whether we're in a
;; processing view just by looking at the mode line.
(defun spw/gnus-summary-processing-view-p ()
  (string-prefix-p "nnselect:Process-" gnus-newsgroup-name))

(defun spw/all-group-process-view-ids (group)
  (when-let* ((query (spw/gnus-group-nnselect-query group))
	      (overlap (spw/nm& "tag:unread" spw/gnus-all-process-groups
				(format "thread:\"{%s}\""
					(string-replace "\"" "\"\"" query)))))
    (call-process "notmuch" nil nil nil "new" "--no-hooks")
    (mapcar (lambda (line) (format "<%s>" (substring line 3)))
	    (process-lines "notmuch" "search" "--output=messages"
			   "--format=text" "--format-version=4" overlap))))

;; Empty hash table means we know there is no mail from processing views.
;; nil means we haven't yet / couldn't check, so no catching up is allowed.
;;
;; Note that this machinery can be defeated by `gnus-summary-clear-*'.
;; We call notmuch(1) in `spw/all-group-process-view-ids' to update its idea
;; of what's unread, but if there is more than one copy of a message, both
;; marked seen, and then one of them is marked unread by Gnus, notmuch won't
;; restore tag:unread.
(defvar-local spw/process-view-ids nil)

(defun spw/check-group-process-view-ids (&optional id)
  (if spw/process-view-ids
      (or (not id) (gethash id spw/process-view-ids))
    (let ((ids (spw/all-group-process-view-ids gnus-newsgroup-name))
	  (table (make-hash-table :test #'equal)))
      (dolist (id ids) (puthash id t table))
      ;; Only point the variable at the table if we got this far.
      (setq spw/process-view-ids table)
      ;; Now try the check again.
      (or (not id) (gethash id spw/process-view-ids)))))

(with-eval-after-load 'gnus-sum
  (add-hook 'gnus-summary-generate-hook
	    (lambda () (setq spw/process-view-ids nil))))

(defun spw/gnus-mark-article-hook ()
  "Don't mark any mail from processing views as read just for viewing it."
  (unless (or (spw/gnus-summary-processing-view-p)
	      (memq (gnus-summary-article-mark)
		    (list gnus-read-mark gnus-del-mark)))
    (if (spw/check-group-process-view-ids (gnus-summary-header "message-id"))
	(message "Not marking mail from processing views as read")
      (gnus-summary-mark-read-and-unread-as-read))))

(defun spw/guard-gnus-group-catchup (group &optional _all)
  (when (string-prefix-p "nnselect:Process-" group)
    (user-error "Cannot catch up processing views"))
  (when (spw/all-group-process-view-ids group)
    (error "This group contains articles from processing views")))
(advice-add 'gnus-group-catchup :before #'spw/guard-gnus-group-catchup)

(defun spw/guard-gnus-summary-catchup (&rest _ignore)
  ;; `gnus-group-select-group' also calls `gnus-summary-catchup'.
  (when (string-prefix-p "gnus-summary-catchup" (symbol-name this-command))
    (when (spw/gnus-summary-processing-view-p)
      (user-error "Cannot catch up processing views"))
    ;; We could pay attention to the TO-HERE and REVERSE arguments and check
    ;; only those IDs, though it'd be slower.
    (unless (and (spw/check-group-process-view-ids)
		 (zerop (hash-table-count spw/process-view-ids)))
      (error "This group/range may contain articles from processing views"))))
(advice-add 'gnus-summary-catchup :before #'spw/guard-gnus-summary-catchup)

(defun spw/gnus-summary-mark-as-read-backward (n)
  (interactive "p")
  (spw/gnus-summary-mark-as-read-forward (- n)))

(defun spw/gnus-summary-mark-as-read-forward (n)
  (interactive "p")
  (unless (zerop n)
    (let* ((processing-p (or (spw/gnus-summary-processing-view-p)
			     (spw/check-group-process-view-ids
			      (gnus-summary-header "message-id"))))
	   (mark (if processing-p gnus-read-mark gnus-del-mark)))
      (when processing-p (setq n (if (> 0 n) -1 1)))
      (gnus-set-global-variables)
      (if (not (get-buffer-window gnus-article-buffer t))
	  (gnus-summary-mark-forward n mark gnus-inhibit-user-auto-expire)
	(save-excursion (gnus-summary-mark-forward n mark))
	(if (> 0 n) (gnus-summary-prev-unread-article)
	  (gnus-summary-next-unread-article))))))

;; See (info "(gnus) Generic Marking Commands").
(with-eval-after-load 'gnus-sum
  (define-key gnus-summary-mode-map [remap gnus-summary-mark-as-read-backward]
	      #'spw/gnus-summary-mark-as-read-backward)
  (define-key gnus-summary-mode-map [remap gnus-summary-mark-as-read-forward]
	      #'spw/gnus-summary-mark-as-read-forward)

  ;; Given how we use flagging, described above, it makes sense to advance to
  ;; the next message after flagging ...
  (define-key gnus-summary-mode-map [remap gnus-summary-tick-article-backward]
	      #'gnus-summary-put-mark-as-ticked-prev)
  (define-key gnus-summary-mode-map [remap gnus-summary-tick-article-forward]
	      #'gnus-summary-put-mark-as-ticked-next)

  ;; ... and then for consistency we want M-u the same as '!' and 'd'.
  ;; (We might otherwise just leave M-u with its default behaviour.)
  (define-key gnus-summary-mode-map [remap gnus-summary-clear-mark-backward]
	      #'gnus-summary-put-mark-as-unread-prev)
  (define-key gnus-summary-mode-map [remap gnus-summary-clear-mark-forward]
	      #'gnus-summary-put-mark-as-unread-next))

;; Unlike `notmuch-extract-thread-patches' and
;; `notmuch-extract-message-patches', it does not make sense to check out a
;; branch when performing an action which will not make a commit.  If that's
;; wanted, the code which calls `spw/gnus-mime-apply-part' should perform the
;; checkout.
;;
;; Probably also want `spw/gnus-article-apply-part' for summary buffers.
(defun spw/gnus-mime-apply-part ()
  (interactive)
  (let ((default-directory (expand-file-name (project-prompt-project-dir))))
    (gnus-mime-pipe-part "git apply")))
(with-eval-after-load 'gnus-art
  (define-key gnus-mime-button-map "a" #'spw/gnus-mime-apply-part))

(dolist (fn '(gnus-mime-save-part-and-strip
	      gnus-article-save-part-and-strip
	      gnus-article-replace-part
	      gnus-article-delete-part))
  (advice-add fn :override #'ignore))

(with-eval-after-load 'gnus-sum
  (define-key gnus-summary-mode-map "k" "ToTkg")
  (define-key gnus-summary-mode-map "\M-k" "Tkg"))

;;; Following bindings go under 'v' because that is reserved to Gnus users.

;; There's an alternative to having a dedicated command for this described in
;; (info "(gnus) Security"), "Snarfing OpenPGP keys".
(defun spw/gnus-import-gpg ()
  (interactive)
  (gnus-summary-save-in-pipe "gpg --decrypt | gpg --import" t)
  (display-buffer "*Shell Command Output*"))
(with-eval-after-load 'gnus-sum
  (define-key gnus-summary-mode-map "vg" #'spw/gnus-import-gpg))

(defun spw/gnus-reader ()
  (interactive)
  ;; Can't use `gnus-eval-in-buffer-window' because we want eww buffer to be
  ;; left selected, if that's what we use.
  (gnus-summary-select-article-buffer)
  (save-excursion
    (goto-char (point-min))
    (cond
     ((re-search-forward
       "https://www.wsj.com/.*-WSJNewsPaper-[0-9-]+\\.pdf" nil t)
      (call-process-shell-command
       (format "evince %s"
	       (shell-quote-argument
		(buffer-substring-no-properties (match-beginning 0) (point))))
       nil 0)
      ;; We used an external program, so switch back.
      (gnus-article-show-summary))
     (t
      (re-search-forward "^URL:\\( \\|\n\\)")
      (let ((url (buffer-substring-no-properties (point) (line-end-position))))
	;; alternative to eww readable view:
	;; (start-process "firefox" nil "firefox"
	;;                "-new-window"
	;;                (concat "about:reader?url=" url))
	;;
	;; There is also Gnus's `A w' binding.
	(spw/add-once-hook 'eww-after-render-hook #'eww-readable)
	(let ((saved gnus-summary-buffer))
	  (eww url)
	  (setq-local gnus-summary-buffer saved)))))))
(with-eval-after-load 'gnus-sum
  (define-key gnus-summary-mode-map "vo" #'spw/gnus-reader))

(spw/feature-define-keys eww "h" gnus-article-show-summary)

;; In a group with patches, try to expunge messages not relevant for reviewing
;; those patches.  Optional numeric prefix argument specifies the version of
;; the series to review, in case there is more than one series in the summary
;; buffer.  Include ticked messages, as these may contain unresolved review
;; comments on older versions of the series.
;;
;; In the case where you want to compare the new series against review
;; comments on the old series, and the series are in different threads, use
;; C-c g m to open a distinct summary buffer for each thread, in two frames,
;; use this command in the buffer with the new series, and possibly use / m to
;; see only ticked articles in the old series' summary buffer.
(defun spw/gnus-summary-limit-to-patches (&optional reroll-count)
  (interactive "P")
  (gnus-summary-limit-to-subject
   (if reroll-count
       (cl-case (prefix-numeric-value reroll-count)
	 (1 "\\[.*PATCH\\(?:[^v]*\\|.*v1.*\\)\\]")
	 (t (format "\\[.*PATCH.*v%s.*\\]"
		    (prefix-numeric-value reroll-count))))
     "\\[.*PATCH.*\\]"))
  (gnus-summary-limit-to-subject (regexp-opt '("Re:" "Info received")) nil t)
  ;; Would be good also to reinsert all unread messages.
  (gnus-summary-insert-ticked-articles))
(with-eval-after-load 'gnus-sum
  (define-key gnus-summary-mode-map "vf" #'spw/gnus-summary-limit-to-patches))

(defun spw/gnus-summary-save-all-parts ()
  "Save all parts to ~/tmp/."
  (interactive)
  (gnus-summary-save-parts "" (expand-file-name "~/tmp/") current-prefix-arg))

(defun spw/gnus-summary-save-all-attachments ()
  "Save all attachments to ~/tmp/."
  (interactive)
  (gnus-eval-in-buffer-window gnus-article-buffer
    ;; `gnus-summary-save-parts' has some alternative ways to get the handles
    ;; if `gnus-article-mime-handles' is nil.
    (let ((handles gnus-article-mime-handles))
      (when (stringp (car handles)) (pop handles))
      (mapc #'mm-save-part (cl-remove-if-not #'mm-handle-filename handles)))))

(with-eval-after-load 'gnus-sum
  ;; Like `X m' binding.
  (define-key gnus-summary-mode-map
	      "vm" #'spw/gnus-summary-save-all-attachments)
  (define-key gnus-summary-mode-map "vM" #'spw/gnus-summary-save-all-parts))

(defun spw/gnus-warp-to-article ()
  (interactive)
  (let* ((specs
	  (gnus-group-get-parameter gnus-newsgroup-name 'nnselect-specs t)))
    (if (gnus-search-notmuch-p
	 (gnus-search-server-to-engine
	  (caadr (assq 'search-group-spec
		       (cdr (assq 'nnselect-args specs))))))
	(let* ((mid (gnus-summary-header "message-id"))
	       (search (concat "id:" (string-trim mid "<" ">"))))
	  (spw/gnus-notmuch-ephemeral-search search 0 t)
	  (gnus-summary-goto-article mid))
      (gnus-warp-to-article))))
(with-eval-after-load 'gnus-sum
  (define-key gnus-summary-mode-map
	      [remap gnus-warp-to-article] #'spw/gnus-warp-to-article))

(defun spw/org-gnus-follow-link (orig-fun &optional group article)
  (if (not article)
      (apply orig-fun group nil)
    (spw/gnus-notmuch-ephemeral-search (concat "id:" article) 0 t)
    (gnus-summary-goto-article article)))
(advice-add 'org-gnus-follow-link :around #'spw/org-gnus-follow-link)

(defun spw/gnus-fastmail-trash (n)
  (interactive "p")
  (gnus-summary-move-article n "nnmaildir+fmail:trash"))
(with-eval-after-load 'gnus-sum
  (define-key gnus-summary-mode-map
	      [remap gnus-summary-delete-article] #'spw/gnus-fastmail-trash))

(defun spw/gnus-fastmail-learn-spam (n)
  (interactive "p")
  (save-excursion (gnus-summary-mark-forward n))
  (gnus-summary-move-article n "nnmaildir+fmail:spam")
  (gnus-summary-next-unread-article))
(with-eval-after-load 'gnus-sum
  (define-key gnus-summary-mode-map [f5] #'spw/gnus-fastmail-learn-spam)
  (define-key gnus-summary-mode-map "\C-z\C-s" #'spw/gnus-fastmail-learn-spam))

(defun spw/gnus-with-expert (orig-fun &rest args)
  (let ((gnus-expert-user t)) (apply orig-fun args)))
(advice-add #'gnus-summary-exit-no-update :around #'spw/gnus-with-expert)


;;;; rcirc

(defun spw/rcirc-generate-log-filename (process target)
  (concat (file-name-concat (format-time-string "%Y/%m")
			    (process-name process) (or target "server"))
	  ".log"))

(defalias 'rcirc-handler-305 #'ignore)
(defalias 'rcirc-handler-306 #'ignore)

(defun spw/irc-autoaway ()
  (dolist (process (rcirc-process-list))
    (rcirc-send-string process "AWAY :This Emacs is idle"))
  (spw/add-once-hook 'post-command-hook
		     (lambda ()
		       (dolist (process (rcirc-process-list))
			 (rcirc-send-string process "AWAY :")))))

(when (spw/on-host-primary-p "athena.silentflame.com")
  (run-with-idle-timer
   120 nil (lambda ()
	     (load (expand-file-name "irc-init" user-emacs-directory))
	     (irc nil)
	     (defvar spw/irc-autoaway-timer
	       (run-with-idle-timer 240 t #'spw/irc-autoaway)))))

(defun spw/rcirc-log-for-mail (process sender response target text)
  (with-rcirc-process-buffer process
    (when (and (string= "PRIVMSG" response)
	       (or (string= sender target)
		   (string-match-p
		    (format "\\`\\(?:spwhitton\\|seanw\\|%s\\).? " rcirc-nick)
		    text)))
      (with-temp-buffer
	(let ((time (format-time-string rcirc-time-format))
	      (name (rcirc-generate-new-buffer-name process target)))
	  (insert
	   (if (string= sender target)
	       (format "\n\n%s\t\t%s\n\n    " time name)
	     (format "\n\n%s\t\t%s\n\n    <%s> " time name sender))))
	(insert text)
	(fill-region (pos-bol) (point))
	(write-region nil nil "~/local/irclogs/mail.log" t 'silent)))))
(spw/feature-add-hook spw/rcirc-log-for-mail (rcirc rcirc-print-functions))

(defun spw/rcirc-mail-hilights ()
  (when (file-exists-p "~/local/irclogs/mail.log")
    (ignore-errors
      (rename-file "~/local/irclogs/mail.log" "~/local/irclogs/mail.log.tmp"))
    (let (mail-signature
	  (mail-from-style 'parens)
	  (user-full-name "Cron Daemon")
	  (user-mail-address user-login-name))
      (mail 'new user-login-name "IRC messages")
      (mail-text) (insert-file "~/local/irclogs/mail.log.tmp")
      (mail-text) (delete-blank-lines) (delete-blank-lines)
      (let ((inhibit-quit t))
       (mail-send)
       (kill-buffer)
       (delete-file "~/local/irclogs/mail.log.tmp")))))

(when (spw/on-host-primary-p "athena.silentflame.com")
  (defvar spw/rcirc-mail-hilights-timer
    (run-at-time t 21600 #'spw/rcirc-mail-hilights)))

(defun spw/rcirc-dak (cmd)
  (if-let ((buffer (get-buffer "#debian-ftp-private@OFTC"))
	   (process (get-buffer-process "*OFTC*")))
      (progn (pop-to-buffer buffer)
	     (rcirc-send-privmsg process "#debian-ftp-private" cmd))
    (user-error "Missing buffer or process")))

(spw/feature-define-keys rcirc
  "\C-z\C-n" (lambda () (interactive) (spw/rcirc-dak "!lock NEW"))
  "\C-z\C-r" (lambda () (interactive) (spw/rcirc-dak "!lock rm"))
  "\C-z\C-o" (lambda () (interactive) (spw/rcirc-dak "!lock override"))
  "\C-z\C-u" (lambda () (interactive) (spw/rcirc-dak "!unlock")))


;;;; VC

;;; Want Magit installed for `git-commit-mode', `git-rebase-mode' and these
;;; reflog commands.  Otherwise, I prefer how VC is more buffer-oriented, such
;;; as in eschewing the (singular) Git staging area for `diff-mode' buffers.

(require 'git-commit nil t)

(global-set-key "\C-cvr" #'magit-reflog-current)
(global-set-key "\C-cvH" #'magit-reflog-head)
(global-set-key "\C-cvO" #'magit-reflog-other)

(spw/defun-pass-to-gdbmacs spw/mailscripts-prepare-patch ()
  (interactive)
  ;; Ensure the current buffer is one `vc-deduce-backend' can handle.
  (spw/with-project-root-dired (mailscripts-prepare-patch)))
(spw/when-library-available mailscripts
  (global-set-key "\C-cvm" #'spw/mailscripts-prepare-patch)
  ;; Want a dedicated binding for this because often need it with Debian BTS.
  (global-set-key "\C-cvw" #'spw/mailscripts-git-format-patch-attach)

  (spw/feature-define-keys ((gnus-sum gnus-summary-mode-map)
			    (gnus-art gnus-article-mode-map))
    "vt" notmuch-extract-thread-patches-to-project
    "vw" mailscripts-extract-message-patches-to-project))

(spw/reclaim-keys-from magit magit-mode-map "\M-w")

;; Emacs 30: move into `custom-set-variables'.
(when (>= emacs-major-version 30)
  (setopt vc-git-log-switches '("--format=fuller" "--stat")))

(defun spw/log-view-set-mark-command ()
  (interactive)
  (let ((beg (car (log-view-current-entry))))
    (if (and beg (> (point) (save-excursion (goto-char beg) (pos-eol))))
	(progn (setq this-command 'set-mark-command)
	       (call-interactively #'set-mark-command))
      (spw/ensure-whole-lines-mode 1 t))))

(defun spw/log-view-git-range ()
  (let* ((beg (use-region-beginning))
	 (start (and beg (cadr (log-view-current-entry beg))))
	 (end (and beg (region-end)))
	 (finish (and end (cadr (log-view-current-entry end)))))
    (setq deactivate-mark 'dont-save)
    (cond ((or (not beg) (< (count-lines beg end) 2))
	   ;; Leave it to the user to type "-1" if that's wanted.
	   (cadr (log-view-current-entry (point))))
	  ((> beg end) (format "%s..%s" start finish))
	  (t (format "%s..%s" finish start)))))

(defun spw/log-view-eshell-git-range (&optional subcommand)
  (interactive)
  (let ((buffer (current-buffer))
	(range (spw/log-view-git-range))
	(default-directory (project-root (project-current))))
    (spw/eshell-jump t)
    (when (> (point-max) eshell-last-output-end)
      (eshell-interrupt-process))
    (insert "git ")
    (when subcommand (insert subcommand ?\s))
    (save-excursion (insert ?\s range))))

(defun spw/log-view-git-cherry-pick ()
  (interactive)
  (spw/log-view-eshell-git-range "cherry-pick"))

(defun spw/log-view-git-fixup (&optional instant)
  (interactive "P")
  (let ((project-root (project-root (project-current)))
	(summary
	 (format "Summary: fixup! %s\n\n"
		 (cadr
		  (process-lines
		   "git" "rev-list" "--format=%s" (log-view-current-tag)))))
	(previous (format "%s~1" (log-view-current-tag))))
    (if (and (get-buffer "*vc-log*")
	     (with-current-buffer "*vc-log*"
	       (file-equal-p project-root (project-root (project-current)))))
	(progn (pop-to-buffer "*vc-log*")
	       (erase-buffer)
	       (insert summary)
	       (call-interactively #'log-edit-done)
	       (when instant
		 (let ((process-environment
			(cons "EDITOR=true" process-environment)))
		   (call-process "git" nil "*log-view-instant-fixup*" nil
				 "rebase" "-i" "--autosquash" previous)))
	       (when (derived-mode-p 'vc-git-log-view-mode)
		 (revert-buffer)))
      (require 'log-edit)
      (log-edit-remember-comment summary)
      (message "Pushed fixup! commit summary to Log Edit comment ring"))))

(defun spw/log-view-git-rebase (&optional interactive)
  (interactive "P")
  (deactivate-mark)
  (spw/log-view-eshell-git-range
   (if interactive "rebase -i --autosquash" "rebase")))

(defun spw/log-view-copy-git-range ()
  (interactive)
  (let ((range (spw/log-view-git-range)))
    (kill-new range)
    (message "Copied \"%s\" to kill ring." range)))

(defun spw/log-view-git-reset (&optional hard)
  (interactive "P")
  (deactivate-mark)
  (spw/log-view-eshell-git-range (if hard "reset --hard" "reset --mixed")))

(defun spw/log-view-msg-this ()
  (interactive)
  (when-let ((beg (car (log-view-current-entry))))
    (let ((expanded (get-text-property beg 'log-view-entry-expanded)))
      (log-view-toggle-entry-display)
      (unless expanded (log-view-diff (point) (point))))))

(defun spw/log-view-msg-next (n)
  (interactive "p")
  (log-view-msg-next n)
  (when-let ((beg (car (log-view-current-entry))))
    (unless (get-text-property beg 'log-view-entry-expanded)
      (log-view-toggle-entry-display)))
  (log-view-diff (point) (point))
  (setq deactivate-mark nil))

(defun spw/log-view-msg-prev (n)
  (interactive "p")
  (spw/log-view-msg-next (- n)))

(spw/feature-define-keys ((vc-git vc-git-log-view-mode-map))
  "\C-z:" spw/log-view-eshell-git-range
  "\C-zA" spw/log-view-git-cherry-pick
  "\C-zf" spw/log-view-git-fixup
  "\C-zF" "\C-u\C-zf"
  "\C-zr" spw/log-view-git-rebase
  "\C-zi" "\C-u\C-zr"
  "\C-zw" spw/log-view-copy-git-range
  "\C-zx" spw/log-view-git-reset
  "\C-zX" "\C-u\C-zx")

(spw/feature-define-keys log-view
  "\C-@" spw/log-view-set-mark-command
  [?\C- ] spw/log-view-set-mark-command
  "\s" scroll-other-window
  "" scroll-other-window-down
  "\t" spw/log-view-msg-this
  "\M-n" spw/log-view-msg-next
  "\M-p" spw/log-view-msg-prev)

(defun spw/vc-diff-no-select (orig-fun &rest args)
  (save-selected-window (apply orig-fun args)))
;; Not `vc-root-diff', as often we want to edit that for a partial commit.
(dolist (cmd '(vc-diff log-view-diff log-view-diff-changeset))
  (advice-add cmd :around #'spw/vc-diff-no-select))

(defun eshell/rld ()
  (interactive)
  (require 'vc)
  (save-selected-window
   (vc-diff-internal t `(Git (,(project-root (project-current))))
		     "@{1}" "@{0}" nil "*vc-reflog-diff*")))
(global-set-key "\C-cv=" #'eshell/rld)

(defun spw/log-edit-show-diff ()
  "Unless directly committing a diff, immediately show what we're committing."
  (interactive)
  (unless (and vc-parent-buffer
	       (with-current-buffer vc-parent-buffer
		 (derived-mode-p 'diff-mode)))
    (log-edit-show-diff)))

;;; If we just add `vc-print-root-log' to `project-switch-commands', it seems
;;; to work, but if you try to expand any commits it'll try to run git(1) in
;;; the old project/dir, not the new one.  `vc-root-diff' has issues too.
;;; So add these commands instead.

(defun spw/project-vc-root-diff ()
  (interactive)
  (spw/with-project-root-dired (vc-root-diff nil)))

(defun spw/project-vc-print-root-log ()
  (interactive)
  (spw/with-project-root-dired (vc-print-root-log)))

(defun spw/eshell-find-git-subcommand ()
  (or (and-let* ((gitdir
		  (ignore-errors
		    (car (process-lines "git" "rev-parse" "--git-dir")))))
	;; See git's contrib/completion/git-prompt.sh.
	;; More than one of these could be in progress, so the order matters.
	;; See also how `vc-git--cmds-in-progress' returns a list.
	(cond ((file-exists-p (expand-file-name "REVERT_HEAD" gitdir))
	       "revert")
	      ((file-exists-p (expand-file-name "CHERRY_PICK_HEAD" gitdir))
	       "cherry-pick")
	      ((file-exists-p
		(expand-file-name "rebase-apply/applying" gitdir))
	       "am")
	      ((file-exists-p (expand-file-name "BISECT_START" gitdir))
	       "bisect")
	      ((file-exists-p (expand-file-name "MERGE_HEAD" gitdir))
	       "merge")
	      ((or (file-directory-p (expand-file-name "rebase-merge" gitdir))
		   (file-exists-p
		    (expand-file-name "rebase-apply/rebasing" gitdir)))
	       "rebase")))
      (user-error "Cannot determine what git command is in progress")))

(defun spw/eshell-git-abort ()
  (interactive)
  (let* ((subcommand (spw/eshell-find-git-subcommand))
	 (option (pcase subcommand
		   ("bisect" "reset")
		   (_        "--abort"))))
    (spw/eshell-insert-and-send "git " subcommand ?\s option)))

(defun spw/eshell-git-continue ()
  (interactive)
  (spw/eshell-insert-and-send
   "git " (spw/eshell-find-git-subcommand) ?\s "--continue"))

(spw/feature-define-keys ((esh-mode eshell-mode-map))
  "\C-z\C-c" spw/eshell-git-continue "\C-z\C-v" spw/eshell-git-abort)

;; C-z C-v to discard changes.
;; Save only buffers that weren't already modified.
(defun spw/diff-discard-hunk ()
  (interactive)
  (let* (diff-advance-after-apply-hunk
	 (buffer (car (diff-find-source-location)))
	 (to-save (and (not (buffer-modified-p buffer)) buffer)))
    ;; We cannot just bind `display-buffer-no-window' into
    ;; `display-buffer-overriding-action' because `diff-apply-hunk' assumes
    ;; `display-buffer' returns non-nil.  See docstring for
    ;; `display-buffer-no-window'.
    (save-window-excursion (diff-apply-hunk t))
    (diff-hunk-kill)
    (when to-save
      (with-current-buffer to-save
	(basic-save-buffer)))))

(defun spw/diff-kill-to-bob ()
  (interactive)
  (diff-beginning-of-hunk t)
  (when (save-excursion (re-search-backward diff-hunk-header-re nil t))
   (let ((end (point-marker)))
     (goto-char (point-min))
     (unwind-protect
	 (while (not (= (point) end))
	   (diff-hunk-kill))
       (set-marker end nil)))))

(defun spw/diff-kill-to-eob ()
  (interactive)
  (diff-beginning-of-hunk t)
  (when (save-excursion (forward-line 1)
			(re-search-forward diff-hunk-header-re nil t))
   (let ((end (point)))
     (diff-hunk-next 1)
     (while (not (= (point) end))
       (diff-hunk-kill)))))

;; Might want to upstream some or all of the functionality bound here, if it
;; proves often enough useful.
(spw/feature-define-keys diff-mode
  "\C-z\M-<" spw/diff-kill-to-bob
  "\C-z\M->" spw/diff-kill-to-eob
  "\C-z\C-c" "\C-z\M-<\C-z\M->"
  "\C-z\C-v" spw/diff-discard-hunk
  "\C-z\M-s" "\C-c\C-s\M-k\M-p\C-n"
  "\C-z\C-s" "\C-c\C-s\M-p\M-p\M-k\C-n")

;; Ensure that after two C-x C-q, we retain our `diff-mode' bindings.
;; (We can't use `setq-mode-local': Emacs bug#60787.)
(defun spw/disable-view-read-only ()
  (setq-local view-read-only nil))
(spw/feature-add-hook spw/disable-view-read-only diff-mode)

(defun spw/vc-next-action-for-git-fixup ()
  (interactive)
  (call-interactively #'vc-next-action)
  (let ((display-buffer-overriding-action
	 '(display-buffer-same-window (inhibit-same-window . nil))))
    (call-interactively #'vc-print-root-log))
  (message "Move point to the commit to fixup! into and type C-z f or C-z F"))
(global-set-key "\C-cvf" 'spw/vc-next-action-for-git-fixup)


;;;; Assorted packages

(diminish 'ws-butler-mode)

;; message-mode is sensitive to trailing whitespace in sig dashes and empty
;; headers.  markdown-mode is sensitive in empty headers (e.g. "# " which I
;; use in writing essays) and newlines that indicate paragraph flow (obscure
;; Markdown feature)
;;
;; The message-mode case is handled by `spw/normalise-message', which is
;; better than setting `ws-butler-trim-predicate' to a complicated function
;; because the code in `spw/normalise-message' gets called less often.  Could
;; try setting `ws-butler-trim-predicate' to handle the markdown-mode case,
;; but chances are someday I'll want to use that obscure markdown-mode feature
(setq ws-butler-global-exempt-modes '(markdown-mode message-mode))

(autoload 'redtick "redtick")
(global-set-key "\C-cP" #'redtick)
(autoload 'redtick-mode "redtick")
(global-set-key "\C-cgP" #'redtick-mode)

(with-eval-after-load 'org-d20
  (setq org-d20-dice-sound
        "~/annex/media/sounds/147531__ziembee__diceland.wav"
	org-d20-display-rolls-buffer t
        ;; the roll20 tokens I'm using for NPCs are lettered
        org-d20-letter-monsters t
        ;; ... and they come in only two colours, so let's just have
        ;; one monster per letter
        org-d20-continue-monster-numbering t)

  (define-key org-d20-mode-map [f5]          #'org-d20-initiative-dwim)
  (define-key org-d20-mode-map [f6]          #'org-d20-damage)

  (define-key org-d20-mode-map [f7]          (lambda (arg)
					       (interactive "P")
					       (call-interactively
						(if arg
						    #'org-d20-roll-last
						  #'org-d20-roll))))
  (define-key org-d20-mode-map [f8]          #'org-d20-roll-at-point)
  (define-key org-d20-mode-map [f9]          (lambda (arg)
					       (interactive "P")
					       (call-interactively
						(if arg
						    #'org-d20-d%
						  #'org-d20-d20)))))

(spw/when-library-available nov
  (add-to-list 'auto-mode-alist '("\\.epub\\'" . nov-mode)))

(setq ggtags-mode-line-project-name nil)

(spw/when-library-available ggtags
  (dolist (hook '(cperl-mode-hook c-mode-hook))
    (add-hook hook #'ggtags-mode)))

(spw/when-library-available rainbow-mode
  (dolist (hook '(html-mode-hook css-mode-hook))
    (add-hook hook 'rainbow-mode)))

(spw/feature-add-hook subword-mode haskell-mode)

;; Use a local hook to turn on an appropriate indentation mode.  Use
;; `haskell-indentation-mode' by default, but if our .dir-locals.el specifies
;; `indent-tabs-mode', we should instead use my `haskell-tab-indent-mode'.
(spw/when-library-available haskell-tab-indent
  (spw/feature-add-hook (lambda ()
			  (add-hook 'hack-local-variables-hook
				    (lambda ()
				      (if indent-tabs-mode
					  (haskell-tab-indent-mode 1)
					(haskell-indentation-mode 1)))
				    nil t))
    haskell-mode))

(spw/when-library-available orgalist
  (spw/feature-add-hook orgalist-mode message))

(spw/feature-add-hook orgtbl-mode message)

(spw/feature-add-hook (lambda ()
			(dired-hide-details-mode
			 (if bongo-dired-library-mode 1 -1)))
  (bongo bongo-dired-library-mode-hook))

(defun spw/make-bongo-dired ()
  (dired-noselect bongo-default-directory))

(defun spw/maybe-activate-or-deactivate-bongo-dired-library-mode ()
  (require 'bongo)
  (if (eq major-mode 'wdired-mode)
      (bongo-dired-library-mode 0)
    (when (file-in-directory-p default-directory bongo-default-directory)
      (bongo-dired-library-mode 1))))

;; follow with 'h' to get to dired browse
(global-set-key "\C-cM" #'bongo-playlist)

(spw/when-library-available bongo
  ;; at first launch, ensure a buffer with `bongo-dired-library-mode' exists,
  ;; so 'h' takes us there, rather than to a library buffer
  (advice-add 'bongo-default-playlist-buffer :before #'spw/make-bongo-dired)

  ;; apparently bongo-dired-library-mode can interfere with wdired, so toggle
  (add-hook 'dired-mode-hook
	    #'spw/maybe-activate-or-deactivate-bongo-dired-library-mode)
  (advice-add 'wdired-change-to-wdired-mode
	      :after #'spw/maybe-activate-or-deactivate-bongo-dired-library-mode)
  (advice-add 'wdired-change-to-dired-mode
	      :after #'spw/maybe-activate-or-deactivate-bongo-dired-library-mode))

;; 'v' again to exit
(global-set-key "\C-cgv" #'volume)

(with-eval-after-load 'elpher
  ;; standard Emacs conventions
  (define-key elpher-mode-map "l" #'elpher-back)
  (define-key elpher-mode-map "d" #'elpher-back-to-start)
  (define-key elpher-mode-map "<" #'elpher-root-dir)

  (add-hook 'elpher-mode-hook (lambda () (variable-pitch-mode 1))))


;;;; Lisp

(find-function-setup-keys)

(define-key emacs-lisp-mode-map "\C-z\C-e" #'eval-buffer)

;; This defeats `slime-repl-mode-map' grabbing backspace from Paredit.
;; Unconditionally unbinding should be safe as always use Paredit for Lisp.
(define-key lisp-mode-shared-map "\177" nil)

;; Catch custom defining forms, and include them at the top level of the menu.
;; We completely replace the default value, rather than appending to the list,
;; because a basic expression to find custom defining forms will also find
;; everything that the default value finds, and indeed merge them into the top
;; level of the menu, anyway.
(when (get 'lisp-mode-symbol 'rx-definition) ; for Emacs 28
  (setq lisp-imenu-generic-expression
	(rx-let ((spc (in blank ?\n))
		 (sym (| word (syntax symbol))))
	  `((nil ,(rx bol (0+ blank) ?\( (opt "spw/") (opt "cl-") "def"
		      (| (1+ word)
			 (: "ine-"
			    ;; Require symbol constituents next, but we don't
			    ;; want to index calls to `define-key' ...
			    ;; There is also `define-abbrev'.
			    (| (: (in "a-jl-z0-9-") (0+ sym))
			       (: ?k (opt (in "a-df-z0-9-") (0+ sym)))
			       (: "ke" (opt (in "a-xz0-9-") (0+ sym)))
			       (: "key" (1+ sym)))))
		      (1+ spc) (opt ?') (group lisp-mode-symbol)
		      ;; Exclude declarations like (defvar FOO) in Elisp.
		      (1+ spc) (not ?\)))
		 1)))))

(defun spw/consfig-indentation-hints ()
  (put 'spwcrontab 'common-lisp-indent-function '1)
  (put 'kvm-boots-trusted-chroot. 'common-lisp-indent-function '1)
  (put 'athenet-container-for. 'common-lisp-indent-function '3))

(spw/when-library-available consfigurator
  (advice-add 'activate-consfigurator-indentation-hints
	      :after #'spw/consfig-indentation-hints))

;; Without xscheme, the *scheme* buffer is not Paredit-compatible.
(with-eval-after-load 'scheme (require 'xscheme))

(spw/reclaim-keys-from xscheme scheme-mode-map "\eo" "\ez")
(spw/feature-define-keys ((xscheme scheme-mode-map))
  "\C-j" xscheme-send-previous-expression "\C-z\C-e" #'xscheme-send-buffer)

(let ((tb (expand-file-name "~/annex/media/HyperSpec-7-0.tar.gz"))
      (hd (expand-file-name "~/local/clhs/HyperSpec/")))
  (when (and (file-exists-p tb) (not (file-directory-p hd)))
    (make-directory (expand-file-name "~/local/clhs/" t))
    (let ((default-directory "~/local/clhs/"))
      (call-process-shell-command (concat "tar xfz " tb))))
  (when (file-directory-p hd)
    (setq common-lisp-hyperspec-root (concat "file://" hd))
    (when (boundp 'browse-url-handlers)	; Emacs 27
      (add-to-list 'browse-url-handlers '("/local/clhs/HyperSpec/" . eww)))))

(global-set-key "\C-cgh" #'hyperspec-lookup)

;; `inf-lisp' says this is a defcustom and `slime' says it is a defvar, so
;; `custom-save-variables' will print the NOW field in the corresponding
;; argument to `custom-set-variables' as t or nil depending on whether or not
;; `inf-lisp' and/or `slime' happen to be loaded, and possibly even depending
;; on the order in which they were loaded.  To prevent spurious changes to the
;; NOW field randomly showing up in git diffs of init.el, set the variable
;; without using the customisation interface.
(setq inferior-lisp-program "sbcl")

(defun spw/record-last-command-was-slime-async-eval (&rest ignore)
  (spw/add-once-hook 'pre-command-hook
		     (lambda ()
		       (setq spw/last-command-was-slime-async-eval nil)))
  (setq spw/last-command-was-slime-async-eval t
	spw/last-slime-async-eval-command-frame (selected-frame)))

;; Here we assume that (spw/use-tabs-not-frames) yields nil.
(defun spw/sldb-setup-avoid-focus-grab (orig-fun &rest args)
  "Don't allow the Slime debugger to grab keyboard focus unless we are sure
that the user is expecting that it might pop up."
  (if spw/last-command-was-slime-async-eval
      (apply orig-fun args)
    (save-selected-window
      (if (frame-live-p spw/last-slime-async-eval-command-frame)
	  (with-selected-frame spw/last-slime-async-eval-command-frame
	    (apply orig-fun args))
	(apply orig-fun args))))
  (setq spw/last-slime-async-eval-command-frame nil))

(defun spw/slime-repl-header-line (&optional pwd)
  (with-current-buffer (slime-connection-output-buffer)
    (let* ((pwd (abbreviate-file-name
		 (string-remove-suffix
		  "/" (or pwd (slime-eval '(swank:default-directory))))))
	   (conn (slime-connection))
	   (host (car (process-contact conn))))
      (setq header-line-format
	    (format "%s@%s:%s  Port: %s  Pid: %s"
		    (slime-lisp-implementation-type)
		    (if (string= "localhost" host) system-name host)
		    (propertize pwd 'face 'bold)
		    (slime-connection-port conn) (slime-pid))))))
(advice-add 'slime-repl-insert-banner :before #'spw/slime-repl-header-line)
(advice-add 'slime-set-default-directory :after #'spw/slime-repl-header-line)
(with-eval-after-load 'slime-repl
  (add-hook 'slime-change-directory-hooks #'spw/slime-repl-header-line))

(with-eval-after-load 'slime
  (setq slime-contribs (remq 'slime-banner slime-contribs))

  (defvar spw/last-command-was-slime-async-eval nil)
  (defvar spw/last-slime-async-eval-command-frame nil)

  (dolist (f '(slime-repl-return slime-mrepl-return
	       slime-compile-region slime-compile-file sldb-eval-in-frame
	       sldb-invoke-restart-0 sldb-invoke-restart-1
	       sldb-invoke-restart-2 sldb-invoke-restart-3
	       sldb-invoke-restart-4 sldb-invoke-restart-5
	       sldb-invoke-restart-6 sldb-invoke-restart-7
	       sldb-invoke-restart-8 sldb-invoke-restart-9
	       slime-interactive-eval slime-interrupt spw/go-to-consfig))
    (advice-add f :after #'spw/record-last-command-was-slime-async-eval))

  (advice-add 'sldb-setup :around #'spw/sldb-setup-avoid-focus-grab))

(defun spw/slime-clear-source-registry ()
  (interactive)
  (slime-repl-shortcut-eval-async '(asdf:clear-source-registry) #'message))

(with-eval-after-load 'slime-repl
  (defslime-repl-shortcut nil ("clear-source-registry")
    (:handler #'spw/slime-clear-source-registry)))

(defun spw/comment-form (n)
  "Replacement for \\[comment-line] in Lisp modes which is more
likely to keep parentheses balanced."
  (interactive "p")
  (if (use-region-p)
      (comment-line n)
    (let ((begin (point))
          (end (line-end-position)))
      (skip-chars-forward "; \t" end)
      (forward-sexp)
      (unless (> (point) (line-end-position))
        (comment-or-uncomment-region begin (point))))))
(define-key lisp-mode-shared-map [?\C-x ?\C-\;] #'spw/comment-form)
(when (boundp 'lisp-data-mode-map)	; Emacs 27
  (define-key lisp-data-mode-map [?\C-x ?\C-\;] #'spw/comment-form))

;; Loading `slime' puts `slime-macrostep' on `load-path'.
;; `slime-macrostep' knows how to load an embedded copy of `macrostep'.
(with-eval-after-load 'slime (require 'slime-macrostep))
(when-let ((lib (cl-find-if #'locate-library '("macrostep" "slime"))))
  (autoload 'macrostep-expand lib nil t))
(define-key lisp-mode-shared-map "\C-ze" #'macrostep-expand)

;; Ignore Genera/Zmacs file attributes that a number of CL systems include.
(dolist (var '(base package syntax Base Package Syntax BASE PACKAGE SYNTAX))
  (cl-pushnew var ignored-local-variables))

;;; Paredit

(spw/feature-add-hook enable-paredit-mode
  (nil lisp-data-mode-hook) (nil emacs-lisp-mode-hook)
  (nil eval-expression-minibuffer-setup-hook)
  scheme (xscheme xscheme-start-hook) slime-repl)

(diminish 'paredit-mode)

(defun spw/paredit-unix-word-rubout (arg)
  (interactive "p")
  (cond ((save-excursion
	   (skip-chars-backward "[:space:]\n") (paredit-in-comment-p))
	 (spw/unix-word-rubout arg))
	((paredit-in-string-p)
	 (let ((start (1+ (car (paredit-string-start+end-points)))))
	   (if (> (point) start)
	       (save-restriction
		 (narrow-to-region start (point)) (spw/unix-word-rubout arg))
	     (paredit-backward-delete-in-string))))
	(t (backward-kill-sexp (abs arg)))))
(define-key paredit-mode-map "\C-w" #'spw/paredit-unix-word-rubout)

(spw/macroexp-for (key command)
    (;; This fixes RET in 'M-:'.
     ([?\r] paredit-RET)
     ;; This fixes C-j in `lisp-interaction-mode', `edebug-eval-mode' etc.
     ([?\C-j] paredit-C-j))
  (let ((new-command (intern (format "spw/%s" command))))
    `(progn (defun ,new-command ()
	      ,(format
		"Defer to major mode's binding for %s if present, else `%s'."
		(key-description key) command)
	      (interactive)
	      (call-interactively
	       (if-let* ((map (current-local-map))
			 (binding (lookup-key map ,key)))
		   binding
		 #',command)))
	    (define-key paredit-mode-map ,key #',new-command))))

;; Fix M-a, M-e, M-k and C-x DEL in Lisp string literals.
(defun spw/paredit-narrow-to-string (orig-fun &rest args)
  (save-restriction
    (when (and paredit-mode (paredit-in-string-p))
      (cl-destructuring-bind (beg . end) (paredit-string-start+end-points)
	(narrow-to-region (1+ beg) end)))
    (apply orig-fun args)))
(dolist (cmd '(backward-sentence forward-sentence
	       backward-kill-sentence kill-sentence))
  (advice-add cmd :around #'spw/paredit-narrow-to-string))

(spw/reclaim-keys-from paredit paredit-mode-map "\M-r" "\M-s" "\M-?")
(define-key paredit-mode-map "\M-R" #'paredit-raise-sexp)
(define-key paredit-mode-map "\M-U" #'paredit-splice-sexp)
(define-key paredit-mode-map "\M-C" #'paredit-convolute-sexp)

(defun spw/paredit-try-expand-list (old)
  "Fix `try-expand-list' with `paredit-mode'."
  (or old (not paredit-mode)
      (always (delete-region (point) (progn (paredit-forward-up) (point))))))
(advice-add 'try-expand-list :after-while #'spw/paredit-try-expand-list)

;; Drop `try-expand-line', and move completion of Lisp symbols earlier than
;; `try-expand-list'.
(define-key paredit-mode-map [remap dabbrev-expand]
	    (make-hippie-expand-function
	     '(try-complete-file-name-partially try-complete-file-name
	       try-expand-all-abbrevs
	       try-complete-lisp-symbol-partially try-complete-lisp-symbol
	       try-expand-list
	       try-expand-dabbrev try-expand-dabbrev-all-buffers
	       try-expand-dabbrev-from-kill)))

(defun spw/paredit-no-space-after (endp delimiter)
  (rx-let ((comma-at (: ?, (0+ (any ?, ?@))))
	   (sharpsign (: (opt comma-at) ?#)))
    (or endp (save-excursion
	       (skip-syntax-backward "^-" (pos-bol))
	       (skip-syntax-forward "(")
	       (not (looking-at
		     (cl-case delimiter
		       (?\" (rx sharpsign (| ?? ?p ?P ?~ "!~")))
		       (?\( (rx (| comma-at (: sharpsign (| ?? ?~ "!~")))))
		       (t (rx sharpsign (| ?? ?~ "!~"))))))))))
(add-to-list
 'paredit-space-for-delimiter-predicates #'spw/paredit-no-space-after)

(defun spw/paredit-insert-comment-before-defun ()
  "Don't use three semicolons immediately before a top-level form."
  (when (and (not (looking-at "\n\n")) (looking-back "^;;; "))
    (delete-char -2) (insert " ")))
(advice-add 'paredit-insert-comment
	    :after #'spw/paredit-insert-comment-before-defun)

(defun spw/scratch-paredit-in-lisp-p ()
  "Does point's paragraph look to be within a defun?"
  (or
   ;; Is point at an empty paragraph, ready to start typing it?  Assume Lisp.
   (save-excursion
     (goto-char (pos-bol 0))
     (looking-at (rx (| (: buffer-start (= 2 (* blank) ?\n))
			(: (= 2 (* blank) ?\n) (* blank) (| ?\n buffer-end))
			(: (* blank) ?\n (* blank) buffer-end)))))
   ;; This code attempts to classify non-empty paragraphs.
   (save-excursion
     ;; Unless we're already right before a paragraph, skip backwards into the
     ;; previous paragraph.
     (unless (looking-at "[[:space:]]*\n[[:space:]]*[^[:space:]\n]+")
       (skip-chars-backward "[:space:]\n"))
     (catch 'done
       (while t
	 ;; Go back to the start of the paragraph.
       	 (re-search-backward "\\`\\|^\\s-*$" nil t)
	 ;; Examine the syntax of the first character of the paragraph.
	 ;; If it's whitespace, we need to go back and check the previous
	 ;; paragraph, to handle multiple paragraphs within a defun.
	 (let ((syn
		(char-syntax
		 (char-after
		  ;; (1+ point) unless at end of buffer or on first line of a
		  ;; paragraph beginning right at the beginning of the buffer.
		  (and (not (eobp))
		       (not (and (bobp)
				 (looking-at "[[:space:]]*[^[:space:]\n]")))
		       (1+ (point)))))))
	   (cond ((bobp)             (throw 'done (eq syn ?\()))
		 ((eq syn ?\()       (throw 'done t))
		 ((not (eq syn ?\s)) (throw 'done nil))))
	 (skip-chars-backward "[:space:]\n"))))))

(define-derived-mode spw/scratch-lisp-interaction-mode lisp-interaction-mode
  "Lisp Interaction"
  (let (;; Bind `minor-mode-map-alist' such that our call to `key-binding'
	;; ignores the bindings of minor modes that have priority over
	;; Paredit.  This avoids an infinite loop if one of those minor modes
	;; wants to defer to our binding, e.g. in the way `orgtbl-mode' does.
	(minor-mode-map-alist
	 (or (cdr (cl-member 'paredit-mode minor-mode-map-alist :key #'car))
	     minor-mode-map-alist))
	(map (make-sparse-keymap)))
    (set-keymap-parent map paredit-mode-map)
    (named-let define-keys ((from paredit-mode-map) (into map) (prefix []))
      (map-keymap
       (lambda (event paredit-binding)
	 ;; `paredit-mode-map' has no parents; otherwise, we should
	 ;; conditionalise on (eq (lookup-key keymap key) paredit-binding).
	 (let* ((key (vector event))
		(prefixed (vconcat prefix key)))
	   (cond ((keymapp paredit-binding)
		  (let ((map (make-sparse-keymap)))
		    (define-key into key map)
		    (define-keys paredit-binding map prefixed)))
		 ((commandp paredit-binding)
		  (when-let* ((normal-binding (key-binding prefixed))
			      (new-binding
			       (intern (format "spw/scratch-%s"
					       (if (symbolp paredit-binding)
						   paredit-binding
						 (gensym))))))
		    (defalias new-binding
		      (lambda ()
			(interactive)
			(call-interactively
			 (if (spw/scratch-paredit-in-lisp-p)
			     paredit-binding
			   normal-binding)))
		      (format "Like `%s', but for `spw/scratch-lisp-interaction-mode'."
			      paredit-binding))
		    (define-key into key new-binding))))))
       from))
    (push `(paredit-mode . ,map) minor-mode-overriding-map-alist))
  (setq-local fill-paragraph-function
	      (lambda (&optional justify)
		(and (spw/scratch-paredit-in-lisp-p)
		     (lisp-fill-paragraph justify)))
	      normal-auto-fill-function
	      (lambda ()
		(and (not (spw/scratch-paredit-in-lisp-p))
		     (let (comment-start) (do-auto-fill)))))
  ;; (orgtbl-mode 1) ; appears to break `eldoc-mode' and/or `show-paren-mode'
  (spw/when-library-available orgalist (orgalist-mode 1)))
(define-key spw/scratch-lisp-interaction-mode-map "\M-q" #'fill-paragraph)
;; Override earlier `setq-mode-local' for `prog-mode'.
(setq-mode-local spw/scratch-lisp-interaction-mode
		 comment-auto-fill-only-comments nil)


;;;; Text mode

(add-hook 'text-mode-hook #'turn-on-auto-fill)
(diminish 'auto-fill-function)

;; for writing notes on ftp-master.debian.org
(add-to-list 'auto-mode-alist '("dak[A-Za-z0-9_]+\\'" . text-mode))
;; make sure we can copy/paste from local Emacs into terminal
(defun spw/maybe-disable-electric-indent-local ()
  (when (string-match "\\(?:tmp[A-Za-z0-9_]+\\.txt\\|dak[A-Za-z0-9_]+\\)\\'"
                      (buffer-name))
    (electric-indent-local-mode 0)))
(add-to-list 'text-mode-hook #'spw/maybe-disable-electric-indent-local)

(spw/define-skeleton spw/markdown-meta (markdown-mode :abbrev "meta")
  "" "Variable: " "[[!meta " str "=\"" _ "\"]")

(spw/define-skeleton spw/ftp-other (text-mode :key "\C-z\C-o" :file nil)
  "" "" "+----------------------+" \n "|    Other comments    |" \n
  "+----------------------+" \n \n -)

(spw/define-skeleton spw/ftp-reject (text-mode :key "\C-z\C-r" :file nil)
  "" ""
  "+----------------------+" \n "|   REJECT reasoning   |" \n
  "+----------------------+" \n \n _ \n \n
  "+----------------------+" \n "|         N.B.         |" \n
  "+----------------------+" \n \n
  "This review may not be exhaustive.  Please check your source package
against your d/copyright and the ftpmaster REJECT-FAQ, throughly,
before uploading to NEW again." \n \n
"Thank you for your time and contribution!" \n \n "Sean")

(spw/define-skeleton spw/ftp-prod (text-mode :key "\C-z\C-p" :file nil)
  "" "" "Hello,\n\n" _ "\n\n-- \nSean Whitton")


;;;; Org-mode

(global-set-key "\C-coc" #'org-capture)
(global-set-key "\C-col" #'org-store-link)
(global-set-key "\C-coa" #'org-agenda)
(global-set-key "\C-co[" #'org-agenda-file-to-front)
(global-set-key "\C-co]" #'org-remove-file)

(setq
 ;; we just use a completely custom agenda view
 ;; org-agenda-todo-ignore-with-date nil
 ;; org-agenda-todo-list-sublevels nil
 ;; org-agenda-skip-additional-timestamps-same-entry nil

 ;; inline tasks
 ;; prefix arg can be used to override this setting
 org-inlinetask-default-state "TODO"

 ;; we don't actually use Org's built-in stuck project support,
 ;; instead generating our own review agenda from scratch which
 ;; includes the right tasks.  See the view assigned to the '#' key
 org-stuck-projects '("TODO" '("NEXT") nil "")

 ;; org-yank-adjusted-subtrees t
 ;; org-yank-folded-subtrees nil

 org-tag-alist
 '((:startgroup)
   ("@Tucson"       . ?t)
   ("@Sheffield"    . ?s)
   ("@LaAldea"      . ?h)
   ("@Office"       . ?o)
   (:endgroup)
   ("@iPad"         . ?i)
   ;; following are needed when at times when I'm regularly accessing
   ;; my Org-mode agenda over SSH
   ;; (:startgroup)
   ;; ("@Emacs"        . ?e) ; SSH Emacs only
   ;; ("@workstation"  . ?m) ; on my fully set-up personal (m)achine
   ;; (:endgroup)
   ("UA"            . ?w) ; academic work
   ("Debian"        . ?d)
   ("FLOSS"         . ?f)

   ;; these two probably don't need to be in the list; can remove to
   ;; reclaim the shortcut keys
   ("NOARCHIVE"     . ?N)
   ("NOAGENDA"      . ?A))

 org-capture-templates-contexts
 '(("t" "m" ((in-mode		. "gnus-summary-mode")))
   ("t"     ((not-in-mode	. "gnus-summary-mode")))
   ("T"     ((in-mode		. "gnus-summary-mode")))
   ("m"     ((in-mode		. "gnus-summary-mode"))))
 org-capture-templates
 '(("t" "Task to be refiled" entry (file org-default-notes-file)
    "* TODO %^{Title}\n%?")
   ("T" "Task to be refiled" entry (file org-default-notes-file)
    "* TODO %^{Title}\n%?")
   ("n" "Information to be refiled" entry (file org-default-notes-file)
    "* %^{Title}\n%?")
   ("m" "Task from mail to be refiled" entry (file org-default-notes-file)
    ;; Lisp is to filter square brackets out of the subject as these mean that
    ;; the Org-mode link does not properly form.  In Org 9.3, the escaping
    ;; syntax for links has changed, so might be able to do something smarter
    ;; than this
    "* TODO [[gnus:%:group#%:message-id][%^{Title|\"%(replace-regexp-in-string \"\\\\\\[\\\\\\|\\\\\\]\" \"\" \"%:subject\")\" from %:fromname}]]\n%?")

   ;; ("a" "Appointment" entry (file+datetree "~/doc/howm/diary.org")
   ;;     "* %^{Time} %^{Title & location}
   ;; %^t" :immediate-finish t)
   ;;    ("A" "Appointment (untimed)" entry (file+datetree "~/doc/howm/diary.org")
   ;;     "* %^{Title & location}
   ;; %^t" :immediate-finish t)

   ("s" "Task for the future to be refiled" entry (file org-default-notes-file)
    "* SOMEDAY %^{Title}\n%?")
   ("d" "Diary entry" entry (file+datetree "~/.labbook.gpg")
    "* %^{Title}\n%U\n\n%?")
   ("u" "URI on clipboard" entry (file org-default-notes-file)
    "* SOMEDAY [[%^{URI|%x}][%^{Title}]]" :immediate-finish t)))

;; `org-forward-paragraph', `org-backward-paragraph' and `org-mark-element' do
;; not leave point where someone who uses `forward-paragraph',
;; `backward-paragraph', `mark-paragraph' very regularly would expect, so
;; allow M-h, M-{ and M-} to have their global bindings.
(spw/reclaim-keys-from org org-mode-map "\M-{" "\M-}" "\M-h"
		       [remap backward-paragraph] [remap forward-paragraph]
		       [remap mark-paragraph])

;; With recent Org we need to unset these variables, too, to have the keys
;; behave as normal.
(defun spw/restore-standard-paragraphs ()
  (kill-local-variable 'paragraph-start)
  (kill-local-variable 'paragraph-separate))

(with-eval-after-load 'org
  (require 'org-agenda)
  (require 'org-inlinetask)
  (require 'org-checklist nil t)

  ;; With the new exporter in Org version 8, must explicitly require the
  ;; exporters I want to use.
  (require 'ox-odt) (require 'ox-ascii) (require 'ox-beamer)

  (add-hook 'org-agenda-mode-hook #'hl-line-mode)
  (add-hook 'org-mode-hook #'spw/restore-standard-paragraphs)

  ;; for cyling remote visibility
  (define-key org-agenda-mode-map " " #'org-agenda-cycle-show)

  ;; This works well whether or not `org-adapt-indentation' is t for a buffer.
  (define-key org-mode-map "
" (lambda () (interactive) (org-return t)))

  ;; `org-forward-element', `org-backward-element' are already on C-M-a and
  ;; C-M-e, so for consistency, put `org-mark-element' on C-M-h
  (define-key org-mode-map (kbd "C-M-h") #'org-mark-element)

  (font-lock-add-keywords
   'org-mode `(;; Variable pitch default font without causing misalignment.
	       ;; Regexp derived from Göktuğ Kayaalp's org-variable-pitch.el.
	       (,(rx bol (or (: (0+ blank)
				(or (: (or (+ digit) letter) (in ".)"))
				    (: (or (in "-+") (1+ blank "*"))
				       (opt blank "[" (in "-X ") "]")))
				blank)
			     (1+ blank)
			     (: (1+ "*") blank)))
		0 '(face (:inherit fixed-pitch)) prepend)

	       ;; Howm goto and come-from links.
	       ;; There is `howm-mode-keyword-face' to customise but it
	       ;; doesn't extend to the text of the link.
	       (,(rx (: (or ">>>" "<<<") blank (0+ not-newline)))
		0 `(face (:inherit fixed-pitch
			  :height ,(face-attribute 'default :height)))
		prepend))
   t)
  (add-hook 'org-mode-hook
	    (lambda () (face-remap-add-relative 'default 'variable-pitch)))

  (define-key org-agenda-mode-map "\C-cgf" #'spw/org-agenda-priority-filter))

(defun spw/org-agenda-priority-filter (arg)
  "Hide low-priority items.  If ARG, hide slightly fewer."
  (interactive "P")
  (push (regexp-opt (if arg '("[#A]" "Appt") '("[#A]" "[#B]" "Appt")))
	org-agenda-regexp-filter)
  (org-agenda-filter-apply org-agenda-regexp-filter 'regexp))

;; used by %.docx target in ~/doc/newpapers/philos.mk before commit f3bbd7ec3
(defun spw/process-org-essay-for-pandoc-export ()
  (goto-char (point-max))
  (insert "\n\n")
  (unless (string-match "submission" (buffer-file-name))
    (insert "\n-----\n")
    (insert "/This =.docx/.pdf= generated from plain text master/\n\n")
    (insert (concat "/at " (format-time-string "%-I:%M%#p %Z, %-d %B %Y")
		    ;; " by user =" (user-login-name) "="
		    ;; " on host =" (system-name) "="
		    "/\n")))
  (insert "* References"))

(defun spw/save-my-doc-buffers ()
  "Save all buffers visiting files under ~/doc/.
Called by doccheckin script."
  (let ((root (expand-file-name "~/doc/")))
    (dolist (buffer (buffer-list))
      ;; Avoid recreating most files deleted by `spw/delete-visited-file'.
      (when (and (buffer-modified-p buffer)
		 (or (string-prefix-p root (buffer-file-name buffer))
		     (with-current-buffer buffer
		       (bound-and-true-p remember-notes-mode))))
	(with-current-buffer buffer (basic-save-buffer))))))

;;; Org-mode export
;;;
;;; Org-mode's export engine is great for producing versions of arbitrary Org
;;; files which are more easily shareable with people who don't use Emacs.
;;; For this purpose, exporting to PDF via .odt and LibreOffice's headless
;;; mode is less complex than going via LaTeX, and additionally produces a
;;; .docx which looks the same as the .pdf, which is often wanted for sending
;;; to others.  Keep export engine config simple so that exporting works
;;; robustly.
;;;
;;; For longer term projects where (i) the goal is to produce an output file
;;; distinct from what we edit, rather than simply wanting to export something
;;; for the benefit of non-Emacs users, and/or (ii) for whatever reason we
;;; want to produce PS/PDF with LaTeX, possibly via Pandoc, it is preferable
;;; to have build scripts and/or Makefiles alongside the source files such
;;; that the output files can be rebuilt noninteractively and the external
;;; dependencies are clearly defined -- so, we don't want our document build
;;; to rely on Org-mode export config in this init file, but it would be okay
;;; to rely on Org-mode export config in a separate .el file loaded into Emacs
;;; batch mode.
;;;
;;; (Experience suggests that just authoring in plain LaTeX is probably most
;;; robust, except where we want to produce .docx files, in which case
;;; probably Pandoc with Org-mode source (as is done in ~/doc/newpapers))

;; setting this means if we type C-c C-e o O then the PDF opens for inspection
(setq org-odt-preferred-output-format "pdf")
(with-eval-after-load 'org
  (add-to-list 'org-file-apps '(system . "xdg-open %s")))

;; ... but also ensure we get a .docx (would be better to make
;; `org-odt-preferred-output-format' accept a list)
(defun spw/org-odt-export-docx (&rest ignore)
  (let ((org-input (concat (file-name-sans-extension (buffer-file-name))
			   ".odt")))
    (org-odt-convert org-input "docx")))
(advice-add 'org-odt-export-to-odt :after #'spw/org-odt-export-docx)


;;;; Org-mode agenda

(setq
 org-agenda-custom-commands
 '(;; Minimal agenda on 'a' and a fuller agenda on 'A'.  The idea is to open
   ;; the 'A' agenda, schedule tasks to be done today, and then reference 'a'
   ;; throughout the day.  This is mainly for times when the full agenda has
   ;; too much information that picking out what to do next takes too long.
   ;; At other times, can comment out the minimal view and move the full view
   ;; to 'a', as I had it from approx. 2015--2022.
   ("a" "Primary agenda view"
    ((agenda "day" ((org-agenda-span 'day)
                    (org-agenda-overriding-header
                     "Tasks, appointments and waiting tasks to be chased today")
                    ;; (org-agenda-time-grid nil)
                    (org-agenda-include-diary t)
		    (org-agenda-include-deadlines nil))))
    ((org-agenda-start-with-log-mode t)
     ;; (org-agenda-tag-filter-preset '("-Sariul"))
     ;; (org-agenda-start-with-entry-text-mode t)
     (org-agenda-start-with-follow-mode nil)))
   ("A" "Daily planning view"
    ((agenda "day" ((org-agenda-span 'day)
                    (org-agenda-time-grid nil)
		    (org-agenda-include-diary t)
                    (org-agenda-overriding-header
                     "Plan for today & upcoming deadlines")
		    (org-agenda-skip-function #'spw/skip-routine)))
     (agenda "" ((org-agenda-span 3)
                 (org-agenda-start-day "+1d")
                 (org-agenda-time-grid nil)
                 (org-agenda-repeating-timestamp-show-all t)
                 (org-agenda-include-deadlines nil) ; avoid duplication
                 (org-agenda-entry-types '(:timestamp :sexp :deadline))
                 (org-agenda-show-all-dates nil)
                 (org-agenda-include-diary t)
                 (org-agenda-overriding-header "Coming up")))
     (todo "TODO|NEXT" ((org-agenda-todo-ignore-scheduled t)
			;; Used to have this bound to `far' because I often
			;; set deadlines on tasks far in the future that I
			;; can't complete until much closer to the deadline.
			;; An example is archiving files at the end of an
			;; academic year.
			;;
			;; Currently have it bound to `all' to avoid too much
			;; duplication in this agenda view when a large number
			;; of items have deadlines.  Possibly we could modify
			;; the skip function such that deadlined tasks with
			;; only certain categories are excluded, where those
			;; categories tend to contain many deadlines.
                        (org-agenda-todo-ignore-deadlines 'all)
                        (org-agenda-overriding-header
                         "Unscheduled standalone tasks & project next actions")
                        (org-agenda-skip-function #'spw/skip-non-actionable)))))
   ("#" "Weekly review view"
    ((todo "WAITING" ((org-agenda-todo-ignore-scheduled t)
                      (org-agenda-todo-ignore-deadlines nil)
                      (org-agenda-todo-ignore-with-date nil)
                      (org-agenda-overriding-header
                       "Waiting on others & not scheduled to chase up")))
     (todo "TODO|NEXT" ((org-agenda-todo-ignore-with-date t)
                        (org-agenda-overriding-header "Stuck projects")
                        (org-agenda-skip-function #'spw/skip-non-stuck-projects)))
     (tags "LEVEL=1+REFILE"
           ((org-agenda-todo-ignore-with-date nil)
            (org-agenda-todo-ignore-deadlines nil)
            (org-agenda-todo-ignore-scheduled nil)
            (org-agenda-overriding-header
             "Items to add context tag and priority, and refile")))

     ;; This view shows *only top-level* TODOs (i.e. projects) that
     ;; are complete (and that, for safety, contain no incomplete
     ;; (sub)projects or tasks).  Sometimes I want to archive complete
     ;; subprojects of very large projects that are not yet complete,
     ;; but I don't want to have to make that decision when looking at
     ;; my review agenda.  I can archive these as required.
     ;;
     ;; Add the NOARCHIVE tag if want to stop something from appearing
     ;; in this list, because for whatever reason don't want to
     ;; archive it (e.g. tasks which are in top-level headings
     ;; labelled by semester in Arizona.org (e.g. "* Fall 2019"),
     ;; which I archive all at once after that semester)
     (todo "DONE|CANCELLED"
           ((org-agenda-overriding-header "Tasks to be archived")
            (org-agenda-todo-ignore-scheduled nil)
            (org-agenda-todo-ignore-deadlines nil)
            (org-agenda-todo-ignore-with-date nil)
            (org-agenda-skip-function
             #'spw/skip-incomplete-projects-and-all-subprojects-and-NOARCHIVE)))

     ;; to find files which were mistakenly not added to
     ;; `org-agenda-files'.  to exclude whole files from this list,
     ;; when they contains TODOs for state tracking but I don't need
     ;; to worry about those TODOs except when visiting the file, just
     ;; add #+FILETAGS: NOAGENDA
     (todo "TODO|NEXT|WAITING"
           ((org-agenda-overriding-header
             "Tasks from outside of org-agenda-files")
            (org-agenda-files (spw/org-non-agenda-files))
            (org-agenda-skip-function #'spw/skip-subprojects-and-NOAGENDA)))))

   ("d" "Two month diary" agenda ""
    ((org-agenda-span 60)
     ;; (org-agenda-start-on-weekday 1)
     (org-agenda-time-grid nil)
     ;; (org-agenda-repeating-timestamp-show-all t)
     (org-deadline-warning-days 0)
     (org-agenda-include-deadlines t)
     (org-agenda-skip-deadline-prewarning-if-scheduled nil)
     (org-agenda-entry-types '(:timestamp :sexp :deadline))
     (org-agenda-show-all-dates nil)
     (org-agenda-include-diary t)
     (org-agenda-remove-tags t)
     (org-agenda-overriding-header "Sean's diary for the next two months")))))

(defun spw/org-agenda-filter-by-tag (&rest _ignore)
  (when org-agenda-entry-text-mode (org-agenda-entry-text-mode)))
(advice-add 'org-agenda-filter-by-tag :before #'spw/org-agenda-filter-by-tag)

(defun spw/org-auto-exclude-function (tag)
  (let ((hour-of-day
	 ;; (info "(elisp) Time of Day") suggests you really are meant to use
	 ;; `substring' to get at the hour of the day
         (string-to-number (substring (current-time-string) 11 13))))
    (and
     (cond
       ;; tags passed to org-agenda-auto-exclude-function always
       ;; lower case per Org version 6.34 changelog

       ;; ;; only show La Aldea tasks when on hephaestus
       ;; ((string= tag "@laaldea")
       ;;  (not (string= (system-name) "hephaestus")))

       ;; always hide FLOSS, since I tend to to a tag filter to look at
       ;; those on their own
       ((string= tag "floss")
	t)

       ;; determine whether to hide work or home tasks depending on the
       ;; time of day
       ((string= tag (if (< hour-of-day 16)
                         "@laaldea" "ua"))
	t)

       ;; hide campus tasks in evening
       ((and (string= tag "@campus") (> hour-of-day 16))
	t)
       ((and (string= tag "@office") (> hour-of-day 16))
	t)

       ;; ;; hide office tasks when at home
       ;; ((string= tag "@office")
       ;;  (string= (system-name) "hephaestus"))

       ;; ((string= tag "@campus")
       ;;  (string= (system-name) "athena"))
       ;; ((string= tag "@workstation")
       ;;  (not (or (string= (system-name) "iris")
       ;;           (string= (system-name) "zephyr")
       ;;           (string= (system-name) "hephaestus"))))
       ;; ((string= tag "ua")
       ;;  (= (calendar-day-of-week (calendar-current-date)) 6))
       )
     (concat "-" tag))))
(setq org-agenda-auto-exclude-function #'spw/org-auto-exclude-function)

;;; agenda skipping functions.  Many of these are adapted from Bernt
;;; Hansen's http://doc.norang.ca/org-mode.html

(defmacro spw/has-subheading-such-that (pred)
  `(catch 'matches
     (save-excursion
       (save-restriction
	 (org-narrow-to-subtree)
	 (while (ignore-errors (outline-next-heading))
	   (when ,pred (throw 'matches t)))))))

(defmacro spw/skip-when (condition)
  "Skip trees where CONDITION is false when evaluated when point is on the headline of the tree."
  `(let ((next-headline (save-excursion (outline-next-heading))))
     (when ,condition
       (or next-headline
           ;; if there is no next headline, skip by going to the end
           ;; of the buffer.  An alternative would be (save-excursion
           ;; (forward-line 1) (point))
           (point-max)))))

(defun spw/is-task-or-project-p ()
  (and (not (org-before-first-heading-p))
       (member (org-get-todo-state) org-todo-keywords-1)))

(defun spw/is-project-p ()
  "Any task with a todo keyword subtask"
  (and (spw/is-task-or-project-p)
       (spw/has-subheading-such-that (spw/is-task-or-project-p))))

(defun spw/is-subproject-p ()
  "Any task which is a subtask of another project"
  (and (spw/is-task-or-project-p)
       (catch 'is-subproject
	 (save-excursion
	   (while (org-up-heading-safe)
	     (when (spw/is-task-or-project-p)
	       (throw 'is-subproject t)))))))

(defun spw/is-task-p ()
  "Any task with a todo keyword and no subtask"
  (and (spw/is-task-or-project-p)
       (not (spw/has-subheading-such-that (spw/is-task-or-project-p)))))

(defun spw/skip-subprojects-and-NOAGENDA ()
  "Skip trees that are subprojects, and trees with (possibly
inherited) NOAGENDA tag"
  (spw/skip-when (or (spw/is-subproject-p)
                     (member "NOAGENDA" (org-get-tags)))))

(defun spw/skip-projects-with-scheduled-or-deadlined-subprojects ()
  "Skip projects that have subtasks, where at least one of those
  is scheduled or deadlined"
  (spw/skip-when (spw/has-scheduled-or-deadlined-subproject-p)))

(defun spw/skip-subprojects-and-projects-with-scheduled-or-deadlined-subprojects ()
  "Skip subprojects projects that have subtasks, where at least
  one of those is scheduled or deadlined."
  (spw/skip-when
   (or (spw/is-subproject-p)
       (spw/has-scheduled-or-deadlined-subproject-p))))

(defun spw/skip-incomplete-projects-and-all-subprojects-and-NOARCHIVE ()
  "Skip all subprojects and projects with subprojects not yet
completed, and trees with (possibly inherited) NOARCHIVE tag"
  (spw/skip-when
   (or (spw/is-subproject-p)
       (spw/has-incomplete-subproject-or-task-p)
       (member "NOARCHIVE" (org-get-tags)))))

(defun spw/skip-non-stuck-projects ()
  (spw/skip-when
   (or (spw/is-task-p)
       (spw/has-scheduled-or-deadlined-subproject-p)
       (spw/has-next-action-p))))

(defun spw/skip-routine ()
  (spw/skip-when (string= "Routine" (org-get-category))))

(defun spw/skip-non-actionable ()
  "Skip:
- anything tagged @Sheffield when I'm in Tucson
- anything tagged @Tucson when I'm in Sheffield
- projects (i.e. has subtasks)
- subtasks of projects that are not NEXT actions
- subtasks of SOMEDAY projects
- subtasks of WAITING projects
- subtasks of scheduled projects

In the last case, the idea is that if I've scheduled the project
then I intend to tackle all the NEXT actions on that date (or at
least the next chunk of them); I've broken the project down into
NEXT actions but not for the purpose of handling them on
different occasions."
  (spw/skip-when
   (or
    ;; #1
    ;; melete is a laptop, but usually it's not in Sheffield
    (and (or (spw/on-host-p "melete.silentflame.com")
	     (spw/on-host-p "erebus.silentflame.com"))
         (member "@Sheffield" (org-get-tags)))
    ;; #2
    (and (spw/on-host-p "zephyr.silentflame.com")
         (member "@Tucson" (org-get-tags)))
    ;; #3
    (spw/is-project-p)

    ;; we used to skip deadlined standalone tasks but actually those
    ;; are actionable in general
    ;; (and (spw/is-task-p)
    ;;      (spw/org-has-deadline-p))

    ;; #4--#7
    (and (spw/is-subproject-p)
         (or
          ;; #4
          (not (string= (nth 2 (org-heading-components)) "NEXT"))
          (save-excursion
            (and
             (org-up-heading-safe)
             (or
              ;; # 5
              (string= (nth 2 (org-heading-components)) "SOMEDAY")
              ;; # 6
              (string= (nth 2 (org-heading-components)) "WAITING")
              ;; # 7
              (spw/org-is-scheduled-p)))))))))

;; We look only right after the headline for SCHEDULED: and DEADLINE:, whereas
;; `org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item' searches
;; until the next headline.  This should be okay because I only ever put those
;; on the line right after the headline.
(cl-macrolet ((task-with-first-line-such-that (&body forms)
		`(and (spw/is-task-or-project-p)
		      (save-excursion (beginning-of-line-text 2) ,@forms))))
  (defun spw/org-is-scheduled-p ()
    "A task that is scheduled."
    (task-with-first-line-such-that
     (when (looking-at (org-re-timestamp 'deadline))
       (goto-char (match-end 0)) (skip-syntax-forward "\\s-"))
     (looking-at (org-re-timestamp 'scheduled))))

  (defun spw/org-has-deadline-p ()
    "A task that has a deadline."
    (task-with-first-line-such-that
     (when (looking-at (org-re-timestamp 'scheduled))
       (goto-char (match-end 0)) (skip-syntax-forward "\\s-"))
     (looking-at (org-re-timestamp 'deadline))))

  (defun spw/org-is-scheduled-or-deadlined-p ()
    "A task that is scheduled or has a deadline."
    (task-with-first-line-such-that
     (looking-at (org-re-timestamp 'scheduled-or-deadline)))))

(defun spw/has-scheduled-or-deadlined-subproject-p ()
  "A task that has a scheduled or deadlined subproject"
  (spw/has-subheading-such-that (spw/org-is-scheduled-or-deadlined-p)))

(defun spw/has-next-action-p ()
  "A task that has a NEXT subproject"
  (spw/has-subheading-such-that (string= (org-get-todo-state) "NEXT")))

(defun spw/has-incomplete-subproject-or-task-p ()
  "A task that has an incomplete subproject or task."
  (spw/has-subheading-such-that
   (not (member (org-get-todo-state) '("DONE" "CANCELLED")))))

(defun spw/org-non-agenda-files ()
  "Return a list of all Org files which are not normally part of my agenda"
  (let ((agenda-files (org-agenda-files)))
    (cl-remove-if
     (lambda (file)
       (or (member file agenda-files)
	   (let ((name (file-name-nondirectory file)))
	     (or (string-prefix-p "." name)
		 ;; Exclude older files whose filenames aren't dates.
		 ;; Most of those used to be in ~/doc/org/philos and this
		 ;; function ignored that directory.  There are a few files
		 ;; this gets wrong, e.g. entzlist.org.
		 (not (cl-digit-char-p (string-to-char name)))))))
     (directory-files-recursively
      (expand-file-name org-directory) "\\.org\\'" nil))))


;;;; Diary

;; Don't bind `diary' globally as for viewing purposes we use Org agenda
;; bindings, and for editing purposes just C-x b suffices.
(global-set-key "\C-cC" #'calendar)

(when (file-readable-p "~/doc/emacs-diary")
  (require 'org-agenda)	; for `org-class'
  (unless
      (bound-and-true-p appt-timer)    ; avoid msgs when `eval-buffer' init.el
    (appt-activate 1))
  (add-to-list 'auto-mode-alist
	       `(,(format "\\`%s\\'" (expand-file-name "~/doc/emacs-diary"))
		  . diary-mode)))

(defun spw/diary-archive-entry (year)
  "Archive diary entry at point to archive for YEAR."
  (interactive (list (nth 5 (decode-time))))
  (goto-char (line-beginning-position))
  (while (looking-at "[[:blank:]]+") (forward-line -1))
  (let ((start (point)))
    (forward-line 1)
    (while (looking-at "[[:blank:]]+") (forward-line 1))
    (append-to-file start (point) (format "~/doc/archive/emacs-diary-%d" year))
    (delete-region start (point))
    (when (and (bolp) (eolp)) (delete-blank-lines))))
(with-eval-after-load 'diary-lib
  (define-key diary-mode-map "\C-z\C-a" #'spw/diary-archive-entry))

(defvar spw/archiveable-diary-entries-re
  (rx bol (? ?&)
      (or
       ;; Basic dated entries.  We're using the Y/M/D not D/M/Y because I have
       ;; to deal with dates written by both Americans and Europeans and using
       ;; the ISO order seems to result in fewer mistakes overall.
       (seq (group-n 1 (** 2 4 num))
	    (or ?/ ?-) (group-n 2 (** 1 2 num))
	    (or ?/ ?-) (group-n 3 (** 1 2 num)))
       ;; Blocks.  The (0+ nonl) is because the call might occur within a call
       ;; to another function.
       (seq "%%(" (0+ nonl) (or "diary-block" "org-class") " "
	    (1+ num) " " (1+ num) " " (1+ num)
	    " " (group-n 1 (** 2 4 num))
	    " " (group-n 2 (** 1 2 num))
	    " " (group-n 3 (** 1 2 num)) ")")))
  "Regexp matching diary entries of mine which are candidates for
automatic removal from `diary-file', if dated in the past.")

(defun spw/diary-archive-old-entries ()
  "Archive diary entries which are dated in the past.
Helps keep the length of `diary-file' manageable."
  (interactive)
  (save-excursion
    (goto-char (point-min))
    (let* ((date (cdddr (decode-time)))
	   (today (encode-time (cl-list* 0 0 0 date)))
	   (tail (cdddr date)))
      (while (re-search-forward spw/archiveable-diary-entries-re nil t)
	(let ((y (string-to-number (match-string 1)))
	      (m (string-to-number (match-string 2)))
	      (d (string-to-number (match-string 3))))
	  (when (> 100 y) (cl-incf y 2000))
	  (when (time-less-p (encode-time (cl-list* 0 0 0 d m y tail)) today)
	    (spw/diary-archive-entry y)))))))
(with-eval-after-load 'diary-lib
  (define-key diary-mode-map "\C-z\C-c" #'spw/diary-archive-old-entries))

(defun spw/export-diary-web-view ()
  "Update athena's ~/local/diary-export.html.

On athena, for the purpose of anonymous access, there is a
manually-created symlink to ~/local/diary-export.html from a
private name under ~/local/pub/hidden/.

We don't use the FILES parameter in the entry for \"d\" in
`org-agenda-custom-commands' to do this because the destination
~/local/diary-export.html is valid only for athena."
  ;; For an alternative approach see the code of `diary-mail-entries', but
  ;; would insert into a buffer visiting ~/local/diary-export.html not a mail
  ;; composition buffer.
  (let (org-agenda-sticky
	(default-directory (expand-file-name "~/doc/")))
    (call-process-shell-command "git pull-safe")
    (save-window-excursion
      (org-agenda nil "d")
      ;; Use HTML not plain text primarily so that links are more readable.
      (org-agenda-write "~/local/diary-export.html"))))

(when (spw/on-host-primary-p "athena.silentflame.com")
  ;; Update the web view every four hours.
  (defvar spw/export-diary-web-view-timer
    (run-at-time t 14400 #'spw/export-diary-web-view)))


;;;; Howm

(setq howm-prefix "\C-cc"

      ;; Use Org-mode style because our notes are in `org-mode'.
      howm-date-format "%Y-%m-%d %a"
      howm-dtime-body-format "%Y-%m-%d %a %H:%M"
      howm-dtime-format "[%Y-%m-%d %a %H:%M]"
      howm-view-title-header "#+title:"

      howm-template
      '(;; If it is to have a title, add it after writing some content.
	;; We have point start before %file as we will often want to delete
	;; the link or replace its target.
	"%date%cursor %file\n\n"

	;; Literature note, will write a title before any content.  We make
	;; the title a come-from link such that the literature note appears
	;; early in the list of results if we follow a goto link with the same
	;; title as the literature note.
	;;
	;; Have point start before %file, not ready to insert a title, for
	;; consistency with the other template.  (However, we will indeed
	;; often replace the link target with a URL, PDF filename etc..)
	"#+title: <<< %title\n%date%cursor %file\n\n")

      howm-buffer-name-limit 40
      howm-buffer-name-total-limit 40)

;; Default sorting for certain views.
(defun spw/howm-list-all (&rest ignore)
  (howm-view-sort-by-reverse-date))
(advice-add 'howm-list-recent :after #'howm-view-sort-by-mtime)
(advice-add 'howm-list-all :after #'spw/howm-list-all)

(spw/reclaim-keys-from howm-menu howm-menu-mode-map "\C-h")
(spw/reclaim-keys-from riffle riffle-summary-mode-map "\C-h")
(spw/reclaim-keys-from howm-view howm-view-contents-mode-map "\C-h")

;; Alternatively we might rename the file and buffer based on the title, for
;; notes that have one.  But not clear that achieves anything, and it
;; introduces complexity because we would probably want to transform titles.
(spw/feature-add-hook howm-mode-set-buffer-name
  howm (howm howm-after-save-hook))

;; Incrementally replace #+TITLE in old notes.
(defun spw/howm-replace-title-option ()
  (when howm-mode
    (save-excursion
      (save-restriction
	(widen)
	(goto-char (point-min))
	(let (case-fold-search)
	  (when (re-search-forward "^#\\+TITLE: " nil t)
	    (replace-match "#+title: " t)))))))
(spw/when-library-available howm
  (add-hook 'before-save-hook #'spw/howm-replace-title-option))

(defun spw/howm-directory-howm-mode ()
  (when-let ((file (buffer-file-name)))
    (when (file-in-directory-p file howm-directory)
      (howm-mode 1))))
(spw/when-library-available howm
  (with-eval-after-load 'org
    (add-hook 'org-mode-hook #'spw/howm-directory-howm-mode)))

;; Have the global bindings set up right away if we've Howm.
(when (file-directory-p "~/doc/howm/") (require 'howm nil t))


;;;; C and friends

;; following setting also part of Linux kernel style, but it's from
;; newcomment.el, not cc-mode, so must be set in addition to
;; `c-default-style' -- and it's my preference in general
(setq comment-style 'extra-line)

(with-eval-after-load 'cc-mode
  ;; Use the mode-specific paren binding.  Default M-( binding will insert
  ;; spaces before the paren which is not called for by all C styles
  (define-key c-mode-base-map "\M-(" #'c-electric-paren)

  ;; I've seen this interact badly with electric-indent-mode (which is now on
  ;; globally by default, and has been on locally in c-mode for longer I
  ;; believe) outside of comments, but I cannot currently reproduce the
  ;; problem.  Can always just use C-M-j and M-q within comments
  (define-key c-mode-base-map (kbd "RET") #'c-context-line-break)

  ;; would be nice to have a global version of this
  (define-key c-mode-base-map "\C-o" #'c-context-open-line))

;; M-; is adequate for GNU-style comments.  This is for other styles.
(spw/define-skeleton spw/cc-com (c-mode :abbrev "comm" :file 'cc-mode)
  "" nil "/*" \n
  " * " '(c-indent-line-or-region) - \n "*/" '(c-indent-line-or-region))


;;;; Perl

(defun spw/perl-add-use (module)
  (interactive "suse ")
  (let ((line (concat "use " module
                      (and (not (string-match ";$" module)) ";"))))
    (save-excursion
      (goto-char (point-min))
      (while (re-search-forward "^use " nil t))
      (forward-line 1)
      (open-line 1)
      (insert line)
      (message (concat "Inserted: " line)))))

(defun spw/perltidy-region (begin end)
  (interactive "r")
  (let ((perltidy-env (getenv "PERLTIDY")))
    (setenv "PERLTIDY"
            (or (concat (expand-file-name
                         (locate-dominating-file
                          (buffer-file-name)
                          ".perltidyrc")) ".perltidyrc")
                perltidy-env))
    (shell-command-on-region begin end "perltidy -q" nil t)
    (font-lock-ensure)
    (setenv "PERLTIDY" perltidy-env)))

;; an older version of this would use the region if it's active, but that
;; rarely produces good results -- perltidy would get the indentation wrong
(defun spw/perltidy-block-or-buffer (&optional arg)
  "Run perltidy on the current block or the whole buffer."
  (interactive "P")
  (if arg
      (spw/perltidy-region (point-min) (point-max))
    (save-excursion
      ;; move to start of current top level block, and tidy that
      ;; (it will probably be the current subroutine).  Although
      ;; `backward-up-list' docstring says that point can end up
      ;; anywhere if there's an error, and this code will always
      ;; produce an error when it tries to call `backward-up-list'
      ;; when it's already at the top level, in fact
      ;; `backward-up-list' does not seem to move point once we
      ;; are at the top level
      ;;
      ;; note that we can't use `beginning-of-defun' as not every top
      ;; level perl block is a defun to Emacs
      (cl-loop for count upfrom 1
	       for start = (point)
	       do (ignore-errors (backward-up-list))
	       until (= start (point))
	       finally (if (= count 1)
			   ;; we didn't move; do whole buffer
			   (spw/perltidy-region (point-min) (point-max))
			 ;; tidy the top level block
			 (let ((begin (line-beginning-position)))
			   (forward-sexp)
			   (forward-line)
			   (spw/perltidy-region begin (point))))))))

(spw/feature-define-keys cperl-mode
  "\C-ciu" spw/perl-add-use "\C-z\C-c" spw/perltidy-block-or-buffer)

;; TODO Take "head" as input too so that we can do =method and =func too.
(spw/define-skeleton spw/cperl-headsub (cperl-mode :abbrev "headsub")
  ""
  "Name and arguments: "
  "=head " str \n \n
  _ \n \n
  "=cut" \n \n
  "sub " (substring str 0 (cl-position ?\( str)) " {" \n
  > _ \n
  "}")

(spw/define-skeleton spw/cperl-trytiny (cperl-mode :abbrev "try")
  ""
  nil
  "#<<<" \n
  "try {" \n _ ?\n
  "} catch {" '(cperl-indent-line) \n _ \n "};" '(cperl-indent-line)
  \n "#>>>")

(spw/define-skeleton spw/cperl-shebang (cperl-mode :abbrev "shebang")
  "" (read-string "Command line options: " "-w")
  "#!/usr/bin/env perl " str "\n\n")

(spw/define-skeleton spw/cperl-program (cperl-mode :abbrev "use5")
  "" nil (and (buffer-file-name)
	      (not (file-name-extension (buffer-file-name)))
	      "#!/usr/bin/env perl\n\n")
  "use 5.032;\nuse strict;\nuse warnings;\n\n" -)

(spw/define-skeleton spw/cperl-package (cperl-mode :abbrev "package")
  ""
  (progn (setq v1 (file-name-base (buffer-file-name)))
	 (read-string (concat "...::" v1 " ")))
  "package " str "::" v1 \n \n
  "use 5.032;\nuse strict;\nuse warnings;\n\n" - "\n\n1;")

;;; init.el ends here