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

;;; Commentary:

;;; Code:

;;;; ---- package management ----

;; be sure not to load stale bytecode-compiled lisp
(setq load-prefer-newer t)

(add-to-list 'load-path (concat user-emacs-directory "site-lisp"))
(require 'use-package)
(require 'package)

(setq
 package-user-dir "~/local/src/elpa"
 package-archives
 '(("melpa" . "http://melpa.org/packages/")
   ("melpa-stable" . "http://stable.melpa.org/packages/")
   ;; ("marmalade" . "http://marmalade-repo.org/packages/")
   ("org" . "http://orgmode.org/elpa/")
   ("gnu" . "http://elpa.gnu.org/packages/")))

(package-initialize)
(unless package-archive-contents
  (package-refresh-contents))
(setq package-enable-at-startup nil)

;;;; ---- basic settings ----

;;; customisation -- must be loaded early so that zenburn theme is
;;; considered safe

(defconst custom-file (concat user-emacs-directory "init-custom.el"))
(load custom-file 'noerror)

;; when I try do elisp experimentation I use IELM so make scratch
;; buffer a little more co-operative
(setq initial-major-mode 'text-mode)

;;; load terminal fixes

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

;;; preferred charset at work

(prefer-coding-system 'utf-8)

;;; put backups and autosaves in /tmp

(defconst emacs-tmp-dir (format "%s/%s%s/" temporary-file-directory "emacs" (user-uid)))
(make-directory emacs-tmp-dir t)
(chmod emacs-tmp-dir (string-to-number "700" 8))
(setq backup-by-copying t                    ; don't clobber symlinks
      backup-directory-alist `((".*" . ,emacs-tmp-dir))
      tramp-backup-directory-alist backup-directory-alist
      auto-save-file-name-transforms `((".*" ,emacs-tmp-dir t))
      auto-save-list-file-prefix emacs-tmp-dir
      tramp-auto-save-directory emacs-tmp-dir

      ;; disable backups for files accessed through tramp's sudo and su
      ;; protocols, to prevent copies of root-owned files being in a user's
      ;; homedir
      backup-enable-predicate (lambda (name)
                                (and (normal-backup-enable-predicate name)
                                     (not
                                      (let ((method (file-remote-p name 'method)))
                                        (when (stringp method)
                                          (member method '("su" "sudo"))))))))

;;; misc display settings

;; focus follow mouse
(setq mouse-autoselect-window nil
      focus-follows-mouse nil)

;; y/n rather than yes/no
(fset 'yes-or-no-p 'y-or-n-p)

;; warn before killing Emacs
(setq confirm-kill-emacs #'y-or-n-p)

;; don't handle keyboard events before redrawing
(setq redisplay-dont-pause t)

;; don't prompt to create scratch buffers
(setq confirm-nonexistent-file-or-buffer nil)

;; initial frame width -- commented out in favour of maximising
;; (if window-system (set-frame-width (selected-frame) 80))

;; soft word wrapping for easier editing of long lines
(setq-default visual-line-mode t
              word-wrap t
              wrap-prefix "    ")

;; kill the fringes, if we have window system support compiled in
(if (fboundp 'set-fringe-mode)
    (set-fringe-mode 0))

;; Terminus
(if (member "Terminus-11" (font-family-list))
    (set-default-font "Terminus-11"))
(add-to-list 'default-frame-alist '(font . "Terminus-11"))

;; disable GUI elements
(if (fboundp 'set-scroll-bar-mode) (set-scroll-bar-mode nil))
(if (fboundp 'tool-bar-mode) (tool-bar-mode -1))
(if (fboundp 'menu-bar-mode) (menu-bar-mode -1))

;;; cursor settings

(setq x-stretch-cursor t)
(setq-default cursor-type 'box)
(if (fboundp 'blink-cursor-mode) (blink-cursor-mode 0)) ; turns off blink-cursor-mode if it ended up on

;; get the mouse out of the way
(mouse-avoidance-mode 'exile)

;;; zenburn

(use-package zenburn-theme
  :ensure
  :init (load-theme 'zenburn))

;;; sexy mode line

(use-package smart-mode-line
  :ensure
  :init
  (use-package powerline :ensure)
  (use-package smart-mode-line-powerline-theme :ensure)
  (sml/setup)
  (sml/apply-theme 'powerline)
  (setq sml/shorten-directory nil
        sml/shorten-modes t
        sml/mode-width 'right
        sml/vc-mode-show-backend t))

;;; I'm in Korea

(if (not (eq system-type 'windows-nt))
    (set-time-zone-rule "/usr/share/zoneinfo/Asia/Seoul"))

;;; be sure to start the server

(require 'server)
(unless (server-running-p)
  (server-start))



;;;; ---- packages ----

;;; clean up the mode line

(use-package diminish :ensure)

;;; libraries of useful lisp functions

(use-package f :ensure) (use-package s :ensure) (use-package dash :ensure)

;;; instead of vim text objects

(use-package expand-region
  :ensure
  :bind ("M-i" . er/expand-region)
  :init
  (setq expand-region-contract-fast-key (kbd "o"))

  ;; fill out the region to the beginning and ends of the
  ;; lines at either end of it when we're not using
  ;; expand-region but we've activated the mark (but only do
  ;; this once)
  (defadvice er/expand-region (around fill-out-region activate)
    (if (or (not (region-active-p))
            (eq last-command 'er/expand-region))
        ad-do-it
      (if (< (point) (mark))
          (let ((beg (point)))
            (goto-char (mark))
            (end-of-line)
            (forward-char 1)
            (push-mark)
            (goto-char beg)
            (beginning-of-line))
        (let ((end (point)))
          (goto-char (mark))
          (beginning-of-line)
          (push-mark)
          (goto-char end)
          (end-of-line)
          (forward-char 1))))))

;;; keep parentheses under control: modern replacement for the mighty paredit

(use-package smartparens
  :ensure
  :bind (("M-J" . sp-join-sexp)

         ;; for when I use Emacs via PuTTY
         ("M-<right>" . sp-forward-slurp-sexp)
         ("M-<left>" . sp-forward-barf-sexp))
  :commands (smartparens-strict-mode
             smartparens-mode
             show-smartparens-global-mode)
  :defer 5
  :init

  (dolist (hook '(emacs-lisp-mode-hook
                  lisp-mode-hook
                  lisp-interaction-mode-hook
                  ielm-mode-hook
                  scheme-mode-hook
                  inferior-scheme-mode-hook
                  python-mode-hook
                  minibuffer-setup-hook
                  haskell-mode-hook))
    (add-hook hook
              (lambda ()
                (smartparens-strict-mode 1))))

  :config

  (require 'smartparens-config)
  (setq sp-navigate-consider-symbols t)

  ;; global smartparens bindings
  (sp-use-smartparens-bindings)
  (bind-key "C-w" 'sp-backward-kill-word emacs-lisp-mode-map)
  (bind-key "C-k" 'sp-kill-hybrid-sexp emacs-lisp-mode-map)
  (bind-key "M-<up>" 'sp-raise-sexp smartparens-mode-map)

  ;; and now undo some of that in particular major modes
  (add-hook 'org-mode-hook (lambda ()
                             (crowding/local-set-minor-mode-key
                              'smartparens-mode (kbd "M-<up>") nil)))

  ;; override smartparens binding for C-k outside of lisp,
  ;; since sp-kill-hybrid-sexp isn't very smart in comint
  ;; and I like using C-u C-k
  ;; (define-key smartparens-strict-mode-map [remap kill-line] 'kill-line)
  ;; (bind-key "C-k" 'sp-kill-hybrid-sexp
  ;; emacs-lisp-mode-map)

  (defadvice sp-backward-kill-word (after sp-backward-kill-word-fix-punctuation activate)
    ;; when killing the first word of a sentence, leave the
    ;; two spaces after the previous sentence's terminal
    ;; period
    (save-excursion
      (backward-char 2)
      (if (and
           (or
            (looking-at "\\. ")
            (looking-at   "! ")
            (looking-at "\\? "))
           (not (looking-back "^[1-9]+")))
          (progn
            (forward-char 1)
            (insert " ")))))

  ;; fix cursor position after M-d at the beginning of a line
  (defadvice sp-kill-word (after sp-kill-word-beg-of-line-fix activate)
    (if (looking-back "^[[:space:]]")
        (backward-char 1)))

  (defadvice sp-backward-delete-char (around sp-backward-delete-char-remove-indentation activate)
    ;; when after whitespace at the beginning of a line or
    ;; an Org bullet or heading, delete it all
    (if (and
         ;; do it if we're not at the beginning of the line,
         ;; and there's whitespace: if we're at the
         ;; beginning of the line we should always delete
         (not (equal (point) (line-beginning-position)))
         (or
          (looking-back "^[[:space:]]+")
          (looking-back "^[[:space:]]*- ")
          (looking-back "^[*]+ ")))
        (kill-line 0)
      ;; if not after whitespace at the beginning of the
      ;; line, just call as usual
      ad-do-it))

  (defadvice sp-backward-kill-word (around sp-backward-delete-word-remove-indentation activate)
    ;; when after whitespace at the beginning of a line or
    ;; an Org bullet or heading, delete it all.  This is
    ;; more intuitive when C-w is one's main way to delete
    ;; stuff
    (if (and
         ;; do it if we're not at the beginning of the line,
         ;; and there's whitespace: if we're at the
         ;; beginning of the line we should always delete
         (not (equal (point) (line-beginning-position)))
         (or
          (looking-back "^[[:space:]]+")
          (looking-back "^[[:space:]]*- ")
          (looking-back "^[*]+ ")))
        (kill-line 0)
      ;; if not after whitespace at the beginning of the
      ;; line, just call as usual
      ad-do-it))

  ;; define some additional pairings for Org-mode
  (sp-local-pair 'org-mode "=" "=") ; verbatim
  ;; (sp-local-pair 'org-mode "*" "*")
  ;; (sp-local-pair 'org-mode "/" "/")
  ;; (sp-local-pair 'org-mode "~" "~") ; code
  ;; (sp-local-pair 'org-mode "+" "+")
  ;; (sp-local-pair 'org-mode "_" "_")

  (defadvice sp--cleanup-after-kill (after haskell-sp-unindent activate)
    (when hi2-mode
      (hi2-indent-backwards)))
  (show-smartparens-global-mode 1))

;;; Org

(eval-after-load 'org '(load "~/.emacs.d/init-org.el"))

(use-package org
  :ensure org-plus-contrib
  :pin org
  :mode (("\\.org" . org-mode)
         ("\\.org_archive" . org-mode))
  :commands (org-capture
             org-store-link
             org-agenda
             spw/org-agenda-file-to-front
             spw/org-remove-file))

;;; keep pop up windows under control

(use-package popwin
  :ensure
  :commands popwin-mode
  :defer 5
  :config (popwin-mode 1))

;;; save my places in buffers; this is all the session management I need

(setq recentf-save-file "~/.emacs.d/recentf")

;; the three hooks added by the idle progn below don't stay set when
;; set by (require 'saveplace), nor do they remain in place if simply
;; added in this config file or even in 'after-init-hook.  So have
;; use-package add them a few seconds after Emacs starts

(use-package saveplace
  :init (setq-default save-place t
                      save-place-file "~/.emacs.d/saveplace")
  :defer 5
  :config
  (add-hook 'find-file-hook 'save-place-find-file-hook t)
  (add-hook 'kill-emacs-hook 'save-place-kill-emacs-hook)
  (add-hook 'kill-buffer-hook 'save-place-to-alist))

;;; fix up whitespace around kill and yanking (package seems to be
;;; unavailable for download)

(use-package smart-whitespace-comment-fixup :disabled t :ensure
  ;; the advice that this package applies to indent-for-tab-command
  ;; uses a function (line-matches) which doesn't seem to exist
  :config (ad-deactivate 'indent-for-tab-command))

;;; more useful unique buffer names

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

;;; OpenWith

(use-package openwith
  :ensure
  :commands openwith-mode

  :demand
  :config (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 100MB)

(setq large-file-warning-threshold 100000000)

;;; doc-view

(use-package doc-view
  :init (setq doc-view-resolution 150
              doc-view-continuous t)
  :config (add-hook 'doc-view-mode-hook 'auto-revert-mode))

;;; magit

(use-package magit
  :ensure
  :diminish magit-auto-revert-mode
  :demand
  :config

  (setq magit-completing-read-function 'magit-ido-completing-read)

  ;; C-c C-a to amend without any prompt
  (defun magit-just-amend ()
    (interactive)
    (save-window-excursion
      (magit-with-refresh
       (shell-command "git --no-pager commit --amend --reuse-message=HEAD"))))

  (bind-key "C-c C-a" 'magit-just-amend magit-status-mode-map)

  (use-package magit-annex :ensure)

  (use-package magit-wip
    :disabled t
    :diminish magit-wip-save-mode
    :config (global-magit-wip-save-mode 1)))

;;; pointback mode: make sure that point is back where I left it when
;;; switching between buffers where at least one buffer is displayed
;;; in more than one window

(use-package pointback
  :ensure
  :commands global-pointback-mode
  :defer 5
  :config
  (global-pointback-mode 1))

;;; colour those parentheses

(setq-default frame-background-mode 'dark)
(use-package rainbow-delimiters
  :ensure
  :commands rainbow-delimiters-mode)

;;; and colour those colours

(use-package rainbow-mode
  :ensure
  :commands rainbow-mode
  :init
  (add-hook 'html-mode-hook 'rainbow-mode)
  (add-hook 'css-mode-hook 'rainbow-mode))

;;; keep reindenting lisp

(use-package aggressive-indent
  :ensure
  :commands aggressive-indent-mode)

;;; ElDoc and rainbow delimiters activation

(dolist (hook '(emacs-lisp-mode-hook
                lisp-mode-hook
                lisp-interaction-mode-hook
                ielm-mode-hook
                scheme-mode-hook
                inferior-scheme-mode-hook))
  (add-hook hook
            (lambda ()
              (eldoc-mode 1)
              (aggressive-indent-mode 1)
              (rainbow-delimiters-mode 1))))

;;; boxquotes

(use-package boxquote
  :ensure
  :commands (boxquote-title
             boxquote-region
             boxquote-buffer
             boxquote-insert-file
             boxquote-insert-buffer
             boxquote-kill-ring-save
             boxquote-yank
             boxquote-defun
             boxquote-paragraph
             boxquote-boxquote
             boxquote-describe-function
             boxquote-describe-variable
             boxquote-describe-key
             boxquote-shell-command
             boxquote-where-is
	     boxquote-text
             boxquote-narrow-to-boxquote
             boxquote-narrow-to-boxquote-content
             boxquote-kill
             boxquote-fill-paragraph
             boxquote-unbox-region
             boxquote-unbox))

;;; word count in modeline, when I want it

(use-package wc-mode :ensure)

;;; company-mode for smart and easy completion

(use-package company
  :ensure
  ;; :commands global-company-mode
  ;; :bind ("<tab>" . company-complete)
  ;; :idle (global-company-mode)
  :diminish company-mode
  :config

  ;; startup company

  (defun spw/company-prog-setup ()
    "Setup company mode carefully when its needed, rather than using the brash global-company-mode"
    (company-mode 1)
    (define-key (current-local-map) (kbd "M-/") 'company-complete)
    )
  (add-hook 'prog-mode-hook 'spw/company-prog-setup)
  ;; alternative approach: https://github.com/company-mode/company-mode/issues/94#issuecomment-40884387

  ;; I like my C-w binding so move one of company's bindings
  (define-key company-active-map "\C-w" nil)
  (bind-key "M-o" 'company-show-location company-active-map)

  ;; settings

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

  (add-to-list 'company-backends 'company-capf)
  (add-to-list 'company-transformers 'company-sort-by-occurrence)

  ;; python code completion

  (use-package anaconda-mode
    :disabled t
    :ensure
    :config (progn
              (add-hook 'python-mode-hook 'anaconda-mode)
              (add-to-list 'company-backends 'company-anaconda)
              (add-hook 'python-mode-hook 'anaconda-eldoc))))
;; 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

;;; Randomize the order of lines in a region

(use-package randomize-region :commands randomize-region)

;;; Markdown mode

(use-package markdown-mode
  :ensure
  :mode "\\.md"

  :init
  (add-hook 'markdown-mode-hook 'turn-on-orgstruct)
  (add-hook 'markdown-mode-hook 'turn-on-orgstruct++)

  :config
  ;; This binding replaces a `markdown-export'.
  (bind-key "C-c C-c e" 'spw/pandoc-paper-compile markdown-mode-map))

;;; PHP mode

(use-package php-mode :ensure :mode (("\\.php" .  php-mode)))

;;; AHK mode

(use-package ahk-mode
  :mode "\\.ahk"
  :init (setq ahk-syntax-directory "c:/Program Files/AutoHotKey/Extras/Editors/Syntax"))

;;; Deft

(use-package deft
  :ensure
  :commands deft
  :init (setq deft-extension "org"
              deft-text-mode 'org-mode
              deft-directory "~/doc/org/"
              deft-use-filename-as-title nil
              deft-auto-save-interval 20.0
              deft-incremental-search t
              ;; don't just strip the leading hash but the whole #+TITLE:
              deft-strip-title-regexp "\\(?:\\#\\+TITLE\\: \\|\\#\\+FILETAGS\\: \\|^%+\\|^[#* ]+\\|-\\*-[[:alpha:]]+-\\*-\\|#+$\\)")
  :config
  (bind-key "C-w" 'deft-filter-decrement-word deft-mode-map)

  (defadvice deft (before persp-deft activate)
    (projectile-persp-switch-project "~/doc"))

  (defadvice deft-new-file (after insert-org-TITLE activate)
    (save-excursion
      (goto-char (point-min))
      (insert "#+TITLE: "))))

;;; The following two python packages seem to be unavailable for
;;; download.  Disable them for now.

;;; allow lisp to interact with python

(use-package pymacs :disabled t :ensure)

;;; Get Python documentation as info files

(use-package python-info :disabled t :ensure)
;;(use-package pydoc-info :ensure)

;;; flycheck

(use-package flycheck
  :ensure
  :defer 5
  :init
  ;; try to disable flymake; having both running at the same time is annoying
  (setq flymake-allowed-file-name-masks nil)
  :config
  (global-flycheck-mode 1))

;;; TRAMP

(use-package tramp
  :config

  ;; plink on Windows
  (setq tramp-default-method "plink")
  (setq tramp-auto-save-directory "C:/Users/swhitton/AppData/Local/Temp")

  (add-to-list 'tramp-default-user-alist '(nil "sdf" "spw"))
  (add-to-list 'tramp-default-user-alist '("sudo" "localhost" "root"))
  (add-to-list 'tramp-default-user-alist '(nil nil "swhitton") t)
  (add-to-list 'tramp-default-user-alist '(nil "ma" "spw"))
  (add-to-list 'tramp-default-user-alist '(nil "sage" "spwhitton"))

  ;; TRAMP and zsh are not friends so might as well switch
  ;; over here
  (setenv "SHELL" "/bin/bash"))

;;; ebib for editing BiBTeX databases

(use-package ebib
  :ensure
  :bind ("C-c g e" . ebib)
  :init
  (defadvice ebib (before spw/persp-ebib activate)
    (persp-switch "ebib"))
  (setq ebib-preload-bib-files '("~/doc/spw.bib")))

;;; dired enhancements

(setq dired-recursive-deletes 'always
      dired-recursive-copies 'always
      dired-dwim-target t)

;; should be able to unzip with Z
(eval-after-load "dired-aux"
  '(add-to-list 'dired-compress-file-suffixes
                '("\\.zip\\'" ".zip" "unzip")))

(use-package dired-sort-map
  :init (setq dired-listing-switches "--group-directories-first -alh"))

(use-package git-annex :ensure)

;;; simple concept of projects

(use-package projectile
  :ensure
  :commands projectile-vc
  :demand
  :config
  (projectile-global-mode 1)
  (setq projectile-switch-project-action 'projectile-dired
        projectile-completion-system 'ido)
  (diminish 'projectile-mode))

(use-package persp-projectile :ensure)

(use-package perspective
  :ensure
  :commands (persp-toggle persp-switch)
  :demand
  :config
  (setq persp-modestring-dividers '("" "" "|"))

  ;; activate persp mode, but don't activate it if it's
  ;; already active cos this removes all existing perspectives
  ;; which is annoying
  (unless persp-mode
    (persp-mode))

  (defun persp-toggle (arg)
    (interactive "P")
    (if arg (call-interactively 'persp-switch)
      (persp-switch (persp-find-some))))

  ;; save and restore a base window configuration ala
  ;; workgroups.el.  Designed to handle the perennial Emacs
  ;; problem of Emacs totally screwing up your windows in the
  ;; middle of your work
  (setq persp-basewcs nil)
  (defun persp-basewc-save ()
    (interactive)
    (let* ((name (persp-name persp-curr))
           (wc (current-window-configuration))
           (pair (cons name wc)))
      (setq persp-basewcs
            (remove* name persp-basewcs
                     :test 'equal :key 'car))
      (add-to-list 'persp-basewcs pair)))
  ;; Save when opening a perspective.
  (add-hook 'persp-created-hook 'persp-basewc-save)
  ;; Also do a save of the basewc after
  ;; `projectile-persp-switch-project' (I never use
  ;; `projectile-switch-project' directly) switches to dired
  ;; as this is a more sensible initial basewc to go back to.
  (add-hook 'projectile-switch-project-hook 'persp-basewc-save)
  (defun persp-basewc-restore ()
    (interactive)
    (let* ((name (persp-name persp-curr))
           (pair (assoc name persp-basewcs))
           (wc (cdr pair)))
      (set-window-configuration wc))))

;; completion with ido

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

(setq ido-use-filename-at-point 'guess
      ido-create-new-buffer 'always
      ido-file-extensions-order '(".org" ".tex" ".py" )
      ido-default-file-method 'selected-window
      ido-max-directory-size 100000
      ido-auto-merge-delay-time 99999 ; only search when I tell you to M-s
      ido-use-virtual-buffers t
      ido-use-virtual-buffers-automatically t
      ido-enable-regexp nil
      ido-use-url-at-point nil
      ido-max-file-prompt-width 0.1
      ido-save-directory-list-file "~/.emacs.d/ido.last"

      ;; Have Ido respect completion-ignored-extensions
      ido-ignore-extensions t

      ;; When moving through work directories with M-n/M-p, ignore those
      ;; that don't match the current input
      ido-work-directory-match-only t)

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

(use-package flx-ido
  :ensure
  :config
  (flx-ido-mode 1)
  (setq ido-enable-flex-matching t
        ido-use-faces nil
        flx-ido-threshhold 7500
        gc-cons-threshold 20000000))

(use-package ido-ubiquitous
  :ensure
  :config
  (ido-ubiquitous-mode 1))

;; (use-package ido-vertical-mode
;;   :ensure
;;   :init (ido-vertical-mode 1))

(use-package smex
  :ensure
  ;; TODO: get keyboard macro bindings, that vanilla emacs has under
  ;; the prefix C-x C-m, back
  :bind ("C-x C-m" . smex))

;; imenu

(use-package imenu-anywhere :ensure)

;;; use Helm for a few things

(use-package helm
  :ensure
  :defer 5
  :config
  (use-package helm-mode
    :bind ("M-s o" . helm-occur))
  (use-package helm-descbinds
    :ensure
    :defer 5
    :config
    (helm-descbinds-mode)))

;;; I don't want to have to use the start menu

(use-package helm-w32-launcher
  :ensure
  :bind ("C-c z" . helm-w32-launcher))

;;; snippets

(use-package yasnippet
  :ensure
  :diminish yas-minor-mode

  :defer 5
  :config
  (yas-global-mode 1))

;;; htmlize for Org HTML export/publishing

(use-package htmlize :ensure)

;;; close old buffers once per day

(use-package midnight
  :init (midnight-delay-set 'midnight-delay "3am"))

;;; make indentation in python nice and visible

(use-package highlight-indentation
  :ensure
  :init
  (add-hook 'python-mode-hook 'highlight-indentation-current-column-mode))

;;; jump around what's visible

(use-package ace-jump-mode
  :ensure
  ;; :bind ("M-o" . ace-jump-mode)
  ;; :config

  ;; make `ace-jump-mode' respect dired-isearch-filenames
  ;; from https://www.reddit.com/r/emacs/comments/2x3mke/making_acejump_play_nice_with_dired/
  ;; (add-hook 'dired-mode-hook
  ;;           (lambda ()
  ;;             (setq-local ace-jump-search-filter
  ;;                         (lambda ()
  ;;                           (get-text-property (point) 'dired-filename)))))

  )

(use-package avy
  :ensure
  :bind ("M-o" . spw/avy-goto-word)
  :config

  ;; Make avy overlays look more like ace-jump
  (setq avy-style 'at-full)

  ;; Attempt to restore ace-jump-mode functionality whereby M-o jumps
  ;; by word start, C-u M-o by any char in the word.  We're taking the
  ;; input ourselves so that `avy-goto-word-1' doesn't see arg and
  ;; thus narrow to the current window
  (defun spw/avy-goto-word (char &optional arg)
    (interactive (list (read-char "char: ")
                       current-prefix-arg))
    (if arg (avy-goto-char char nil)
      (avy-goto-word-1 char nil))))

;;; use ace-jump-mode to move between links in help file

(use-package ace-link
  :ensure
  :defer 5
  :config
  (ace-link-setup-default))

;;; chat on Jabber

(use-package jabber
  :disabled t
  :ensure
  :config (progn (when (f-exists? "~/.emacs.d/init-jabber.el")
                   (load-file "~/.emacs.d/init-jabber.el")
                   (jabber-connect-all))
                 (defun spw/persp-jabber ()
                   (interactive)
                   (persp-switch "xmpp"))
                 ;; TODO: when have Emacs 24.4 everywhere, switch this
                 ;; to nadvice.el macros
                 (defadvice jabber-activity-switch-to (before spw/persp-jabber activate)
                   (spw/persp-jabber))
                 (defadvice jabber-switch-to-roster-buffer (before spw/persp-jabber activate)
                   (spw/persp-jabber))
                 (defadvice jabber-chat-with (before spw/persp-jabber activate)
                   (spw/persp-jabber))))

;;; make dired copy and move asynchronously

(use-package async
  :disabled t
  :ensure
  :init (when (require 'dired-aux)
          (require 'dired-async)))

;;; give dired some nice keybindings for browsing images

(use-package image-dired
  :init (image-dired-setup-dired-keybindings))

;;; allow Emacs to resize images: keybinding S f

(use-package eimp
  :disabled t
  :ensure
  :init (add-hook 'image-mode-hook 'eimp-mode))

;;; alternative to my old `spw/centre-window'

(use-package centered-window-mode :commands centered-window-mode)

;;; IRC client, for when I need it

(use-package rcirc
  :config (progn
            ;; basic settings
            (setq rcirc-default-nick "seanw"
                  rcirc-default-user-name user-login-name
                  rcirc-default-full-name user-full-name)

            ;; networks and channels
            (setq rcirc-server-alist nil)
            (add-to-list 'rcirc-server-alist
                         '("chat.freenode.net" :port 6697 :encryption tls
                           :channels ("#freenode-social")))

            ;; authentication data
            (when (f-exists? "~/.emacs.d/init-rcirc.el")
              (load-file "~/.emacs.d/init-rcirc.el"))))

;;; zap-up-to-char is at least as useful as zap-to-char, so load it
;;; out of misc.el.  Don't need M-m binding as have smarter C-a

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

;;; make Emacs regexps easier

(use-package visual-regexp :ensure)

;;; toggle quotes for when I fail to follow the style guidelines

(use-package toggle-quotes
  :ensure
  :bind ("C-c t '" . toggle-quotes))

;;; have M-w and C-xC-k work on the whole line when region is inactive

(use-package whole-line-or-region
  :ensure
  :diminish whole-line-or-region-mode
  :defer 5
  :config
  (whole-line-or-region-mode 1))

(use-package hydra
  :ensure
  :config
  (setq hydra-windows-config nil)
  (defun spw/maybe-delete-other-windows ()
    (interactive)
    (if (= (count-windows) 1)
        (set-window-configuration hydra-windows-config)
      (setq hydra-windows-config (current-window-configuration))
      (delete-other-windows)))
  (defhydra hydra-windows (global-map "C-x" :color red)
    "windows"
    ("o" other-window "next" :color red)
    ("O" (lambda () (interactive) (other-window -1)) "previous" :color red)
    ("S" spw/toggle-window-split "toggle" :color red)
    ("0" delete-window "del" :color red)
    ("1" spw/maybe-delete-other-windows "max" :color red)
    ("2" split-window-below "horiz" :color red)
    ("3" split-window-right "vert" :color red))

  ;;; winner mode: undo window configuration changes

  (winner-mode 1)

  ;; Undo the bindings so that the hydra bindings take precedence
  (define-key winner-mode-map (kbd "C-c <left>") nil)
  (define-key winner-mode-map (kbd "C-c <right>") nil)

  (defhydra hydra-winner (global-map "C-c" :color red)
    "winner"
    ("<left>" winner-undo "back" :color red)

    ;; We need a lambda here to override `winner-redo''s check that
    ;; the last command was winner-undo, since the last command will
    ;; be `hydra-winner/winner-undo' if we replace the lambda with
    ;; just `winner-undo'
    ("<right>" (lambda () (interactive)
                 (let ((last-command 'winner-undo))
                   (winner-redo))) "forward" :color red)))

;;; aligning rule for Haskell adapted from Haskell mode wiki

(use-package align
  :config
  (add-to-list 'align-rules-list
               '(haskell-defns
                 (regexp . "\\(\\s-+\\)\\(::\\|∷\\|=\\)\\s-+")
                 (modes quote (haskell-mode literate-haskell-mode))))
  (add-to-list 'align-rules-list
               '(haskell-arrows
                 (regexp . "^[^:\n]+\\(\\s-+\\)\\(->\\)\\s-+")
                 (modes quote (haskell-mode literate-haskell-mode))))
  (add-to-list 'align-rules-list
               '(haskell-left-arrows
                 (regexp . "\\(\\s-+\\)\\(<-\\|←\\)\\s-+")
                 (modes quote (haskell-mode literate-haskell-mode)))))

;;; edit .nix files

(use-package nix-mode :ensure)

;;; Haskell (load after packages that it depends on)

(load "~/.emacs.d/init-haskell.el")

;; key-chord to save my hands

(use-package key-chord
  :ensure
  :init (key-chord-mode 1))

;;; god-mode to maybe save my hands

(use-package god-mode
  :ensure
  :config
  ;; (unless god-global-mode (god-mode))

  ;; activate with a key-chord to avoid having to have
  ;; capslock bound to both escape and control
  (key-chord-define-global "hj" 'god-mode-all)

  ;; just a little vi in god-mode
  (define-key god-local-mode-map (kbd ".") 'repeat)
  (define-key god-local-mode-map (kbd "i") 'god-mode-all)

  ;; change a part of the modeline depending on whether in god-mode
  (defun spw/god-mode-update-modeline ()
    (set-face-background 'sml/filename (if god-local-mode
                                           "red"
                                         ;; following from smart-mode-line-powerline-theme.el
                                         (or (face-background 'powerline-active1) "Grey30"))))

  (add-hook 'god-mode-enabled-hook 'spw/god-mode-update-modeline)
  (add-hook 'god-mode-disabled-hook 'spw/god-mode-update-modeline))

;; good key chords from
;; <http://www.johndcook.com/blog/2015/02/01/rare-bigrams/> via
;; <https://github.com/kaushalmodi/.emacs.d/blob/master/setup-files/setup-key-chord.el>

;; BF BG BQ BX BZ
;; CJ CV
;; DX DZ
;; FB FJ FQ FV FZ
;; GB GJ GP GQ GV GX GZ
;; HJ HQ HV
;; JJ JC JF JG JH JK JL JM JP JQ JS JT JV JW JX JY JZ
;; KK KJ KQ KV KX KZ
;; LJ LQ
;; MJ MQ MV MX MZ
;; PG PJ PQ PV PZ
;; QQ QB QF QG QH QJ QK QL QM QP QT QV QW QX QY QZ
;; SJ SX SZ
;; TJ TQ
;; VV VC VF VG VH VJ VK VM VP VQ VW VZ
;; WW WJ WQ WV WX WZ
;; XB XD XG XJ XK XM XQ XS XW XZ
;; YY YJ YQ
;; ZB ZD ZF ZG ZJ ZK ZM ZP ZQ ZS ZV ZW ZX

;;; jump back and forth to and from Emacs lisp definitions with
;;; M-. and M-, and C-c C-d [C-]d to describe

(use-package elisp-slime-nav
  :ensure
  :commands (turn-on-elisp-slime-nav-mode elisp-slime-nav-mode)
  :init (dolist (hook '(emacs-lisp-mode-hook ielm-mode-hook))
          (add-hook hook 'elisp-slime-nav-mode)))

(use-package world-time-mode)

;; and set up time zones I'm interested in

(if (eq system-type 'windows-nt)

    (setq display-time-world-list '(("MST7" "Phoenix")
                                    ("GMT0BST" "London")
                                    ("CET-1CDT" "Paris")
                                    ("KST-9" "Seoul")))

  (setq display-time-world-list '(("America/Phoenix" "Phoenix")
                                  ("Europe/London" "London")
                                  ("Europe/Paris" "Paris")
                                  ("Asia/Seoul" "Seoul"))))



;;;; ---- functions ----

(defun mwf/narrow-or-widen-dwim (p)
  "If the buffer is narrowed, it widens.  Otherwise, it narrows 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'.

With prefix P, don't widen, just narrow even if buffer is already
narrowed."
  (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)
         ;; `org-edit-src-code' is not a real narrowing command.
         ;; Remove this first conditional if you don't want it.
         (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))))

;;; toggle some features on and off to make Emacs better at prose editing

(defun spw/writing-on ()
  "Activate my prose writing features."
  (wc-mode 1)
  (variable-pitch-mode 1)
  (setq-local cursor-type 'bar)
  (unless (or (eq system-type 'windows-nt)
              (not (fboundp 'set-fringe-mode)))
    (centered-window-mode 1)
    ;; indent mode need only be turned off if we're using centered
    ;; window mode
    (when (eq major-mode 'org-mode)
      (org-indent-mode 0)))
  (if (and (or (eq system-type 'windows-nt)
               (not (fboundp 'set-fringe-mode)))
           (> (window-width) 120))
      (spw/centre-window nil)))

(defun spw/writing-off ()
  "Deactivate my prose writing features."
  (wc-mode 0)
  (variable-pitch-mode 0)
  (setq-local cursor-type 'box)
  (unless (or (eq system-type 'windows-nt)
              (not (fboundp 'set-fringe-mode)))
    (centered-window-mode 0)
    ;; indent mode need only be turned off if we're using centered
    ;; window mode
    (when (eq major-mode 'org-mode)
      ;; TODO: finesse this.  don't turn it on if it wouldn't be on by default
      (org-indent-mode 1)))
  (if (and (or (eq system-type 'windows-nt)
               (not (fboundp 'set-fringe-mode)))
           (> (window-width) 120))
      (delete-other-windows)))

(defun spw/writing-toggle ()
  "Toggle on and off my prose writing features."
  (interactive)
  (let ((activate (if (boundp 'buffer-face-mode) buffer-face-mode)))
    (if activate
        (spw/writing-off)
      (spw/writing-on))))
;; note: activate this in a whole file tree by putting
;; e.g. `((org-mode . ((eval . (spw/writing-toggle)))))` in
;; .dir-locals.el

(defun spw/eval-surrounding-sexp (levels)
  "Go up LEVELS sexps from point and eval.

Originally from http://stackoverflow.com/a/2172827"
  (interactive "p")
  (save-excursion
    (if (looking-at "(")
        (progn (forward-char 1) (eval-surrounding-sexp 1))
      (up-list (abs levels))
      (eval-last-sexp nil))))

;;; backwards and forward deletions of words

(defun spw/delete-word (arg)
  "Delete ARG characters forward until encountering the end of a word."
  (interactive "p")
  (delete-region (point) (progn (forward-word arg) (point))))

(defun spw/backward-delete-word (arg)
  "Delete characters ARG backward until encountering the end of a word."
  (interactive "p")
  (spw/delete-word (- arg)))

(bind-key "C-w" 'spw/backward-delete-word)
(bind-key "C-x C-k" 'kill-region)
(global-set-key "\M-d" 'spw/delete-word)

;;; my buffer save cleanup functions

(defun spw/delete-trailing-whitespace-except-current-line ()
  "Delete trailing whitespace on all lines except the current one.

Originally from <http://stackoverflow.com/a/3533815>."
  (interactive)
  (let ((begin (line-beginning-position))
        (end (line-end-position)))
    (save-excursion
      (when (< (point-min) begin)
        (save-restriction
          (narrow-to-region (point-min) (1- begin))
          (delete-trailing-whitespace)))
      (when (> (point-max) end)
        (save-restriction
          (narrow-to-region (1+ end) (point-max))
          (delete-trailing-whitespace))))))

(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
        (previous-line)
        (beginning-of-line)
        (when (not (looking-at ".*;.*"))
          (next-line)
          (delete-indentation))))))

(defun spw/auto-cleanup ()
  "Unoffensive automatic cleanups."
  (interactive)
  (case major-mode
    (haskell-mode
     (spw/delete-trailing-whitespace-except-current-line)
     (spw/compact-blank-lines))
    (python-mode
     (spw/delete-trailing-whitespace-except-current-line)
     (spw/compact-blank-lines))
    (message-mode
     (save-excursion
       (message-goto-body)
       (save-restriction
         (narrow-to-region (point) (point-max))
         ;; (fill-region (point-min) (point-max))
         (whitespace-cleanup))))
    (emacs-lisp-mode
     (spw/delete-trailing-whitespace-except-current-line)
     (spw/compact-blank-lines))))

(defun spw/manual-cleanup ()
  "Clean up a buffer depending on major mode.

Sufficiently aggressive clean-ups that should not be called
automatically."
  (interactive)
  (spw/auto-cleanup)
  (untabify (point-min) (point-max))
  (unless (or (not (fboundp 'aggressive-indent-mode))
              (eq major-mode 'haskell-mode)
              aggressive-indent-mode)
    (indent-region (point-min) (point-max)))
  (case major-mode
    (emacs-lisp-mode
     (spw/clean-lisp-dangling-brackets))
    (haskell-mode
     (haskell-mode-stylish-buffer))))

(add-hook 'before-save-hook 'spw/auto-cleanup)

;;; Typing Hangul

(defun spw/input-method-setup ()
  "Set up or tear down hangeul input method."
  (cond ((equal current-language-environment "English")
         (set-input-method nil))
        ((equal current-language-environment "Korean")
         (set-input-method "korean-hangul"))))
(add-hook 'set-language-environment-hook 'spw/input-method-setup)

(defun spw/toggle-language-environment ()
  "Toggle typing hangeul."
  (interactive)
  (set-language-environment
   (if (equal current-language-environment "English")
       "Korean" "English")))

;; <menu> should activate ibus Korean typing but in case we want the
;; Emacs version, bind that to S-<menu>.  Hanja key is the same as the
;; key imenu uses: Alt Gr.  I might want to use this as a compose key
;; outside of Emacs but only when Hangeul typing is disabled so it's
;; okay to find it for this purpose.

(bind-key "S-<menu>" 'spw/toggle-language-environment)
(bind-key "<Multi_key>" 'hangul-to-hanja-conversion)

;; and for Windows (shift modifier has no effect)

(bind-key "<apps>" 'spw/toggle-language-environment)
(bind-key "<kanji>" 'hangul-to-hanja-conversion)

;; kill the binding korea-utils.el seems to be setting

(global-unset-key (kbd "S-SPC"))

(defun spw/centre-window (arg)
  "Make editing window 95 cols wide and centre it in the frame.

With argument ARG, also bound it on the right."
  (interactive "P")
  (delete-other-windows)
  (split-window-horizontally)
  (if arg (split-window-horizontally))
  (shrink-window-horizontally (- (window-width) (/ (- (frame-width) 97) 2)))
  (switch-to-buffer "*blank*")
  (toggle-read-only 1)
  (setq mode-line-format nil)
  (other-window 1)
  (when arg
    (shrink-window-horizontally (- (window-width) 95))
    (other-window 1)
    (switch-to-buffer "*blank*")
    (other-window -1)))

(defun spw/toggle-window-split ()
  "Toggle the orientation of a two-window split."
  (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))))))

;;; join up setqs when editing Emacs config

(defun spw/join-setqs ()
  "Interactively join a series of setq forms into a single definition."
  (interactive)
  (open-line 1)
  (insert "(setq)")
  (next-line)
  (beginning-of-line)
  (while (looking-at "(setq")
    (call-interactively 'sp-kill-word)
    (sp-backward-sexp)
    (sp-join-sexp)
    (next-line)
    (beginning-of-line))
  (sp-backward-sexp)
  (next-line)
  (delete-indentation)
  (beginning-of-line)
  (mark-sexp)
  (indent-region (region-beginning) (region-end)))

(defun magnars/move-beginning-of-line-dwim (arg)
  "Move point back to indentation of beginning of line.

Move point to the first non-whitespace character on this line.
If point is already there, move to the beginning of the line.
Effectively toggle between the first non-whitespace character and
the beginning of the line.

If ARG is not nil or 1, move forward ARG - 1 lines first.  If
point reaches the beginning or end of the buffer, stop there."
  (interactive "^p")
  (setq arg (or arg 1))

  ;; Move lines first
  (when (/= arg 1)
    (let ((line-move-visual nil))
      (forward-line (1- arg))))

  (let ((orig-point (point)))
    (back-to-indentation)
    (when (= orig-point (point))
      (move-beginning-of-line 1))))

(defun magnars/copy-to-end-of-line ()
  "Save from point to end of line to keyring."
  (interactive)
  (kill-ring-save (point)
                  (line-end-position))
  (message "Copied to end of line"))
(defun magnars/copy-whole-lines (arg)
  "Copy ARG lines to the kill ring."
  (interactive "p")
  (kill-ring-save (line-beginning-position)
                  (line-beginning-position (+ 1 arg)))
  (message "%d line%s copied" arg (if (= 1 arg) "" "s")))
(defun magnars/copy-line (arg)
  "Copy to end of line.

If ARG, just copy that many lines."
  (interactive "P")
  (if (null arg)
      (magnars/copy-to-end-of-line)
    (magnars/copy-whole-lines (prefix-numeric-value arg))))
(defun magnars/kill-ring-save-dwim (arg)
  "If region active, save it.  Otherwise, save to end of line.

If ARG and region inactive, save that many lines."
  (interactive "P")
  (if (region-active-p)
      (kill-ring-save (region-beginning) (region-end))
    (magnars/copy-line arg)))

;;; 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))
            (replace-regexp key value)))))

(defun prelude/eval-and-replace ()
  "Replace the preceding sexp with its value."
  (interactive)
  (backward-kill-sexp)
  (condition-case nil
      (prin1 (eval (read (current-kill 0)))
             (current-buffer))
    (error (message "Invalid expression")
           (insert (current-kill 0)))))

(defun magnars/new-line-dwim ()
  "Smart way to open lines below.  Originally by magnars."
  (interactive)
  (let* ((break-open-pair (or (and (looking-back "{" 1) (looking-at "}"))
                              (and (looking-back ">" 1) (looking-at "<"))
                              (and (looking-back "(" 1) (looking-at ")"))
                              ;; we always break out in elisp since
                              ;; it's easier to see for writing code,
                              ;; and then my cleanup function will
                              ;; handle the dangling parentheses
                              (and (eq major-mode 'emacs-lisp-mode)
                                   (looking-at ")"))
                              (and (looking-back "\\[" 1) (looking-at "\\]"))))
         (break-open-list (and (eq major-mode 'org-mode)
                               (not break-open-pair))))
    (if break-open-list
        (org-meta-return)
      (newline)
      (when break-open-pair
        (save-excursion
          (newline)
          (indent-for-tab-command))))
    (indent-for-tab-command)))

;;; my functions for a very useful eshell

(defun evil/resize-window (new-size &optional horizontal)
  "Set the current window's with or height to NEW-SIZE.

With optional argument HORIZONTAL, change the horizontal size instead.

Originally from evil's `evil-window.el'."
  (let ((wincfg (current-window-configuration))
        (nwins (length (window-list)))
        (count (if horizontal
                   (- new-size (window-width))
                 (- new-size (window-height)))))
    (catch 'done
      (save-window-excursion
        (while (not (zerop count))
          (if (> count 0)
              (progn
                (enlarge-window 1 horizontal)
                (setq count (1- count)))
            (progn
              (shrink-window 1 horizontal)
              (setq count (1+ count))))
          (if (= nwins (length (window-list)))
              (setq wincfg (current-window-configuration))
            (throw 'done t)))))
    (set-window-configuration wincfg)))

(defun spw/small-vertical-split (&optional height)
  "Make a HEIGHT-lines vertical split.  HEIGHT defaults to 8."
  (interactive)
  (let ((split-height (or height 8)))
    (split-window-vertically)
    (other-window 1)
    (evil/resize-window split-height)))

(defun spw/persp-eshell (arg)
  "Switch to perspective's eshell or create it.

With arg ARG, put shell in current window."
  (interactive "P")
  (let* ((in-project (and (projectile-project-p)
                          (not (equal (persp-name persp-curr) "main"))))
         (correct-eshell-name (if in-project
                                  (concat "*eshell* (" (persp-name persp-curr) ")")
                                "*eshell"))
         (eshell-window (get-buffer-window correct-eshell-name))
         (cd-to default-directory))
    ;; first check if eshell already visible
    (if eshell-window
        (select-window eshell-window)
      ;; create split
      (unless arg (spw/small-vertical-split))
      ;; switch to buffer
      (if in-project
          ;; we're in a project: name buffer carefully
          (if (get-buffer correct-eshell-name)
              (switch-to-buffer correct-eshell-name)
            (eshell "a")
            (rename-buffer correct-eshell-name))
        ;; we're not in a project: don't
        (if (get-buffer "*eshell*")
            (switch-to-buffer "*eshell*")
          (call-interactively 'eshell))))
    ;; now change current dir and position the cursor
    (end-of-buffer)
    (eshell-bol)
    (ignore-errors (kill-line))
    (unless (string= default-directory cd-to)
      (insert (concat "cd " cd-to))
      (eshell-send-input))))

(defun spw/dired-jump (arg)
  "Call `dired-jump'.  Unless ARG, in a small vertical split."
  (interactive "P")
  (if arg
      (dired-jump)
    (spw/small-vertical-split 10)
    (let ((dired-name (buffer-file-name)))
      (dired-jump nil dired-name))))

;;; Sariul functions

(defun spw/tblesson (grade lesson period)
  "Start a textbook-based lesson plan for grade GRADE, lesson LESSON, period PERIOD."
  (interactive "sGrade: \nsGrade %s, lesson: \nsGrade %s, lesson %s, period: ")
  (let* ((read-only (not (string= (system-name) "SPWHITTON")))
         (teaching (if read-only "s:/" "~/Documents/Teaching"))
         (parent (f-join teaching grade lesson))
         (path (f-join teaching grade lesson period))
         (name (f-join path (concat grade "-" lesson "-" period ".org"))))
    (if (not read-only)
        (projectile-persp-switch-project teaching)
      (persp-switch "Teaching")
      (dired teaching))
    (when (and (not (f-exists? name))
               (not read-only))
      (f-mkdir parent)
      (f-mkdir path))
    (if read-only
        (dired (f-dirname name))
      (find-file name))
    (when (and (not (f-exists? name))
               (not read-only))
      (insert "tblesson")
      ;; (if evil-mode (evil-append-line 1))
      (yas-expand))))

(defun spw/textbook (grade lesson)
  "Open the textbook's accompanying CD for grade GRADE and lesson LESSON."
  (interactive "sGrade: \nsGrade %s, lesson: ")
  (let* ((g (string-to-number grade))
         (l (string-to-number lesson))
         (cd (if (and (<= g 4) (<= l 7))                "1"
               (if (and (<= g 4) (> l 7))               "2"
                 (if (and (>= g 5) (<= l 5))            "1"
                   (if (and (>= g 5) (> l 5) (<= l 10)) "2"
                     (if (and (>= g 5) (> l 10))        "3"))))))
         (circle (if (= g 3) "①" "②"))
         (path (if (<= g 4)
                   (concat "C:\\e-Book\\start\\초등영어\\3~4학년군 영어 "
                           circle " 지도서_CD " cd "\\start.exe")
                 (concat "D:\\Textbook CDs\\Grade "
                         grade "\\CD" cd "\\start.exe"))))
    (call-process path nil 0)))

(defun spw/teachers-book (grade lesson)
  "Open the textbook's teacher's guide for grade GRADE and lesson LESSON."
  (interactive "sGrade: \nsGrade %s, lesson: ")
  (let* ((lesson-string (if (<= (string-to-number grade) 4)
                            (concat "_" lesson "단")
                          (concat "L" lesson "-")))
         (path (car (f-glob (concat "D:\\Teacher's guides\\*" grade "]*" lesson-string "*.pdf")))))
    (find-file path)))

(defun spw/auto-textbook ()
  "Call `spw/textbook', guessing appropriate arguments from current directory."
  (interactive)
  (let* ((path (split-string default-directory "/"))
         (grade (car (last path 4)))
         (lesson (car (last path 3))))
    (spw/textbook grade lesson)))

(defun spw/auto-teachers-book ()
  "Call `spw/teachers-book', guessing appropriate arguments from current directory."
  (interactive)
  (let* ((path (split-string default-directory "/"))
         (grade (car (last path 4)))
         (lesson (car (last path 3))))
    (spw/teachers-book grade lesson)))

(defun spw/persp-clone (new-name)
  "Clone current perspective with the name NEW-NAME."
  (interactive "sNew name: \n")
  (make-persp
    :name new-name
    :buffers (persp-buffers persp-curr)
    :window-configuration (current-window-configuration))
  (persp-switch new-name))

(defun spw/align-dwim ()
  "Align, if region inactive first mark paragraph."
  (interactive)
  (if (region-active-p)
      (let ((align-region-separate 'entire))
        (call-interactively 'align))
    (save-excursion
      (mark-paragraph)
      (call-interactively 'align))))

(defun crowding/local-set-minor-mode-key (mode key def)
  "Overrides a minor mode MODE's binding to KEY with DEF for the local buffer.

Does this by creating or altering keymaps stored in buffer-local
`minor-mode-overriding-map-alist'.

From <http://stackoverflow.com/a/14769115>."
  (let* ((oldmap (cdr (assoc mode minor-mode-map-alist)))
         (newmap (or (cdr (assoc mode minor-mode-overriding-map-alist))
                     (let ((map (make-sparse-keymap)))
                       (set-keymap-parent map oldmap)
                       (push `(,mode . ,map) minor-mode-overriding-map-alist)
                       map))))
    (define-key newmap key def)))

(defun spw/set-from-address ()
  "Set e-mail from address correctly by looking at other headers."
  (interactive)
  (save-excursion
    (message-narrow-to-headers)
    (goto-char (point-min))
    (when (or (search-forward-regexp "^To:.*arizona.edu" nil t)
              (search-forward-regexp "^Cc:.*arizona.edu" nil t)
              (search-forward-regexp "^Bcc:.*arizona.edu" nil t))
      (goto-char (point-min))
      (search-forward-regexp "^From:.*$")
      (replace-match "From: Sean Whitton <spwhitton@email.arizona.edu>"))
    (widen)))

;;; Find and open projects in ~/src/ that aren't yet known to
;;; projectile.  Inspired by
;;; <https://alanpearce.uk/post/opening-projects-with-projectile>.

(defvar 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)))

(defun spw/pandoc-paper-compile ()
  "Compile a paper to PDF with pandoc.

Lightweight alternative to pandoc-mode."
  (interactive)
  (when (and (string= default-directory (expand-file-name "~/doc/papers/"))
             (eq major-mode 'markdown-mode))
    (let ((output-file (f-join "~/tmp" (f-filename (f-swap-ext (buffer-file-name) "pdf")))))
      (call-process-shell-command
       "pandoc" nil "*pandoc output*" nil
       "-s" "--filter" "pandoc-citeproc" (concat "--bibliography=" (expand-file-name "~/doc/spw.bib"))
       "--template" "pessay" "-V" "documentclass=pessay"
       (buffer-file-name) "-o" output-file)
      (find-file output-file))))



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

;;; no tabs please

(setq-default indent-tabs-mode nil)

;;; key bindings

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

;; opening new lines below
(bind-key "M-RET" 'magnars/new-line-dwim)

;; `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.
(bind-key "RET" 'newline-and-indent)

;; fixup-whitespace seems to make just-one-space redundant
(bind-key "M-SPC" 'fixup-whitespace)

;; never want to send any e-mail
(unbind-key "C-x m")

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

;; smart versions of C-a, M-w from magnars
(bind-key "C-a" 'magnars/move-beginning-of-line-dwim)
(bind-key "M-w" 'magnars/kill-ring-save-dwim)

;;; bind all up into the C-c keymap

(setq spw/personal-map (make-sparse-keymap))
(key-chord-define-global "jk" spw/personal-map)

(defmacro spw/C-c-bind (key bindee)
  "Bind BINDEE to C-c KEY with `bind-key' macro.

BINDEE may be a command or another keymap, but whatever it is, it should not be quoted."
  `(if (keymapp ,bindee)
       (progn
         (bind-key (concat "C-c " ,key) ,bindee)
         (define-key spw/personal-map (kbd ,key) ,bindee))
     (bind-key (concat "C-c " ,key) bindee)
     (define-key spw/personal-map (kbd ,key) bindee)))

(setq spw/personal-bindings
      '(("p" . projectile-command-map)
        ;; ("j" . projectile-find-file-dwim)
        ("j" . projectile-find-file)
        ("v" . projectile-vc)
        ("n" . mwf/narrow-or-widen-dwim)
        ("s" . spw/persp-eshell)
        ("d" . spw/dired-jump)
        ("f" . deft)
        ("a" . spw/align-dwim)
        ("A" . align-regexp)
        ("l" . persp-toggle)
        ("L" . persp-switch)

        ;; perspectives map
        ("q s" . persp-switch)
        ("q k" . persp-remove-buffer)
        ("q c" . persp-kill)
        ("q r" . persp-rename)
        ("q a" . persp-add-buffer)
        ("q A" . persp-set-buffer)
        ("q i" . persp-import)
        ("q n" . persp-next)
        ("q <right>" . persp-next)
        ("q p" . persp-prev)
        ("q <left>" . persp-prev)
        ("q u" . persp-basewc-save)
        ("q q" . persp-basewc-restore)
        ("q C" . spw/persp-clone)
        ("q o" . spw/open-programming-project)

        ;; Org-mode map
        ("o c" . org-capture)
        ("o l" . org-store-link)
        ("o a" . org-agenda)
        ("o [" . spw/org-agenda-file-to-front)
        ("o ]" . spw/org-remove-file)

        ;; launcher map
        ("g k" . kill-emacs)
        ("g c" . spw/manual-cleanup)
        ("g l" . spw/tblesson)
        ("g r" . (lambda ()
                   (interactive)
                   (projectile-persp-switch-project "~/src/dotfiles")
                   (find-file "~/src/dotfiles/.emacs.d/init.el")
                   (eval-buffer)))

        ("g t l" . world-time-list)
        ("g t h" . helm-world-time)
        ("g t t" . display-time-world)

        ;; Sariul launcher map
        ("S l" . spw/tblesson)
        ("S S" . spw/auto-textbook)
        ("S s" . spw/textbook)
        ("S t" . spw/auto-teachers-book)

        ;; toggle map
        ("t e" . toggle-debug-on-error)
        ("t i" . org-indent-mode)
        ("t w" . spw/writing-toggle)

        ;; insertion map
        ("i h" . add-file-local-variable-prop-line)

        ;; evaluation map
        ("e e" . spw/eval-surrounding-sexp)
        ("e f" . eval-defun)
        ("e r" . eval-region)
        ("e b" . eval-buffer)
        ("E" . prelude/eval-and-replace)))

(defun spw/personal-bindings ()
  (interactive)
  (dolist (pair spw/personal-bindings)
    (let ((key (car pair))
          (bindee (cdr pair)))
      (spw/C-c-bind key bindee))))

(spw/personal-bindings)

;;; abbreviations

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

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

;;; 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
  (defadvice bookmark-write-file (before save-bookmarks-buffer activate)
    (if (get-buffer "emacs-bookmarks")
        (with-current-buffer (get-buffer "emacs-bookmarks")
          (save-buffer))))
  (defadvice kill-buffer (before kill-buffer-clear-modified activate)
    (if (get-buffer "emacs-bookmarks")
        (with-current-buffer (get-buffer "emacs-bookmarks")
          (set-buffer-modified-p nil)))))

;;; miscellaneous personal settings

;; isearch should leave you at the beginning of the match
(add-hook 'isearch-mode-end-hook 'spw/isearch-match-beginning)
(defun spw/isearch-match-beginning ()
  "Move point to beginning of isearch match."
  (when isearch-other-end
    (when isearch-forward (goto-char isearch-other-end))))

;; 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)

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

;; mark settings
(setq transient-mark-mode t
      set-mark-command-repeat-pop t)

;; recursive minibuffers
(setq enable-recursive-minibuffers t)

;; 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 "C:\\Program Files\\Mozilla Firefox\\firefox.exe"
      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
      x-select-enable-primary nil
      x-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)
(setq ido-default-buffer-method 'selected-window)

;; 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)

;;; avoid some prompts when saving all buffers

(defun spw/save-org-buffers-first (&optional arg pred)
  "Save all Org buffers without prompting.

ARG, PRED ignored."
  (when (featurep 'org)
    ;; gotta remove ourselves since `org-save-all-org-buffers' calls
    ;; `save-some-buffers'
    (advice-remove 'save-some-buffers #'spw/save-org-buffers-first)
    (org-save-all-org-buffers)
    (advice-add 'save-some-buffers :before #'spw/save-org-buffers-first)))

;; no `advice-add' on Emcas 24.3 on ma
(if (fboundp 'advice-add)
    (advice-add 'save-some-buffers :before #'spw/save-org-buffers-first))



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

;;; auto fill comments in modes with a reliable comment syntax

(defun spw/turn-on-comment-filling ()
  "Turn on filling comments."
  (setq-local comment-auto-fill-only-comments t)
  (auto-fill-mode 1))
(add-hook 'emacs-lisp-mode-hook 'spw/turn-on-comment-filling)

;;; mail mode for mutt

(use-package message
  :mode ("/mutt-.*$" . message-mode)
  :init (progn
          (defadvice message-newline-and-reformat (before spw/delete-superflous-newlines activate)
            "Have `message-newline-and-reformat' get rid of some more superflous blank quoted lines."
            (save-excursion
              (beginning-of-line)
              (when (looking-at ">[[:space:]]*$")
                (kill-line 1))))
          (setq mail-header-separator "")
          (add-hook 'message-mode-hook (lambda ()
                                         (auto-fill-mode)
                                         (spw/set-from-address)
                                         (footnote-mode)
                                         (message-goto-body)))))

(defun djcb/snip (b e summ)
  "Replace region B to E with SUMM like this: [snip:summary (n lines)]."
  (interactive "r\nsSummary:")
  (let ((n (count-lines b e)))
    (delete-region b e)
    (insert (format "[snip%s (%d line%s)]"
                    (if (= 0 (length summ)) "" (concat ": " summ))
                    n
                    (if (= 1 n) "" "s")))))

;;; IELM

(setq ielm-dynamic-return nil)

;;; text mode

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

;;; dired

(use-package dired-x)
(setq-default dired-omit-mode t)
(setq dired-omit-files "^\\...+$")
(setq dired-isearch-filenames 'dwim)

;; dired omit mode mapping conflicts with my ace jump mode
;; binding
(define-key dired-mode-map (kbd "M-o") 'nil)
(bind-key "C-c g o" 'dired-omit-mode dired-mode-map)

;;; 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?$" "." "C:\\Program Files\\Mozilla Firefox\\firefox.exe %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)
(put 'narrow-to-region 'disabled nil)

;;; 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))))

;;; eshell prompt

;; from the Emacs Wiki [[EshellPrompt]]
(defun fish-path (path max-len)
  "Maybe trim PATH down to MAX-LEN (sans slashes).

Replaces parent directories with their initial characters."
  (let* ((components (split-string (abbreviate-file-name path) "/"))
         (len (+ (1- (length components))
                 (reduce '+ components :key 'length)))
         (str ""))
    (while (and (> len max-len)
                (cdr components))
      (setq str (concat str
                        (cond ((= 0 (length (car components))) "/")
                              ((= 1 (length (car components)))
                               (concat (car components) "/"))
                              (t
                               (if (string= "."
                                            (string (elt (car components) 0)))
                                   (concat (substring (car components) 0 2)
                                           "/")
                                 (string (elt (car components) 0) ?/)))))
            len (- len (1- (length (car components))))
            components (cdr components)))
    (concat str (reduce (lambda (a b) (concat a "/" b)) components))))

(setq eshell-prompt-function
      (lambda nil
        (concat
         (propertize (car (split-string (system-name) "\\.")) 'face `(:foreground "#DFAF8F"))
         " "
         (propertize (fish-path (eshell/pwd) 40) 'face `(:foreground "#60b48a"))
         (propertize " $" 'face `(:foreground "#506070"))
         " ")))
(setq eshell-highlight-prompt nil)

(provide 'init)
;;; init.el ends here