~thecatster/.emacs.d

.emacs.d/init.el -rw-r--r-- 53.0 KiB
2c969f2eDaniil Rose Update gitignore to include elpa 7 months ago
                                                                                
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
(defconst IS-WINDOWS (memq system-type '(cygwin windows-nt ms-dos)))
(defconst IS-MAC     (eq system-type 'darwin))
(defconst IS-LINUX   (eq system-type 'gnu/linux))

(defconst engineered-version "2.4.0"
  "Current version of Engineered Emacs.")

;; Prevent unwanted runtime builds in gccemacs (native-comp); packages are
;; compiled ahead-of-time when they are installed and site files are compiled
;; when gccemacs is installed.
(setq comp-deferred-compilation nil)
(setq comp-async-report-warnings-errors nil)

;; Getting strange messages with Guix that do not affect performance
(setq warning-minimum-level :error)

;;; Shut up, startup
;; Legacy system advice, who cares
(setq ad-redefinition-action 'accept)

;; "For information about GNU Emacs..." I'll read the docs or go to the website, moving on
(unless (daemonp)
  (advice-add #'display-startup-echo-area-message :override #'ignore))

;; Shut up, *Message*
(setq inhibit-startup-message t
      large-file-warning-threshold nil
      vc-follow-symlinks t
      ad-redefinition-action 'accept
      inhibit-startup-echo-area-message user-login-name
      inhibit-default-init t
      byte-compile-warnings '(not cl-functions))

;;; Optimizations!
;; Don't rely on case insensitivity.
(setq auto-mode-case-fold nil)

;; Disabling bidirectional text rendering gives a performance boost.
(setq-default bidi-display-reordering 'left-to-right
              bidi-paragraph-direction nil)
(setq bidi-inhibit-bpa t)

;; Don't render in non-focused, why would you?
(setq-default cursor-in-non-selected-windows nil)
(setq highlight-nonselected-windows nil)

;; *Zoom* scrolling
(setq fast-but-imprecise-scrolling t)

;; Can't figure out what for, but this is needed.
(require 'ido)

;; Why are you pinging domain names?
(setq ffap-machine-p-known 'reject)

;; Don't waste time on resizing the frame with font size.
(setq frame-inhibit-implied-resize t)

;; Here's where we handle the GC
(setq gcmh-idle-delay 5
      gc-cons-threshold (* 2000 1024 1024) ;; 2000mb
      gcmh-high-cons-threshold (* 4000 1024 1024))  ;; 4000mb

;; This increases from the default of 4k, helps LSP
(setq read-process-output-max (* 16 1024 1024)) ;; 16mb

;; Slow the UI updates
(setq idle-update-delay 1.0)

;; Increase memory usage, but increase performance. No thank you, font compacting!
(setq inhibit-compacting-font-caches t)

;; I said, **Zoom** scrolling!
(setq redisplay-skip-fontification-on-input t)

;; Remove unnecessary CLI options
(unless IS-MAC   (setq command-line-ns-option-alist nil))
(unless IS-LINUX (setq command-line-x-option-alist nil))

;; A hack from Doom again, this helps with terminal Emacs startup
(unless (daemonp)
  (advice-add #'tty-run-terminal-initialization :override #'ignore))

;; I know this is from Doom again, but again, Henrik knows what he's doing!
;;; Security

;; Emacs is essentially one huge security vulnerability, what with all the
;; dependencies it pulls in from all corners of the globe. Let's try to be at
;; least a little more discerning.
(setq gnutls-verify-error (not (getenv-internal "INSECURE"))
      gnutls-algorithm-priority
      (when (boundp 'libgnutls-version)
        (concat "SECURE128:+SECURE192:-VERS-ALL"
                (if (and (not IS-WINDOWS)
                         (not (version< emacs-version "26.3"))
                         (>= libgnutls-version 30605))
                    ":+VERS-TLS1.3")
                ":+VERS-TLS1.2"))
      ;; `gnutls-min-prime-bits' is set based on recommendations from
      ;; https://www.keylength.com/en/4/
      gnutls-min-prime-bits 3072
      tls-checktrust gnutls-verify-error
      tls-program '("gnutls-cli -p %p %h"))

;; Emacs stores `authinfo' in $HOME and in plain-text. WHY!?
(setq auth-sources (list (concat user-emacs-directory "authinfo.gpg")
                         "~/.authinfo"
                         "~/.authinfo.gpg"))

;; UTF-8!
(when (fboundp 'set-charset-priority)
  (set-charset-priority 'unicode))
(set-default-coding-systems 'utf-8)
(prefer-coding-system 'utf-8)
(setq locale-coding-system 'utf-8)

;; MELPA!
(require 'package)
(add-to-list 'package-archives '("melpa" . "https://melpa.org/packages/") t)
(add-to-list 'package-archives '("org" . "https://orgmode.org/elpa/") t)
(add-to-list 'package-archives '("gnu" . "https://elpa.gnu.org/packages/") t)
(package-initialize)

(setq load-prefer-newer t)

(defvar bootstrap-version)
(defvar native-comp-deferred-compilation-deny-list ())
(let ((bootstrap-file
       (expand-file-name "straight/repos/straight.el/bootstrap.el" user-emacs-directory))
      (bootstrap-version 5))
  (unless (file-exists-p bootstrap-file)
    (with-current-buffer
        (url-retrieve-synchronously
         "https://raw.githubusercontent.com/raxod502/straight.el/develop/install.el"
         'silent 'inhibit-cookies)
      (goto-char (point-max))
      (eval-print-last-sexp)))
  (load bootstrap-file nil 'nomessage))
(straight-use-package 'use-package)
(setq straight-use-package-by-default t)

(setq user-full-name "Daniil Rose"
      user-mail-address "daniil.rose@member.fsf.org")

(use-package diminish)

(scroll-bar-mode -1)
(tool-bar-mode   -1)
(tooltip-mode    -1)
(menu-bar-mode   -1)

(use-package so-long
  :config
  (global-so-long-mode 1))

(when IS-MAC
  ;; Switch keys around, since it's easier to hit Command
  (setq mac-option-key-is-meta nil
        mac-command-key-is-meta t
        mac-command-modifier 'meta
        mac-option-modifier 'super)

  ;; Use spotlight as search
  (setq locate-command "mdfind")

  ;; Curse Lion and its sudden but inevitable fullscreen mode!
  ;; NOTE Meaningless to railwaycat's emacs-mac build
  (setq ns-use-native-fullscreen nil)

  ;; Visit files opened outside of Emacs in existing frame, not a new one
  (setq ns-pop-up-frames nil)

  ;; sane trackpad/mouse scroll settings
  (setq mac-redisplay-dont-reset-vscroll t
        mac-mouse-wheel-smooth-scroll nil)

  ;; Sets `ns-transparent-titlebar' and `ns-appearance' frame parameters so window
  ;; borders will match the enabled theme.
  (and (or (daemonp)
           (display-graphic-p))
       (require 'ns-auto-titlebar nil t)
       (ns-auto-titlebar-mode +1))

  ;; Integrate with Keychain
  (add-to-list 'auth-sources 'macos-keychain-internet)
  (add-to-list 'auth-sources 'macos-keychain-generic)

  ;; Delete files to trash
  (use-package osx-trash
    :init
    (setq delete-by-moving-to-trash t)
    (and IS-MAC
         (not (fboundp 'system-move-file-to-trash))
         (defalias #'system-move-file-to-trash #'osx-trash-move-file-to-trash))))

(when IS-MAC
  (use-package exec-path-from-shell
    :init
    (exec-path-from-shell-initialize)))

(use-package volatile-highlights
  :hook (after-init . volatile-highlights-mode))

(setq tramp-default-method "ssh")

(use-package auto-sudoedit
  :diminish auto-sudoedit-mode
  :config
  (auto-sudoedit-mode 1))

(remove-hook 'find-file-hooks 'vc-find-file-hook)
(setq vc-follow-symlinks t)

(setq initial-scratch-message "Welcome to Engineered Emacs!")
(setq initial-major-mode 'fundamental-mode)

(setq ring-bell-function 'ignore)

(setq-default indent-tabs-mode nil)
(setq-default tab-width 2)

(setq-default
 window-combination-resize t
 delete-by-moving-to-trash t
 x-stretch-cursor t)

(setq undo-limit 80000000
      auto-save-default nil
      truncate-string-ellipsis "…"
      scroll-margin 20)

(with-eval-after-load 'subword
  (diminish 'subword-mode))
(global-subword-mode 1)

(setq set-mark-command-repeat-pop t)

(setq global-auto-revert-non-file-buffers t)
(global-auto-revert-mode 1)

(line-number-mode nil)

(add-to-list 'load-path "~/.emacs.d/lisp/")

(setq scroll-step 1)

(defalias 'yes-or-no-p 'y-or-n-p)

(setq backup-directory-alist '(("." . "~/.emacs.d/backup"))
      backup-by-copying t    ; Don't delink hardlinks
      version-control t      ; Use version numbers on backups
      delete-old-versions t  ; Automatically delete excess backups
      kept-new-versions 20   ; how many of the newest versions to keep
      kept-old-versions 5)

(add-hook 'before-save-hook 'delete-trailing-whitespace)

(add-to-list 'default-frame-alist '(font . "JetBrainsMono Nerd Font"))
(use-package emojify
  :hook (after-init . global-emojify-mode)
  :custom
  (emojify-set-emoji-style 'unicode)
  :commands emojify-mode)

(use-package default-text-scale
  :defer 1
  :config
  (default-text-scale-mode))

(use-package super-save
  :defer 1
  :diminish super-save-mode
  :config
  (super-save-mode +1)
  (setq super-save-auto-save-when-idle t))

(setq display-buffer-base-action
      '(display-buffer-reuse-mode-window
        display-buffer-reuse-window
        display-buffer-same-window))

;; If a popup does happen, don't resize windows to be equal-sized
(setq even-window-sizes nil)

(use-package all-the-icons-dired)
(use-package peep-dired)

(add-hook 'dired-mode-hook 'all-the-icons-dired-mode)

(use-package dired-subtree
  :bind (:map dired-mode-map
              ("i" . dired-subtree-insert)
              (";" . dired-subtree-remove)))

(use-package dired-ranger
  :bind (:map dired-mode-map
              ("W" . dired-ranger-copy)
              ("X" . dired-ranger-move)
              ("Y" . dired-ranger-paste)))

(add-hook 'dired-mode-hook 'auto-revert-mode)

(setq dired-open-extensions '(("gif" . "sxiv")
                              ("jpg" . "sxiv")
                              ("png" . "sxiv")
                              ("mkv" . "mpv")
                              ("mp4" . "mpv")))

(setq catster/use-evil nil)

(when catster/use-evil
   (require 'catsters-evil))

(use-package atom-one-dark-theme
  :config
  (load-theme 'atom-one-dark t))
(use-package all-the-icons)

(setq catster/use-doom-ml t)

(when catster/use-doom-ml
  (use-package doom-modeline
    :custom
    (doom-modeline-major-mode-icon t)
    (doom-modeline-minor-modes nil)
    :hook (after-init . doom-modeline-mode)))

(unless catster/use-doom-ml
  (use-package smart-mode-line-atom-one-dark-theme)
  (use-package smart-mode-line
    :after smart-mode-line-atom-one-dark-theme
    :init
    (setq sml/theme 'atom-one-dark)
    (setq sml/no-confirm-load-theme t)
    :config
    (sml/setup)))

(use-package anzu
  :init
  (global-anzu-mode))

;; Don't bring up key recipient dialogue.
(require 'epa-file)
(setq epa-file-select-keys 1)
(setq epa-file-encrypt-to '("<daniil.rose@member.fsf.org>"))

;; Increase the password cache expiry time, technically doesn't do anything for GPG2
(setq password-cache-expiry (* 60 15))

;; Fix EasyPG error.
;; From https://colinxy.github.io/software-installation/2016/09/24/emacs25-easypg-issue.html.
(defvar epa-pinentry-mode)
(setq epa-pinentry-mode 'loopback)

(use-package pinentry)
(setf epg-pinentry-mode 'loopback)
(defun pinentry-emacs (desc prompt ok error)
   (let ((str (read-passwd
               (concat (replace-regexp-in-string "%22" "\""
                                                 (replace-regexp-in-string "%0A" "\n" desc)) prompt ": "))))
     str))

(straight-use-package '(vertico :files (:defaults "extensions/*")
                                :includes (vertico-buffer
                                           vertico-directory
                                           vertico-flat
                                           vertico-indexed
                                           vertico-mouse
                                           vertico-quick
                                           vertico-repeat
                                           vertico-reverse)))
(vertico-mode)
(setq vertico-cycle t)

(defun basic-remote-try-completion (string table pred point)
  (and (vertico--remote-p string)
       (completion-basic-try-completion string table pred point)))
(defun basic-remote-all-completions (string table pred point)
  (and (vertico--remote-p string)
       (completion-basic-all-completions string table pred point)))
(add-to-list
 'completion-styles-alist
 '(basic-remote basic-remote-try-completion basic-remote-all-completions nil))
(setq completion-styles '(orderless)
      completion-category-overrides '((file (styles basic-remote partial-completion)))
      completion-category-defaults nil)

(use-package vertico-directory
  :bind (:map vertico-map
              ("RET" . vertico-directory-enter)
              ("DEL" . vertico-directory-delete-char)
              ("M-DEL" . vertico-directory-delete-word))
  :hook (rfn-eshadow-update-overlay . vertico-directory-tidy))

(use-package orderless
  :init
  (setq completion-styles '(orderless)
        completion-category-overrides '((file (styles partial-completion)))))

(use-package savehist
  :init
  (savehist-mode))

(use-package emacs
  :init
  (defun crm-indicator (args)
    (cons (concat "[CRM] " (car args)) (cdr args)))
  (advice-add #'completing-read-multiple :filter-args #'crm-indicator)

  (setq minibuffer-prompt-properties
        '(read-only t cursor-intangible t face minibuffer-prompt))
  (add-hook 'minibuffer-setup-hook #'cursor-intangible-mode)

  (setq read-extended-command-predicate
        #'command-completion-default-include-p)

  (setq enable-recursive-minibuffers t))

(use-package marginalia
  :bind (("M-A" . marginalia-cycle)
         :map minibuffer-local-map
         ("M-A" . marginalia-cycle))

  :init
  (marginalia-mode))

(use-package all-the-icons-completion
  :init
  (all-the-icons-completion-mode))

(use-package consult
  :bind (;; C-c bindings (mode-specific-map)
         ("C-c h" . consult-history)
         ("C-c m" . consult-mode-command)
         ("C-c b" . consult-bookmark)
         ("C-c k" . consult-kmacro)
         ;; C-x bindings (ctl-x-map)
         ("C-x M-:" . consult-complex-command)     ;; orig. repeat-complex-command
         ("C-x b" . consult-buffer)                ;; orig. switch-to-buffer
         ("C-x 4 b" . consult-buffer-other-window) ;; orig. switch-to-buffer-other-window
         ("C-x 5 b" . consult-buffer-other-frame)  ;; orig. switch-to-buffer-other-frame
         ;; Custom M-# bindings for fast register access
         ("M-#" . consult-register-load)
         ("M-'" . consult-register-store)          ;; orig. abbrev-prefix-mark (unrelated)
         ("C-M-#" . consult-register)
         ;; Other custom bindings
         ("M-y" . consult-yank-pop)                ;; orig. yank-pop
         ("<help> a" . consult-apropos)            ;; orig. apropos-command
         ;; M-g bindings (goto-map)
         ("M-g e" . consult-compile-error)
         ("M-g f" . consult-flymake)               ;; Alternative: consult-flycheck
         ("M-g g" . consult-goto-line)             ;; orig. goto-line
         ("M-g M-g" . consult-goto-line)           ;; orig. goto-line
         ("M-g o" . consult-outline)               ;; Alternative: consult-org-heading
         ("M-g m" . consult-mark)
         ("M-g k" . consult-global-mark)
         ("M-g i" . consult-imenu)
         ("M-g I" . consult-project-imenu)
         ;; M-s bindings (search-map)
         ("M-s f" . consult-find)
         ("M-s L" . consult-locate)
         ("M-s g" . consult-grep)
         ("M-s G" . consult-git-grep)
         ("M-s r" . consult-ripgrep)
         ;; Replace isearch with consult-line
         ("C-s" . consult-line)
         ("M-s m" . consult-multi-occur)
         ("M-s k" . consult-keep-lines)
         ("M-s u" . consult-focus-lines)
         ;; Isearch integration
         ("M-s e" . consult-isearch)
         :map isearch-mode-map
         ("M-e" . consult-isearch)                 ;; orig. isearch-edit-string
         ("M-s e" . consult-isearch)               ;; orig. isearch-edit-string
         ("M-s l" . consult-line))                 ;; needed by consult-line to detect isearch

  :hook (completion-list-mode . consult-preview-at-point-mode)

  :init
  (setq register-preview-delay 0
        register-preview-function #'consult-register-format)

 (add-hook 'vertico-mode-hook (lambda ()
                                (setq completion-in-region-function
                                      (if vertico-mode
                                          #'consult-completion-in-region
                                        #'completion--in-region))))

 (advice-add #'register-preview :override #'consult-register-window)

 (advice-add #'completing-read-multiple :override #'consult-completing-read-multiple)

 (setq xref-show-xrefs-function #'consult-xref
       xref-show-definitions-function #'consult-xref)

 :config
 (consult-customize
  consult-theme
  :preview-key '(:debounce 0.2 any)
  consult-ripgrep consult-git-grep consult-grep
  consult-bookmark consult-recent-file consult-xref
  consult--source-file consult--source-project-file consult--source-bookmark
  :preview-key (kbd "M-."))

 (setq consult-narrow-key "<") ;; (kbd "C-+")
 (setq consult-project-root-function
       (lambda ()
         (when-let (project (project-current))
           (car (project-roots project))))))

(use-package embark
  :bind
  (("C-." . embark-act)         ;; pick some comfortable binding
   ("C-;" . embark-dwim)        ;; good alternative: M-.
   ("C-h B" . embark-bindings)) ;; alternative for `describe-bindings'

  :init
  (setq prefix-help-command #'embark-prefix-help-command)

  :config
  (add-to-list 'display-buffer-alist
               '("\\`\\*Embark Collect \\(Live\\|Completions\\)\\*"
                 nil
                 (window-parameters (mode-line-format . none)))))

(use-package embark-consult
  :after (embark consult)
  :demand t
  :hook
  (embark-collect-mode . consult-preview-at-point-mode))

(use-package corfu
  :hook ((prog-mode hy-mode) . corfu-mode)
  :custom
  (corfu-cycle t)            ;; Enable cycling for `corfu-next/previous'
  (corfu-auto t)             ;; Enable auto completion
  (corfu-quit-at-boundary t) ;; Automatically quit at word boundary
  (corfu-quit-no-match t)    ;; Automatically quit if there is no match
  (corfu-auto-delay 0)
  (corfu-auto-prefix 2)
  :bind (:map corfu-map
          ("TAB" . corfu-next)
          ([tab] . corfu-next)
          ("S-TAB" . corfu-previous)
          ([backtab] . corfu-previous)))

(use-package orderless
  :init
  (setq completion-styles '(orderless)
        completion-category-defaults nil
        completion-category-overrides '((file (styles . (partial-completion))))))

(use-package dabbrev
  :bind (("M-/" . dabbrev-completion)
         ("C-M-/" . dabbrev-expand)))

(use-package emacs
  :init

  (setq completion-cycle-threshold 3)
  (setq read-extended-command-predicate
         #'command-completion-default-include-p)
  (setq tab-always-indent 'complete))

(use-package affe
  :after orderless
  :config
  ;; Configure Orderless
  (setq affe-regexp-function #'orderless-pattern-compiler
        affe-highlight-function #'orderless--highlight)

  ;; Manual preview key for `affe-grep'
  (consult-customize affe-grep :preview-key (kbd "M-.")))

(use-package which-key
  :init
  (which-key-mode 1)
  :diminish which-key-mode
  :config
  (setq which-key-idle-delay 0.3)
  (setq which-key-separator " ")
  (setq which-key-prefix-prefix "+"))

(use-package projectile
  :diminish projectile-mode
  :config
  (setq projectile-require-project-root nil)
  (setq projectile-mode-line "")
  (projectile-mode)
  :demand t
  :bind-keymap ("C-c p" . projectile-command-map)
  :init
  (when (file-directory-p "~/Projects/Programming")
    (setq projectile-project-search-path '("~/Projects/Programming"))))

(use-package crux
  :config
  ;; Replace default commands with CRUX
  (global-set-key [remap move-beginning-of-line] #'crux-move-beginning-of-line)
  (global-set-key (kbd "C-c o") #'crux-open-with)
  (global-set-key [(shift return)] #'crux-smart-open-line)
  (global-set-key (kbd "C-<backspace>") #'crux-kill-line-backwards)
  (global-set-key [remap kill-whole-line] #'crux-kill-whole-line))

(use-package no-littering
  :config
  (require 'recentf)
  (add-to-list 'recentf-exclude no-littering-var-directory)
  (add-to-list 'recentf-exclude no-littering-etc-directory)
  (setq auto-save-file-name-transforms
        `((".*" ,(no-littering-expand-var-file-name "auto-save/") t)))
  (setq custom-file (expand-file-name "custom.el" user-emacs-directory)))

(defun rk/open-compilation-buffer (&optional buffer-or-name shackle-alist shackle-plist)
  "Helper for selecting window for opening *compilation* buffers."
  ;; find existing compilation window left of the current window or left-most window
  (let ((win (or (loop for win = (if win (window-left win) (get-buffer-window))
                       when (or (not (window-left win))
                                (string-prefix-p "*compilation" (buffer-name (window-buffer win))))
                       return win)
                 (get-buffer-window))))
    ;; if the window is dedicated to a non-compilation buffer, use the current one instead
    (when (window-dedicated-p win)
      (let ((buf-name (buffer-name (window-buffer win))))
        (unless (string-prefix-p "*compilation" buf-name)
          (setq win (get-buffer-window)))))
    (set-window-buffer win (get-buffer buffer-or-name))
    (set-frame-selected-window (window-frame win) win)))


(use-package shackle
  :diminish
  :custom
  (shackle-rules '((compilation-mode :custom rk/open-compilation-buffer :select t)
                   ("\\*Apropos\\|Help\\|Occur\\|tide-references\\*" :regexp t :same t :select t :inhibit-window-quit t)
                   ("\\*magit" :regexp t :same t :select t)
                   ("\\*shell.*" :regexp t :same t :select t)
                   ("\\*PowerShell.*" :regexp t :same t :select t)
                   ("\\*Cargo.*" :regexp t :other t :select nil)
                   ("*Messages*" :select nil :other t)
                   ("*go-guru-output*" :select t :same t)
                   ("*Proced*" :select t :same t)
                   ("*Buffer List*" :select t :same t)
                   ("\\*Pp Eval" :regexp t :same nil :select t :other t)
                   ("*Messages*" :same nil :other t :select t :inhibit-window-quit t)

                   ;; slime
                   ("*slime-source*" :select nil :same nil :other t)
                   ("*slime-description*" :select nil :other t :inhibit-window-quit t)
                   ("\\*slime-repl" :regexp t :same nil :select nil :other t)
                   ;; ("\\*sldb" :regexp t :other t :inhibit-window-quit t :select t)
                   ("\\*slime-compilation" :regexp t :same nil :select nil :other t)
                   ("*slime-scratch*" :same nil :select t :other t)

                   ;; ert
                   ("*ert*" :select nil :same nil :other t)

                   ;; clojure
                   ("*sesman CIDER browser*" :inhibit-window-quit t :select t :same t)
                   ("\\*cider-repl" :regexp t :same nil :other t)))
  (shackle-default-rule nil))

(shackle-mode)

(use-package undo-fu
  :config
  (global-unset-key (kbd "C-/"))
  (global-set-key (kbd "C-/")   'undo-fu-only-undo)
  (global-set-key (kbd "C-S-/") 'undo-fu-only-redo))

(use-package helpful
  :config
  ;; Note that the built-in `describe-function' includes both functions
  ;; and macros. `helpful-function' is functions only, so we provide
  ;; `helpful-callable' as a drop-in replacement.
  (global-set-key (kbd "C-h f") #'helpful-callable)

  (global-set-key (kbd "C-h v") #'helpful-variable)
  (global-set-key (kbd "C-h k") #'helpful-key)
  ;; Lookup the current symbol at point. C-c C-d is a common keybinding
  ;; for this in lisp modes.
  (global-set-key (kbd "C-c C-d") #'helpful-at-point)

  ;; Look up *F*unctions (excludes macros).
  ;;
  ;; By default, C-h F is bound to `Info-goto-emacs-command-node'. Helpful
  ;; already links to the manual, if a function is referenced there.
  (global-set-key (kbd "C-h F") #'helpful-function)

  ;; Look up *C*ommands.
  ;;
  ;; By default, C-h C is bound to describe `describe-coding-system'. I
  ;; don't find this very useful, but it's frequently useful to only
  ;; look at interactive functions.
  (global-set-key (kbd "C-h C") #'helpful-command))

(use-package latex
  :straight nil
  :defer t
  :ensure auctex
  :hook ((LaTeX-mode . prettify-symbols-mode))
  :bind (:map LaTeX-mode-map
         ("C-S-e" . latex-math-from-calc))
  :config
  ;; Format math as a Latex string with Calc
  (defun latex-math-from-calc ()
    "Evaluate `calc' on the contents of line at point."
    (interactive)
    (cond ((region-active-p)
           (let* ((beg (region-beginning))
                  (end (region-end))
                  (string (buffer-substring-no-properties beg end)))
             (kill-region beg end)
             (insert (calc-eval `(,string calc-language latex
                                          calc-prefer-frac t
                                          calc-angle-mode rad)))))
          (t (let ((l (thing-at-point 'line)))
               (end-of-line 1) (kill-line 0)
               (insert (calc-eval `(,l
                                    calc-language latex
                                    calc-prefer-frac t
                                    calc-angle-mode rad))))))))

(use-package preview
  :straight nil
  :after latex
  :hook ((LaTeX-mode . preview-larger-previews))
  :config
  (defun preview-larger-previews ()
    (setq preview-scale-function
          (lambda () (* 1.25
                   (funcall (preview-scale-from-face)))))))

(use-package cdlatex
  :ensure t
  :hook (LaTeX-mode . turn-on-cdlatex)
  :bind (:map cdlatex-mode-map
              ("<tab>" . cdlatex-tab)))

(use-package yasnippet-snippets)

(use-package yasnippet
  :hook ((LaTeX-mode . yas-minor-mode)
         (post-self-insert . my/yas-try-expanding-auto-snippets))
  :after yasnippet-snippets
  :diminish yas-minor-mode
  :hook ((prog-mode text-mode) . yas-minor-mode)
  :config
  (add-to-list 'yas-snippet-dirs "~/.emacs.d/snippets")
  (yas-reload-all)
  (use-package warnings
    :config
    (cl-pushnew '(yasnippet backquote-change)
                warning-suppress-types
                :test 'equal))
  (setq yas-triggers-in-field t)
  ;; Function that tries to autoexpand YaSnippets
  ;; The double quoting is NOT a typo!
  (defun my/yas-try-expanding-auto-snippets ()
    (when (and (boundp 'yas-minor-mode) yas-minor-mode)
      (let ((yas-buffer-local-condition ''(require-snippet-condition . auto)))
        (yas-expand)))))

(use-package cdlatex
  :hook ((cdlatex-tab . yas-expand)
         (cdlatex-tab . cdlatex-in-yas-field))
  :config
  (use-package yasnippet
    :bind (:map yas-keymap
           ("<tab>" . yas-next-field-or-cdlatex)
           ("TAB" . yas-next-field-or-cdlatex))
    :config
    (defun cdlatex-in-yas-field ()
      ;; Check if we're at the end of the Yas field
      (when-let* ((_ (overlayp yas--active-field-overlay))
                  (end (overlay-end yas--active-field-overlay)))
        (if (>= (point) end)
            ;; Call yas-next-field if cdlatex can't expand here
            (let ((s (thing-at-point 'sexp)))
              (unless (and s (assoc (substring-no-properties s)
                                    cdlatex-command-alist-comb))
                (yas-next-field-or-maybe-expand)
                t))
          ;; otherwise expand and jump to the correct location
          (let (cdlatex-tab-hook minp)
            (setq minp
                  (min (save-excursion (cdlatex-tab)
                                       (point))
                       (overlay-end yas--active-field-overlay)))
            (goto-char minp) t))))

    (defun yas-next-field-or-cdlatex ()
      (interactive)
      "Jump to the next Yas field correctly with cdlatex active."
      (if (bound-and-true-p cdlatex-mode)
          (cdlatex-tab)
        (yas-next-field-or-maybe-expand)))))

(use-package magit
  :commands (magit-status magit-get-current-branch)
  :custom
  (magit-display-buffer-function #'magit-display-buffer-same-window-except-diff-v1)
  :bind ("C-x g" . magit-status))

;; well yeah I want git gutter
(use-package git-gutter
  :diminish
  :hook ((prog-mode) . git-gutter-mode)
  :config
  (setq git-gutter:update-interval 2))

(use-package ediff)
;; don't start another frame
;; this is done by default in prelude
(setq ediff-window-setup-function 'ediff-setup-windows-plain)
;; put windows side by side
(setq ediff-split-window-function (quote split-window-horizontally))
;;revert windows on exit - needs winner mode
(winner-mode)
(add-hook 'ediff-after-quit-hook-internal 'winner-undo)

(setq catster/use-pdf-view t)

(when catster/use-pdf-view
  ;; wrapper for save-buffer ignoring arguments
  (defun bjm/save-buffer-no-args ()
    "Save buffer ignoring arguments"
    (save-buffer))

  (use-package pdf-tools
    :config
    ;; initialise
    (pdf-tools-install :no-query)
    (setq-default pdf-view-display-size 'fit-page)
    ;; automatically annotate highlights
    (setq pdf-annot-activate-created-annotations t)
    ;; use isearch instead of swiper
    (define-key pdf-view-mode-map (kbd "C-s") 'isearch-forward)
    ;; turn off cua so copy works
    (add-hook 'pdf-view-mode-hook (lambda () (cua-mode 0)))
    ;; more fine-grained zooming
    (setq pdf-view-resize-factor 1.1)
    ;; keyboard shortcuts
    (define-key pdf-view-mode-map (kbd "h") 'pdf-annot-add-highlight-markup-annotation)
    (define-key pdf-view-mode-map (kbd "t") 'pdf-annot-add-text-annotation)
    (define-key pdf-view-mode-map (kbd "D") 'pdf-annot-delete)
    ;; wait until map is available
    (with-eval-after-load "pdf-annot"
      (define-key pdf-annot-edit-contents-minor-mode-map (kbd "<return>") 'pdf-annot-edit-contents-commit)
      (define-key pdf-annot-edit-contents-minor-mode-map (kbd "<S-return>") 'newline)
      ;; save after adding comment
      (advice-add 'pdf-annot-edit-contents-commit :after 'bjm/save-buffer-no-args))))

(use-package dashboard
  :preface
  (defun my/dashboard-banner ()
    "Set a dashboard banner including information on package initialization
  time and garbage collections."""
    (setq dashboard-banner-logo-title
          (format "Emacs ready in %.2f seconds with %d garbage collections."
                  (float-time (time-subtract after-init-time before-init-time)) gcs-done)))
  :custom
  (dashboard-set-heading-icons t)
  (dashboard-set-file-icons t)
  (dashboard-center-content t)
  :config
  (setq dashboard-startup-banner 'logo)
  (dashboard-setup-startup-hook)
  :hook ((after-init     . dashboard-refresh-buffer)
         (dashboard-mode . my/dashboard-banner)))

(setq initial-buffer-choice (lambda () (get-buffer "*dashboard*")))

(use-package dockerfile-mode
  :mode "Dockerfile\\'")

(use-package docker
  :bind ("C-c d" . docker))

(use-package docker-compose-mode)

(use-package docker-tramp)

(use-package hydra)

(setq lv-use-separator t)

(use-package caddyfile-mode)

(use-package erc-hl-nicks
  :after erc)

(use-package erc-image
  :after erc)

(use-package erc
  :straight nil
  :preface
  (defun connect-irc-or-switch ()
    "Connects to ERC, or switch to last active buffer."
    (interactive)
    (if (get-buffer "bnc.irccloud.com:6697")
        (erc-track-switch-buffer 1)
      (when (y-or-n-p "Start ERC? ")
        (erc-tls :server "bnc.irccloud.com" :port 6697 :nick "thecatster"))))

  (defun my/erc-notify (nickname message)
    "Displays a notification message for ERC."
    (let* ((channel (buffer-name))
           (nick (erc-hl-nicks-trim-irc-nick nickname))
           (title (if (string-match-p (concat "^" nickname) channel)
                      nick
                    (concat nick " (" channel ")")))
           (msg (s-trim (s-collapse-whitespace message))))
      (alert (concat nick ": " msg) :title title)))

  (defun my/erc-count-users ()
    "Displays the number of users connected on the current channel."
    (interactive)
    (if (get-buffer "bnc.irccloud.com:6697")
        (let ((channel (erc-default-target)))
          (if (and channel (erc-channel-p channel))
              (message "%d users are online on %s"
                       (hash-table-count erc-channel-users)
                       channel)
            (user-error "The current buffer is not a channel")))
      (user-error "You must first start ERC")))

  (defun my/erc-preprocess (string)
    "Avoids channel flooding."
    (setq str
          (string-trim
           (replace-regexp-in-string "\n+" " " str))))

  :hook ((ercn-notify . my/erc-notify)
         (erc-send-pre . my/erc-preprocess))
  :commands erc
  :init
  (require 'erc-desktop-notifications)
  :custom
  (erc-autojoin-timing 'ident)
  (erc-fill-function 'erc-fill-static)
  (erc-fill-static-center 22)
  (erc-hide-list '("JOIN" "PART" "QUIT"))
  (erc-lurker-hide-list '("JOIN" "PART" "QUIT"))
  (erc-lurker-threshold-time 43200)
  (erc-prompt-for-nickserv-password nil)
  (erc-prompt-for-password nil)
  (erc-auto-query 'bury)
  (erc-join-buffer 'bury)
  (erc-rename-buffers t)
  (erc-kill-buffer-on-part t)
  (erc-fill-column 120)
  (erc-autojoin-channels-alist '(("bnc.irccloud.com" "#systemcrafters" "#emacs" "#guix" "#emacs-conf" "#archlinux" "#org-mode")))
  (erc-quit-reason (lambda (s) (or s "Exiting hyperspace... prepare for jump by jump")))
  (erc-server-reconnect-attempts 3)
  (erc-server-reconnect-timeout 3)
  (erc-track-exclude-types '("JOIN" "MODE" "NICK" "PART" "AWAY"
                             "324" "329" "332" "333" "353" "477"))
  (erc-modules '(
                 autojoin
                 button
                 completion
                 fill
                 hl-nicks
                 image
                 irccontrols
                 keep-place
                 list
                 log
                 match
                 menu
                 move-to-prompt
                 netsplit
                 networks
                 noncommands
                 notify
                 notifications
                 readonly
                 ring
                 stamp
                 track))
  :config
  (erc-services-mode 1)
  (erc-update-modules))

(use-package flycheck
  :hook ((lsp-mode ledger-mode org-mode) . flycheck-mode)
  :config
  (setq-default flycheck-temp-prefix ".flycheck"))

(add-hook 'text-mode-hook 'flyspell-mode)
(add-hook 'org-mode-hook 'flyspell-mode)

(flycheck-define-checker proselint
  "A linter for prose."
  :command ("proselint" source-inplace)
  :error-patterns
  ((warning line-start (file-name) ":" line ":" column ": "
	    (id (one-or-more (not (any " "))))
	    (message) line-end))
  :modes (text-mode markdown-mode gfm-mode org-mode))

(add-to-list 'flycheck-checkers 'proselint)

(use-package treemacs
  :defer t
  :config
  (treemacs-follow-mode t)
  (treemacs-filewatch-mode t)
  (treemacs-fringe-indicator-mode 'always)
  (treemacs-git-mode 'deferred))

(use-package lsp-treemacs
  :after treemacs)

(use-package treemacs-projectile
  :after (treemacs projectile))

(use-package treemacs-magit
  :after (treemacs magit))

(use-package screenshot
  :config
  (load-file (locate-library "screenshot.el")))

(use-package editorconfig
  :config
  (editorconfig-mode 1))

(use-package quickrun)

(use-package scad-mode)
(use-package scad-preview)

(setq catster/use-mail nil)

(when catster/use-mail
  (add-to-list 'load-path "~/.emacs.d/mu4e/")
  (require 'catsters-mail))

(use-package format-all
  :hook (prog-mode . format-all-mode))

(show-paren-mode 1)
  (use-package smartparens
    :hook (prog-mode . smartparens-mode)
    :config
    (setq sp-highlight-pair-overlay t)
    (setq sp-autoskip-closing-pair 'always)
    (setq sp-cancel-autoskip-on-backward-movement nil))

(use-package compile
  :custom
  (compilation-scroll-output t))

(use-package rainbow-delimiters
  :diminish rainbow-delimiters-mode
  :hook ((hy-mode python-mode rustic-mode c-mode js-mode rjsx-mode web-mode css-mode html-mode) . rainbow-delimiters-mode))

(use-package rainbow-mode
  :diminish rainbow-mode
  :hook ((org-mode emacs-lisp-mode web-mode typescript-mode rjsx-mode) . rainbow-mode)
  :config
  (setq rainbow-x-colors nil))

(use-package kurecolor)

(use-package fzf)

(use-package deadgrep)

(use-package hl-todo
  :hook (prog-mode . hl-todo-mode)
  :hook (yaml-mode . hl-todo-mode)
  :custom
  (hl-todo-highlight-punctuation ":")
  (hl-todo-keyword-faces
        `(;; For things that need to be done, just not today.
          ("TODO" warning bold)
          ;; For problems that will become bigger problems later if not
          ;; fixed ASAP.
          ("FIXME" error bold)
          ;; For tidbits that are unconventional and not intended uses of the
          ;; constituent parts, and may break in a future update.
          ("HACK" font-lock-constant-face bold)
          ;; For things that were done hastily and/or hasn't been thoroughly
          ;; tested. It may not even be necessary!
          ("REVIEW" font-lock-keyword-face bold)
          ;; For especially important gotchas with a given implementation,
          ;; directed at another user other than the author.
          ("NOTE" success bold)
          ;; For things that just gotta go and will soon be gone.
          ("DEPRECATED" font-lock-doc-face bold)
          ;; For a known bug that needs a workaround
          ("BUG" error bold)
          ;; For warning about a problematic or misguiding code
          ("XXX" font-lock-constant-face bold))))

(use-package lsp-mode
  :defer t
  :hook (((rustic-mode
     python-mode
     rjsx-mode
     web-mode
     typescript-mode
     clojure-mode) . lsp)
   (lsp-mode . lsp-enable-which-key-integration))
  :commands (lsp)
  :init
  (setq  lsp-keymap-prefix "C-c l"
   lsp-eslint-run "onSave"
   lsp-completion-provider :capf
   lsp-log-io nil
   lsp-idle-delay 1
   lsp-headerline-breadcrumb-enable nil))

(use-package lsp-ui
  :hook (lsp-mode . lsp-ui-mode)
  :commands lsp-ui-mode
  :init
  (setq lsp-ui-sideline-show-hover nil
  lsp-ui-sideline-enable t
  lsp-ui-doc-enable nil
  lsp-signature-auto-activate nil
  lsp-signature-render-document nil
  ;; This is SO annoying. Believe it or not, I know what a `fn` does
  ;; in Rust!
  lsp-eldoc-render-all nil))

;; (use-package dap-mode
;;   :after lsp-mode
;;   :custom
;;   (lsp-enable-dap-auto-configure nil)
;;   :config
;;   (dap-ui-mode 1)
;;   (dap-tooltip-mode 1)
;;   (require 'dap-python)
;;   (require 'dap-lldb)
;;   (require 'dap-gdb-lldb)
;;   (dap-register-debug-template "Rust::GDB Run Configuration"
;;                                (list :type "gdb"
;;                                      :request "launch"
;;                                      :name "GDB::Run"
;;                                      :gdbpath "rust-gdb"
;;                                      :target nil
;;                                      :cwd nil))
;;   (require 'dap-node)
;;   (dap-node-setup))

;; (add-hook 'dap-stopped-hook
;;           (lambda (arg) (call-interactively #'dap-hydra)))

;;; Source: Configuring Emacs for Rust development - https://robert.kra.hn/posts/2021-02-07_rust-with-emacs/
(use-package ron-mode)

(use-package rustic
  :after lsp-mode
  :bind (:map rustic-mode-map
              ("C-c C-c l" . flycheck-list-errors)
              ("M-?" . lsp-find-references)
              ("C-c C-c a" . lsp-execute-code-action)
              ("C-c C-c r" . lsp-rename)
              ("C-c C-c q" . lsp-workspace-restart)
              ("C-c C-c Q" . lsp-workspace-shutdown)
              ("C-c C-c s" . lsp-rust-analyzer-status)
              ("C-c C-c d" . dap-hydra))
  :config
  (setq lsp-rust-analyzer-cargo-watch-command "clippy")
  (setq lsp-rust-analyzer-server-display-inlay-hints t)
  (setq rustic-format-on-save nil)
  (add-hook 'rustic-mode-hook 'rk/rustic-mode-hook))

(defun rk/rustic-mode-hook ()
  (setq-local buffer-save-without-query t))

(use-package cargo-mode
  :config
  (add-hook 'rustic-mode-hook 'cargo-minor-mode))

(use-package lsp-python-ms
  :after lsp-mode
  :defer 0.3
  :custom (lsp-python-ms-auto-install-server t))

(use-package python
  :after lsp-mode
  :delight "π "
  :bind (("M-[" . python-nav-backward-block)
         ("M-]" . python-nav-forward-block))
  :preface
  (defun python-remove-unused-imports()
    "Removes unused imports and unused variables with autoflake."
    (interactive)
    (if (executable-find "autoflake")
        (progn
          (shell-command (format "autoflake --remove-all-unused-imports -i %s"
                                 (shell-quote-argument (buffer-file-name))))
          (revert-buffer t t t))
      (warn "python-mode: Cannot find autoflake executable."))))

(use-package blacken
  :delight
  :hook (python-mode . blacken-mode)
  :custom (blacken-line-length 79))

(use-package py-isort
  :after python
  :hook ((python-mode . pyvenv-mode)
         (before-save . py-isort-before-save)))

(use-package pyenv-mode
  :after python
  :hook ((python-mode . pyenv-mode)
         (projectile-switch-project . projectile-pyenv-mode-set))
  :custom (pyenv-mode-set "3.8.5")
  :preface
  (defun projectile-pyenv-mode-set ()
    "Set pyenv version matching project name."
    (let ((project (projectile-project-name)))
      (if (member project (pyenv-mode-versions))
          (pyenv-mode-set project)
        (pyenv-mode-unset)))))

(use-package pyvenv
  :after python
  :hook (python-mode . pyvenv-mode)
  :custom
  (pyvenv-default-virtual-env-name "env")
  (pyvenv-mode-line-indicator '(pyvenv-virtual-env-name ("[venv:"
                                                         pyvenv-virtual-env-name "]"))))

(use-package pipenv
  :hook (python-mode . pipenv-mode)
  :init
  (setq
   pipenv-projectile-after-switch-function
   #'pipenv-projectile-after-switch-extended))

;; BUG: Currently, you have to manually activate Hy mode again due to a bug in the package.
;; A PR has been open since February 2021, but not yet merged.
(use-package hy-mode)

(use-package ccls
  :after projectile
  :custom
  (ccls-args nil)
  (ccls-executable (executable-find "ccls"))
  (projectile-project-root-files-top-down-recurring
   (append '("compile_commands.json" ".ccls")
           projectile-project-root-files-top-down-recurring))
  :config (push ".ccls-cache" projectile-globally-ignored-directories))

(use-package cmake-mode
  :mode ("CMakeLists\\.txt\\'" "\\.cmake\\'"))

(use-package cmake-font-lock
  :after (cmake-mode)
  :hook (cmake-mode . cmake-font-lock-activate))

(use-package google-c-style
  :hook ((c-mode c++-mode) . google-set-c-style)
  (c-mode-common . google-make-newline-indent))

(use-package arduino-mode)

(use-package typescript-mode
  :hook (typescript-mode . (lambda () (electric-indent-local-mode -1) (setq-local create-lockfiles nil)))
  :init
  (define-derived-mode typescript-tsx-mode typescript-mode "tsx")
  :config
  (setq typescript-indent-level 2)
  (add-to-list 'auto-mode-alist '("\\.tsx?\\'" . typescript-tsx-mode)))

(use-package tree-sitter
  :hook ((typescript-mode . tree-sitter-hl-mode)
         (typescript-tsx-mode . tree-sitter-hl-mode)))

(use-package tree-sitter-langs
  :after tree-sitter
  :config
  (tree-sitter-require 'tsx)
  (add-to-list 'tree-sitter-major-mode-language-alist '(typescript-tsx-mode . tsx)))

(use-package rjsx-mode
  :hook (rjsx-mode . (lambda () (electric-indent-local-mode -1) (setq-local create-lockfiles nil)))
  :mode "\\.js.*$")

(use-package json-mode
  :mode "\\.json$")

(use-package prettier-js
  :hook ((typescript-mode typescript-tsx-mode rjsx-mode json-mode css-mode html-mode) . prettier-js-mode)
  :config
  (setq prettier-js-show-errors nil))

(use-package geiser-mit)

(use-package macrostep-geiser
  :after geiser-mode
  :config (add-hook 'geiser-mode-hook #'macrostep-geiser-setup))

(use-package macrostep-geiser
  :after geiser-repl
  :config (add-hook 'geiser-repl-mode-hook #'macrostep-geiser-setup))

(defun +org|setup-ui ()
  "Configures the UI for `org-mode'."
  (auto-fill-mode 0)
  (visual-line-mode 1)
  (setq-default org-adapt-indentation nil
                org-cycle-include-plain-lists t
                org-eldoc-breadcrumb-separator " → "
                org-entities-user '(("flat" "\\flat" nil "" "" "266D" "♭") ("sharp" "\\sharp" nil "" "" "266F" "♯"))
                org-fontify-done-headline t
                org-fontify-quote-and-verse-blocks t
                org-fontify-whole-heading-line t
                org-footnote-auto-label 'plain
                org-hidden-keywords nil
                org-hide-emphasis-markers t
                org-hide-leading-stars t
                org-hide-leading-stars-before-indent-mode t
                org-image-actual-width nil
                org-indent-indentation-per-level 2
                org-indent-mode-turns-on-hiding-stars t
                org-list-description-max-indent 4
                org-pretty-entities nil
                org-pretty-entities-include-sub-superscripts t
                org-priority-faces '((?a . error) (?b . warning) (?c . success))
                org-refile-targets '((nil :maxlevel . 3) (org-agenda-files :maxlevel . 3))
                org-startup-folded t
                org-startup-indented t
                org-startup-with-inline-images nil
                org-tags-column 0
                org-todo-keywords '((sequence "TODO(t)" "|" "DONE(d)") (sequence "[ ](T)" "[-](p)" "[?](m)" "|" "[X](D)") (sequence "NEXT(n)" "WAITING(w)" "LATER(l)" "|" "CANCELLED(c)"))
                org-todo-keyword-faces '(("[-]" :inherit (font-lock-constant-face bold)) ("[?]" :inherit (warning bold)) ("WAITING" :inherit bold) ("LATER" :inherit (warning bold)))
                org-use-sub-superscripts '{}))

(add-hook 'org-mode-hook #'+org|setup-ui)

(setq org-src-preserve-indentation nil
      org-edit-src-content-indentation 0)

(font-lock-add-keywords 'org-mode
                        '(("^ *\\([-]\\) "
                           (0 (prog1 () (compose-region (match-beginning 1) (match-end 1) "•"))))))

(custom-theme-set-faces
 'user
 '(org-block ((t (:inherit fixed-pitch))))
 '(org-code ((t (:inherit (shadow fixed-pitch)))))
 '(org-document-info ((t (:foreground "dark orange"))))
 '(org-document-info-keyword ((t (:inherit (shadow fixed-pitch)))))
 '(org-indent ((t (:inherit (org-hide fixed-pitch)))))
 '(org-link ((t (:foreground "royal blue" :underline t))))
 '(org-meta-line ((t (:inherit (font-lock-comment-face fixed-pitch)))))
 '(org-property-value ((t (:inherit fixed-pitch))) t)
 '(org-special-keyword ((t (:inherit (font-lock-comment-face fixed-pitch)))))
 '(org-table ((t (:inherit fixed-pitch :foreground "#83a598"))))
 '(org-tag ((t (:inherit (shadow fixed-pitch) :weight bold :height 0.8))))
 '(org-verbatim ((t (:inherit (shadow fixed-pitch))))))

(defun ck/org-confirm-babel-evaluate (lang body)
  (not (or (string= lang "latex") (string= lang "emacs-lisp") (string= lang "ledger"))))
(setq org-confirm-babel-evaluate 'ck/org-confirm-babel-evaluate)

;; Change colours for headings
(custom-set-faces
 '(default     ((t (:foreground "#BBC2CF"))))
 '(org-level-1 ((t (:foreground "#BF9D7A"))))
 '(org-level-2 ((t (:foreground "#E4E9CD"))))
 '(org-level-3 ((t (:foreground "#EBF2EA"))))
 '(org-level-4 ((t (:foreground "#0ABDA0"))))
 '(org-level-5 ((t (:foreground "#80ADD7")))))

(use-package org-superstar
  :diminish org-superstar-mode
  :hook (org-mode . org-superstar-mode))

(use-package org-appear
  :diminish org-appear-mode
  :hook (org-mode . org-appear-mode))

(setq org-directory "~/Nextcloud/org/" ; This way, all org mode files are synced across devices
      org-agenda-files '("~/Nextcloud/org/")
      org-default-notes-file (expand-file-name "notes.org" org-directory)
      org-ellipsis " ▼ "
      org-capture-templates
      '(("t" "todo" entry (file+headline "~/Nextcloud/org/todo.org" "Tasks")
         "* TODO [#A] %?\nSCHEDULED: %(org-insert-time-stamp (org-read-date nil t \"+0d\"))\n%a\n")
        ("j" "Journal Entry" entry (file+olp+datetree "~/Nextcloud/org/journal.org.gpg")
         "* %? %i %a Added: %U")
        ("K" "Cliplink capture task" entry (file "")
         "* TODO %(org-cliplink-capture) \n  SCHEDULED: %t\n" :empty-lines 1))
      org-log-done 'time
      org-journal-date-format "%B %d, %Y (%A) "
      org-hide-emphasis-markers t
      org-link-abbrev-alist    ; This overwrites the default Doom org-link-abbrev-list
      '(("google" . "http://www.google.com/search?q=")
        ("arch-wiki" . "https://wiki.archlinux.org/index.php/")
        ("ddg" . "https://duckduckgo.com/?q=")
        ("wiki" . "https://en.wikipedia.org/wiki/"))
      org-todo-keywords        ; This overwrites the default Doom org-todo-keywords
      '((sequence
         "TODO(t)"           ; A task that is ready to be tackled
         "BLOG(b)"           ; Blog writing assignments
         "GYM(g)"            ; Things to accomplish at the gym
         "PROJ(p)"           ; A project that contains other tasks
         "VIDEO(v)"          ; Video assignments
         "WAIT(w)"           ; Something is holding up this task
         "|"                 ; The pipe necessary to separate "active" states and "inactive" states
         "DONE(d)"           ; Task has been completed
         "CANCELLED(c)"))) ; Task has been cancelled

(setq calc-angle-mode 'rad  ; radians are rad, screw degrees
      calc-symbolic-mode t) ; keeps expressions like \sqrt{2} irrational for as long as possible

(with-eval-after-load 'org-indent
  (add-hook 'org-mode-hook 'org-indent-mode))

;; Word choice and such
(use-package writegood-mode
  :bind ("C-c g" . writegood-mode)
  :config
  (add-to-list 'writegood-weasel-words "actionable"))

;; Various good settings
(setq org-agenda-window-setup (quote current-window)) ;; open agenda in current window
(setq org-deadline-warning-days 7) ;; warn me of any deadlines in next 7 days
(setq org-agenda-span (quote fortnight)) ;; show me tasks scheduled or due in next fortnight
(setq org-agenda-skip-scheduled-if-deadline-is-shown t) ;; don't show tasks as scheduled if they are already shown as a deadline
(setq org-agenda-skip-deadline-prewarning-if-scheduled (quote pre-scheduled))
(setq org-agenda-todo-ignore-deadlines (quote all))
(setq org-agenda-todo-ignore-scheduled (quote all))
(setq org-agenda-sorting-strategy
      (quote
       ((agenda deadline-up priority-down)
        (todo priority-down category-keep)
        (tags priority-down category-keep)
        (search category-keep))))

(use-package org-journal
  :init
  (setq org-journal-prefix-key "C-x j")
  :config
  (setq org-journal-dir "~/Nextcloud/org/journal/"
        org-journal-date-format "%A, %d %B %Y"))

(use-package ob-hy)
(use-package ob-rust)

(org-babel-do-load-languages
 'org-babel-load-languages
 '((arduino . t)
   (C . t)
   (emacs-lisp . t)
   (gnuplot . t)
   (hy . t)
   (js . t)
   (latex . t)
   (lisp . t)
   (python . t)
   (rust . t)
   (shell . t)))

(setq org-roam-v2-ack t)

(use-package org-roam
      :custom
      (org-roam-v2-ack t)
      (org-roam-db-gc-threshold most-positive-fixnum)
      (org-roam-directory (file-truename "~/Nextcloud/org/org-roam"))
      :config
      (org-roam-setup)
      (require 'org-roam-protocol))

(use-package org-roam-ui
    :after org-roam
    :hook (after-init . org-roam-ui-mode)
    :config
    (setq org-roam-ui-sync-theme t
          org-roam-ui-follow t
          org-roam-ui-update-on-save t
          org-roam-ui-open-on-start t))

(use-package org-cliplink
  :config
  (global-set-key (kbd "C-x p i") 'org-cliplink))

(use-package org-web-tools
  :custom
  (org-web-tools-pandoc-sleep-time 0.5))

(defun dw/org-present-prepare-slide ()
  (org-overview)
  (org-show-entry)
  (org-show-children))

(defun dw/org-present-hook ()
  (setq-local face-remapping-alist '((default (:height 1.5) variable-pitch)
                                     (header-line (:height 4.5) variable-pitch)
                                     (org-code (:height 1.55) org-code)
                                     (org-verbatim (:height 1.55) org-verbatim)
                                     (org-block (:height 1.25) org-block)
                                     (org-block-begin-line (:height 0.7) org-block)))
  (setq header-line-format " ")
  (org-display-inline-images)
  (dw/org-present-prepare-slide))

(defun dw/org-present-quit-hook ()
  (setq-local face-remapping-alist '((default variable-pitch default)))
  (setq header-line-format nil)
  (org-present-small)
  (org-remove-inline-images))

(defun dw/org-present-prev ()
  (interactive)
  (org-present-prev)
  (dw/org-present-prepare-slide))

(defun dw/org-present-next ()
  (interactive)
  (org-present-next)
  (dw/org-present-prepare-slide))

(use-package org-present
  :bind (:map org-present-mode-keymap
              ("C-c C-j" . dw/org-present-next)
              ("C-c C-k" . dw/org-present-prev))
  :hook ((org-present-mode . dw/org-present-hook)
         (org-present-mode-quit . dw/org-present-quit-hook)))

(use-package org-make-toc
  :hook (org-mode . org-make-toc-mode))

;; NO spell check for embedded snippets
(defadvice org-mode-flyspell-verify (after org-mode-flyspell-verify-hack activate)
  (let* ((rlt ad-return-value)
         (begin-regexp "^[ \t]*#\\+begin_\\(src\\|html\\|latex\\|example\\|quote\\)")
         (end-regexp "^[ \t]*#\\+end_\\(src\\|html\\|latex\\|example\\|quote\\)")
         (case-fold-search t)
         b e)
    (when ad-return-value
      (save-excursion
        (setq b (re-search-backward begin-regexp nil t))
        (if b (setq e (re-search-forward end-regexp nil t))))
      (if (and b e (< (point) e)) (setq rlt nil)))
    (setq ad-return-value rlt)))

(use-package general
  :init
  ;; My Caps Lock is bound to escape, so this is always close.
  (defconst my-leader "<escape>")
  (general-create-definer my-leader-def :prefix my-leader)
  (general-auto-unbind-keys)
  :config
  (my-leader-def
    "" '(:ignore t :wk "personal keybindings"))
  ;; Org Agenda
  (my-leader-def
    "a" '(:ignore t :wk "org")
    "aa" '(org-agenda :wk "agenda"))
  ;; Org Roam
  (my-leader-def
    "n" '(:ignore t :wk "org roam")
    "nl" '(org-roam-buffer-toggle :wk "buffer toggle")
    "nf" '(org-roam-node-find :wk "find node")
    "ng" '(org-roam-graph :wk "graph")
    "ni" '(org-roam-node-insert :wk "insert node")
    "nc" '(org-roam-capture :wk "capture")
    "nj" '(org-roam-dailies-capture-today :wk "daily capture")
    "nu" '(org-roam-ui-open :wk "ui")))