summaryrefslogtreecommitdiffhomepage
path: root/init.el
blob: 6dfd260ccd3e44f9351d70c8789abd1635d1cff5 (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
;; -*- lexical-binding: t; -*-

;;; Portability macros
(defmacro jao-syscase (clauses)
  (let ((cls (assoc system-type clauses)))
    (when cls `(progn ,@(cdr cls)))))

(defmacro jao-d-l (darw linux)
  `(jao-syscase ((darwin ,darw) (gnu/linux ,linux))))

(defmacro jao-when-darwin (&rest body)
  `(jao-syscase ((darwin ,@body))))

(defmacro jao-when-linux (&rest body)
  `(jao-syscase ((gnu/linux ,@body))))

(defun jao-is-linux () (jao-when-linux t))
(defun jao-is-darwin () (jao-when-darwin t))

;;; Initialisation
;;;; Bootstrap and use package
(defvar jao-emacs-dir
  (expand-file-name (jao-d-l "~/.emacs.d/config" "~/etc/emacs")))

(setq package-user-dir
      (expand-file-name (format "~/.emacs.d/elpa.%s" emacs-major-version))
      package-check-signature 'allow-unsigned)

(require 'package)
(setq package-archives
      '(("gnu-devel" . "https://elpa.gnu.org/devel/")
        ("nongnu-devel" . "https://elpa.nongnu.org/nongnu-devel/")
        ("melpa" . "https://melpa.org/packages/"))
      package-archive-priorities '(("gnu-devel" . 2)
                                   ("nongnu-devel" . 1)
                                   ("melpa" . 0)))

(package-initialize)

(unless (package-installed-p 'use-package)
  (package-refresh-contents)
  (package-install 'use-package))
(require 'use-package)

(use-package gnu-elpa-keyring-update :ensure t)

;;;; .elc vs .el loading

(setq load-prefer-newer t)
(setq comp-async-report-warnings-errors nil
      warning-suppress-types '((comp)))

;;; Paths
(defvar jao-local-lisp-dir (jao-d-l "~/Library/elisp" "~/lib/elisp")
  "Directory for external elisp libraries and repos")

(defvar jao-data-dir (expand-file-name "data" jao-emacs-dir)
  "Directory containing static data, such as images.")

(defun jao-data-file (file) (expand-file-name file jao-data-dir))

(defvar jao-doc-dir (expand-file-name (jao-d-l "~/Documents/doc" "~/doc")))

(setq jao-org-dir (expand-file-name "org" jao-doc-dir))

(defvar jao-sink-dir
  (file-name-as-directory (expand-file-name "sink" jao-doc-dir))
  "Directory used for downloads and such.")

(defvar jao-site-dir (expand-file-name "site" jao-emacs-dir))
(defun jao-site-el (basename &optional gpg)
  (expand-file-name (concat basename ".el" (when gpg ".gpg")) jao-site-dir))

(defun jao-load-site-el (basename &optional gpg)
  (let ((lf (jao-site-el basename gpg)))
    (if (file-exists-p lf)
        (load lf)
      (message "Attempted to load non existing %s" lf))))

(defun jao-exec-path (dir)
  (let ((fn (expand-file-name dir)))
    (setq exec-path (remove fn exec-path))
    (add-to-list 'exec-path fn)
    (setenv "PATH" (concat fn ":" (getenv "PATH")))))

(defun jao-load-path (subdir)
  "Add to load path a subdir of `jao-local-lisp-dir'"
  (let ((path (expand-file-name subdir jao-local-lisp-dir)))
    (when (file-directory-p path) (add-to-list 'load-path path))))

;;;; load and info path initialisation
(add-to-list 'load-path jao-site-dir)
(add-to-list 'load-path jao-local-lisp-dir)
(add-to-list 'load-path (expand-file-name "custom" jao-emacs-dir))
(add-to-list 'load-path "/usr/local/share/emacs/site-lisp/")

(let ((libd (expand-file-name "lib" jao-emacs-dir)))
  (add-to-list 'load-path libd)
  (dolist (f (directory-files libd t "^[^.]+$"))
    (when (file-directory-p f) (add-to-list 'load-path f))))

(defvar jao-info-dir (expand-file-name "info" jao-doc-dir))
(require 'info)
(add-to-list 'Info-directory-list jao-info-dir)

(jao-when-darwin
 (setenv "HOMEBREW_PREFIX" "/opt/homebrew")
 (setenv "HOMEBREW_CELLAR" "/opt/hombrew/Cellar")
 (setenv "HOMEBREW_REPOSITORY" "/opt/homebrew")
 (dolist (p '("/Applications/Emacs.app/Contents/MacOS/bin-arm64-11"
              "/Applications/Emacs.app/Contents/MacOS/libexec-arm64-11"
              "/opt/homebrew/sbin"
              "/opt/homebrew/bin"))
   (jao-exec-path p))
 (add-to-list 'Info-directory-list "/opt/homebrew/share/info"))

;;;; custom location of custom.el and co.
(setq custom-file (jao-site-el "custom"))
(load custom-file)
(setq custom-unlispify-tag-names nil)
(setq custom-buffer-done-kill t)
(setq custom-raised-buttons nil)

;;; Preamble
;;;; preamble (pre.el)
(jao-load-site-el "pre")

;;; System Utilities
;;;; persist
(use-package persist
  :ensure t)

;;;; (no) backups
(setq vc-make-backup-files nil
      make-backup-files nil)

;;;; history (saveplace, recentf, savehist)
(require 'saveplace)
(setq save-place-file (expand-file-name "~/.emacs.d/cache/places"))
(save-place-mode 1)

(setq recentf-save-file (expand-file-name "~/.emacs.d/cache/recentf")
      recentf-max-saved-items 2000
      recentf-exclude '("/home/jao/\\.emacs\\.d/elpa.*/.*"
                        ".*/.git/COMMIT_EDITMSG"))

(require 'recentf)
(recentf-mode 1)


(setq savehist-file (expand-file-name "~/.emacs.d/cache/history"))
(require 'savehist)

(savehist-mode t)

(defun jao-unpropertize-kill-ring ()
  (setq kill-ring (mapcar #'substring-no-properties kill-ring)))

(add-hook 'kill-emacs-hook #'jao-unpropertize-kill-ring)

(setq savehist-additional-variables '(kill-ring search-ring regexp-search-ring)
      savehist-ignored-variables '(ido-file-history))

;;;; yes/no, bell, startup message

(setq use-short-answers t)
(setq inhibit-startup-message t)
(setq visible-bell t)

;;;; server
(setenv "EDITOR" "emacsclient")
(require 'server)
(unless (or (daemonp) (server-running-p)) (server-start))

;;;; timers
(put 'list-timers 'disabled nil)

;;;; tramp
(inhibit-remote-files)

;;;; sleep/awake
(use-package jao-sleep
  :if (jao-is-linux)
  :demand t
  :config (jao-sleep-dbus-register))

;;;; process runners
(use-package jao-shell
  :demand t
  :bind (("s-r" . jao-shell-exec)))

;;;; app launcher
(jao-when-linux
 (jao-load-path "app-launcher")
 (use-package app-launcher
   :bind (("s-R" . app-launcher-run-app))))

;;;; brightness control
(jao-when-linux
 (jao-shell-def-exec jao-bright-set-up "brightnessctl" "-q" "s" "5%+")
 (jao-shell-def-exec jao-bright-set-down "brightnessctl" "-q" "s" "5%-")

 (defun jao-brightness ()
   (string-trim (or (cadr (jao-shell-cmd-lines "brightnessctl")) "(Unknown)")))

 (defun jao-bright-show ()
   (interactive)
   (message "%s" (jao-brightness)))

 (defun jao-bright-up ()
   (interactive)
   (jao-shell-exec "brightnessctl -q s 5%%+" t)
   (jao-bright-show))

 (defun jao-bright-down ()
   (interactive)
   (jao-shell-exec "brightnessctl -q s 5%%-" t)
   (jao-bright-show)))

;;;; keyboard
(jao-when-darwin
 (setq mac-command-modifier 'meta)
 (setq mac-option-modifier 'super)
 (global-set-key (kbd "£") [?#]))

(use-package repeat
  :demand t
  :config
  (setq repeat-echo-function 'repeat-echo-mode-line
                repeat-exit-key "SHIFT"
                repeat-exit-timeout 2)
  (repeat-mode))

(jao-when-linux
 (defun jao-kb-toggle (&optional lyt)
   (interactive)
   (shell-command-to-string (or lyt
				(if (jao-kb-toggled-p)
                                    "setxkbmap us"
                                  "setxkbmap us -variant intl"))))

 (defun jao-set-uk-kb (&optional lyt)
   (interactive)
   (jao-kb-toggle "setxkbmap gb"))

 (defun jao-kb-disable-laptop ()
   (interactive)
   (jao-shell-exec "xinput float 13"))

 (defun jao-kb-toggled-p ()
   (not (string-empty-p
         (shell-command-to-string "setxkbmap -query|grep variant")))))

(customize-set-variable 'default-input-method "catalan-prefix")
;; http://mbork.pl/2022-03-07_Transient_input_method
(customize-set-variable 'default-transient-input-method "TeX")

(setq echo-keystrokes 1
      suggest-key-bindings nil)

;;;; transient
(use-package transient
  :init (setq transient-show-popup t)
  :demand t
  :config
  (transient-bind-q-to-quit))

(defmacro jao-transient-major-mode (mode &rest suffix)
  (declare (indent defun))
  (let ((mode (intern (format "%s-mode" mode)))
        (mmap (intern (format "%s-mode-map" mode)))
        (name (intern (format "jao-transient-%s" mode))))
    `(progn
       (transient-define-prefix ,name ()
         ,(format "Transient ops for %s" mode)
         [,(format "Operations for %s" mode) :if-derived ',mode ,@suffix])
       (define-key ,mmap (kbd "s-SPC") #',name)
       (define-key ,mmap (kbd "C-c SPC") #',name))))

(defmacro jao-transient-major-mode+1 (mode suffix)
  (declare (indent defun))
  (let ((name (intern (format "jao-transient-%s" mode))))
    (if (fboundp name)
        `(transient-append-suffix ',name '(0 -1) ,suffix)
      `(jao-transient-major-mode ,mode ,suffix))))

(defmacro jao-transient-major-mode+ (mode &rest suffixes)
  (declare (indent defun))
  `(progn ,@(mapcar (lambda (s) `(jao-transient-major-mode+1 ,mode ,s))
                    suffixes)))

;;;; disk monitoring
(use-package jao-dirmon
  :if (jao-is-linux)
  :commands jao-dirmon-report)

;;;; mailcap
(use-package mailcap
  :if (jao-is-linux)
  :config
  (add-to-list 'mailcap-mime-extensions '(".JPEG" . "image/jpeg"))
  (add-to-list 'mailcap-mime-extensions '(".JPG" . "image/jpeg"))

  (defun jao-icalendar-import-buffer (&optional no-kill)
    (let ((icalendar-import-format "%s%u%l%d"))
      (icalendar-import-buffer diary-file t nil))
    (unless no-kill (kill-buffer))
    (message "Event imported into diary"))

  (defun jao-icalendar-import-invite (file)
    (with-temp-buffer
      (insert-file-contents file)
      (jao-icalendar-import-buffer t)))

  :custom
  ((mailcap-user-mime-data
    `((jao-icalendar-import-buffer "application/ics")
      ("emacsclient -e '(jao-icalendar-import-invite \"%s\")'" "application/ics")
      (doc-view-mode "application/.*pdf" (display-graphic-p))
      ("zathura \"%s\"" "application/.*pdf")
      (image-mode "image/.*" (display-graphic-p))
      ("firefox %s && riverctl set-focused-tags 2" "text/html" jao-river-enabled)
      ("swayimg \"%s\"" "image/.*" jao-sway-enabled)
      ("imv-wayland \"%s\"" "image/.*" jao-wayland-enabled)
      ("imv-x11 \"%s\"" "image/.*")))))

;;; tmr
(use-package tmr
  :ensure t
  :init
  (jao-when-linux
   (setq tmr-sound-file
	 "/usr/share/sounds/freedesktop/stereo/message.oga")))

;;; Crypto
;;;; PGP, EPG, passwords
(setq auth-source-debug nil)

(require 'auth-source)
(add-to-list 'auth-source-protocols '(local "local"))
(setq auth-sources '("~/.emacs.d/authinfo.gpg" "~/.netrc"))

(use-package epa-file
  :demand t
  :init (setq epa-file-cache-passphrase-for-symmetric-encryption t
              epa-file-encrypt-to "A247C4780736A6156BC8DA748C081D34D321D881"
              plstore-encrypt-to epa-file-encrypt-to)
  :config (epa-file-enable))

(defun jao--get-user/password (h)
  (let ((item (car (auth-source-search :type 'netrc :host h :max 1))))
    (when item
      (let ((user (plist-get item :user))
            (pwd (plist-get item :secret)))
        (list user (when pwd (funcall pwd)))))))

(defun jao-call-with-auth (host fun)
  (let ((up (jao--get-user/password host)))
    (funcall fun (car up) (cadr up))))

(defmacro jao-with-auth (host usr pwd &rest body)
  (declare (indent defun))
  `(jao-call-with-auth ,host (lambda (,usr ,pwd) ,@body)))

;;;; pass
(use-package password-store-menu
  :ensure t
  :config (password-store-menu-enable)
  :custom (password-store-menu-key "C-c p"))

;;; Fonts and color themes
;;;; widgets
(setq widget-image-enable nil
      widget-link-prefix ""
      widget-link-suffix ""
      widget-button-prefix " "
      widget-button-suffix " "
      widget-push-button-prefix ""
      widget-push-button-suffix "")

;;;; nobreak char display
(setq nobreak-char-display nil)

;;;; vertical separator
(unless (display-graphic-p)
  (set-display-table-slot standard-display-table
                          'vertical-border
                          (make-glyph-code ?│)))

;;;; transparency
(defvar jao-transparent-only-bg (jao-is-linux))

(defvar jao-frames-default-alpha
  (cond ((eq window-system 'pgtk) 85)
        (jao-transparent-only-bg 88)
        (t 85)))

(defvar jao-transparent-frame (< jao-frames-default-alpha 100))

(defun jao-alpha-parameters (&optional level)
  (let ((level (or level jao-frames-default-alpha)))
    (if jao-transparent-only-bg
        `((alpha-background . ,level) (alpha))
      `((alpha . ,(cons level level)) (alpha-background)))))

(defun jao-set-transparency (&optional level all)
  (interactive "nOpacity (0-100): ")
  (let ((level (or level jao-frames-default-alpha)))
    (setq jao-transparent-frame (< level 100))
    (if all
        (modify-all-frames-parameters (jao-alpha-parameters level))
      (modify-frame-parameters nil (jao-alpha-parameters level)))))

(defun jao-toggle-transparency (&optional all)
  (interactive "P")
  (let ((level (if jao-transparent-frame 100 jao-frames-default-alpha)))
    (jao-set-transparency level all)))

(jao-when-linux (jao-set-transparency))

;;;; themes
(defun jao-colors-scheme-dark-p ()
  (equal "dark" (getenv "JAO_COLOR_SCHEME")))

(defun jao-colors-scheme ()
  (if (jao-colors-scheme-dark-p) 'dark 'light))

(customize-set-variable 'frame-background-mode (jao-colors-scheme))

(setq custom-theme-directory
      (expand-file-name "lib/themes" jao-emacs-dir))

(require 'jao-themes)

(defvar jao-theme-dark 'jao-dark)
(defvar jao-theme-light 'jao-light)
(defvar jao-theme-term-dark 'modus-vivendi)
(defvar jao-theme-term-light 'jao-light-term)

(defun jao-themes-setup ()
  (let* ((dark (jao-colors-scheme-dark-p))
         (theme (cond ((and dark window-system) jao-theme-dark)
                      (dark jao-theme-term-dark)
                      (window-system jao-theme-light)
                      (t jao-theme-term-light))))
    (load-theme theme t)
    (modify-all-frames-parameters `((font . ,jao-themes-default-face)))))

(use-package doric-themes
  :if (jao-is-darwin)
  :ensure t
  :demand t
  :config
  ;; These are the default values.
  (setq doric-themes-to-toggle '(doric-light doric-marble))
  (setq doric-themes-to-rotate doric-themes-collection)

  (doric-themes-select 'doric-marble)

  (set-face-attribute 'default nil :family "Menlo" :height 120)
  ;; (set-face-attribute 'variable-pitch nil :family "Aporetic Sans" :height 1.0)
  ;; (set-face-attribute 'fixed-pitch nil :family "Aporetic Sans Mono" :height 1.0)

  :bind
  (("<f5>" . doric-themes-toggle)
   ("C-<f5>" . doric-themes-select)
   ("M-<f5>" . doric-themes-rotate)))

(jao-when-linux (jao-themes-setup))



;;; Help system
;;;; help buffers
(setq help-window-select t
      help-window-keep-selected nil
      help-link-key-to-documentation t)

;;;; find-func/var/lib
(use-package find-func
  :bind (("C-h C-v" . find-variable)
         ("C-h C-f" . find-function)
         ("C-h C-k" . find-function-on-key)
         ("C-h C-l" . find-library)))

;;;; eldoc
(use-package eldoc
  :init (setq eldoc-minor-mode-string nil
              eldoc-idle-delay 0.1
              eldoc-echo-area-display-truncation-message nil
              eldoc-echo-area-use-multiline-p 5
              eldoc-echo-area-prefer-doc-buffer 'maybe
              eldoc-display-functions '(eldoc-display-in-echo-area))
  :config (global-eldoc-mode 1))

(defun jao-eldoc-toggle ()
  "Toggle eldoc's documentation buffer."
  (interactive)
  (let ((buffer (eldoc-doc-buffer)))
    (if-let (w (and buffer (get-buffer-window buffer)))
        (delete-window w)
      (eldoc-doc-buffer t))))

;;;; bookmarks
(setq bookmark-default-file "~/.emacs.d/emacs.bmk"
      bookmark-fringe-mark nil)

;;;; man pages
(use-package man
  :config (setq Man-notify-method 'pushy)) ;; pushy - same window

;;; Minibuffer
(use-package jao-minibuffer
  :init
  (if (jao-colors-scheme-dark-p)
      (setq jao-minibuffer-active-buffer-line-color "azure4"
            jao-minibuffer-inactive-buffer-line-color "grey25")
    (setq jao-minibuffer-active-buffer-line-color "burlywood3"
          jao-minibuffer-inactive-buffer-line-color "grey65"))
  (setq jao-minibuffer-adaptive-alignment nil)
  :commands (jao-minibuffer-add-variable
             jao-minibuffer-refresh
             jao-minibuffer-mode))

(setq enable-recursive-minibuffers t)
(require 'mb-depth)
(minibuffer-depth-indicate-mode 1)

(setq minibuffer-default-prompt-format " (default %s)")
(minibuffer-electric-default-mode 1)

(jao-minibuffer-mode (jao-d-l -1 1))

;;; Mode line
;;;; config
(setq line-number-display-limit-width 250
      mode-line-position-column-format '(" %c")
      mode-line-position-line-format '(" %c %l")
      mode-line-end-spaces nil
      mode-line-percent-position
      '("%2l" (:eval (format " %d " (line-number-at-pos (point-max)))) "%2c"))

(line-number-mode -1)
(column-number-mode -1)

;;;; jao-mode-line
(defvar jao-mode-line-in-minibuffer (jao-is-linux))

(use-package jao-mode-line
  :commands (jao-mode-line-add-to-minibuffer-left
             jao-mode-line-add-to-minibuffer-right
             jao-mode-line-remove-from-minibuffer))

;;;; time display
(setq world-clock-list
      '(("Europe/London" "Edinburgh")
        ("Europe/Paris" "Barcelona")
        ("Asia/Tokyo" "Tokyo")
        ("America/Los_Angeles" "Corvallis")
        ("America/New_York" "New York")))

(setq display-time-day-and-date nil
      display-time-24hr-format nil
      display-time-default-load-average nil
      display-time-format " %a %e %H:%M")

(defun jao-time-to-epoch (&optional s)
  "Transform a time string to an epoch integer in milliseconds."
  (interactive)
  (let ((s (or s (read-string "Time string: " (thing-at-point 'string)))))
    (message "%s = %s"
             s
             (round (* 1000 (time-to-seconds (parse-time-string s)))))))

(defun jao-epoch-to-time (&optional v)
  "Transform an epoch, given in milliseconds, to a time string."
  (interactive)
  (let ((v (or v (read-number "Milliseconds: " (thing-at-point 'number)))))
    (message "%s = %s" v
             (format-time-string "%Y-%m-%d %H:%M:%S"
                                 (seconds-to-time (/ v 1000.0))))))

;;;; mode line toggle
(use-package jao-mode-line
  :init
  (when (and window-system (not jao-mode-line-in-minibuffer))
    (add-to-list 'after-make-frame-functions #'jao-mode-line-hide-inactive)
    (add-hook 'after-init-hook #'jao-mode-line-toggle-inactive))
  :demand t
  :bind (("<home>" . jao-mode-line-toggle-inactive)
         ("<end>" . jao-mode-line-toggle)
         ("<insert>" . jao-mode-line-echo)))

;;;; diminish
(use-package diminish
  :ensure t
  :demand t
  :diminish ((auto-fill-function . " §")
             (auto-revert-mode . "")))

(use-package outline
  :diminish ((outline-minor-mode . "")))

;;;; battery
(use-package battery
  :init
  (setq battery-load-low 15
        battery-load-critical 8
        battery-mode-line-limit 40
        battery-echo-area-format
        "%L %r %B (%p%% load, remaining time %t)"
        battery-mode-line-format " 🔋%b%p% ")

  (with-eval-after-load "jao-minibuffer"
    (if jao-mode-line-in-minibuffer
        (display-battery-mode 1)
      (jao-minibuffer-add-variable 'battery-mode-line-string 80)))
  :config
  (jao-when-darwin (display-battery-mode 1)))

;;; Notifications
;;;; jao-notify
(use-package jao-notify
  :demand t
  :init (setq jao-notify-use-messages t))

;;;; tracking
(use-package tracking
  :ensure t
  :demand t
  :init (setq tracking-position 'before-modes
              tracking-frame-behavior nil
              tracking-most-recent-first nil
              tracking-max-mode-line-entries 10
              tracking-sort-faces-first t
              tracking-shorten-modes '())
  :config  (setq erc-track-enable-keybindings nil))

(use-package jao-tracking
  :demand t
  :init
  (setq jao-tracking-bkg (if (jao-colors-scheme-dark-p) "grey20" "grey93"))
  :config (jao-tracking-setup t))

;;;; ednc

(jao-when-linux
 (use-package ednc
   :ensure t
   :diminish nil))

(use-package jao-ednc
  :if (jao-is-linux)
  :demand t
  :init (setq jao-ednc-use-tracking nil)
  :commands (jao-ednc-setup)
  :after ednc
  :config
  (jao-ednc-ignore-app "Firefox")
  (transient-define-prefix jao-transient-ednc ()
    ["Notifications"
     ("s" "show last" jao-ednc-show)
     ("S" "show all" jao-ednc-pop)
     ("n" "dismiss and show" jao-ednc-dismiss-and-show :transient t)
     ("d" "dismiss last" jao-ednc-dismiss)
     ("D" "dismiss all" jao-ednc-dismiss-all)
     ("i" "invoke last action" jao-ednc-invoke-last-action)])
  (global-set-key (kbd "s-n") #'jao-transient-ednc))

;;; Calendar, diary, weather
;;;; diary
(setq diary-file (expand-file-name "diary" jao-org-dir)
      diary-display-function 'diary-fancy-display
      diary-mail-addr "jao@localhost"
      diary-comment-start ";;"
      diary-comment-end "")

(add-hook 'diary-list-entries-hook 'diary-sort-entries t)

;;;; calendar

(use-package calendar
  :init
  (setq appt-display-format nil
        calendar-latitude 55.9533
        calendar-longitude -3.1883
        calendar-left-margin 4
        calendar-location-name "Edinburgh, Scotland"
        calendar-mark-diary-entries-flag t
        calendar-week-start-day 1 ;; 0 sunday
        calendar-date-echo-text '(format "ISO date: %s"
                                         (calendar-iso-date-string
                                          (list month day year))))
  (setq calendar-holidays
        '((holiday-fixed 1 1 "New Year's Day")
          (holiday-fixed 4 1 "April Fools' Day")
          (holiday-float 5 0 2 "Mother's Day")
          (holiday-fixed 3 19 "Father's Day")
          (holiday-float 11 4 4 "Thanksgiving")
          (holiday-fixed 12 25 "Christmas")
          (holiday-chinese-new-year)
          (solar-equinoxes-solstices)
          (holiday-sexp calendar-daylight-savings-starts
                        (format "Daylight Saving Time Begins %s"
                                (solar-time-string
                                 (/ calendar-daylight-savings-starts-time
                                    (float 60))
                                 calendar-standard-time-zone-name)))
          (holiday-sexp calendar-daylight-savings-ends
                        (format "Daylight Saving Time Ends %s"
                                (solar-time-string
                                 (/ calendar-daylight-savings-ends-time
                                    (float 60))
                                 calendar-daylight-time-zone-name)))))

  (setq org-calendar-insert-diary-entry-key nil
        org-agenda-diary-file 'diary-file)

  :config
  (appt-activate 1)
  (calendar-set-date-style 'european)

  (add-to-list 'display-buffer-alist
               `(,(regexp-quote diary-fancy-buffer)
                 (display-buffer-at-bottom)
                 (window-parameters (mode-line-format . none))
                 (window-height . fit-window-to-buffer)))

  (defun jao-diary--select ()
    (switch-to-buffer diary-fancy-buffer))

  (add-hook 'diary-fancy-display-mode-hook #'jao-diary--select))

;;;; persistent scratch
(use-package persistent-scratch
  :ensure t
  :config (persistent-scratch-setup-default))

;;;; dired
(use-package dired
  :init
  (setq dired-recursive-deletes 'top
        dired-recursive-copies 'top
        dired-listing-switches "-alhF --group-directories-first"
        ls-lisp-dirs-first t
        dired-dwim-target t
        dired-kill-when-opening-new-dired-buffer t
        dired-mouse-drag-files t
        wdired-create-parent-directories t)

  (jao-when-linux
   (setq dired-guess-shell-alist-user
        '(;; ("\\.\\(png\\|jpe?g\\|tiff\\)" "feh" "xdg-open")
          ("\\.\\(mp[34]\\|m4a\\|ogg\\|flac\\|webm\\|mkv\\)" "mpv" "xdg-open")
          (".*" "xdg-open"))))

  (put 'dired-find-alternate-file 'disabled nil)

  :hook (dired-mode . turn-on-gnus-dired-mode)

  :bind (:map dired-mode-map
              ("C-c C-r" . wdired-change-to-wdired-mode)
              ("C-M-m" . gnus-dired-attach)))

(use-package dired-x :demand t)

(use-package find-dired
  :init (setq find-ls-option '("-print0 | xargs -0 ls -ld" . "-ld"))
  :bind ("C-c D" . find-name-dired))

(use-package dired-duplicates :ensure t)

;;; General editing
;;;; automatically uncompress
(require 'jka-compr)
(auto-compression-mode 1)

;;;; wgrep
(use-package wgrep :ensure t)

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

;;;; spaces, tabs, kill
(setq kill-whole-line t)
(setq-default indent-tabs-mode nil)
(setq indent-tabs-width 4)
(setq-default default-tab-width 8)
(setq kill-read-only-ok t)
(setq view-read-only nil)

;;;; whitespace and filling column
(add-hook 'write-file-functions 'delete-trailing-whitespace)
(setq-default indicate-empty-lines nil)
(setq-default fill-column 78)
(setq comment-auto-fill-only-comments nil)

(use-package whitespace
  :init
  (setq whitespace-style '(face tabs trailing ;; lines-tail
                           empty  missing-newline-at-eof)
        whitespace-line-column 80)
  :hook (prog-mode . whitespace-mode)
  :diminish nil)

(use-package display-fill-column-indicator
  :init (setq-default display-fill-column-indicator-column 80)
  :hook (prog-mode . display-fill-column-indicator-mode))

;;;; visible mode
(use-package visible-mode
  :bind (("s-v" . visible-mode)))

;;;; changes
(use-package goto-chg
  :ensure t
  :bind (("C-." . goto-last-change)
         ("C-c ." . goto-last-change)
         ("C-c ," . goto-last-change-reverse)))

;;;; eval-and-replace
(defun fc-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)))))

 (global-set-key "\C-ce" 'fc-eval-and-replace)

;;;; skeletons and autoinsert
(use-package autoinsert
  :config
  (setq auto-insert-directory "~/.emacs.d/autoinsert/"
        auto-insert t
        auto-insert-query t)
  (setf (alist-get 'html-mode auto-insert-alist nil t) nil))
(add-hook 'find-file-hook #'auto-insert)

(use-package jao-skel
  :demand t
  :config
  (defvar flymake-allowed-file-name-masks nil)
  (require 'jao-skel-geiser)
  (require 'jao-skel-lisp)
  (require 'jao-skel-haskell)
  (require 'jao-skel-latex))

;;; Completion and search
;;;; completion
(require 'jao-custom-completion)

;;;; recoll
(jao-when-linux (jao-load-path "consult-recoll"))

(use-package consult-recoll
  :if (jao-is-linux)
  :commands (consult-recoll consult-recoll-embark-setup)
  :init
  (defun jao-recoll-format (title url _mtype)
    (let* ((u (replace-regexp-in-string "file://" "" url))
           (u (replace-regexp-in-string "/home/jao/" "" u))
           (u (replace-regexp-in-string
               "\\(doc\\|org/doc\\|.emacs.d/gnus/Mail\\|var/mail\\)/" "" u)))
      (format "%s (%s)" ;; "%s (%s, %s)"
              title
              (propertize u 'face 'jao-themes-f01)
              ;; (propertize mtype 'face 'jao-themes-f01)
              )))

  (defun jao-recoll-open-html (file &optional _page)
    (if (string-match-p "\.epub\\'" file)
        (find-file file)
      (jao-afio-goto-www)
      (if jao-afio-use-w3m (w3m-find-file file) (eww-open-file file))))

  (defun jao-recoll-open-pdf (file &optional page)
    (if (string-match-p "/gnus/Mail/" file)
        (funcall
         (or (cdr (assoc-string "message/rfc822" consult-recoll-open-fns))
             'find-file)
         file
         page)
      (jao-open-doc file page)))

  (defun jao-recoll-consult-messages ()
    (interactive)
    (consult-recoll "mime:message "))

  (defun jao-recoll-consult-docs ()
    (interactive)
    (consult-recoll (format "dir:%s/doc " jao-org-dir)))

  (defun jao-recoll-consult-notes ()
    "Use consult-recoll to search notes."
    (interactive)
    (consult-recoll (format "dir:%s " jao-org-notes-dir)))

  (setq consult-recoll-open-fns
        '(("application/pdf" . jao-recoll-open-pdf)
          ("text/html" . jao-recoll-open-html))
        consult-recoll-search-flags 'query
        consult-recoll-inline-snippets t
        consult-recoll-format-candidate #'jao-recoll-format)

  :config

  (consult-customize consult-recoll :preview-key 'any)
  (with-eval-after-load "embark" (consult-recoll-embark-setup))

  (transient-define-prefix jao-transient-recoll ()
    ["Consult recoll queries"
     ("r" "everywhere" consult-recoll)
     ("n" "on notes" jao-recoll-consult-notes)
     ("d" "on docs" jao-recoll-consult-docs)
     ("m" "on messages" jao-recoll-consult-messages)])

  :bind (("s-r" . #'jao-transient-recoll)))

;;; Buffers
;;;; cursor and mark
(transient-mark-mode -1)
(blink-cursor-mode -1)
(setopt cursor-in-non-selected-windows nil
        visible-cursor nil) ;; stop blinking in xterm

;;;; uniquifiy
(require 'uniquify)
(setq uniquify-buffer-name-style 'forward
      uniquify-trailing-separator-p t)

;;;; autosave
(setq auto-save-list-file-prefix "~/.emacs.d/auto-save-list/.saves-"
      auto-save-no-message t
      kill-buffer-delete-auto-save-files t)

(setq lock-file-name-transforms
      '(("\\`/.*/\\([^/]+\\)\\'" "/tmp/emacs-lock/\\1" t)))

;;;; autorevert
(setq auto-revert-check-vc-info nil)
(setq auto-revert-verbose nil)
(setq auto-revert-avoid-polling t)
(setq auto-revert-mode-text "")
(require 'autorevert)
(global-auto-revert-mode 1)

;;;; attached buffers
(defun jao-display-buffer-below-selected (buffer alist)
  (delete-other-windows-vertically)
  (display-buffer-below-selected buffer alist))

(defun jao-attached-buffer-entry (name-rx height)
  `(,name-rx (display-buffer-reuse-window
              jao-display-buffer-below-selected)
             (window-height . ,(or height 25))))

(defmacro jao-with-attached-buffer (name-rx height &rest body)
  (declare (indent defun))
  `(let ((display-buffer-alist '(,(jao-attached-buffer-entry name-rx height))))
     ,@body))

(defun jao-define-attached-buffer (name-rx &optional height)
  (add-to-list 'display-buffer-alist
               (jao-attached-buffer-entry name-rx height)))

(jao-define-attached-buffer "\\*eldoc\\( .*\\)?\\*" 0.33)

;;;; same mode
(defun jao-buffer-same-mode (&optional mode pre-fn switch-fn)
  (interactive)
  (let* ((mode (or mode major-mode))
         (modes (if (symbolp mode) (list mode) mode))
         (pred `(lambda (b)
                  (let ((b (get-buffer (if (consp b) (car b) b))))
                    (member (buffer-local-value 'major-mode b)
                            ',modes))))
         (buff (read-buffer "Buffer: " nil t pred)))
    (when pre-fn (funcall pre-fn))
    (if switch-fn (funcall switch-fn buff) (switch-to-buffer buff))))

(defun jao-buffer-same-mode-cmd (&optional pop)
  (interactive "P")
  (jao-buffer-same-mode nil nil (and pop #'pop-to-buffer)))

(global-set-key (kbd "C-c C-b") #'jao-buffer-same-mode-cmd)

;;;; projects
;; (use-package project :demand t)
;; (use-package list-projects :ensure t)

;;;; buffer quit function (the triple ESC)
(setq buffer-quit-function (lambda () t))

;;;; redisplay escape hatch
;; (setq max-redisplay-ticks 2250000)
;;;; scrolling
(if window-system
    (setq scroll-preserve-screen-position 'always
          scroll-conservatively most-positive-fixnum
          scroll-margin 0
          scroll-step 2
          redisplay-skip-fontification-on-input t)
  (setq scroll-preserve-screen-position nil
        scroll-conservatively 0
        scroll-margin 0
        scroll-step 1
        redisplay-skip-fontification-on-input nil))

(use-package ultra-scroll
  :ensure t
  :init
  (setq scroll-conservatively 3 ; or whatever value you prefer, since v0.4
        scroll-margin 0)        ; important: scroll-margin>0 not yet supported
  :config
  (ultra-scroll-mode 1))

;;;; show diffs when running C-x s
(add-to-list 'save-some-buffers-action-alist
             `("d"
               ,(lambda (buffer)
                  (diff-buffer-with-file (buffer-file-name buffer)))
               "show diff between the buffer and its file"))

;;;; copy buffer file name
;; https://stackoverflow.com/questions/18812938/copy-full-file-path-into-copy-paste-clipboard
(defun copy-buffer-file-name-as-kill (choice)
  "Copy the buffer-file-name to the kill-ring"
  (interactive "cCopy Buffer Name (F) Full, (D) Directory, (N) Name")
  (let ((new-kill-string)
        (name (if (eq major-mode 'dired-mode)
                  (dired-get-filename)
                (or (buffer-file-name) ""))))
    (cond ((eq choice ?f)
           (setq new-kill-string name))
          ((eq choice ?d)
           (setq new-kill-string (file-name-directory name)))
          ((eq choice ?n)
           (setq new-kill-string (file-name-nondirectory name)))
          (t (message "Quit")))
    (when new-kill-string
      (message "%s copied" new-kill-string)
      (kill-new new-kill-string))))

;;;; warnings display
(setq warning-display-at-bottom nil)

;;; Windows
;;;; splitting and switch
(setq split-height-threshold 80
      split-width-threshold 144
      display-buffer-avoid-small-windows 20)

(setq switch-to-buffer-preserve-window-point nil
      switch-to-buffer-obey-display-actions t
      switch-to-prev-buffer-skip 'this) ;; don't switch to a
                                        ;; buffer already visible in
                                        ;; this frame

(global-set-key (kbd "C-x _") #'delete-other-windows-vertically)

;;;; first window
(defvar jao-first-window--from nil)

(defun jao-first-window ()
  "Go to previous windows in frame, remembering where we were."
  (interactive)
  (let ((cb (current-buffer)))
    (if (eq (get-buffer-window cb) (select-window (frame-first-window)))
        (when jao-first-window--from (pop-to-buffer jao-first-window--from))
      (setq jao-first-window--from cb))))

(global-set-key (kbd "s-a") #'jao-first-window)
(global-set-key (kbd "M-a") #'jao-first-window)

;;;; window navigation (custom)
(defun jao-nth-window (n)
  (if (zerop n)
      'jao-first-window
    `(lambda ()
       (interactive)
       (select-window (frame-first-window))
       (dotimes (x ,n) (other-window 1)))))

(defun jao-prev-window ()
  "Go to previous window."
  (interactive)
  (other-window -1))

(defvar jao-prev-window-repeat-map
  (let ((map (make-sparse-keymap)))
    (define-key map "p" 'jao-prev-window)
    (define-key map "P" (lambda ()
                          (interactive)
                          (setq repeat-map 'jao-prev-window-repeat-map)
                          (other-window 1)))
    map)
  "Keymap to repeat `prev-window' key sequences.  Used in `repeat-mode'.")

(put 'jao-prev-window 'repeat-map jao-prev-window-repeat-map)

(mapc (lambda (n)
        (global-set-key (format "\C-c%s" (1+ n)) (jao-nth-window n)))
      '(0 1 2 3 4 5 6 7 8))

(global-set-key "\C-xp" 'jao-prev-window)

;; transposing windows
(defun transpose-windows (arg)
  "Transpose the buffers shown in two windows."
  (interactive "p")
  (let ((selector (if (>= arg 0) 'next-window 'previous-window)))
    (while (/= arg 0)
      (let ((this-win (window-buffer))
            (next-win (window-buffer (funcall selector))))
        (set-window-buffer (selected-window) next-win)
        (set-window-buffer (funcall selector) this-win)
        (select-window (funcall selector)))
      (setq arg (if (> arg 0) (1- arg) (1+ arg))))))

(define-key ctl-x-4-map (kbd "t") 'transpose-windows)

;;;; winner mode
(winner-mode 1)

;;; Frames
;;;; frame geometry
(setq frame-resize-pixelwise t)
(modify-all-frames-parameters
 `((horizontal-scroll-bars . nil)
   (vertical-scroll-bars . nil)
   (scroll-bar-width . 0)
   (menu-bar . nil)))

;;;; frame layout, title, etc
(setq frame-title-format '("%b - emacs"))
(use-package fringe)
(fringe-mode)

(jao-when-linux (menu-bar-mode -1))

;; (setting it to nil avoids mouse wrapping after other-frame)
(setq focus-follows-mouse (and (jao-is-linux) window-system t))

(use-package scroll-bar)
(set-scroll-bar-mode nil)
(use-package tool-bar)
(tool-bar-mode -1)

(defalias 'jao-trisect 'jao-afio-trisect)

(defun jao-bisect ()
  (interactive)
  (jao-trisect t)
  (other-window 1)
  (delete-window))

;;;; afio
(use-package jao-afio
  :if (jao-is-linux)
  :demand t
  :config
  (jao-afio-setup (not window-system))
  (add-hook 'jao-afio-switch-hook 'jao-minibuffer-refresh t)

  (defun jao-current--frame-id ()
    (propertize (cond ((and (fboundp 'jao-exwm-enabled)
                            (jao-exwm-enabled-p)
                            (not (bound-and-true-p jao-exwm--use-afio))
                            (boundp 'exwm-workspace-current-index))
                       (format "F%s" exwm-workspace-current-index))
                      (t jao-afio-use-frames (or (jao-afio-frame-name) ""))
                      (t (format "%s" (or (jao-afio-frame-no) ""))))
                'face 'font-lock-warning-face))
  (jao-minibuffer-add-variable '(jao-current--frame-id) 100)

  :bind (("C-c f" . 'jao-afio-goto-main)
         ("C-c g" . 'jao-afio-goto-mail)
         ("C-c w" . 'jao-afio-goto-www)
         ("C-c z" . 'jao-afio-goto-docs)
         ("C-c t" . 'jao-afio-goto-chats)
         ("C-c 0" . 'jao-afio-goto-scratch)
         ("M-o" . 'jao-afio-toggle)))

;;; Writing and writing modes
;;;; copyright notices
(setq copyright-year-ranges t)
(add-hook 'write-file-functions 'copyright-update)

;;;; indent on yank
(defvar jao-auto-indent-modes
  '(emacs-lisp-mode ;; clojure-mode
    scheme-mode objc-mode
    tuareg-mode c-mode c++-mode
    tcl-mode sql-mode
    perl-mode cperl-mode
    java-mode jde-mode
    LaTeX-mode TeX-mode))

(defadvice yank (after indent-region activate)
  (if (member major-mode jao-auto-indent-modes)
      (indent-region (region-beginning) (region-end) nil)))

;;;; org mode
(require 'jao-custom-org)

;;;; blog
(require 'jao-custom-blog)

;;;; text-ish mode settings
;; SENTENCES separated by just one space
(setq sentence-end "[.?!][]\"')]*\\($\\|\t\\| \\)[ \t\n]*")
(setq sentence-end-double-space t)
;; copy rectangle
(defun kill-rectangle-save (start end)
  "Save the region-rectangle as the last killed one."
  (interactive "r")
  (require 'rect)           ; Make sure killed-rectangle is defvar'ed.
  (setq killed-rectangle (extract-rectangle start end))
  (message "Rectangle saved"))

;; text mode, autoinserts and write hooks
(setq default-major-mode 'text-mode)
(add-hook 'text-mode-hook 'turn-on-auto-fill)

;;;; dictionaries
(use-package dictionary
  :init (setq dictionary-use-single-buffer t
              dictionary-server "localhost")
  :commands (dictionary-search
             dictionary-match-words
             dictionary-lookup-definition
             dictionary
             dictionary-mouse-popup-matching-words
             dictionary-popup-matching-words
             dictionary-tooltip-mode
             global-dictionary-tooltip-mode)
  :bind (("C-c d" . dictionary-search)))

(use-package ispell
  :custom ((ispell-personal-dictionary
            (expand-file-name "~/.emacs.d/ispell.dict"))))

(use-package reverso
  :ensure t
  :init (setq reverso-languages '(english spanish french german)))

;; (use-package wordreference
;;   :ensure t
;;   :init (setq wordreference-target-lang "es"
;;               wordreference-source-lang "en")
;;   :bind (("C-c D" . wordreference-search)))

;;;; markdown
(use-package markdown-mode
  :ensure t
  :init (setq markdown-command '("pandoc" "--from=markdown" "--to=html5")
              markdown-asymmetric-header t
              markdown-enable-wiki-links t
              markdown-wiki-link-fontify-missing t
              markdown-enable-math  nil ;; toggle with M-x markdown-toggle-math
              markdown-link-space-sub-char "-"
              markdown-gfm-additional-languages '("whizzml" "flatline")
              markdown-hide-urls t
              markdown-hide-markup nil
              markdown-fontify-code-blocks-natively t
              markdown-fontify-whole-heading-line t
              markdown-unordered-list-item-prefix t)
  :hook (markdown-mode . outline-minor-mode)
  :config
  (dolist (u '("doc" "message" "notmuch"))
    (add-to-list 'markdown-uri-types u))
  (use-package markdown-toc :ensure t))

;; used by markdown mode to edit code blocks
(use-package edit-indirect :ensure t)

(dolist (ext '("\\.md$" "\\.markdown$"))
  (add-to-list 'auto-mode-alist (cons ext 'markdown-mode)))

;;;; TeX and LaTex
(use-package tex-site
  :ensure auctex
  :init
  (setq TeX-auto-save t)
  (setq TeX-parse-self t)
  (setq TeX-a4-paper t)
  (setq TeX-auto-local ".tex-auto-local")
  ;; Preferred view format: dvi, ps, pdf, pdfs
  (setq TeX-view-format "pdf")
  (setq-default TeX-master "../main") ; nil to ask
  (setq TeX-view-program-selection
        ;;  '((output-dvi "open")
        ;;    (output-pdf "open")
        ;;    (output-html "open"))
        '(((output-dvi has-no-display-manager) "dvi2tty")
          ((output-dvi style-pstricks) "dvips and gv")
          (output-dvi "xdvi")
          (output-pdf "xdg-open")
          (output-html "xdg-open")))
  ;; to make RefTeX faster for large documents, try these:
  (setq reftex-enable-partial-scans t)
  (setq reftex-save-parse-info t)
  (setq reftex-use-multiple-selection-buffers t)
  ;; to integrate with AUCTeX
  (setq reftex-plug-into-AUCTeX t)
  (setq reftex-ref-style-default-list
        '("Hyperref" "Varioref" "Fancyref"))
  (setq LaTeX-command "latex -shell-escape")
  (setq LaTeX-biblatex-use-Biber t)
  (setq bibtex-dialect 'biblatex)
  :config
  (add-hook 'TeX-after-compilation-finished-functions
            'TeX-revert-document-buffer)
  (add-hook 'LaTeX-mode-hook 'turn-on-reftex))

;;; Browsing
(jao-when-linux
 (require 'jao-custom-browse)
 (require 'jao-custom-eww))

;;; PDFs and other docs

;;;; doc view &co.

(jao-when-linux (require 'jao-custom-pdf))

;;;; epub
(use-package nov
  :ensure t
  :after doc-view
  :init (setq nov-variable-pitch t
              nov-text-width nil)
  :config
  (add-to-list 'auto-mode-alist '("\\.epub\\'" . nov-mode))
  (defun jao-nov-register-session ()
    (jao-doc-session-mark nov-file-name))
  (add-hook 'nov-mode-hook #'jao-nov-register-session))

;;; Email
(jao-when-linux (require 'jao-custom-email))

;;; Shells and terms
;;;; shell modes
(setq sh-basic-offset 2)
;; translates ANSI colors into text-properties, for eshell
(autoload 'ansi-color-for-comint-mode-on "ansi-color" nil t)
(add-hook 'shell-mode-hook 'ansi-color-for-comint-mode-on)
(defvar jao-use-vterm nil)
(defvar jao-use-eat nil)

(add-to-list 'display-buffer-alist
             '("\\*Async Shell Command\\*" (display-buffer-no-window)))

;;;; eat
(use-package eat
  :ensure t
  :commands jao-exec-in-term
  :init (setq jao-use-eat t
              eat-kill-buffer-on-exit t
              eat-enable-yank-to-terminal t)
  :hook ((eshell-mode . eat-eshell-mode)
         (eshell-mode . eat-eshell-visual-command-mode))
  :diminish ((eat-eshell-mode . "")))

;;;; term
(defvar-local jao-term--cmd nil)

(defun jao-term--find (cmd)
  (seq-find (lambda (b)
              (with-current-buffer b
                (and (derived-mode-p 'eat-mode 'term-mode 'vterm-mode)
                     (string= (or jao-term--cmd "") cmd))))
            (buffer-list)))

(defun jao-exec-in-term (cmd &optional name)
  (interactive "SCommand")
  (require 'eat nil t)
  (cond ((and jao-use-vterm (fboundp 'jao-exec-in-vterm))
         (jao-exec-in-vterm cmd name))
        (jao-use-eat (let ((eat-term-name "xterm-256color"))
                       (with-current-buffer (eat cmd t)
                         (setq-local jao-term--cmd cmd))))
        (t (ansi-term "bash" name)
           (set-process-sentinel (get-buffer-process (current-buffer))
                                 (lambda (process event)
                                   (when (string= event "finished\n")
                                     (kill-buffer (process-buffer process)))))
           (setq-local jao-term--cmd cmd)
           (term-send-string nil (concat cmd " ; exit\n")))))

(defmacro jao-def-exec-in-term (name cmd &rest prelude)
  `(defun ,(intern (format "jao-term-%s" name)) (&optional term)
     (interactive "P")
     ,@prelude
     (let ((jao-use-vterm (if term (not jao-use-vterm) jao-use-vterm)))
       (if-let ((b (jao-term--find ,cmd)))
           (pop-to-buffer b)
         (jao-exec-in-term ,cmd ,(format "*%s*" name))))))

;;;; eshell
;;;;; basic custom
(use-package eshell
  :init
  (setq eshell-directory-name "~/.emacs.d/eshell"
        eshell-hist-ignoredups 'erase
        eshell-history-size 1000000
        eshell-error-if-no-glob nil)

  (defun jao-eshell--outline ()
    (setq-local outline-regexp eshell-prompt-regexp))

  :config (setq eshell-prompt-repeat-map nil)

  :hook (eshell-mode . jao-eshell--outline))

;;;;; colors
(autoload 'ansi-color-apply "ansi-color")
;; (add-hook 'eshell-preoutput-filter-functions 'ansi-color-filter-apply)
(add-hook 'eshell-preoutput-filter-functions 'ansi-color-apply)

(use-package eshell-syntax-highlighting
  :after esh-mode
  :ensure t
  :config
  ;; Enable in all Eshell buffers.
  (eshell-syntax-highlighting-global-mode +1))

;;;;; visual commands
(require 'em-term)

(dolist (c '("editor" "more" "wget" "dict" "vim" "links" "w3m" "guile"
             "zmore" "pager" "aptitude" "su" "htop" "top"
             "screen" "whizzml" "iex" "spt"))
  (add-to-list 'eshell-visual-commands c))

(setq eshell-visual-subcommands '(("git" "log" "diff" "show")
                                  ("sudo" "vim")
                                  ("rebar3" "shell"))
      eshell-destroy-buffer-when-process-dies nil
      eshell-escape-control-x t)

;;;;; bol
(defun jao-eshell-maybe-bol ()
  (interactive)
  (let ((p (point)))
    (eshell-bol)
    (if (= p (point))
        (beginning-of-line))))

;;;;; prompt
;; tracking git repos
(defun jao-eshell--git-dirty ()
  (shell-command-to-string "git diff-index --quiet HEAD -- || echo -n '*'"))

(use-package git-ps1-mode
  :ensure t
  :init (setq git-ps1-mode-showupstream "1"
              git-ps1-mode-showdirtystate "1"))

(defun jao-eshell--git-info ()
  (if (fboundp 'git-ps1-mode-get-current)
      (git-ps1-mode-get-current)
    (let ((desc (shell-command-to-string "git branch --no-color")))
      (when (string-match "^* \\(\\<.+\\>\\)" desc)
        (format "%s%s" (match-string 1 desc) (jao-eshell--git-dirty))))))

(defun jao-eshell--git-current-branch (suffix)
  (let ((desc (or (jao-eshell--git-info) "")))
    (cond ((and (string-empty-p desc) suffix) (format " (%s)" suffix))
          ((string-empty-p (or suffix "")) (format " (%s)" desc))
          (t (format " (%s %s)" desc suffix)))))

(defun jao-eshell--virtualenv ()
  (let ((venv (getenv "VIRTUAL_ENV")))
    (when (and venv (string-match ".*/\\([^/]+\\)/$" venv))
      (match-string-no-properties 1 venv))))

(defun jao-eshell-prompt-function ()
  (let* ((venv (jao-eshell--virtualenv))
         (venv (if venv (format "%s" venv) "")))
    (concat (abbreviate-file-name (eshell/pwd))
            (jao-eshell--git-current-branch venv)
            (if (= (user-uid) 0) " # " " $ "))))

(setq eshell-prompt-function 'jao-eshell-prompt-function)

;;;;; in-term
(defun eshell/in-term (prog &rest args)
  (switch-to-buffer
   (apply #'make-term (format "in-term %s %s" prog args) prog nil args))
  (term-mode)
  (term-char-mode))

;;;;; dir navigation
(use-package eshell-up
  :ensure t
  :config (setq eshell-up-print-parent-dir t))

(use-package eshell-autojump :ensure t)

;;;;; completion

(defun jao-eshell--set-up-completion ()
  (setq-local completion-styles '(basic partial-completion))
  (add-hook 'completion-at-point-functions
            'bash-completion-capf-nonexclusive nil t))

(use-package bash-completion
  :ensure t
  :hook (eshell-mode . jao-eshell--set-up-completion))

;;;;; toggle
(use-package jao-eshell-here
  :demand t
  :config (jao-define-attached-buffer "^\\*eshell" 0.5)
  :bind (("<f1>" . jao-eshell-here-toggle)
         ("C-<f1>" . jao-eshell-here-toggle-new)))

;;;;; workarounds
;; at some point, bash completion started insertig the TAB
;; after the commands ends
;; (defun jao-eshell--clean-prompt ()
;;   (eshell-bol)
;;   (ignore-errors (kill-line)))

;; (add-hook 'eshell-after-prompt-hook 'jao-eshell--clean-prompt)

;;;;; keybindings
(defun jao-eshell--kbds ()
  (define-key eshell-mode-map "\C-a" 'jao-eshell-maybe-bol)
  (define-key eshell-mode-map "\C-ci" 'consult-outline))

(jao-eshell--kbds)

;;; Version control and CI
;;;; vc options
(setq vc-follow-symlinks t)
(setq auto-revert-check-vc-info nil)

;;;; diff fringe indicators (diff-hl)
(use-package diff-hl
  :ensure t
  :custom ((diff-hl-draw-borders nil)
           (diff-hl-side 'right)
           (diff-hl-margin-symbols-alist
            '((insert . "█")
              (delete . "█")
              (change . "█")
              (unknown . "█")
              (ignored . "█"))))
  :config
  (map-keymap (lambda (_k cmd)
                (put cmd 'repeat-map 'diff-hl-command-map))
              diff-hl-command-map)
  (add-hook 'magit-post-refresh-hook 'diff-hl-magit-post-refresh))

(global-diff-hl-mode 1)
(unless (display-graphic-p) (diff-hl-margin-mode 1))

;;;; magit/forge
(use-package magit
  :ensure t
  :commands magit-status
  :init
  (setq magit-repository-directories
        (jao-d-l
         '(("/Users/jao/Projects" 3))
         '(("/home/jao/usr/bigml" . 2)
           ("/home/jao/usr/jao" . 3)
           ("/usr/local/src" . 1))))

  (setq magit-status-initial-section nil
        magit-define-global-key-bindings nil
        magit-completing-read-function 'magit-builtin-completing-read
        magit-display-buffer-function
        'magit-display-buffer-fullcolumn-most-v1
        magit-delete-by-moving-to-trash nil
        magit-last-seen-setup-instructions "1.4.0"
        magit-log-edit-confirm-cancellation t
        magit-omit-untracked-dir-contents t
        magit-process-connection-type nil
        magit-push-always-verify nil
        magit-save-repository-buffers 'dontask
        magit-section-visibility-indicator '("…" . t)
        magit-status-buffer-switch-function 'switch-to-buffer
        magit-status-show-hashes-in-headers t))

;;;; forge
(use-package forge
  :ensure t
  :after magit
  :init
  (setq forge-topic-list-limit (cons 100 -1)
        forge-pull-notifications nil)
  :config
  (use-package embark-vc :ensure t)
  :bind ((:map forge-topic-mode-map ("M-w" . copy-region-as-kill))))

;;;; other git packages
(use-package git-timemachine :ensure t)

;; (use-package consult-git-log-grep
;;   :ensure t
;;   :custom (consult-git-log-grep-open-function #'magit-show-commit)
;;   :bind (("C-c K" . consult-git-grep)))

;; git config --local git-link.remote / git-link.branch
(use-package git-link :ensure t)
(use-package git-modes :ensure t)

;;; Programming

(require 'jao-custom-programming)

;;; Text/data formats
;;;; json
(use-package json-mode :ensure t)
;;;; yaml
(use-package yaml-mode :disabled t :ensure t)

;;; Graphics
;;;; images
(setq image-use-external-converter t
      image-cache-eviction-delay 120)
(setq widget-image-enable nil)

;;;; gnuplot
(use-package gnuplot
  :disabled t
  :ensure t
  :commands (gnuplot-mode gnuplot-make-buffer)
  :init (add-to-list 'auto-mode-alist '("\\.gp$" . gnuplot-mode)))

;;; Network
;;;; nm applet
(jao-when-linux
 (jao-shell-def-exec jao-nm-applet "nm-applet")

 (defun jao-toggle-nm-applet ()
   (interactive)
   (or (jao-shell-kill-p "nm-applet") (jao-nm-applet))))

;;;; bluetooth
(jao-when-linux (use-package bluetooth :ensure t))

;;;; ssh
(defun jao-tramp-hosts ()
  (seq-uniq
   (mapcan (lambda (x)
             (remove nil (mapcar 'cadr (apply (car x) (cdr x)))))
           (tramp-get-completion-function "ssh"))
   #'string=))

(defun jao-ssh (&optional scratch)
  (interactive "P")
  (let ((h (completing-read "Host: " (jao-tramp-hosts))))
    (when scratch (jao-afio-goto-scratch))
    (jao-exec-in-term (format "ssh %s" h) (format "*ssh %s*" h))))

;;; Chats

(jao-when-linux (require 'jao-custom-chats))

;;; Multimedia

(jao-when-linux (require 'jao-custom-multimedia))

;;; Graphical window system

(jao-when-linux (require 'jao-custom-window-system))

;;; Global transients
(defun jao-list-packages ()
  (interactive)
  (jao-when-linux (jao-afio-goto-scratch))
  (package-list-packages))

(defun jao-window-system-p ()
  (or (not (jao-is-linux))
      jao-exwm-enabled jao-xmonad-enabled jao-wayland-enabled))

(defun jao-x11-p ()
  (jao-when-linux (or jao-exwm-enabled jao-xmonad-enabled)))

(defun jao-reveal ()
  (interactive)
  (cond ((or outline-minor-mode (derived-mode-p 'outline-mode ))
         (outline-show-entry))
        ((derived-mode-p 'org-mode) (org-reveal))))

(jao-def-exec-in-term "aptitude" "aptitude" (jao-afio-goto-scratch))
(jao-def-exec-in-term "htop" "htop" (jao-afio-goto-scratch))

(jao-d-l
 (transient-define-prefix jao-transient-utils ()
   "Global operations."
   [["Notes"
     ("n" "create new note" jao-org-notes-create)
     ("/" "open note" jao-org-notes-open)
     ("\\" "open note by tags" jao-org-notes-consult-tags)
     ("g" "ripgrep notes" jao-org-notes-consult-ripgrep)]
    ["Timers"
     ("t t" "set new" tmr)
     ("t c" "cancel" tmr-cancel)
     ("t l" "list" tmr-list-timers)]
    ["Network"
     ("s" "ssh" jao-ssh)]
    ["Utilities"
     ("l" "packages" jao-list-packages)
     ("r" "translate" reverso)
     ("f" "copy buffer file name" copy-buffer-file-name-as-kill)]])
 (transient-define-prefix jao-transient-utils ()
   "Global operations."
   [["Notes"
     ("n" "create new note" jao-org-notes-create)
     ("/" "open note" jao-org-notes-open)
     ("\\" "open note by tags" jao-org-notes-consult-tags)
     ("g" "ripgrep notes" jao-org-notes-consult-ripgrep)]
    ["Documents"
     ("dd" "go to doc" jao-select-pdf :if display-graphic-p)
     ("do" "open doc" jao-open-doc)
     ("dr" "search docs with recoll" jao-recoll-consult-docs)]
    ["Monitors"
     ("p" "list projects" list-projects)
     ;; ("p" "htop" jao-term-htop)
     ("P" "pasytray" jao-toggle-pasystray-applet)
     ("x" "restart i3bar" jao-river-restart-i3bar :if jao-river-enabled-p)
     ("x" "restart xmobar" jao-xmobar-restart :if jao-exwm-enabled-p)
     ("x" "kill xmobar" jao-xmobar-kill :if jao-xmonad-enabled-p)]
    ["Network"
     ("s" "ssh" jao-ssh)
     ("b" "bluetooth" bluetooth-list-devices)
     ("c" "connect chats" jao-all-chats)
     ("m" "proton bridge" run-proton-bridge)]
    ["Chats"
     ("i"  "irc" jao-chats-irc)
     ("M" "mastodon" jao-mastodon)
     ("T" "telegram rooster" jao-telega)]
    ["Window system" :if jao-window-system-p
     ("w" "set wallpaper" jao-set-wallpaper)
     ("W" "set radom wallpaper" jao-set-random-wallpaper)
     ("B u" (lambda ()
              (let ((b (jao-brightness)))
                (format "bright up %s" (and (string-match ".*\\((.+)\\).*" b)
                                            (match-string 1 b)))))
      jao-bright-up :transient t)
     ("B d" "bright down" jao-bright-down :transient t)]
    ["Utilities"
     ("a" "aptitude" jao-term-aptitude)
     ("l" "packages" jao-list-packages)
     ("v" "view video" jao-view-video)]
    ["Timers"
     ("t t" "set new" tmr)
     ("t c" "cancel" tmr-cancel)
     ("t l" "list" tmr-list-timers)]
    ["Helpers"
     ;; ("r" "reveal" jao-reveal)
     ("r" "translate" reverso)
     ("f" "copy buffer file name" copy-buffer-file-name-as-kill)
     ("k" (lambda () (concat "keyboard" (when (jao-kb-toggled-p) "*")))
      jao-kb-toggle :if jao-x11-p)]]))

(global-set-key (kbd "s-w") #'jao-transient-utils)

;;; Global key bindings
(defun jao-global-keybindings ()
  (interactive)
  (global-set-key (kbd "<f2>") #'magit-status)
  (global-set-key (kbd "C-x p") #'jao-prev-window)
  (global-set-key (kbd "C-x o") 'other-window)
  (global-set-key "\C-cj" #'join-line)
  (global-set-key "\C-cn" #'next-error)
  (global-set-key "\C-cq" #'auto-fill-mode)
  (global-set-key "\C-xr\M-w" #'kill-rectangle-save)
  (global-set-key "\C-c\C-z" #'comment-or-uncomment-region)
  (global-set-key "\C-z" #'comment-or-uncomment-region))

(jao-global-keybindings)

;;; Last minute (post.el)
(jao-load-site-el "post")