summaryrefslogtreecommitdiff
path: root/tw/home/files/emacs-init.el
blob: dcf7e784e99a1dc24339c1e31f77a4a14eaf8ba0 (about) (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
;;; init.el --- Emacs configuration. -*- lexical-binding: t -*-
;;; Commentary:
;;; Code:

;; Load settings set through Custom.
;; (setq custom-file (locate-user-emacs-file "custom.el"))
;; (when (file-readable-p custom-file)
;;   (load custom-file))

(defun tw/xdg-emacs-subdir (type name)
  "Get the name of a subdirectory called NAME under $XDG_<TYPE>_HOME/emacs."
  (expand-file-name
   (concat "emacs/" (string-trim-right name "/"))
   (pcase type
     ('cache (or (getenv "XDG_CACHE_HOME") "~/.cache/"))
     ('config (or (getenv "XDG_CONFIG_HOME") "~/.config/"))
     ('data (or (getenv "XDG_DATA_HOME") "~/.local/share/"))
     ;; The following two are Guix/GuixSD extensions.
     ('log (or (getenv "XDG_LOG_HOME") "~/.local/var/log/"))
     ('state (or (getenv "XDG_STATE_HOME") "~/.local/var/lib/"))
     (_ (error "Unknown XDG directory type: %S" type)))))

;; Global/built-in Custom settings
;; Apply these as early as possible so that e.g. the native-comp files go to the right place.
(mapc (apply-partially #'apply #'customize-set-variable)
      `((native-comp-async-report-warnings-errors silent "Don't pop up Warnings buffer for native compilation.")
        ;; Emacs GUI customization.
        (inhibit-startup-screen t "Don't show the startup screen with help links.")
        (menu-bar-mode nil "Hide the menu bar globally.")
        (tool-bar-mode nil "Hide the tool bar globally.")
        (tooltip-mode nil "Show tooltips in the echo area instead.")
        (max-mini-window-height 3 "Let the echo area grow to a maximum of 3 lines, e.g. when using `eldoc-mode'.")
        (scroll-up-aggressively 0.0 "Don't recenter the window if the point moves off the page.")
        (scroll-down-aggressively 0.0 "Don't recenter the window if the point moves off the page.")
        ;; Indentation.
        (indent-tabs-mode nil "Always use spaces to indent.")
        ;; Niceties.
        (global-hl-line-mode t "Highlight the current line in all buffers.")
        (column-number-mode t "Show the column number in the statusline.")
        (electric-pair-mode t "Auto-pair suitable characters like parentheses.")
        (completion-cycle-threshold 6 "Allow cycling through completions if there are 6 or fewer of them.")
        ;; Text formatting.
        (sentence-end-double-space nil "Use a single space after a sentence.")
        (fill-column 78 "Make hard-wrapped text a bit wider.")
        ;; Make Emacs a good Guix citizen.
        (package-archives nil "Don't fetch packages from the internet; only get them from Guix.")
        ;; Don't clutter the disk with backup files.
        (make-backup-files nil "Don't create backup files. Backup files break hardlinks.")
        ;; Recent files and history. Keep them out of ~/.config.
        (package-user-dir ,(tw/xdg-emacs-subdir 'data "elpa") "Save ELPA-related files here.")
        (auto-save-list-file-prefix ,(tw/xdg-emacs-subdir 'data "auto-save-list/saves-") "Put auto-save lists here.")
        (recentf-max-saved-items 1000 "Save lots of recently-opened files.")
        (recentf-save-file ,(tw/xdg-emacs-subdir 'data "recentf.el") "Save recently-opened files here.")
        (recentf-mode t "Save recently-opened files.")
        (savehist-file ,(tw/xdg-emacs-subdir 'data "savehist.el") "Save minibuffer history here.")
        (savehist-mode t "Save minibuffer history on quit.")))

(defalias 'yes-or-no-p #'y-or-n-p
  "Always use `y-or-n-p' when asking for confirmation.")

;; Custom modes depending on file names.
(mapc (apply-partially #'add-to-list 'auto-mode-alist)
      `((,(rx (or bos "/") "PKGBUILD" eos) . sh-mode)
        (,(rx ".install" eos) . sh-mode)
        (,(rx (or bos "/") "COMMIT_EDITMSG" eos) . diff-mode)  ; useful for `git commit -v'
        (,(rx bos "/tmp/neomutt-") . mail-mode)
        (,(rx ".eml" eos) . mail-mode)
        (,(rx "." (1+ anything) "rc" eos) . conf-unix-mode)))

(add-to-list 'magic-mode-alist
             `(,(rx "#!" (* (not space))
                    (? "env" (+ space) (? "-S" (+ space)))
                    (or "guile" "racket"))
               . scheme-mode))

(add-hook 'mail-mode-hook #'auto-fill-mode)

(defun tw/enable-word-wrap ()
  "Enable word wrapping."
  (toggle-word-wrap +1))
(add-hook 'markdown-mode-hook #'tw/enable-word-wrap)
(add-hook 'org-mode-hook #'tw/enable-word-wrap)

;; `use-package' requirements.
(require 'package)
(package-initialize t)
(eval-when-compile
  (require 'use-package))
(use-package diminish)  ; for using :diminish later
(use-package bind-key)  ; for using :bind later

;; Some packages below have `:commands (...) :demand t'.
;; We need :commands for the byte-compiler, but we want to load the package immediately.

;; Look and feel
(set-face-attribute 'default nil :family "Hermit" :height 100)

(use-package autothemer
  ;; The "catppuccin" theme is linked to the appropriate variant by guix home.
  :config (load-theme 'catppuccin-mocha t))

(defun tw/get-catppuccin-color (name)
  "Get the hex code of the Catppuccin color named NAME."
  (cl-loop for color in (autothemer--theme-colors autothemer-current-theme)
           when (string= (autothemer--color-name color) name)
           return (autothemer--color-value color)))

(custom-set-faces
 `(cursor ((default :background ,(tw/get-catppuccin-color "rosewater"))) t
          "Make the cursor \"rosewater\", as recommended by Catppuccin upstream, overriding catppuccin/emacs."))

(use-package smart-mode-line
  :hook (after-init . sml/setup)
  :custom
  (sml/no-confirm-load-theme t "Stop Emacs from constantly asking for user confirmation.")
  (sml/mode-width 'right "Move the minor-mode list to the right of the modeline.")
  (sml/theme 'respectful "Make `smart-mode-line' blend in with the active theme."))

;; General editor behaviour.
;; TODO: Move from ivy + counsel to vertico + orderless + consult + marginalia
;; (+ embark?), to integrate better with vanilla Emacs and `completing-read'.
;; https://github.com/minad/vertico -- light completion engine
;; https://github.com/minad/vertico#child-frames-and-popups
;; https://github.com/minad/vertico#complementary-packages
;; https://github.com/minad/marginalia -- docstrings in M-x menu
;; https://github.com/oantolin/orderless -- regex search for vertico
;; https://github.com/minad/consult -- collection of commands using vertico
;; https://github.com/oantolin/embark -- make vertico better depending on thing at point

(use-package ivy
  :commands (ivy-mode) :demand t
  :custom
  (ivy-use-selectable-prompt t "Allow selecting the ivy input as-is.")
  (ivy-use-virtual-buffers t "Show recentf and bookmarks in buffers list.")
  :config (ivy-mode +1)
  :diminish ivy-mode)

(use-package counsel  ; extra niceties for `ivy-mode'
  :after (ivy evil)   ; evil for :bind-ing to <leader>
  :bind (("<leader>SPC" . counsel-M-x)  ; <leader><leader> doesn't work
         ("<leader>fr" . counsel-buffer-or-recentf)
         :map evil-visual-state-map
         ("<leader>SPC" . counsel-M-x))
  :commands (counsel-mode) :demand t
  :config (counsel-mode +1)
  :diminish counsel-mode)

(use-package dash-docs)

(defun tw/counsel-dash-is-help ()
  "Install `counsel-dash-at-point' as `evil-lookup-func'."
  ;; Note: `evil-lookup-func' is already set to something else by
  ;; `tw/help-is-eldoc' for `eglot-mode'.
  (setq-local evil-lookup-func #'counsel-dash-at-point
              counsel-dash-docsets
              (cl-case major-mode
                (python-mode '("Python 3"))
                (c++-mode '("C++"))
                (cmake-mode '("CMake"))
                (puppet-mode '("Puppet"))
                (tcl-mode '("Tcl"))
                (common-lisp-mode '("Common Lisp")))))

(use-package counsel-dash
  :after (dash-docs which-key)
  :commands (counsel-dash-at-point) :demand t
  :init (which-key-add-key-based-replacements
          "<leader>d" '("docs" . "Documentation"))
  :bind (("<leader>K" . counsel-dash-at-point)
         ("<leader>dK" . counsel-dash)
         ("<leader>di" . counsel-dash-install-docset)
         ("<leader>da" . counsel-dash-activate-docset)
         ("<leader>dd" . counsel-dash-deactivate-docset))
  :hook ((python-mode cmake-mode c++-mode puppet-mode tcl-mode common-lisp-mode)
         . tw/counsel-dash-is-help)
  :config
  ;; Activate all installed docsets by default.
  (setq counsel-dash-common-docsets (dash-docs-installed-docsets))
  :custom
  (counsel-dash-docsets-path (tw/xdg-emacs-subdir 'data "dash-docsets/") "Store docsets in the XDG data directory.")
  (counsel-dash-browser-func 'eww "Open documentation pages using `eww' instead of an external browser.")
  (counsel-dash-enable-debugging nil "Disable popping up useless warnings."))

(use-package rainbow-mode
  :after (evil)
  :bind (("<leader>tR" . rainbow-mode)))

(use-package form-feed
  :commands (global-form-feed-mode) :demand t
  :config (global-form-feed-mode +1)
  :diminish form-feed-mode)

(use-package display-line-numbers
  ;; Included in Emacs >= 26. Better than `linum-mode'.
  ;; There is also `global-display-line-numbers-mode', but that also
  ;; enables line numbers in help windows, which I don't want.
  :hook (prog-mode conf-mode yaml-mode alidist-mode))

(use-package which-key
  :commands (which-key-mode) :demand t
  :config (which-key-mode +1)
  :diminish which-key-mode)

(use-package undo-tree
  :after (evil)   ; for our :bind-ing
  :bind (("<leader>U" . undo-tree-visualize))
  :custom
  (undo-tree-history-directory-alist
   `(("." . ,(tw/xdg-emacs-subdir 'data "undo-tree-history/")))
   "Store all `undo-tree' history in a single directory, instead of next to the associated file.")
  :commands (global-undo-tree-mode)
  :demand t   ; this is required so that the :config stanza is actually run asap despite :bind
  :config (global-undo-tree-mode +1)
  :diminish undo-tree-mode)

;; IDE-like features.
(use-package project
  :after (which-key evil)
  :init (which-key-add-key-based-replacements
          "<leader>p" '("project" . "Project"))
  :bind-keymap ("<leader>p" . project-prefix-map))

(use-package vc
  :after (which-key evil)
  :init (which-key-add-key-based-replacements
          "<leader>v" '("vc" . "Version control")
          "<leader>vM" '("merge" . "Version control merging"))
  :bind-keymap ("<leader>v" . vc-prefix-map))

(use-package log-edit
  :after (evil vc)
  :config
  (evil-define-key '(normal visual) log-edit-mode-map
    (kbd "<localleader>\\") #'log-edit-done
    (kbd "<localleader>a") #'log-edit-insert-changelog
    (kbd "<localleader>d") #'log-edit-show-diff
    (kbd "<localleader>f") #'log-edit-show-files
    (kbd "<localleader>k") #'log-edit-kill-buffer
    (kbd "<localleader>w") #'log-edit-generate-changelog-from-diff))

(use-package corfu  ; https://github.com/minad/corfu
  :hook (prog-mode ledger-mode shell-mode eshell-mode)
  :custom
  (corfu-auto t "Show completion popup after a few seconds automatically.")
  :diminish corfu-mode)

(use-package corfu-doc
  :after (corfu)
  :hook (corfu-mode)
  :diminish corfu-doc-mode)

(use-package flyspell
  :hook mail-mode)

(use-package flymake
  :after (evil which-key)
  :demand t  ; needed for `flymake-collection'
  :hook (prog-mode yaml-mode alidist-mode)
  :init (which-key-add-key-based-replacements
          "<leader>e" '("errors" . "Flymake"))
  :bind (("<leader>eb" . flymake-start)
         ("<leader>ec" . display-local-help)  ; Show the error message at point in the minibuffer.
                                        ; `flymake' also shows it using `eldoc', but documentation
                                        ; seems to override error messages.
                                        ; `flymake-show-diagnostic' only says "Nothing at point".
         ("<leader>el" . flymake-show-buffer-diagnostics)
         ("<leader>ep" . flymake-show-project-diagnostics)
         ("<leader>en" . flymake-goto-next-error)
         ("<leader>eN" . flymake-goto-prev-error)
         ("<leader>ev" . flymake-running-backends)
         ("<leader>eV" . flymake-disabled-backends))
  :custom
  (flymake-suppress-zero-counters nil "Show severity counters even when they are zero."))

(use-package flymake-collection
  :after (flymake)
  :demand t   ; we need it loaded now
  ;; This needs to be called in `after-init-hook' so that all other
  ;; packages' `:flymake-hook's are processed before f-c-hook-setup is
  ;; called. See https://github.com/mohkale/flymake-collection.
  :hook (after-init . flymake-collection-hook-setup))

;; Language Server Protocol.
(defun tw/help-is-eldoc (&rest _)
  "Set up `evil-lookup-func' to display the `eldoc' buffer."
  (setq-local evil-lookup-func #'eldoc-doc-buffer))

(use-package eglot
  ;; I have clang (for clangd) and python-lsp-server installed.
  ;; `:hook' adds `-mode' to the package name, but `eglot-mode' doesn't exist.
  :hook ((python-mode c-mode c++-mode) . eglot-ensure)
  :commands (eglot)
  :custom
  (eglot-autoshutdown t "Shut down language servers after deleting their last associated buffer.")
  (eglot-sync-connect 0.1 "Wait for the language server in the background if it takes longer than 100ms.")
  :config
  ;; TODO: only run `tw/help-is-eldoc' if `eglot-managed-p' is true.
  (add-hook 'eglot-managed-mode-hook #'tw/help-is-eldoc))

;; Non-LSP language modes.
(use-package cmake-mode
  :mode (rx (or (: (or bos "/") "CMakeLists.txt") ".cmake") eos))

(use-package gnuplot
  :commands (gnuplot-mode gnuplot-make-buffer)
  :mode ((rx ".gnuplot" eos) . gnuplot-mode))

(use-package graphviz-dot-mode
  :mode (rx ".dot" eos)
  :custom (graphviz-dot-view-command "xdot %s" "Use xdot for previewing graphviz files."))

(use-package hcl-mode
  :mode (rx "." (or "hcl" "nomad") eos))

(use-package mmm-mode
  :commands (mmm-mode)
  ;; Don't highlight submodes specially at all. The default background is annoying.
  :custom-face (mmm-default-submode-face ((t (:background nil)))))

(use-package puppet-mode
  :mode (rx ".pp" eos))

(use-package python
  :after (flymake-collection)
  :commands (python-mode)
  :mode (((rx ".py" (? (or ?\i ?\w)) eos) . python-mode)
         ((rx ".aurora" eos) . python-mode))
  ;; :flymake-hook would be better, but it fails with error: (void-variable
  ;; for). Somehow `cl-loop' is getting parsed wrong...
  ;; https://github.com/mohkale/flymake-collection#associating-checkers-with-major-modes
  :init (add-to-list 'flymake-collection-config
                     '(python-mode
                       flymake-collection-flake8
                       flymake-collection-mypy
                       (flymake-collection-pycodestyle :disabled t)
                       flymake-collection-pylint)))

(use-package rec-mode
  :mode (rx ".rec" eos))

(use-package sh-script   ; built-in
  :custom (sh-basic-offset 2 "Use 2 spaces for `sh-mode' indents."))

(use-package tcl
  :mode ((rx ".tcl" eos) . tcl-mode)
  :magic ((rx "#%Module1.0") . tcl-mode))

(use-package web-mode
  :mode (rx "." (or "htm" "html" "js" "css" "scss") eos))

(use-package yaml-mode
  :mode (rx (or (seq ".y" (? "a") "ml")
                (seq "aliPublish" (* (not ?/)) ".conf"))
            eos))

(use-package ledger-mode
  :after (evil)
  :commands (ledger-mode)
  :mode (rx ".journal" eos)
  :custom
  (ledger-default-date-format ledger-iso-date-format "Use hledger-style dates.")
  (ledger-reconcile-default-date-format ledger-iso-date-format "Use hledger-style dates.")
  (ledger-reconcile-default-commodity "€" "Make euros the default currency.")
  (ledger-post-account-alignment-column 2 "Use 2-space indents.")
  (ledger-post-amount-alignment-at :decimal "Align amounts at decimal points/commas.")
  (ledger-post-amount-alignment-column 52 "Align amounts' decimal points to the 52nd column.")
  (ledger-highlight-xact-under-point nil "Don't highlight the transaction at point.")
  :config
  (evil-define-key 'normal ledger-mode-map
    (kbd "TAB") #'ledger-indent-line))

(use-package geiser
  :after (evil)
  :commands (geiser
             geiser-eval-buffer geiser-eval-definition geiser-eval-region
             geiser-eval-last-sexp geiser-mode-switch-to-repl
             geiser-mode-switch-to-repl-and-enter)
  :hook (scheme-mode . geiser-autodoc-mode)
  :config
  (evil-define-key '(normal visual) scheme-mode-map
    (kbd "<localleader>i") #'geiser-mode-switch-to-repl
    (kbd "<localleader>I") #'geiser-mode-switch-to-repl-and-enter
    (kbd "<localleader>eb") #'geiser-eval-buffer
    (kbd "<localleader>ef") #'geiser-eval-definition
    (kbd "<localleader>er") #'geiser-eval-region
    (kbd "<localleader>el") #'geiser-eval-last-sexp)
  :defines scheme-mode-map)

(use-package geiser-guile
  :after (geiser))

;; Org-mode
(use-package org
  :commands (org-mode)
  :mode ((rx ".org" eos) . org-mode)
  :custom
  (org-latex-src-block-backend 'minted "Colourise source code.")
  (org-latex-packages-alist
   '(("" "svg")
     ("" "minted"))
   "Use svg and syntax highlighting packages.")
  (org-latex-pdf-process
   '("latexmk -shell-escape -f -pdf -%latex -interaction=nonstopmode -output-directory=%o %f")
   "Allow -shell-escape needed by svg and minted packages."))

(use-package ob   ; org-babel
  :after (org)
  :custom
  (org-confirm-babel-evaluate nil "Allow running code blocks without confirmation.")
  ;; List of supported languages:
  ;; https://orgmode.org/worg/org-contrib/babel/languages/index.html
  (org-babel-load-languages
   '((emacs-lisp . t)
     (lisp . t)
     (dot . t)
     (python . t)
     (rec . t))   ; see `ob-rec' below
   "Load bindings for more languages for use in #+begin_src blocks."))

(defun tw/latex-section-commands (name)
  "Create a pair of section commands like (\"\\NAME{%s}\" . \"\\NAME*{%s}\").
For use in `org-latex-classes'."
  (cons (format "\\%s{%%s}" name) (format "\\%s*{%%s}" name)))
(defconst tw/latex-part (tw/latex-section-commands "part")
  "Part LaTeX commands for `org-latex-classes'.")
(defconst tw/latex-chapter (tw/latex-section-commands "chapter")
  "Chapter LaTeX commands for `org-latex-classes'.")
(defconst tw/latex-section-and-below
  (mapcar #'tw/latex-section-commands
          '("section" "subsection" "subsubsection" "paragraph" "subparagraph"))
  "Section to subparagraph LaTeX commands for `org-latex-classes'.")

(use-package ox-latex   ; org-export-latex
  :after (org)
  :custom
  (org-latex-classes
   `(("paperlike" "\\documentclass{paperlike}" . ,tw/latex-section-and-below)
     ("examtext" "\\documentclass{examtext}" . ,tw/latex-section-and-below)
     ("minutes" "\\documentclass{minutes}" . ,tw/latex-section-and-below)
     ("mapreport" "\\documentclass{mapreport}" ,tw/latex-chapter . ,tw/latex-section-and-below)
     ("pt3report" "\\documentclass{pt3report}" ,tw/latex-chapter . ,tw/latex-section-and-below)
     ("article" "\\documentclass{article}" . ,tw/latex-section-and-below)
     ("scrartcl" "\\documentclass{scrartcl}" . ,tw/latex-section-and-below)
     ("report" "\\documentclass{report}" ,tw/latex-part ,tw/latex-chapter . ,tw/latex-section-and-below)
     ("report-noparts" "\\documentclass{report}" ,tw/latex-chapter . ,tw/latex-section-and-below)
     ("book" "\\documentclass{book}" ,tw/latex-part ,tw/latex-chapter . ,tw/latex-section-and-below)
     ("book-noparts" "\\documentclass{book}" ,tw/latex-chapter . ,tw/latex-section-and-below)
     ("checklist" "\\documentclass{checklist}" . ,tw/latex-section-and-below))
   "Define more documentclasses for org-latex."))

(use-package outline
  :commands (outline-mode outline-minor-mode)
  :custom
  ;; Mirror the default "C-c @" binding for `outline-minor-mode'.
  (outline-minor-mode-prefix (kbd "<localleader>@") "Use localleader for `outline-minor-mode' keybindings."))

;; My own custom packages, and stuff that isn't on MELPA.
;; (use-package actionlint   ; TODO: port to flymake
;;   :after (flycheck)
;;   :load-path "include/")

(use-package alidist-mode
  :load-path "include/"
  :commands (alidist-mode)
  :mode (rx (or bot "/") "alidist/" (1+ (not ?\/)) ".sh" eot))

(use-package bemscript-mode
  :load-path "include/"
  :mode (rx ".bem" eos))

(use-package ifm-mode
  :load-path "include/"
  :mode (rx ".ifm" eos))

(use-package pam-env-mode
  :load-path "include/"
  :mode (rx (or bos "/") (or "pam_env.conf" ".pam_environment") eos))

(use-package environmentd-mode
  :load-path "include/"
  :mode (rx (or bos "/")
            (or (: (? "etc/") "environment")
                (: ".environment.d/" (1+ (not ?\/)) ".conf"))
            eos))

(use-package ob-rec
  ;; `org-babel' hooks for `rec-mode'
  :after (org ob rec-mode)
  :load-path "include/")

(use-package vcard-mode
  :load-path "include/"
  :mode (rx "." (or "vcf" "vcard") eos))

;; Vim keybindings.
(defun tw/switch-to-other-buffer ()
  "Switch to the last-used buffer."
  (interactive)
  (switch-to-buffer (other-buffer)))

(defun tw/new-buffer ()
  "Open a new, empty buffer."
  (interactive)
  (switch-to-buffer (generate-new-buffer "untitled")))

(defun tw/delete-current-buffer-file ()
  "Ask for confirmation, then delete the file associated with the current buffer."
  (interactive)
  (let ((buffer (current-buffer)))
    (when (yes-or-no-p (concat "Delete `" (buffer-file-name buffer) "'?"))
      (delete-file (buffer-file-name buffer))
      (kill-buffer buffer))))

(use-package evil
  :after (which-key)
  :commands (evil-mode evil-ex-nohighlight)
  :init (setq evil-want-keybinding nil)  ; evil-collection needs this
  :custom
  (evil-undo-system 'undo-tree "Use `undo-tree' for evil's undo-redo function.")
  (evil-want-minibuffer t "Use evil bindings in the minibuffer too.")
  (evil-want-C-u-scroll t "Scroll on C-u in normal mode, not `universal-argument'.")
  (evil-want-C-u-delete t "Delete line on C-u in insert mode, not `universal-argument'.")
  (evil-want-Y-yank-to-eol t "Yank from point to end-of-line on Y.")
  (evil-symbol-word-search t "Always search by full variable names when using * and #.")
  :config
  (evil-mode +1)
  (evil-set-leader '(normal visual) (kbd "SPC"))   ; <leader>
  (evil-set-leader '(normal visual) (kbd "\\") t)  ; <localleader>
  ;; For some reason, in `diff-mode', space isn't assigned to the leader key
  ;; automatically, unlike in other modes.
  (evil-define-key '(normal visual) diff-mode-shared-map  ; not `diff-mode-map', else toggling `read-only-mode' destroys the binding
    (kbd "SPC") #'evil-send-leader
    (kbd "\\") #'evil-send-localleader)
  (evil-define-key '(normal insert visual replace) 'global
    (kbd "C-s") #'save-buffer)
  ;; Global major-mode-independent keys should be defined here. Major
  ;; mode-dependent keys (e.g. for launching a REPL) should go under
  ;; <localleader> instead. Use `use-package' `:bind' for those.
  (evil-define-key '(normal visual) 'global
    ;; These keybindings mirror the default Spacemacs ones because I have
    ;; muscle memory of those.
    (kbd "<leader>:") #'eval-expression
    (kbd "<leader>TAB") #'tw/switch-to-other-buffer
    (kbd "<leader>bb") #'switch-to-buffer
    (kbd "<leader>bd") #'kill-current-buffer
    (kbd "<leader>bn") #'tw/new-buffer
    (kbd "<leader>br") #'revert-buffer-quick
    (kbd "<leader>bw") #'read-only-mode
    (kbd "<leader>bx") #'kill-buffer-and-window
    (kbd "<leader>fd") #'tw/delete-current-buffer-file
    (kbd "<leader>ff") #'find-file
    (kbd "<leader>fs") #'save-buffer
    (kbd "<leader>h") help-map
    (kbd "<leader>hw") #'which-key-show-top-level
    (kbd "<leader>sc") #'evil-ex-nohighlight
    (kbd "<leader>tf") #'auto-fill-mode
    (kbd "<leader>tl") #'toggle-truncate-lines
    (kbd "<leader>tn") #'display-line-numbers-mode
    (kbd "<leader>u") #'universal-argument
    (kbd "<leader>w") evil-window-map
    (kbd "<leader>wd") #'evil-window-delete       ; analogous to "<leader>bd"
    (kbd "<leader>wx") #'kill-buffer-and-window)  ; analogous to "<leader>bx"
  (which-key-add-key-based-replacements
    ;; Names are a `cons' of a short name and a long name.
    ;; E.g. for <leader>b, "buffer" is shown under "b" in the "<leader>" menu,
    ;; while "Buffers" is shown as the title in the "<leader>b" menu.
    "<leader>b" '("buffer" . "Buffers")
    "<leader>f" '("file" . "Files")
    "<leader>h" '("help" . "General help and documentation")
    "<leader>q" '("quit" . "Finish editing the current buffer in emacsclient")
    "<leader>s" '("search" . "Search operations and options")
    "<leader>t" '("toggle" . "Toggles and quick settings")
    "<leader>w" '("window" . "Windows"))
  :functions (evil-define-key evil-set-leader
               evil-define-key* evil-window-delete evil-delay)
  :defines (evil-visual-state-map))

(use-package evil-collection
  :after (evil)
  :commands (evil-collection-init) :demand t
  :config (evil-collection-init)
  :diminish evil-collection-unimpaired-mode
  :custom
  (evil-collection-setup-minibuffer t "Use evil-collection in minibuffer to match `evil-want-minibuffer'."))

(use-package evil-org
  :after (evil org)
  :hook org-mode
  :config
  (evil-define-key '(normal visual) org-mode-map
    (kbd "<localleader>\\") #'org-ctrl-c-ctrl-c
    (kbd "<localleader>ib") #'org-insert-structure-template
    (kbd "<localleader>id") #'org-insert-drawer
    (kbd "<localleader>iD") #'org-insert-time-stamp
    (kbd "<localleader>ih") #'org-insert-heading
    (kbd "<localleader>iH") #'org-insert-subheading
    (kbd "<localleader>it") #'org-insert-todo-heading
    (kbd "<localleader>iT") #'org-insert-todo-subheading
    (kbd "<localleader>ii") #'org-insert-item
    (kbd "<localleader>il") #'org-insert-link
    (kbd "<localleader>p") #'org-set-property
    (kbd "<localleader>t") #'org-set-tags
    ;; Source code block editing
    (kbd "<localleader>'") #'org-edit-src-code
    (kbd "<localleader>e") #'org-export-dispatch)
  (evil-define-key '(normal visual) org-src-mode-map
    (kbd "<localleader>'") #'org-edit-src-exit
    (kbd "<localleader>\\") #'org-edit-src-save
    (kbd "<localleader>a") #'org-edit-src-abort))

(use-package evil-replace-with-register
  :after (evil)
  :commands (evil-replace-with-register-install) :demand t
  ;; :custom (evil-replace-with-register-key "gR" "Use the default key.")
  :config (evil-replace-with-register-install))

(use-package evil-commentary   ; e.g. "gcc" / "gcap" to comment out blocks of text
  :after (evil)
  :commands (evil-commentary-mode) :demand t
  :config (evil-commentary-mode +1)
  :diminish evil-commentary-mode)

(use-package evil-expat  ; for :reverse, :remove, :rename, :colo, :g*, ... ex commands
  :after (evil))

(use-package evil-surround
  :after (evil)
  :commands (global-evil-surround-mode) :demand t
  :config (global-evil-surround-mode +1))

(use-package evil-smartparens
  :after (evil smartparens)
  :hook smartparens-enabled-hook)

(use-package evil-multiedit
  ;; See: https://github.com/hlissner/evil-multiedit#usage
  :commands (evil-multiedit-default-keybinds) :demand t
  :config (evil-multiedit-default-keybinds))

(use-package evil-args
  :after (evil)
  :config
  ;; Bind evil-args text objects only.
  ;; See https://github.com/wcsmith/evil-args for more bindings.
  (define-key evil-inner-text-objects-map "a" 'evil-inner-arg)
  (define-key evil-outer-text-objects-map "a" 'evil-outer-arg))

(use-package evil-numbers
  :after (evil)
  :bind (("<leader>+" . evil-numbers/inc-at-pt)
         ("<leader>-" . evil-numbers/dec-at-pt)))

(use-package evil-goggles   ; visual previews for edit operations
  :after (evil)
  :commands (evil-goggles-mode evil-goggles-use-diff-faces) :demand t
  :config
  (evil-goggles-mode +1)
  (evil-goggles-use-diff-faces)
  :diminish evil-goggles-mode)

(use-package evil-traces   ; visual previews for :ex commands
  :after (evil)
  :commands (evil-traces-mode evil-traces-use-diff-faces) :demand t
  :config
  (evil-traces-mode +1)
  (evil-traces-use-diff-faces)
  :diminish evil-traces-mode)

(use-package evil-markdown
  :after (evil markdown-mode)
  :hook markdown-mode)

(use-package evil-tex
  :after (evil tex)
  :hook tex-mode)

(use-package evil-text-object-python
  :after (evil python)
  :hook (python-mode . evil-text-object-python-add-bindings))

;; Lisp features
(use-package aggressive-indent
  :hook (scheme-mode emacs-lisp-mode common-lisp-mode sh-mode))

(use-package inf-lisp
  :custom
  (inferior-lisp-program "sbcl"))

(defun tw/lisp-evil-setup ()
  "Set up evil in general `lisp-mode' buffers."
  ;; https://github.com/wcsmith/evil-args#customization
  (setq-local evil-args-delimiters '(" ")))

;; Sadly, not all Lisp modes derive from `lisp-mode'.
(add-hook 'lisp-mode-hook #'tw/lisp-evil-setup)
(add-hook 'lisp-data-mode-hook #'tw/lisp-evil-setup)  ; for elisp
(add-hook 'scheme-mode-hook #'tw/lisp-evil-setup)

;; buffer-locally set `evil-lookup-func' (used on K keys) for
;; languages where something better than man pages is available
;; (e.g. `describe-symbol' for elisp).
(defun tw/elisp-lookup-func ()
  "Show help in `emacs-lisp-mode' buffers."
  (let ((sym (symbol-at-point)))
    (if sym (describe-symbol sym)
      (call-interactively #'describe-symbol))))

(defun tw/emacs-lisp-evil-setup ()
  "Set up evil in `emacs-lisp-mode' buffers."
  (setq-local evil-lookup-func #'tw/elisp-lookup-func))

(add-hook 'emacs-lisp-mode-hook #'tw/emacs-lisp-evil-setup)

(evil-define-key '(normal visual) emacs-lisp-mode-map
  (kbd "<localleader>eb") #'eval-buffer
  (kbd "<localleader>ef") #'eval-defun
  (kbd "<localleader>er") #'eval-region
  (kbd "<localleader>el") #'eval-last-sexp
  (kbd "<localleader>ep") #'eval-print-last-sexp)

;; Guix-related .dir-locals.el entries. These are fine; don't prompt every time.
(mapc (apply-partially #'add-to-list 'safe-local-eval-forms)
      '((modify-syntax-entry 126 "'")
        (modify-syntax-entry 36 "'")
        (modify-syntax-entry 43 "'")
        (let ((root-dir-unexpanded (locate-dominating-file default-directory ".dir-locals.el")))
          (when root-dir-unexpanded
            (let* ((root-dir (file-local-name (expand-file-name root-dir-unexpanded)))
                   (root-dir* (directory-file-name root-dir)))
              (unless (boundp 'geiser-guile-load-path)
                (defvar geiser-guile-load-path 'nil))
              (make-local-variable 'geiser-guile-load-path)
              (require 'cl-lib)
              (cl-pushnew root-dir* geiser-guile-load-path :test #'string-equal))))
        (progn
          (require 'lisp-mode)
          (defun emacs27-lisp-fill-paragraph (&optional justify)
            (interactive "P")
            (or (fill-comment-paragraph justify)
                (let ((paragraph-start
                       (concat paragraph-start "\\|\\s-*\\([(;\"]\\|\\s-:\\|`(\\|#'(\\)"))
                      (paragraph-separate
                       (concat paragraph-separate "\\|\\s-*\".*[,\\.]$"))
                      (fill-column
                       (if (and (integerp emacs-lisp-docstring-fill-column)
                                (derived-mode-p 'emacs-lisp-mode))
                           emacs-lisp-docstring-fill-column
                         fill-column)))
                  (fill-paragraph justify))
                t))
          (setq-local fill-paragraph-function #'emacs27-lisp-fill-paragraph))

        ;; Forms used by Guix upstream.
        (add-to-list 'completion-ignored-extensions ".go")
        (setq-local guix-directory (locate-dominating-file
                                    default-directory ".dir-locals.el"))
        (with-eval-after-load 'yasnippet
          (let ((guix-yasnippets (expand-file-name
                                  "etc/snippets/yas"
                                  (locate-dominating-file
                                   default-directory ".dir-locals.el"))))
            (unless (member guix-yasnippets yas-snippet-dirs)
              (add-to-list 'yas-snippet-dirs guix-yasnippets)
              (yas-reload-all))))
        (let ((root-dir-unexpanded (locate-dominating-file
                                    default-directory ".dir-locals.el")))
          (when root-dir-unexpanded
            (let* ((root-dir (expand-file-name root-dir-unexpanded))
                   (root-dir* (directory-file-name root-dir)))
              (unless (boundp 'geiser-guile-load-path)
                (defvar geiser-guile-load-path 'nil))
              (make-local-variable 'geiser-guile-load-path)
              (require 'cl-lib)
              (cl-pushnew root-dir* geiser-guile-load-path
                          :test #'string-equal))))))

;;; init.el ends here