summaryrefslogtreecommitdiff
path: root/.emacs.d/init-spw.el
blob: 2094716d901c68ed2fceca88a36b947a84edbc0f (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
;;; init-spw.el --- Sean's Emacs configuration

;;; 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 a
;; 'spw' feature.

;;; Code:

(eval-and-compile
  ;; 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 (concat user-emacs-directory "site-lisp"))

  ;; 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 (concat user-emacs-directory "initlibs") t))

(require 'diminish)
(require 'highlight-80+)
(require 'seq)
(require 'smex)
(require 'subr-x)

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

You should call `package-initialize' before using this macro, to
add places the library might be available to `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
  (declare (indent 1))
  (let ((libs (mapcar (lambda (l) (if (symbolp l) (symbol-name l) l))
                      (if (listp libraries) libraries (list libraries)))))
    `(unless (member nil (mapcar #'locate-library ',libs))
       ,@forms)))

(setq package-archives '(("GNU ELPA" . "https://elpa.gnu.org/packages/")
                         ("MELPA Stable" . "https://stable.melpa.org/packages/")
                         ("MELPA" . "https://melpa.org/packages/"))
      package-archive-priorities '(("GNU ELPA" . 10)
                                   ("MELPA Stable" . 5)
                                   ("MELPA" . 0)))


;;;; Startup & basic preferences

(setq custom-file (concat user-emacs-directory "init-custom.el"))
(load (concat user-emacs-directory "init-custom"))

;; It would be nice to be able to use *scratch* for both plain text
;; and ad hoc elisp, but since I want always to edit lisp with paredit
;; turned on, it's not possible to combine these two things in one
;; buffer.  So use IELM for ad hoc elisp.  Might consider adding a
;; binding which creates or switches to a Lisp Interaction buffer
;; called *lisp*.
(setq initial-major-mode #'fundamental-mode
      initial-scratch-message nil)
(global-set-key "\C-cl" #'ielm)

;; Put all auto-save files under ~/.emacs.d, both local and TRAMP.
;; Put local backups under ~/.emacs.d and TRAMP backups under remote
;; ~/.emacs.d.  So 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 (string-to-number "700" 8)))
  (setq backup-directory-alist `(("." . ,backups-dir))
        auto-save-file-name-transforms `((".*" ,auto-saves-dir t))
        tramp-auto-save-directory auto-saves-dir))
(setq backup-by-copying-when-linked t
      backup-by-copying-when-mismatch t
      tramp-backup-directory-alist backup-directory-alist)

(when (member (getenv "DESKTOP_SESSION") '("i3"))
  (setq mouse-autoselect-window t
        focus-follows-mouse t)

  ;; disable `mouse-autoselect-window' during `display-buffer', to avoid
  ;; surprise focus changes -- some code that calls `display-buffer'
  ;; does not expect `mouse-autoselect-window' to be on.  E.g.
  ;; `magit-status' can leave focus in the wrong window without this
  (defun spw/disable-mouse-autoselect-window (orig-fun &rest args)
    (let ((mouse-autoselect-window nil))
      (apply orig-fun args)))
  (advice-add 'display-buffer
              :around #'spw/disable-mouse-autoselect-window))

;; this works only for self-insert chars and gets undone by changes in
;; window manager focus, but it's something (and
;; `mouse-avoidance-mode' tends to be more annoying than helpful)
(setq make-pointer-invisible t)

(fset 'yes-or-no-p #'y-or-n-p)

(setq confirm-kill-emacs #'y-or-n-p)

(setq redisplay-dont-pause t)

;; choice of font and size is driven by aim to fit eighty columns of
;; text in both halves of my laptop's monitor
(defvar spw/preferred-latin-fonts '("Inconsolata-12" "Cousine-10"))
(defvar spw/preferred-han-fonts '("Noto Serif CJK JP-10"))
(defun spw/first-available-font (fonts)
  (car (seq-drop-while
        (lambda (font) (not (find-font (font-spec :name font))))
        fonts)))
(defun spw/select-cousine ()
  (buffer-face-set
   (face-remap-add-relative 'default :family "Cousine" :height 100)))
(defun spw/do-font-setup ()
  (remove-hook 'focus-in-hook #'spw/do-font-setup) ; harmless if hook absent
  (when-let ((latin-font (spw/first-available-font spw/preferred-latin-fonts)))
    (set-face-font 'default latin-font))
  (when-let ((han-font (spw/first-available-font spw/preferred-han-fonts)))
    (dolist (charset '(kana han symbol cjk-misc bopomofo))
      (set-fontset-font t charset han-font)))

  ;; again on laptop, need to fit a bit more in these windows than can
  ;; with Inconsolata
  (when (find-font (font-spec :name "Cousine-10"))
    (dolist (pair '((org . org-mode-hook)
                    (org-agenda . org-agenda-mode-hook)))
      (eval-after-load (car pair)
        `(add-hook ',(cdr pair) #'spw/select-cousine)))))

;; `find-font' will fail until there is a graphical frame, which might
;; not be yet, so set up a hook (which will remove itself after
;; running once) to do the font setup
(if (daemonp)
    (add-hook 'focus-in-hook #'spw/do-font-setup)
  (spw/do-font-setup))

(when (fboundp 'set-scroll-bar-mode) (set-scroll-bar-mode nil))
(when (fboundp 'tool-bar-mode) (tool-bar-mode 0))
(when (fboundp 'menu-bar-mode) (menu-bar-mode 0))
(when (fboundp 'blink-cursor-mode) (blink-cursor-mode 0))
(setq x-stretch-cursor t)
(setq-default cursor-type 'box)

;; On remote hosts in the UTC timezone, assume I'm in Arizona.  This
;; is relevant for using Org-mode.  Note that hosts in the UK will be
;; in GMT/BST, not UTC
(when (and (not (eq system-type 'windows-nt))
           (string= (cadr (current-time-zone)) "UTC"))
  (set-time-zone-rule "/usr/share/zoneinfo/America/Phoenix"))

;; Save my place in buffers, but only with newer Emacs.  With older
;; Emacs, the additions to `find-file-hook', `kill-emacs-hook' and
;; `kill-buffer-hook' made by `save-place' kept disappearing, unless I
;; enabled save-place using use-package's `:defer' keyword.  Adding
;; the hooks in this init file didn't work either.  See older dotfiles
;; repo commits
(when (version< "25.1" emacs-version)
  ;; if save-place is slowing down quitting Emacs, uncomment this:
  ;; (setq save-place-forget-unreadable-files nil)
  (save-place-mode 1))

;; 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.  A possible enhancement would be to enter a transient mode in
;; which C-n and C-p can select additional whole lines.
(defun spw/expand-region-to-whole-lines-and-activate ()
  (interactive)
  (when (> (point) (mark))
    (exchange-point-and-mark))
  (beginning-of-line)
  (set-mark (save-excursion (goto-char (mark)) (beginning-of-line 2) (point)))
  (activate-mark transient-mark-mode))
(global-set-key "\M-+" #'spw/expand-region-to-whole-lines-and-activate)

;; Also 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 first M-= second 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'.
(defun spw/activate-mark (&rest ignore)
  (interactive)
  (activate-mark))
(global-set-key "\M-=" #'spw/activate-mark)
(with-eval-after-load 'notmuch-show
  (define-key notmuch-show-mode-map "\M-=" nil))

;; ... and resettle the former occupant of M-= (isearch replaces
;; `move-to-window-line-top-bottom', so we can help ourselves to M-r)
(global-set-key "\C-cw" #'count-words-region)

;; ... and reclaim the keys from some major mode maps
(with-eval-after-load 'notmuch-show
  (define-key notmuch-show-mode-map "\M-=" nil))

(setq transient-mark-mode nil)
(defun spw/remap-mark-command (command &optional map)
  "Remap a mark-* command to temporarily activate Transient Mark mode."
  (let* ((cmd (symbol-name command))
         (fun (intern (concat "spw/" cmd)))
         (doc (concat "Call `"
                      cmd
                      "' and temporarily activate Transient Mark mode.")))
    (fset fun `(lambda ()
                 ,doc
                 (interactive)
                 (call-interactively #',command)
                 (activate-mark)))
    (if map
        (define-key map (vector 'remap command) fun)
      (global-set-key (vector 'remap command) fun))))
(dolist (command '(mark-word
                   mark-sexp
                   mark-paragraph
                   mark-defun
                   mark-page
                   mark-whole-buffer))
  (spw/remap-mark-command command))
(with-eval-after-load 'org
  (spw/remap-mark-command 'org-mark-subtree org-mode-map))

(show-paren-mode 1)

;; In an effort to reduce chording with the control key, provide
;; alternative access to the C-c and C-x keymaps.  Use right alt for
;; M-r, left alt for M-i.
;;
;; Best for entering commands where the key after C-c/C-x is not
;; modified by control.  Otherwise best to just keep control held down
;; and type both modified keys.
(defun spw/access-ctl-c-bindings (arg)
  "Access bindings under C-c."
  (interactive "P")
  (setq prefix-arg arg
        unread-command-events (cons '(t . ?\C-c) unread-command-events)))
(global-set-key "\M-r" #'spw/access-ctl-c-bindings)
(defun spw/access-ctl-x-bindings (arg)
  "Access bindings under C-x."
  (interactive "P")
  (setq prefix-arg arg
        unread-command-events (cons '(t . ?\C-x) unread-command-events)))
(global-set-key "\M-i" #'spw/access-ctl-x-bindings)

;; resettle the previous occupant of M-i
(global-set-key "\M-I" #'tab-to-tab-stop)

(setq gnus-init-file (concat user-emacs-directory "init-gnus"))
;; if know the name of group might want to 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-cgn" #'gnus)
(global-set-key "\C-cgG" #'spw/browse-gmane)

;; 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
(defun spw/unix-word-rubout ()
  (interactive)
  (undo-boundary)
  (let ((beg (point)))
    (kill-region
     (+ beg
        ;; do skip over newlines because `backward-kill-word' does
        (skip-chars-backward "[:space:]\n")
        (skip-chars-backward "^[:space:]\n"))
     beg)))
(global-set-key "\C-w" 'spw/unix-word-rubout)
(global-set-key "\M-\d" 'backward-kill-word)

;; ... and resettle the previous occupant of C-w
(global-set-key "\C-x\C-k" 'kill-region)
;; ... and resettle the previous occupant of C-x C-k (best to use a
;; binding which involves holding down ctrl, because the layout of
;; `kmacro-keymap' seems to assume you enter it holding down ctrl).
;;
;; An alternative would be to have C-w be `kill-region' just when the
;; region is active, but there is no real downside to these two
;; resettlements, and it can be useful to kill an inactive region,
;; with or without Transient Mark mode
(global-set-key "\C-x\C-d" 'kmacro-keymap)

;; We cannot reliably distinguish <C-backspace> from <backspace> so I
;; want to avoid getting into a habit of typing <C-backspace> into
;; Emacs.  Many terminal emulators send ^? for <backspace> and ^H for
;; <C-backspace> these days, or the other way around, but not all of
;; them.  Since Firefox binds <C-backspace> to delete words backwards
;; (apparently following some Microsoft products), there's some risk
;; here, so unbind
(global-unset-key [C-backspace])


;;;; ido

(setq ido-use-filename-at-point 'guess
      ido-default-file-method 'selected-window
      ido-default-buffer-method 'selected-window
      ido-max-directory-size 100000
      ido-auto-merge-work-directories-length -1 ; manual merge with M-s
      ido-use-virtual-buffers t
      ido-enable-regexp nil
      ido-use-url-at-point nil
      ido-enable-tramp-completion nil ; avoid invoking TRAMP
      ido-ignore-extensions t
      ido-confirm-unique-completion nil
      ido-show-dot-for-dired nil ; can just use C-d
      ido-enable-flex-matching t)

(ido-mode 1)
(ido-everywhere 1)

(defun spw/without-ido-everywhere (orig-fun &rest args)
    (let ((everywhere ido-everywhere))
    (when everywhere (ido-everywhere 0))
    (apply orig-fun args)
    (when everywhere (ido-everywhere 1))))
(advice-add 'notmuch-show-save-attachments :around
            #'spw/without-ido-everywhere)

(spw/when-library-available flx
  (setq ido-use-faces nil ; disable ido faces to see flx highlights
        flx-ido-threshold 7500
        gc-cons-threshold (max gc-cons-threshold 20000000))
  (flx-ido-mode 1))

(defun spw/bookmark-jump (&optional display-func)
  (interactive)
  (bookmark-jump
   (ido-completing-read "Jump to bookmark: " (bookmark-all-names) nil t)
   display-func))
;; don't use a remap event because we only want to use our function
;; when invoked via the keyboard, as `bookmark-jump' has additional
;; features when invoked from a menu
(global-set-key "\C-xrb" #'spw/bookmark-jump)

(global-set-key "\C-x\C-m" #'smex)
;; ... and resettle the previous occupant of C-x C-m
(global-set-key "\M-x" mule-keymap)


;;;; Assorted packages

(spw/when-library-available paredit
  (dolist (hook '(lisp-mode-hook
                  emacs-lisp-mode-hook
                  lisp-interaction-mode-hook))
    (add-to-list hook 'enable-paredit-mode)))

(with-eval-after-load 'scheme-mode
  (dolist (hook '(scheme-mode-hook
                  inferior-scheme-mode-hook))
    (add-to-list hook 'enable-paredit-mode)))

(with-eval-after-load 'paredit
  (diminish 'paredit-mode)

  (define-key paredit-mode-map "\C-w" #'backward-kill-sexp)

  (define-key paredit-mode-map "\M-r" nil)
  (define-key paredit-mode-map "\M-R" #'paredit-raise-sexp)

  (define-key paredit-mode-map "\M-s" nil)
  (define-key paredit-mode-map "\M-U" #'paredit-splice-sexp))

(spw/when-library-available elisp-slime-nav
  (dolist (hook '(emacs-lisp-mode-hook ielm-mode-hook))
          (add-hook hook #'elisp-slime-nav-mode)))

;; find lines violating 80 cols rule
;;
;; package is no longer maintained because author suggests using
;; `whitespace-mode'; however, customising whitespace-mode to display
;; only long lines, and not all the stuff it usually displays, means
;; it can't be toggled on and off to quickly show other whitespace,
;; which can be useful
;;
;; note that highlight-80+ has the advantage over the likes of
;; fill-column-indicator of not using overlays, which easily conflict
;; with other packages
;;
;; with Emacs 27 we might be able to replace this with setting
;; `display-fill-column-indicator' in `prog-mode-hook' and
;; `message-mode-hook' (see NEWS.27)
(autoload 'highlight-80+-mode "highlight-80+")
(dolist (hook '(prog-mode-hook message-mode-hook))
          (add-hook hook #'highlight-80+-mode))
(with-eval-after-load 'highlight-80+
  (diminish 'highlight-80+-mode))

(with-eval-after-load 'magit
  (setq
   ;; by default, don't pass -f to `git remote add`
   magit-remote-arguments nil
   ;; by default, don't pass --ff to `git cherry-pick`
   magit-cherry-pick-arguments nil

   magit-completing-read-function #'magit-ido-completing-read
   magit-push-always-verify nil)

  ;; drop "Unpulled from pushremote" which doesn't make sense with how
  ;; I use push remotes
  (remove-hook 'magit-status-sections-hook
               #'magit-insert-unpulled-from-pushremote)

  ;; replace unpushed-to-upstream-or-recent with unpushed-to-upstream
  ;; (undoing recent change to show "Recent commits" after pushing
  ;; everything)
  ;; from: https://github.com/magit/magit/issues/3230
  (magit-add-section-hook 'magit-status-sections-hook
                          #'magit-insert-unpushed-to-upstream
                          #'magit-insert-unpushed-to-upstream-or-recent
                          'replace)

  ;; try to prevent unpushed commits section being collapsed
  (add-to-list 'magit-section-initial-visibility-alist '(unpushed . show)))

(spw/when-library-available ws-butler
  (require 'ws-butler)
  (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))

  (ws-butler-global-mode))

(spw/when-library-available redtick
  (global-set-key "\C-cP" #'redtick-mode)
  (setq redtick-history-file nil))

(spw/when-library-available (notmuch dash) ; dash used in notmuch-config.el
  ;; Loading notmuch will load init-notmuch.el where this function is
  ;; defined (see next `with-eval-after-load' form)
  (autoload 'spw/next-unread-group "notmuch")

  ;; Ensure notmuch does its `message-mode' configuration and that my
  ;; notmuch-config.el gets loaded before certain commands happen.  An
  ;; alternative to advising `compose-mail' and friends here would be
  ;; to remap its keys to `notmuch-mua-new-mail', but it is nice to
  ;; have things work correctly if some lisp code somewhere calls
  ;; `compose-mail' or friends
  (defun spw/load-notmuch (&rest ignore)
    (require 'notmuch))
  (dolist (cmd '(compose-mail
                 compose-mail-other-window
                 compose-mail-other-frame
                 notmuch-jump-search
                 notmuch-hello))
    (advice-add cmd :before #'spw/load-notmuch))

  (global-set-key "\C-cs" #'notmuch-search)
  (global-set-key "\C-cm" #'notmuch-jump-search)
  (global-set-key "\C-cM" #'notmuch-hello)
  (global-set-key "\C-cN" #'spw/next-unread-group))

;; init-notmuch.el used to be notmuch-config.el, but notmuch.el's
;; mechanism for loading notmuch-config.el does not respect
;; `load-prefer-newer', so work around the problem by using
;; our own init-notmuch.el and `with-eval-after-load' form for now
(with-eval-after-load 'notmuch
  (load (concat user-emacs-directory "init-notmuch")))

(with-eval-after-load 'org-d20
  (setq org-d20-dice-sound
        "~/annex/media/sounds/147531__ziembee__diceland.wav"
        ;; 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 [f9]          #'org-d20-initiative-dwim)
  (define-key org-d20-mode-map [S-f9]        #'org-d20-initiative-add)
  (define-key org-d20-mode-map [f10]         #'org-d20-damage)

  (define-key org-d20-mode-map [S-f10]       #'org-d20-roll-at-point)
  (define-key org-d20-mode-map [XF86Launch1] #'org-d20-roll-at-point)

  (define-key org-d20-mode-map [f11]         #'org-d20-roll)
  (define-key org-d20-mode-map [S-f11]       #'org-d20-roll-last))

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

(spw/when-library-available mailscripts
  (global-set-key "\C-cgt" #'notmuch-extract-thread-patches-projectile)
  (global-set-key "\C-cgw" #'notmuch-extract-message-patches-projectile)
  (global-set-key "\C-cgb" #'notmuch-slurp-debbug)
  (global-set-key "\C-cgB" #'notmuch-slurp-this-debbug)
  (setq mailscripts-extract-patches-branch-prefix "mail/"
        mailscripts-detach-head-from-existing-branch t))

(spw/when-library-available ggtags
  (setq ggtags-mode-line-project-name nil)
  (dolist (hook '(cperl-mode-hook c-mode-hook))
    (add-hook hook #'ggtags-mode)))



;;;; ---- packages ----
(require 'use-package)

(defmacro spw--add-mode-pairs (hook pairs)
  `(add-hook
    ,hook
    (lambda ()
      (setq-local electric-pair-pairs
                  (append electric-pair-pairs ,pairs))
      (setq-local electric-pair-text-pairs electric-pair-pairs))))

(use-package elec-pair
  :commands (electric-pair-local-mode electric-pair-mode)
  :init
  ;; insert closing pairs automatically only in programming modes
  (add-hook 'prog-mode-hook 'electric-pair-local-mode)
  :config
  ;; enhance electric-pair-mode with some more pairs
  ;; based on http://emacs.stackexchange.com/a/2554/8610
  (spw--add-mode-pairs 'emacs-lisp-mode-hook '((?` . ?')))
  (spw--add-mode-pairs 'markdown-mode-hook '((?` . ?`)))
  (spw--add-mode-pairs 'org-mode-hook '((?\= . ?\=))))

;; make a list of lisp editing modes
(setq lisp-major-mode-hooks '(emacs-lisp-mode-hook
                              lisp-mode-hook
                              lisp-interaction-mode-hook
                              ielm-mode-hook
                              scheme-mode-hook
                              inferior-scheme-mode-hook
                              clojure-mode-hook))

(defmacro spw--activate-in-lisp-modes (minor-mode)
  "Add hooks to activate MINOR-MODE in all the major modes with
hooks listed in `lisp-major-mode-hooks'."
  `(dolist (hook lisp-major-mode-hooks)
     (add-hook hook ,minor-mode)))

;;; Org

;; disable org-list-allow-alphabetical so that I can start lines with
;; "P. 211 - " to refer to a page and not start a bulleted list.  This
;; has to be set before loading Org, and `use-package' :preface
;; doesn't seem to be early enough
(setq org-list-allow-alphabetical nil)

;; docstring says this has to be set before org.el is loaded
(setq org-enforce-todo-checkbox-dependencies t)

(spw/when-library-available (dash f) ; used by init-org.el
  (use-package org
    :mode (("\\.org" . org-mode))
    :bind (("C-c o c" . org-capture)
           ("C-c o l" . org-store-link)
           ("C-c o a" . org-agenda)
           ("C-c o [" . spw--org-agenda-file-to-front)
           ("C-c o ]" . spw--org-remove-file))
    :commands (org-save-all-org-buffers   ; for ~/bin/save-org-buffers
               orgstruct++-mode)
    :diminish org-indent-mode
    :init
    ;; define this early so that `spw--search-notes' and `spw--new-note'
    ;; can make use of it
    (setq org-directory "~/doc/org")
    :config (load (concat user-emacs-directory "init-org"))))

;;; more useful unique buffer names

(use-package uniquify
  :init (setq uniquify-buffer-name-style 'post-forward))

;;; OpenWith

(spw/when-library-available openwith
  (use-package openwith
    :commands openwith-mode
    :demand
    :config
    (setq
     openwith-associations
     '(("\\.pdf\\'" "evince"
        (file))
       ("\\.\\(ogg\\|mp3\\|flac\\|mkv\\|webm\\|avi\\|mp4\\|wmv\\|flv\\)\\'" "vlc"
        (file))
       ("\\.\\(doc\\|docx\\|odt\\|pages\\|xls\\|xlsx\\|ppt\\|pptx\\|potx\\)\\'" "soffice"
        (file))
       ("\\.hwp\\'" "hanword"
        (file))
       ("\\.\\(jpg\\|JPG\\|jpeg\\|png\\|gif\\)" "eog"
        (file))))
    (openwith-mode 1)))

;; thanks to openwith, the warning for large files can be at a much
;; larger threshold as the chances of hitting it are low (this is
;; about 500MB)

(setq large-file-warning-threshold 500000000)

;;; git-annex in dired

(spw/when-library-available (git-annex magit-annex)
  (use-package git-annex)

 (use-package magit-annex
   :config
   (eval-after-load 'git-annex
     (define-key git-annex-dired-map "f"
       #'magit-annex-file-action-popup))))

;;; colour those parentheses

(spw/when-library-available rainbow-delimiters
 (use-package rainbow-delimiters
   :commands rainbow-delimiters-mode
   :init
   (spw--activate-in-lisp-modes 'rainbow-delimiters-mode)))

;;; and colour those colours

(spw/when-library-available rainbow-mode
 (use-package rainbow-mode
   :commands rainbow-mode
   :init (dolist (hook '(html-mode-hook css-mode-hook))
           (add-hook hook 'rainbow-mode))))

;;; fill comments

(defun spw--turn-on-comment-filling ()
  "Turn on filling comments."
  (setq-local comment-auto-fill-only-comments t)
  (auto-fill-mode 1))
(spw--activate-in-lisp-modes 'spw--turn-on-comment-filling)

;;; company-mode for smart and easy completion

(spw/when-library-available company
 (use-package company
   :diminish company-mode
   :config
   ;; disable activating company for the moment.  Keep company so
   ;; notmuch can activate it
   ;;   (defun spw--activate-company ()
   ;;     "Setup company mode.

   ;; Using this in preference to global-company-mode, with <tab> bound
   ;; to `company-complete'.  For another approach, see
   ;; https://github.com/company-mode/company-mode/issues/94#issuecomment-40884387"
   ;;     (company-mode 1)
   ;;     (define-key (current-local-map) (kbd "M-/") 'company-complete))
   ;;   (add-hook 'prog-mode-hook 'spw--activate-company)

   ;; retain my C-w binding; move company's C-w binding
   (define-key company-active-map "\C-w" nil)
   (bind-key "M-o" 'company-show-location company-active-map)

   (setq company-idle-delay nil
         company-minimum-prefix-length 0
         company-echo-delay 0)

   ;; do I want these?
   ;; (add-to-list 'company-backends 'company-capf)
   ;; (add-to-list 'company-transformers 'company-sort-by-occurrence)
   ))
;; usage notes:
;;
;; C-o during company isearch narrows to stuff matching that search;
;; mnemonic 'occur'.  C-M-s while outside of search to do the same
;; thing

;;; Markdown mode

(spw/when-library-available markdown-mode
  (use-package markdown-mode
    :mode "\\.md"
    :config
    ;; this is called by .dir-locals.el in ~/doc/{pres,papers} and
    ;; relies on the Makefiles in those dirs
    (defun spw--set-pandoc-compile-command (&rest exts)
      (unless exts (setq exts (list "pdf")))
      (setq-local compile-command
                  (concat "make "
                          (mapconcat
                           (lambda (ext)
                             (f-filename (f-swap-ext (buffer-file-name) ext)))
                           exts " ")))
      (local-set-key (kbd "<f9>") 'recompile))))

;;; ebib for editing BiBTeX databases

(spw/when-library-available ebib
  (use-package ebib
    :bind ("C-c g e" . ebib)
    :init (setq ebib-preload-bib-files '("~/doc/spw.bib")
                ebib-index-display-fields '(title)
                ebib-save-xrefs-first t)
    :config (delete "translator" ebib-hidden-fields)))

;;; dired enhancements

(use-package dired
  :defer
  :init
  (setq dired-recursive-deletes 'always
        dired-recursive-copies 'always
        dired-dwim-target t
        dired-listing-switches "--group-directories-first -alh")
  :config
  (bind-key "C-c u w" 'wdired-change-to-wdired-mode dired-mode-map)
  (use-package dired-aux
    :config
    ;; should be able to unzip with Z
    (add-to-list 'dired-compress-file-suffixes
                 '("\\.zip\\'" ".zip" "unzip")))
  (use-package dired-x
    :config
    (setq-default dired-omit-mode t)
    (setq dired-omit-files "^\\...+$")
    (setq dired-isearch-filenames t)))

;;; close old buffers once per day

(midnight-delay-set 'midnight-delay "3am")
(midnight-mode)

;;; simple concept of projects

(spw/when-library-available (f dash projectile)
  (use-package projectile
    :diminish projectile-mode
    :bind (("C-c p" . projectile-command-map)
           ("C-c j" . projectile-find-file)
           ("C-c v" . projectile-vc))
    ;; we have to demand because projectile-command-map is not a
    ;; command, so is not autoloaded by the :bind above.  We could drop
    ;; the :demand and use :bind-keymap but together with my keychord
    ;; that seems to mean trouble
    :demand
    :config
    ;; rebind to take advantage of helm-projectile library here
    (bind-key "s s" 'helm-projectile-ag projectile-command-map)

    ;; `spw--get-programming-projects' needs f & dash
    (use-package f)
    (use-package dash)

    ;; ;; fix bad interaction between projectile and tramp
    ;; (defun projectile-project-root--tramp-fix (orig-fun &rest args)
    ;;   (unless (file-remote-p default-directory)
    ;;     (apply orig-fun args)))
    ;; (advice-add 'projectile-project-root :around #'projectile-project-root--tramp-fix)

    (projectile-global-mode 1)
    (setq projectile-switch-project-action 'projectile-dired
          projectile-completion-system 'ido)
    (add-to-list 'projectile-globally-ignored-directories ".stack-work")
    (add-to-list 'projectile-globally-ignored-directories ".git")
    (add-to-list 'projectile-globally-ignored-directories ".cabal-sandbox")
    (add-to-list 'projectile-globally-ignored-directories "docsets")

    ;; as part of daily cleanup, clean-up projects that no longer exist
    (add-hook 'midnight-hook 'projectile-cleanup-known-projects)

    ;; Find and open projects in ~/src/ that aren't yet known to
    ;; projectile.  Inspired by
    ;; <https://alanpearce.uk/post/opening-projects-with-projectile>.
    ;; (also see projectile() in ~/src/dotfiles/archive/.zshrc)
    (defconst programming-projects-dir (expand-file-name "~/src"))
    (defun spw--get-programming-projects (dir)
      "Find all projectile projects in DIR that are presently unknown to projectile."
      (-filter
       (lambda (d)
         (and (file-directory-p d)
              (not (-contains?
                    projectile-known-projects
                    (f-slash (replace-regexp-in-string (expand-file-name "~") "~" d))))
              (-any? (lambda (f) (funcall f d))
                     projectile-project-root-files-functions)))
       (directory-files dir t "^[^.]")))
    (defun spw--open-programming-project (arg)
      "Open a programming project that is presently unknown to projectile.

Passes ARG to `projectile-switch-project-by-name'."
      (interactive "P")
      (let ((project-dir
             (projectile-completing-read "open new project: "
                                         (spw--get-programming-projects programming-projects-dir))))
        (projectile-switch-project-by-name project-dir arg)))
    (bind-key "n" 'spw--open-programming-project projectile-command-map)))

;;; `helm-projectile-ag' for searching through Org notes (replaces
;;; Deft which has become too slow)

(spw/when-library-available (helm-ag helm-projectile)
  (use-package helm-projectile
    :bind (("C-c f" . spw--search-notes)
           ("C-c F" . spw--new-note))
    :commands helm-projectile-ag
    :config
    (use-package helm-ag)
    (defun spw--search-notes ()
      "Invoke ag to incrementally search through my Org notes."
      (interactive)
      (let ((projectile-project-root org-directory))
        (call-interactively 'helm-projectile-ag)))
    (defun spw--new-note (name)
      "Create a new Org note entitled NAME."
      (interactive "sTitle: ")
      (let* ((sanitised1
              (replace-regexp-in-string "\?" "" name))
             (sanitised2
              (replace-regexp-in-string ": " "," sanitised1))
             (sanitised3
              (replace-regexp-in-string ":" "," sanitised2))
             (sanitised
              (replace-regexp-in-string " " "_" sanitised3)))
        (find-file (expand-file-name
                    (concat sanitised ".org")
                    org-directory))
        (insert (concat "#+TITLE: " name))
        (insert "\n")))))

;;; completion with ido

;; fix C-w
(add-hook
 'ido-setup-hook
 (lambda ()
   (define-key
     ido-completion-map "\C-w"
     'ido-delete-backward-word-updir)))

;; override ido-use-filename-at-point for dired buffers
;; from http://emacs.stackexchange.com/a/5331
(defun spw--ido-ignore-file-at-point ()
  "Disable ido-use-filename-at-point for the current buffer."
  (when (bound-and-true-p ido-use-filename-at-point)
    (setq-local ido-use-filename-at-point nil)))
(add-hook 'dired-mode-hook #'spw--ido-ignore-file-at-point)

;;; snippets

(spw/when-library-available yasnippet
  (use-package yasnippet
    :diminish yas-minor-mode
    :defer 5
    :config
    (yas-global-mode 1)

    ;; kill warnings about snippets that use backquoted lisp to change
    ;; the buffer
    (unless (boundp 'warning-suppress-types)
      (setq warning-suppress-types nil))
    (push '(yasnippet backquote-change) warning-suppress-types)))

;;; htmlize for Org HTML export/publishing

(spw/when-library-available htmlize
  (use-package htmlize))

;;; asynchronous copies and moves in dired -- but don't turn on for
;;; all dired buffers

(spw/when-library-available async
  (use-package dired-async
    :commands dired-async-mode))

;;; zap-up-to-char generally more useful than zap-to-char

(use-package misc
  :bind ("M-z" . zap-up-to-char))

;;; make Emacs regexps easier

(spw/when-library-available visual-regexp
  (use-package visual-regexp))

;;; undo/redo window layout changes

(winner-mode 1)

;;; subword-mode

(use-package subword
  :diminish subword-mode)

;;; Load up Haskell mode settings if Debian haskell-mode package
;;; installed (and load here, as some dependencies of these settings
;;; earlier in this init file)

(spw/when-library-available haskell-mode
  (use-package haskell
    :mode (("\\.hs" . haskell-mode)
           ("\\.lhs" . literate-haskell-mode)
           ("\\.cabal" . haskell-cabal-mode))
    :diminish interactive-haskell-mode
    :init
    (setq
     ;; indentation preferences
     haskell-indentation-layout-offset 4
     haskell-indentation-left-offset 4
     haskell-indentation-show-indentations nil

     ;; haskell-mode is forever hanging, so enable some logging
     haskell-process-log t

     ;; tidy up the REPL buffer
     haskell-process-show-debug-tips nil

     ;; this tends to get in the way
     haskell-mode-contextual-import-completion nil

     ;; enable standard features from haskell-mode docs
     ;; TODO temporarily commented out to try to figure out why
     ;; haskell-mode hangs so often
     ;; haskell-process-suggest-remove-import-lines t
     ;; haskell-process-auto-import-loaded-modules t
     ;; haskell-process-log t

     ;; guess whether this is a stack or pure cabal project
     haskell-process-type 'auto)

    ;; 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'
    (add-hook 'haskell-mode-hook
              (lambda ()
                (add-hook 'hack-local-variables-hook
                          (lambda ()
                            (if indent-tabs-mode
                                (haskell-tab-indent-mode 1)
                              (haskell-indentation-mode 1)))
                          nil t)))
    :config
    ;; (add-hook 'haskell-mode-hook 'turn-on-haskell-doc)
    (use-package haskell-interactive-mode
      :commands interactive-haskell-mode
      :init
      (add-hook 'haskell-mode-hook 'interactive-haskell-mode))
    (add-hook 'haskell-mode-hook 'subword-mode)

    ;; standard Haskell repl interaction bindings

    ;; first use `C-c C-l' and/oror `C-c C-b' to enable the use of
    ;; bindings like `M-.' and `C-c C-c'.  Note that this is quite slow
    ;; so use sparingly; basically when getting an editing session
    ;; going.  In general `C-c C-b' will be enough to make `C-c C-c'
    ;; work properly and is a bit faster; `C-c C-l' is needed to make
    ;; `M-.' work
    (bind-key "C-c C-l" 'haskell-process-load-or-reload  haskell-mode-map)
    (bind-key "C-c C-b" 'haskell-interactive-bring       haskell-mode-map)

    ;; then, use `C-c C-c' to see whether your code compiles/run a type
    ;; check.  Navigate between errors using `M-g n' and `M-g p'.  This
    ;; is much more performant.  (`haskell-compile' is an alternative
    ;; but it does not autodetect whether the project is cabal or stack)
    (bind-key "C-c C-c" 'haskell-process-cabal-build     haskell-mode-map)

    ;; less useful keys
    ;; (bind-key "C-c C-i" 'haskell-process-do-info         haskell-mode-map)
    ;; (bind-key "C-c C-k" 'haskell-interactive-mode-clear  haskell-mode-map)
    ;; (bind-key "C-c C"   'haskell-process-cabal           haskell-mode-map)

    ;; those same bindings again for `haskell-cabal-mode'

    (bind-key "C-c C-b" 'haskell-interactive-bring       haskell-cabal-mode-map)
    ;; (bind-key "C-c C-k" 'haskell-interactive-mode-clear  haskell-cabal-mode-map)
    (bind-key "C-c C-c" 'haskell-process-cabal-build     haskell-cabal-mode-map)
    ;; (bind-key "C-c C"   'haskell-process-cabal           haskell-cabal-mode-map)

    ;; these two bindings require GHCi 8 or newer (or GHCi-ng)

    ;; jump asynchronously; no need for a TAGS file
    (bind-key "M-."     'haskell-mode-goto-loc           interactive-haskell-mode-map)

    ;; pass C-u to insert a missing type signature
    ;; (bind-key "C-c C-t" 'haskell-mode-show-type-at       interactive-haskell-mode-map)

    ;; ensure that company falls back to dabbrevs when haskell-mode cannot
    ;; complete, such as in where clauses (this is straight from
    ;; haskell-mode docs)
    (add-hook 'haskell-mode-hook
              (lambda ()
                (set (make-local-variable 'company-backends)
                     (append '((company-capf company-dabbrev-code))
                             company-backends))))))



;;;; ---- functions and bindings ----

(defun mwf--narrow-or-widen-dwim (p)
  "Unless P, widen if buffer is narrowed.  Otherwise, narrow intelligently.

Intelligently means: region, org-src-block, org-subtree, or
defun, whichever applies first.  Narrowing to org-src-block
actually calls `org-edit-src-code'."
  (interactive "P")
  (declare (interactive-only))
  (cond ((and (buffer-narrowed-p) (not p)) (widen))
        ((region-active-p)
         (narrow-to-region (region-beginning) (region-end)))
        ((derived-mode-p 'org-mode)
         ;; note that `org-edit-src-code' is not a real narrowing command
         (cond ((ignore-errors (org-edit-src-code))
                (delete-other-windows))
               ((org-at-block-p)
                (org-narrow-to-block))
               (t (org-narrow-to-subtree))))
        (t (narrow-to-defun))))
(bind-key "C-c n" 'mwf--narrow-or-widen-dwim)
(put 'narrow-to-region 'disabled nil)

;;; killing of words and regions


;;; my buffer save cleanup functions

(defun spw--compact-blank-lines ()
  "Replace multiple empty blank lines in the buffer with single blank lines."
  (interactive)
  (save-excursion
    (goto-char (point-min))
    (while (search-forward-regexp "\n\n\n+" nil "noerror")
      (replace-match "\n\n"))))

(defun spw--clean-lisp-dangling-brackets ()
  "Clean up dangling brackets."
  (interactive)
  (save-excursion
    (goto-char (point-min))
    (while (search-forward-regexp "^[[:space:]\\)]*\)[[:space:]\\)]*$" nil "noerror")
      (save-excursion
        (forward-line -1)
        (beginning-of-line)
        (when (not (looking-at ".*;.*"))
          (forward-line 1)
          (delete-indentation))))))

(defun spw--cleanup ()
  "Clean up buffer, or region if mark is active, depending on major mode.

Note that `ws-butler-mode' is also at work."
  (save-restriction
    (when (use-region-p)
      (narrow-to-region (region-beginning) (region-end)))
    (case major-mode
      (haskell-mode
       (spw--compact-blank-lines)
       (haskell-mode-stylish-buffer))
      (python-mode
       (spw--compact-blank-lines))
      (emacs-lisp-mode
       (spw--compact-blank-lines)
       (spw--clean-lisp-dangling-brackets))
      (cc-mode
       (indent-region (point-min) (point-max))
       (whitespace-cleanup))
      (message-mode
       (save-excursion
         (message-goto-body)
         (save-restriction
           (narrow-to-region (point) (point-max))
           ;; (fill-region (point-min) (point-max))
           (whitespace-cleanup)))))))
(bind-key "C-c g c" 'spw--cleanup)

;;; more functions

(defun spw--toggle-window-split ()
  "Toggle the orientation of a two-window split.

Author unknown."
  (interactive)
  (if (= (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)
          (if 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)
          (if this-win-2nd (other-window 1))))))
(bind-key "t" 'spw--toggle-window-split ctl-x-4-map)

;; there are many variations on this online
(defun spw--rotate-windows (arg)
  "Rotate your windows, reversing direction if ARG.

By Robert Bost, based on work by Steve Yegge, Colin Doering and others."
  (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)))))))
(bind-key "s" 'spw--rotate-windows ctl-x-4-map)

;;; tidy up troublesome unicode

(defun gleitzman--unicode-hunt ()
  "Destroy some special Unicode characters like smart quotes.

Originally from <http://blog.gleitzman.com/post/35416335505/hunting-for-unicode-in-emacs>."
  (interactive)
  (let ((unicode-map '(("[\u2018\|\u2019\|\u201A\|\uFFFD]" . "'")
                       ("[\u201c\|\u201d\|\u201e]" . "\"")
                       ("[\u2013\|\u2014]" . "-")
                       ("\u2026" . "...")
                       ("\u00A9" . "(c)")
                       ("\u00AE" . "(r)")
                       ("\u2122" . "TM")
                       ("[\u02DC\|\u00A0]" . " "))))
    (save-excursion
      (loop for (key . value) in unicode-map
            do
            (goto-char (point-min))
            (while (re-search-forward key nil t)
              (replace-match value))))))
(bind-key "C-c g u" 'gleitzman--unicode-hunt)

;;; opening terminals

(defun spw--open-term-here ()
  "Open a fresh xfce4 terminal in current directory."
  (interactive)
  (call-process "xfce4-terminal" nil 0 nil
                (concat "--working-directory="
                        (expand-file-name  default-directory))
                "-e"  "/bin/bash"))
(bind-key "C-c g g" 'spw--open-term-here)

;;; rebasing dotfiles

(defun spw--dotfiles-rebase ()
  "Rebase & push dotfiles."
  (interactive)
  (let ((default-directory (expand-file-name "~/src/dotfiles/"))
        (buffer (get-buffer-create "*dotfiles rebase*")))
    (display-buffer "*dotfiles rebase*")
    (async-shell-command "git-dotfiles-rebase" "*dotfiles rebase*")))
(bind-key "C-c g d" 'spw--dotfiles-rebase)

;;; message-mode functions

;; I had my own version of these two functions but Michael
;; Stapelberg's were better, taking better advantage of built-in
;; functions, so these are from his config

(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."
  (let ((to (message-fetch-field "To")))
    (if to
        (spw--extract-first-name (nth 0 (mail-extract-address-components to)))
      "")))

(defun spw--extract-first-name (full-name)
  (if (stringp full-name)
      (if (string-match "\\([^ ]+\\)" full-name)
          (let ((first-name (match-string 0 full-name)))
            (cond
             ;; exceptions for people who have longer forms of their names
             ;; in their From: headers
             ((string= first-name "Nathaniel") "Nathan")
             ((string= first-name "Thomas") "Tom")
             ;; default
             (t first-name)))
        ;; no spaces: assume whole thing is an alias and use it
        full-name)
    ""))

;;; GUD startup/teardown functions

(defconst spw--gud-register 819263
  "Register for window config before and after a GUD session.")
(defvar spw--gud-mouse-autoselect-window nil
  "Value of mouse-autoselect-window before GUD session.")

(defun spw--start-gud ()
  (interactive)
  (window-configuration-to-register spw--gud-register)
  (setq spw--gud-mouse-autoselect-window mouse-autoselect-window)
  (case major-mode
    ('c-mode
     (call-interactively 'gdb)
     (setq mouse-autoselect-window t))
    ('cperl-mode
     (call-interactively 'perldb))
    ('python-mode
     (call-interactively 'pdb))))

(defun spw--quit-gud ()
  (interactive)
  (case (buffer-local-value 'gud-minor-mode gud-comint-buffer)
    ('gdbmi
     (gud-basic-call "quit"))
    ('perldb
     (gud-basic-call "q"))
    ('pdb
     (gud-basic-call "q")))
  (setq mouse-autoselect-window spw--gud-mouse-autoselect-window)
  (jump-to-register spw--gud-register))

;; Supports only a single debugging session per Emacs instance, i.e.,
;; don't try to debug both C and Perl at once.  The 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 call this command to bring GUD's window(s)
;; back.
;;
;; The idea is to have a separate Emacs frame for serious source
;; editing, from which M-x recompile or whatever is called.
(defun spw--run-or-restore-gud (arg)
  (interactive "p")
  (if (and (boundp 'gud-comint-buffer)
           (get-buffer-process gud-comint-buffer))
      (case arg
        (4 ;; quit the GUD session
         (spw--quit-gud))
        (16 ;; restart the GUD session (e.g. can't seem to set breakpoints)
         (spw--quit-gud)
         (spw--start-gud))
        (t ;; restore the GUD session's window(s)
         (if (eq (buffer-local-value 'gud-minor-mode gud-comint-buffer) 'gdbmi)
             (progn
               (gdb-restore-windows)
               ;; ensure (gdb) prompt at bottom of its window
               (recenter (window-body-height)))
           (switch-to-buffer-other-window gud-comint-buffer))))
    ;; start a new GUD session
    (spw--start-gud)))
(bind-key "C-c d" 'spw--run-or-restore-gud)

;;; https://github.com/bbatsov/crux/blob/master/crux.el

(defun crux-rename-file-and-buffer ()
  "Rename current buffer and if the buffer is visiting a file, rename it too."
  (interactive)
  (let ((filename (buffer-file-name)))
    (if (not (and filename (file-exists-p filename)))
        (rename-buffer (read-from-minibuffer "New name: " (buffer-name)))
      (let* ((new-name (read-from-minibuffer "New name: " filename))
             (containing-dir (file-name-directory new-name)))
        (make-directory containing-dir t)
        (cond
         ((vc-backend filename) (vc-rename-file filename new-name))
         (t
          (rename-file filename new-name t)
          (set-visited-file-name new-name t t)))))))

(defun crux-delete-file-and-buffer ()
  "Kill the current buffer and deletes the file it is visiting."
  (interactive)
  (let ((filename (buffer-file-name)))
    (when filename
      (if (vc-backend filename)
          (vc-delete-file filename)
        (when (y-or-n-p (format "Are you sure you want to delete %s? " filename))
          (delete-file filename delete-by-moving-to-trash)
          (message "Deleted file %s" filename)
          (kill-buffer))))))

(bind-key "C-c R" 'crux-rename-file-and-buffer)
(bind-key "C-c D" 'crux-delete-file-and-buffer)

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

(defun spw--datetree-shorty ()
  (interactive)
  (let ((stamp (format-time-string "[%Y-%m-%d %a]")))
    (find-file "~/doc/papers/shorties.org")
    (beginning-of-buffer)
    (outline-show-all)
    (variable-pitch-mode 1)
    (if (org-goto-local-search-headings stamp nil t)
        (progn (forward-line 1) (beginning-of-line))
      (end-of-buffer)
      (unless (bolp) (newline))
      (insert "* " stamp "\n"))))

;; TODO the reverse?  it would work on the assumption (which should be
;; documented) that the frame into which I wish to move the current
;; buffer is the one that will get window manager focus (or Emacs
;; focus?) if the currently focused frame is deleted
(defun spw--window-to-frame ()
  (interactive)
  (let ((buffer (current-buffer)))
    (delete-window)
    (display-buffer-other-frame buffer)))
(bind-key "s" 'spw--window-to-frame ctl-x-5-map)

;; making one of these manually requires quite a few keystrokes, BUT
;; we have a 'com' yasnippet which should be used instead of the
;; following function
;; (defun spw--linux-style-multiline-comment ()
;;   (interactive)
;;   (when (and (not (use-region-p))
;;              (save-excursion (beginning-of-line) (looking-at "\\s-*$")))
;;     (indent-according-to-mode)
;;     (insert "/*")
;;     (newline-and-indent)
;;     (delete-char -1)
;;     (insert "* ")
;;     (save-excursion
;;       (insert "\n")
;;       (indent-according-to-mode)
;;       (insert "*/"))))

;; idea to use `locate-dominating-file' from EmacsWiki
(defun spw--perltidy-region (beg end)
  (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 beg end "perltidy -q" nil t)
    (font-lock-fontify-buffer)
    (setenv "PERLTIDY" perltidy-env)))
(defun spw--perltidy-dwim (arg)
  "Run perltidy on the current region, block or buffer."
  (interactive "P")
  (let (beg end)
    (if arg
        (setq beg (point-min) end (point-max))
      (if (region-active-p)
          (setq beg (min (point) (mark)) end (max (point) (mark)))
        (save-mark-and-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
          (let ((start)
                (count 0))
            (loop do (setq start (point))
                  (ignore-errors (backward-up-list))
                  (setq count (1+ count))
                  until (= start (point)))
            (if (= count 1)
                ;; we didn't move; do whole buffer
                (setq beg (point-min) end (point-max))
              ;; select block for tidying
              (mark-sexp)
              (spw/expand-region-to-whole-lines-and-activate)
              (setq beg (min (point) (mark))
                    end (max (point) (mark))))))))
    (spw--perltidy-region beg end)))

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

;; TODO this won't work if no other frames are open
(defun spw--dedicated-org-agenda-window (arg)
  (let ((frame (or (cdr (assoc "Org-mode agenda" (make-frame-names-alist)))
                   (when arg
                     (make-frame (list '(name . "Org-mode agenda")))))))
    (with-selected-frame frame
      (if (string= "*Org Agenda(a)*"
                   (buffer-name (window-buffer (frame-first-window))))
          (select-window (frame-first-window))
        (org-agenda nil "a")
        (when arg (org-agenda-redo-all))
        (delete-other-windows)))))

;; intended as a `pre-command-hook'
(defun spw--refocus-org-agenda-window ()
  (when (string= (frame-parameter (selected-frame) 'name) "Org-mode agenda")
    (add-hook-run-once
     'post-command-hook
     (lambda ()
       (x-focus-frame
        (cdr (assoc "Org-mode agenda" (make-frame-names-alist))))))))

;;; following alternative approach works by appending
;;;
;;;     (add-hook 'post-command-hook 'spw--fix-dedicated-org-agenda-window-focus)
;;;
;;; to `spw--dedicated-org-agenda-window'
;; (defun spw--fix-dedicated-org-agenda-window-focus ()
;;   (let ((frame (cdr (assoc "Org-mode agenda" (make-frame-names-alist)))))
;;     (when (and frame (memq this-command (list
;;                                          'org-agenda-redo-all
;;                                          'org-agenda-todo))
;;                (eq 0 (call-process-shell-command
;;                       (concat "xdotool search --onlyvisible --desktop"
;;                               " $(xprop -notype -root _NET_CURRENT_DESKTOP | cut -c 24-)"
;;                               " \"Org-mode agenda\"")
;;                       nil "*xdotool dedicated window fix*" nil)))
;;       (x-focus-frame frame)
;;       (kill-buffer "*xdotool dedicated window fix*"))))

(defun spw--dired-other-window-tmp ()
  (interactive)
  (dired-other-window "~/tmp"))
(bind-key "C-c 4 t" 'spw--dired-other-window-tmp)

(defun spw--perl-add-use (module)
  (interactive "suse ")
  (let ((line (concat "use " module
                      (unless (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--sid-report-bug (package subject)
  (interactive "sSource or binary package name: \nsSubject: ")
  (let* ((type (ido-completing-read "Report bug against: "
                                    (list "Source" "Package")))
         (rmadison (shell-command-to-string
                    (concat "rmadison --suite=unstable " package)))
         (version (nth 1 (split-string rmadison "|" t " "))))
    (compose-mail)
    (message-goto-to)
    (insert "Debian Bug Tracking System <submit@bugs.debian.org>")
    (message-goto-subject)
    (insert package ": " subject)
    (message-goto-body)
    (insert type ": " package "\n" "Version: " version "\n")))



;;;; ---- personal settings ----

;;; no tabs by default

(setq-default indent-tabs-mode nil)

;;; key bindings

;; I don't often want to quit
(bind-key "C-x C-c" 'delete-frame)
(bind-key "C-c g k" 'kill-emacs)

;; `reindent-then-newline-and-indent' tends to get things wrong more
;; often than it gets things right with my typing habits.  I hit <TAB>
;; a lot.
;; try disabling this for a while and see if anything unexpected happens
;; (bind-key "RET" 'newline-and-indent)

;; fallback expanding
(bind-key "M-/" 'hippie-expand)

(bind-key "C-c ." 'repeat)

;;; toggling

(bind-key "C-c t e" 'toggle-debug-on-error)
(bind-key "C-c t i" 'org-indent-mode)

;;; evaluation

(bind-key "C-c e f" 'eval-defun)
(bind-key "C-c e r" 'eval-region)
(bind-key "C-c e b" 'eval-buffer)

;;; insertion

(bind-key "C-c i h" 'add-file-local-variable-prop-line)

;;; abbreviations

(setq abbrev-file-name "~/doc/emacs-abbrevs")

;; turn on for all buffers, if our abbrevs file is checked out
(when (file-exists-p abbrev-file-name)
  (setq save-abbrevs t)
  (setq-default abbrev-mode t)
  (diminish 'abbrev-mode)
  (quietly-read-abbrev-file))

;;; bookmarks

;; again, only do stuff if our bookmarks file is checked out
(when (file-exists-p "~/doc/emacs-bookmarks")
  (setq bookmark-default-file "~/doc/emacs-bookmarks"
        ;; avoid annoying "Buffer emacs-bookmarks modified; kill anyway?" messages
        bookmark-save-flag 1)

  ;; something involved in setting bookmarks likes to try to kill the
  ;; bookmarks file buffer which means an annoying y/n query since
  ;; something likes setting the modified flag without actually
  ;; modifying anything.  So save it, or for the very frequently
  ;; called `kill-buffer', clear modification flag for these bogus
  ;; modifications
  ;; TODO fix this upstream
  (defun bookmark-write-file--save-bookmarks-buffer (&rest ignore)
    (when (get-buffer "emacs-bookmarks")
      (with-current-buffer (get-buffer "emacs-bookmarks")
        (save-buffer))))
  (advice-add 'bookmark-write-file :before #'bookmark-write-file--save-bookmarks-buffer)
  (defun kill-buffer--clear-modified (&rest ignore)
    (when (get-buffer "emacs-bookmarks")
      (with-current-buffer (get-buffer "emacs-bookmarks")
        (set-buffer-modified-p nil))))
  (advice-add 'kill-buffer :before #'kill-buffer--clear-modified))

;;; miscellaneous personal settings

;; save script files as executable automatically
(add-hook 'after-save-hook
          'executable-make-buffer-file-executable-if-script-p)

;; always update file contents
(global-auto-revert-mode 1)
(diminish 'auto-revert-mode)

;; and a binding to do so manually
(bind-key "C-x C-r" (lambda () (interactive) (revert-buffer nil t)))

;; recursive minibuffers
(setq enable-recursive-minibuffers t)
(minibuffer-depth-indicate-mode 1)

;; explicitly end sentences with double spaces
(setq sentence-end-double-space t)

;; C-n can't move us past the end of the buffer
(setq next-line-add-newlines nil)

;; re-indent and add newlines automatically, sometimes
;; (electric-layout-mode 1)
(electric-indent-mode 1)

;; templates when creating new files
;; (auto-insert-mode 1)

;; ;; disable for python mode where it makes a mess
;; (defun electric-indent-ignore-python ()
;;   "Ignore electric indentation for `python-mode'."
;;   (if (equal major-mode 'python-mode)
;;       `no-indent'
;;     nil))
;; ;;(add-hook 'electric-indent-functions 'electric-indent-ignore-python)

;; browser
(setq browse-url-generic-program "xdg-open"
      browse-url-browser-function 'browse-url-generic)

;; clipboard & primary selection: see https://www.gnu.org/software/emacs/manual/html_node/emacs/Clipboard.html

;; with this setup, C-y and M-w access the clipboard, while selecting
;; a region and then pressing C-g and middle click access the primary
;; selection

(setq select-active-regions t
      mouse-drag-copy-region t
      select-enable-primary nil
      select-enable-clipboard t
      mouse-yank-at-point t
      yank-pop-change-selection t
      save-interprogram-paste-before-kill t
      x-select-enable-clipboard-manager t)

(global-set-key [mouse-2] 'mouse-yank-primary)

;; require a buffer to have a final newline
(setq require-final-newline 'visit-save)

;; scrolling
(setq scroll-preserve-screen-position t)

(setq switch-to-visible-buffer nil)

;; dabbrev should be case-insensitive
(setq dabbrev-case-fold-search t)

;; view mode should be read-only
(setq view-read-only t)

;;; don't ask me before following symlinks to files in version control
(setq vc-follow-symlinks t)

;;; colours in comint modes

(ansi-color-for-comint-mode-on)

;;; show column numbers as well as line numbers in the mode line

(setq column-number-mode t)

;;; toggle variable-pitch-mode

(bind-key "C-c g v" (lambda ()
                      (interactive)
                      (call-interactively 'variable-pitch-mode)))

;;; isearch

;; these are nice when destination is outside of visible portion of
;; buffer -- when we're just using isearch to jump around what's
;; visible, probably want to keep hands on homerow and use C-s/C-r to
;; repeat the search
(bind-key "<left>" 'isearch-repeat-backward isearch-mode-map)
(bind-key "<right>" 'isearch-repeat-forward  isearch-mode-map)
(bind-key "<left>" 'isearch-reverse-exit-minibuffer
          minibuffer-local-isearch-map)
(bind-key "<right>" 'isearch-forward-exit-minibuffer
          minibuffer-local-isearch-map)



;;;; ---- major modes configuration ----

;;; mail mode for mutt & notmuch

(use-package sendmail :commands mail-add-attachment)

(use-package message
  :mode ("/mutt-.*$" . message-mode)
  :init
  ;; mutt uses a blank line to separate the headers from the message
  ;; body; to ensure proper font locking and other behaviour, tell
  ;; Emacs about that
  (defun spw--mutt-mail-header-separator ()
    (when (string-match-p "^mutt-" (buffer-name (current-buffer)))
      (setq-local mail-header-separator "")))
  (add-hook 'message-mode-hook 'spw--mutt-mail-header-separator)

  ;; automatic formatting/templating of messages
  (spw/when-library-available message-templ
    (use-package message-templ
      :commands message-templ-config-exec
      :init
      (setq message-templ-alist
            '(("default"
               ("From" . "Sean Whitton <spwhitton@spwhitton.name>"))
              ("UA"
               ("From" . "Sean Whitton <spwhitton@email.arizona.edu>"))
              ("Debian"
               ("From" . "Sean Whitton <spwhitton@debian.org>"))))
      (setq message-templ-config-alist
            '(("^\\(To\\|Cc\\|Bcc\\):.+\\(.*@.*debian\\.org\\|sgo-software-announce\\)"
               (lambda ()
                 ;; no PGP signing on athena
                 (unless (string= (system-name) "athena")
                   ;; 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)))))
              ("^\\(To\\|Cc\\|Bcc\\):.*@.*\\(\.edu\\|\.ac\.uk\\)"
               (lambda ()
                 (message-templ-apply "UA")))))))

  (add-hook 'message-mode-hook 'footnote-mode)
  (add-hook 'message-mode-hook 'message-goto-body)
  ;; need orgstruct++ rather than just orgstruct so that filling
  ;; doesn't break lists
  (add-hook 'message-mode-hook 'orgstruct++-mode)

  :config
  ;; it's a really long line with notmuch and it causes word wrapping
  (add-to-list 'message-hidden-headers "^User-Agent:")

  (defun message-newline-and-reformat--delete-superfluous-newlines (&rest ignore)
    "Have `message-newline-and-reformat' get rid of some more superflous blank quoted lines."
    (save-excursion
      (forward-line -2)
      (when (looking-at ">[[:space:]]*$")
        (kill-line 1)))
    (save-excursion
      (forward-line 2)
      (when (looking-at ">[[:space:]]*$")
        (kill-line 1))))
  (advice-add 'message-newline-and-reformat
	      :after #'message-newline-and-reformat--delete-superfluous-newlines)

  ;; code to automatically format a message

  (defvar-local spw--message-normalised nil
    "Whether `spw--message-normalise' has been run in this buffer.")

  (defun notmuch-mua-send-and-exit--check-normalised (orig-fun &rest args)
    "Prompt before sending a message if `spw--normalise-message' not yet called."
    (when (or (bound-and-true-p spw--message-normalised)
              (y-or-n-p "Send message without having invoked `spw--normalise-message'?"))
      (apply orig-fun args)))
  (advice-add 'notmuch-mua-send-and-exit :around
              #'notmuch-mua-send-and-exit--check-normalised)

  (defun spw--normalise-message (arg)
    "Autoformat a message before sending.

The state after this function has been called is meant to be like
mutt's review view after exiting EDITOR."
    (interactive "P")
    ;; set up From address, pgp signing, etc.
    (message-templ-config-exec)
    (spw--compact-blank-lines)
    (save-excursion
      (spw--message-goto-body--skip-mml-secure)
      ;; also skip over Debian BTS pseudoheaders, which shouldn't be
      ;; wrapped
      (when (looking-at "^\\([A-Za-z][a-z]+: [^ ]+\\|[cC]ontrol: .+\\)$")
        (while (looking-at "^\\([A-Za-z][a-z]+: [^ ]+\\|[cC]ontrol: .+\\)$")
          (forward-line 1))
        (if (looking-at "\n")
            (forward-line 1)
          (newline)))
      (let ((body (point)))
        ;; ensure there is at least a basic salutation
        (unless (looking-at "^[A-Z].+,\n\n")
          (insert "Hello,\n\n")
          (when (looking-at "\n")
            (delete-blank-lines)))
        (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"))
        (undo-boundary)
        (when arg
          (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))
  ;; I do not need a key to insert the Newsgroups: header
  (bind-key "C-c C-n" 'spw--normalise-message message-mode-map)

  (defun spw--unfinalise-message ()
    (interactive)
    (setq spw--message-normalised nil)
    (message "unfinalising message"))
  ;; likewise I don't need a binding to delay an article
  (bind-key "C-c C-j" 'spw--unfinalise-message message-mode-map)

  ;; a convenient macro for something I find myself often doing by hand
  (defun spw--message-delete-and-normalise (arg)
    (interactive "P")
    (newline)
    (message-kill-to-signature)
    (spw--normalise-message arg))
  (bind-key "<f9>" 'spw--message-delete-and-normalise message-mode-map)

  (defun spw--notmuch-decrypt-inline ()
    (interactive)
    (epa-decrypt-armor-in-region (point-min) (point-max)))

  ;; bindings

  ;; C-c C-b should skip over mml's sign/encrypt lines (it is a bad
  ;; idea to advise `message-goto-body' as various functions assume it
  ;; does not skip over sign/encrypt lines
  ;; (e.g. `notmuch-mua-check-no-misplaced-secure-tag')
  (defun spw--message-goto-body--skip-mml-secure ()
    (interactive)
    (message-goto-body)
    (when (looking-at "^<#\\(secure\\|part\\)")
      (forward-line)))
  (bind-key "C-c C-b" 'spw--message-goto-body--skip-mml-secure message-mode-map)

  ;; default C-c C-s binding is not much use, and I keep hitting it
  ;; accidently
  (bind-key "C-c C-s" 'message-goto-subject message-mode-map)

  ;; mail-add-attachment has sensible defaults so requires less typing
  ;; than the default binding of C-c C-a.  From Michael Stapelberg's
  ;; config.  Also, put all attachments at the end of the message for
  ;; clarity
  (defun spw--mail-add-attachment ()
    (interactive)
    (save-excursion
      (end-of-buffer)
      (call-interactively 'mail-add-attachment)))
  (define-key message-mode-map (kbd "C-c C-a") 'spw--mail-add-attachment)
  (define-key mml-mode-map [menu-bar Attachments Attach\ File...]
    '("Attach File..." . spw--mail-add-attachment))

  ;; miscellaneous preferences

  ;; follow the rest of the world
  (setq message-forward-before-signature nil
        message-forward-as-mime nil
        message-forward-included-headers
        "^From:\\|^To:\\|^Cc:\\|Subject:\\|Date:\\|Message-ID:"
        message-make-forward-subject-function 'message-forward-subject-fwd)

  ;; try to strip signatures when citing
  (setq notmuch-mua-cite-function 'message-cite-original-without-signature)

  (setq message-citation-line-function 'message-insert-formatted-citation-line
        message-citation-line-format "On %a %d %b %Y at %I:%M%p %Z, %N wrote:\n")

  ;; default dir for saving attachments
  (setq mm-default-directory "~/tmp/")

  ;; ensure encrypted messages are also encrypted to me, so I can read
  ;; them in my sent mail folder
  (setq mml-secure-openpgp-encrypt-to-self t)

  ;; disable openwith-mode when sending mail (i.e. attach the PDF,
  ;; rather than opening it in evince and aborting the send)
  (require 'mm-util)
  (add-to-list 'mm-inhibit-file-name-handlers 'openwith-file-handler)

  ;; don't let sent messages hang around
  (setq message-kill-buffer-on-exit t)

  ;; Use this to mark sent mail as containing unresolved comments.,
  ;; e.g. when responding to a patch posting.  Remove the flag from
  ;; the message when the next version of the patch series is seen to
  ;; resolve the review comments.
  ;;
  ;; Don't use this for review comments where I'll notice, without
  ;; effort, that the revised series does not address the comments.
  ;; E.g. don't flag a review comment only objecting to a
  ;; clone-and-hack of a function: I'll notice the clone-and-hack if
  ;; it still remains in the revised series, so no need to go back and
  ;; look at that review comment on the previous series
  (defun spw--message-fcc-flag ()
    (interactive)
    (save-excursion
      (message-goto-fcc)
      (insert " +spw::unresolved")))
  (bind-key "C-c C-f f" 'spw--message-fcc-flag message-mode-map)

  ;; In a thread with patches, try to collapse 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 thread.  Include spw::unresolved
  ;; mail, 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
  ;; unresolved review comments on the old series, and the series are
  ;; in different threads, open each thread in a separate buffer
  ;; (probably in separate frames).  Run this command in the new
  ;; series' buffer and hit `l tag:spw::unresolved RET' in the old
  ;; series' buffer
  (defun spw--notmuch-show-filter-thread-patches (&optional reroll-count)
    (interactive "P")
    (let ((subject-filter
           (if reroll-count
               (let ((n (prefix-numeric-value reroll-count)))
                 (if (= n 1)
                     "(subject:/\\[.*PATCH[^v]*\\]/ or subject:/\\[.*PATCH.*v1.*\\]/)"
                   (concat "subject:/\\[.*PATCH.*v" (number-to-string n) ".*\\]/")))
             "subject:/\\[.*PATCH.*\\]/ ")))
      (notmuch-show-filter-thread
       (concat "tag:unread or tag:spw::unresolved or ("
               subject-filter
               " and not subject:'Re:' and not subject:'Info received')"))))
  (bind-key "C-c g f" 'spw--notmuch-show-filter-thread-patches))

;;; C-c C-c to save-and-exit emacsclient (like <esc>ZZ in vim)

;; this overrides the major mode's C-c C-c binding (this is important
;; for message-mode, so that the message doesn't get sent by notmuch,
;; bypassing mutt's invocation of emacsclient)

(add-hook 'server-switch-hook
          (lambda ()
            (when (current-local-map)
              (use-local-map (copy-keymap (current-local-map))))
            (when server-buffer-clients
              (local-set-key (kbd "C-c C-c")
                             (lambda ()
                               (interactive)
                               (save-buffer)
                               (server-edit))))))

;;; IELM

;; (setq ielm-dynamic-return nil)

;;; text mode

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

;; writing notes on ftp-master
(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--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--disable-electric-indent-local)

;;; LaTeX

;; (setq TeX-auto-save t
;;       TeX-parse-self t
;;       LaTeX-indent-level 4
;;       LaTeX-item-indent -2
;;       TeX-newline-function 'reindent-then-newline-and-indent)

;; (add-hook 'LaTeX-mode-hook 'turn-on-auto-fill)
;; (add-hook 'LaTeX-mode-hook 'TeX-PDF-mode)

(setq TeX-output-view-style
      (quote
       (("^pdf$" "." "evince %o")
        ("^html?$" "." "firefox %o"))))

;;; fixes for exporting from Org-mode

;; ;; (setq TeX-auto-save t)
;; ;; (setq TeX-parse-self t)
;; (setq-default TeX-master t)
;; (make-variable-buffer-local 'TeX-master)

;;; the Emacs calculator

;; disable line numbering primarily so that killing and copying stack
;; entries puts the number alone in the kill-ring
(setq calc-line-numbering nil)

;; on my "Amazon Basics" keyboard
(bind-key "<XF86Calculator>" 'calc)

;;; javascript

;; don't insert a newline after a semicolon
(add-hook
 'js-mode-hook
 (lambda ()
   (setq-local electric-layout-rules
               (remove (quote (?\; . after)) electric-layout-rules))))

;;; Perl

;; using cperl-mode instead of perl-mode because the former doesn't
;; try to indent lines within a POD

(use-package cperl-mode
  :mode "\\.\\([pP][Llm]\\|al\\)\\'"
  :interpreter (("perl" . cperl-mode)
                ("perl5" . cperl-mode)
                ("miniperl" . cperl-mode))
  :init
  ;; (setq cperl-continued-statement-offset 4)
  (setq cperl-indent-level 4
        cperl-indent-wrt-brace t
        cperl-lineup-step 1
        ;; advantage of following two lines is that we are not
        ;; penalised for choosing long and descriptive subroutine names
        cperl-indent-parens-as-block t
        cperl-close-paren-offset -4)
  :config
  (bind-key "C-c c" 'spw--perltidy-dwim)
  (bind-key "C-c u" 'spw--perl-add-use))

;;; changelogs

(defun spw--change-log-setup ()
  (setq-local indent-tabs-mode nil)
  (setq-local left-margin 2)
  (orgstruct++-mode 1))
(add-hook 'change-log-mode-hook 'spw--change-log-setup)

(setq debian-changelog-mailing-address "spwhitton@spwhitton.name")

;;; cc-mode

;; the built-in 'linux' style doesn't explicitly include tabs, so with
;; indent-tabs-mode set to nil, cc-mode will not use tabs.  But the
;; kernel style guide mandates tabs, so make a slightly modified style
;; TODO fix in the 'linux' style in upstream Emacs
(c-add-style "linux-tabs" '("linux" (indent-tabs-mode . t)))
(setq c-default-style "linux-tabs")

;; 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'
(setq comment-style 'extra-line)

(use-package cc-mode
  :init
  (add-hook 'c-mode-hook 'spw--turn-on-comment-filling)
  :config
  ;; this function interacts badly with electric-indent-mode outside
  ;; of comments (and c-mode activates electric-indent-local-mode by
  ;; default), so for now rely on M-j and M-q within comments
  ;; (bind-key "RET" 'c-context-line-break c-mode-base-map)

  (bind-key "<f9>" (lambda ()
                     (interactive)
                     (delete-other-windows)
                     (recompile)) c-mode-base-map)

  ;; (bind-key "C-M-;" 'spw--linux-style-multiline-comment c-mode-base-map)

  ;; Use the mode-specific paren binding.  For one thing, default M-(
  ;; binding will insert spaces before the paren which the Linux C
  ;; style does not call for
  (bind-key "M-(" 'c-electric-paren c-mode-base-map))

;;; gdb

;; this is for when gdb-many-windows is turned off: still show the
;; source of the program's main(), please
(setq gdb-show-main t)

;; TODO
;; (gdb-speedbar-auto-raise)
;; (gud-tooltip-mode)

;;; init-spw.el ends here