summaryrefslogtreecommitdiffstats
path: root/init.el
blob: 45ba054ea17490e9884ee6c3d6ac87a683dfb48f (plain) (blame)
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
;;; init --- Test
;;; Commentary:

;;; Code:

;; -------- SPEED-UP STARTUP -----------------------------------------

(defvar gc-cons-threshold-original gc-cons-threshold)
(setq gc-cons-threshold (* 1024 1024 100))
(defvar file-name-handler-alist-original file-name-handler-alist)
(setq file-name-handler-alist nil)

(run-with-idle-timer
 5 nil
 (lambda ()
   (setq gc-cons-threshold gc-cons-threshold-original)
   (setq file-name-handler-alist file-name-handler-alist-original)
   (makunbound 'gc-cons-threshold-original)
   (makunbound 'file-name-handler-alist-original)
   (message "gc-cons-threshold and file-name-handler-alist restored")))

;; -------- PACKAGE MANAGEMENT ---------------------------------------

(require 'package)

(setq package-archives '(("gnu"   . "https://elpa.gnu.org/packages/")
                         ("melpa" . "https://melpa.org/packages/")))

(package-initialize)

(or (file-exists-p package-user-dir)
    (package-refresh-contents))

(defun ensure-package-installed (&rest packages)
  "Ensure every PACKAGES is installed.

Ask for installation if it’s
not.  Return a list of installed packages or nil for every skipped
package."
  (mapcar
   (lambda (package)
     (if (package-installed-p package)
         nil
       (package-install package))
     package)
   packages))

(ensure-package-installed 'use-package 'diminish)

(require 'diminish)
(eval-when-compile (require 'use-package))

;; Uncomment this to enable statistics.  Once Emacs is ready, you can
;; use the `use-package-report' to gather data on startup timing.
;; (setq use-package-compute-statistics t)

;; -------- KEYBOARD SET-UP ------------------------------------------

;; Zoom in and out using <C-+> and <C-->
(global-set-key (kbd "C-+") 'text-scale-increase)
(global-set-key (kbd "C--") 'text-scale-decrease)

;; Provide a backend for redo.
;; Will not be necessary once Emacs 28 is released
(use-package undo-fu
  :ensure t)

;; Interact with the clipboard
(defun copy-to-clipboard ()
  "Copy the selection to clipboard."
  (interactive)
  (if (display-graphic-p)
      (progn
        (message "Yanked region to x-clipboard!")
        (call-interactively 'clipboard-kill-ring-save)
        )
    (if (region-active-p)
        (progn
          (shell-command-on-region (region-beginning) (region-end) "xsel -i -b")
          (message "Yanked region to clipboard!")
          (deactivate-mark))
      (message "No region active; can't yank to clipboard!"))))

(defun paste-from-clipboard ()
  "Paste the clipboard content into the buffer at cursor."
  (interactive)
  (setq select-enable-clipboard t)
  (yank)
  (setq select-enable-clipboard nil))

(defun minibuffer-keyboard-quit ()
  "Abort recursive edit.
In Delete Selection mode, if the mark is active, just deactivate it;
then it takes a second \\[keyboard-quit] to abort the minibuffer."
  (interactive)
  (if (and delete-selection-mode transient-mark-mode mark-active)
      (setq deactivate-mark  t)
    (when (get-buffer "*Completions*") (delete-windows-on "*Completions*"))
    (abort-recursive-edit)))

(setq select-enable-clipboard nil)

;; See https://www.reddit.com/r/emacs/comments/8xymph/how_to_jump_to_beginningofnextdefun/e280g59/?utm_source=reddit&utm_medium=web2x&context=3
(defun beginning-of-next-defun ()
  "Jump to the beginning of the next defun."
  (interactive)
  (let ((current-prefix-arg -1))
    (call-interactively 'beginning-of-defun)))

(defmacro defhandler (name default)
  "Define a function NAME that modes can override, with DEFAULT as backup."
  (let ((var-name (intern (concat (symbol-name name) "-handler"))))
    `(progn (defvar-local ,var-name ,default)
            (defun ,name ()
              (interactive)
              (call-interactively ,var-name)))))

(defhandler lthms-goto-prev-phrase 'beginning-of-defun)
(defhandler lthms-goto-next-phrase 'beginning-of-next-defun)
(defhandler lthms-jump-to-definition 'xref-find-definitions)
(defhandler lthms-pop-stack 'xref-pop-marker-stack)

;; I wouldn’t use emacs if evil was not a thing.
;; It is heavily configured to work smoothly with the bépo layout
(use-package evil
  :ensure t
  :defer nil
  :diminish evil-mode
  :init
  (setq evil-want-abbrev-expand-on-insert-exit nil)
  :bind
  (:map evil-motion-state-map
   ("j" . evil-find-char-to)

   ("t" . evil-backward-char)
   ("s" . evil-next-visual-line)
   ("r" . evil-previous-visual-line)
   ("n" . evil-forward-char)

   ("m" . evil-search-next)
   ("M" . evil-search-previous)

   ("à t" . evil-window-left)
   ("à s" . evil-window-down)
   ("à r" . evil-window-up)
   ("à n" . evil-window-right)

   ("|" . split-window-horizontally)
   ("¦" . split-window-vertically)

   ("é" . evil-forward-word-begin)
   ("É" . evil-forward-WORD-begin)

   :map evil-normal-state-map
   ("t" . nil)
   ("T" . nil)
   ("s" . nil)
   ("S" . nil)
   ("r" . nil)
   ("R" . nil)
   ("n" . nil)
   ("m" . nil)
   ("M" . nil)

   ("M-p" . lthms-goto-prev-phrase)
   ("M-n" . lthms-goto-next-phrase)

   ("M-j" . lthms-jump-to-definition)
   ("M-r" . lthms-pop-stack)

   ("l" . evil-replace)
   ("L" . evil-replace-state)

   :map evil-visual-state-map
   ("t" . evil-backward-char)
   ("s" . evil-next-visual-line)
   ("r" . evil-previous-visual-line)
   ("n" . evil-forward-char)

   ("é" . evil-forward-word-begin)
   ("É" . evil-forward-WORD-begin)

   ("m" . evil-search-next)
   ("M" . evil-search-previous)
   ("N" . nil)

   ("l" . evil-replace)

   ("M-c" . copy-to-clipboard)
   ("M-v" . paste-from-clipboard)

   :map evil-insert-state-map
   ("M-c" . copy-to-clipboard)
   ("M-v" . paste-from-clipboard)
   ("C-g" . evil-force-normal-state)

   :map evil-operator-state-map
   ("é" . evil-a-word)
   ("É" . evil-a-WORD))

  :config
  (evil-mode t)
  (evil-set-undo-system 'undo-fu))

(use-package evil-numbers
  :ensure t
  :after evil
  :bind
  (:map evil-normal-state-map
   ("+" . evil-numbers/inc-at-pt)
   ("-" . evil-numbers/inc-at-pt)))

;; -------- UI SET-UP ------------------------------------------------

;; Hide several UI elements.
(scroll-bar-mode -1)
(tool-bar-mode -1)
(menu-bar-mode -1)
(setq inhibit-startup-screen t)
(setq use-dialog-box nil)

;; Do not wait before highlighting search matches.
(setq lazy-highlight-initial-delay 0)

;; Disable blinking cursor
(blink-cursor-mode -1)

;; Smooth scrolling a la vim.
;; From: https://juanjoalvarez.net/posts/2014/vim-emacsevil-chaotic-migration-guide/#smooth-scrolling
(setq scroll-margin 5)
(setq scroll-conservatively 9999)
(setq scroll-step 1)

;; Set a minimal margin for buffers
(setq-default left-margin-width 2)
(setq-default right-margin-width 2)

;; Always highlight current line.
(global-hl-line-mode t)

;; Always highlight matching parentheses
(setq blink-matching-paren -1)
(setq blink-matching-delay 0)
(show-paren-mode 1)

;; Install `rainbow mode'
;; Loading is deferred; either call =rainbow-mode= manually, or install a hook
(use-package rainbow-mode
  :defer t
  :ensure t)

;; Use powerline
(use-package powerline
  :ensure t
  :config
  (powerline-center-evil-theme))

;; Always install ligatures
(use-package composite
  :init
  (defvar composition-ligature-table (make-char-table nil))
  (when (version<= "27.0" emacs-version)
    (let ((alist
           '((33 . ".\\(?:\\(==\\|[!=]\\)[!=]?\\)")
             (35 . ".\\(?:\\(###?\\|_(\\|[(:=?[_{]\\)[#(:=?[_{]?\\)")
             (36 . ".\\(?:\\(>\\)>?\\)")
             (37 . ".\\(?:\\(%\\)%?\\)")
             (38 . ".\\(?:\\(&\\)&?\\)")
             (42 . ".\\(?:\\(\\*\\*\\|[*>]\\)[*>]?\\)")
             ;; (42 . ".\\(?:\\(\\*\\*\\|[*/>]\\).?\\)")
             (43 . ".\\(?:\\([>]\\)>?\\)")
             ;; (43 . ".\\(?:\\(\\+\\+\\|[+>]\\).?\\)")
             (45 . ".\\(?:\\(-[->]\\|<<\\|>>\\|[-<>|~]\\)[-<>|~]?\\)")
             ;; (46 . ".\\(?:\\(\\.[.<]\\|[-.=]\\)[-.<=]?\\)")
             (46 . ".\\(?:\\(\\.<\\|[-=]\\)[-<=]?\\)")
             (47 . ".\\(?:\\(//\\|==\\|[=>]\\)[/=>]?\\)")
             ;; (47 . ".\\(?:\\(//\\|==\\|[*/=>]\\).?\\)")
             (48 . ".\\(?:\\(x[a-fA-F0-9]\\).?\\)")
             (58 . ".\\(?:\\(::\\|[:<=>]\\)[:<=>]?\\)")
             (59 . ".\\(?:\\(;\\);?\\)")
             (60 . ".\\(?:\\(!--\\|\\$>\\|\\*>\\|\\+>\\|-[-<>|]\\|/>\\|<[-<=]\\|=[<>|]\\|==>?\\||>\\||||?\\|~[>~]\\|[$*+/:<=>|~-]\\)[$*+/:<=>|~-]?\\)")
             (61 . ".\\(?:\\(!=\\|/=\\|:=\\|<<\\|=[=>]\\|>>\\|[=>]\\)[=<>]?\\)")
             (62 . ".\\(?:\\(->\\|=>\\|>[-=>]\\|[-:=>]\\)[-:=>]?\\)")
             (63 . ".\\(?:\\([.:=?]\\)[.:=?]?\\)")
             (91 . ".\\(?:\\(|\\)[]|]?\\)")
             ;; (92 . ".\\(?:\\([\\n]\\)[\\]?\\)")
             (94 . ".\\(?:\\(=\\)=?\\)")
             (95 . ".\\(?:\\(|_\\|[_]\\)_?\\)")
             (119 . ".\\(?:\\(ww\\)w?\\)")
             (123 . ".\\(?:\\(|\\)[|}]?\\)")
             (124 . ".\\(?:\\(->\\|=>\\||[-=>]\\||||*>\\|[]=>|}-]\\).?\\)")
             (126 . ".\\(?:\\(~>\\|[-=>@~]\\)[-=>@~]?\\)"))))
      (dolist (char-regexp alist)
        (set-char-table-range composition-ligature-table (car char-regexp)
                              `([,(cdr char-regexp) 0 font-shape-gstring]))))
    (set-char-table-parent composition-ligature-table composition-function-table))
  :config
  (setq-default composition-function-table composition-ligature-table))

;; Display tab and spaces marks
(use-package whitespace
  :ensure t
  :diminish whitespace-mode
  :config
  (setq whitespace-display-mappings
        '((tab-mark 9 [?▶ 9] [92 9])
          (space-mark 32 [] [46])
          (space-mark ?\xA0 [?~] [46])))
  (setq whitespace-style '(space-mark tab-mark))
  :hook
  ((text-mode prog-mode) . whitespace-mode))

;; Assign a dedicated font to space/tabs marks.  Contrary to
;; =whitespace-mode=, =highlight-chars= does not override previous
;; faces
(use-package highlight-chars
  :load-path "~/.emacs.d/lisp"
  :after whitespace
  :config
  (setq-default hc-font-lock-override 'prepend)
  (hc-highlight-chars '(" " " " "\t" "\n") 'whitespace-space))

;; -------- THEMES ---------------------------------------------------

;; On Melpa
(use-package lavenderless-theme :ensure t :defer t)
(use-package nordless-theme :ensure t :defer t)

;; Not yet on melpa
(use-package darkless-theme :load-path "~/.emacs.d/lisp")
(use-package einkless-theme :load-path "~/.emacs.d/lisp")

(defcustom lthms-current-theme 'einkless
  "The theme currently used."
  :type 'symbol
  :group 'faces)

(defun load-theme-and-reset-ui (theme)
  "Clean-up loading of the colorless theme THEME and update the value SYM."
  (load-theme theme t)
  (powerline-reset)
  (when centaur-tabs-mode
    (progn
      (centaur-tabs-mode -1)
      (centaur-tabs-mode t))))

(defun change-default-theme (theme)
  "Change the default theme used by this Emacs to THEME."
  (disable-theme lthms-current-theme)
  (customize-save-variable 'lthms-current-theme theme)
  (load-theme-and-reset-ui theme))

(add-hook
 'after-init-hook
 (lambda ()
   (if lthms-current-theme (load-theme-and-reset-ui lthms-current-theme))))

;; -------- TEXT EDITOR SET-UP ---------------------------------------

;; We use utf-8
(set-language-environment "UTF-8")
(set-default-coding-systems 'utf-8)

;; Please, no backup files
(setq backup-directory-alist `((".*" . ,temporary-file-directory)))
(setq auto-save-file-name-transforms `((".*" ,temporary-file-directory t)))

(add-hook 'before-save-hook 'delete-trailing-whitespace)
(add-hook 'prog-mode-hook
          (lambda ()
            (display-fill-column-indicator-mode)
            (setq-local display-fill-column-indicator-column 80)))

;; Do not try to ident automatically
(setq-default electric-indent-inhibit t)

;; Automatically insert pairs, and ignore them when closing them.
(use-package smartparens
  :ensure t
  :diminish smartparens-mode
  :config
  (require 'smartparens-config)
  :hook
  (prog-mode . smartparens-mode))

;; Indentaton management
(setq-default indent-tabs-mode nil)
(use-package dtrt-indent
  :ensure t
  :diminish dtrt-indent-mode
  :hook
  (prog-mode . dtrt-indent-mode))

(use-package ivy
  :ensure t
  :diminish ivy-mode
  :config
  (ivy-mode 1)
  (setq ivy-re-builders-alist '((t . ivy--regex-fuzzy)))
  (setq ivy-use-virtual-buffers t)
  (setq enable-recursive-minibuffers t))

(use-package counsel
  :ensure t)

;; -------- BUFFERS MANAGEMENT ---------------------------------------

(use-package perspective
  :ensure t
  :config
  (persp-mode))

(use-package projectile
  :ensure t
  :diminish projectile-mode
  :after (ivy counsel)
  :hook (grep-mode . (lambda () (setq truncate-lines t)))
  :config
  (setq projectile-completion-system 'ivy)
  (projectile-mode)

  (defun unified-find-file (&optional args)
    "Choose between projectile and ivy to explore file and pass ARGS to the choice."
    (interactive)
    (if (projectile-project-p)
        (projectile-find-file args)
      (counsel-find-file args)))

  ;; When trying to find a file within a project, start from the project
  ;; root.
  (add-hook 'find-file-hook
            (lambda ()
              (if (and (projectile-project-p)
                       (projectile-project-root))
                  (setq default-directory (projectile-project-root))))))

(use-package occur
  :defer t
  :bind
  (:map occur-mode-map
   ("t" . evil-backward-char)
   ("s" . evil-next-visual-line)
   ("r" . evil-previous-visual-line)
   ("n" . evil-forward-char)))

(use-package dired
  :defer t
  :config
  (evil-define-key 'normal 'dired-mode-map "t" 'evil-backward-char)
  (evil-define-key 'normal 'dired-mode-map "s" 'evil-next-visual-line)
  (evil-define-key 'normal 'dired-mode-map "r" 'evil-previous-visual-line)
  (evil-define-key 'normal 'dired-mode-map "n" 'evil-forward-char)
  (evil-define-key 'normal 'dired-mode-map "m" 'evil-search-next)
  (evil-define-key 'normal 'dired-mode-map "M" 'evil-search-previous))

;; All the icons for centaur tabs
(use-package all-the-icons
  :ensure t)

(use-package centaur-tabs
  :ensure t
  :after evil
  :config
  (setq centaur-tabs-style "bar")
  (setq centaur-tabs-set-bar 'under)
  (setq centaur-tabs-set-icons t)
  (setq centaur-tabs-height 32)
  (setq x-underline-at-descent-line t)
  (setq centaur-tabs-set-modified-marker t)
  (setq centaur-tabs-modified-marker "●")
  (setq centaur-tabs-cycle-scope 'tabs)
  (centaur-tabs-group-by-projectile-project)
  :hook
  (after-init . centaur-tabs-mode)
  :bind
  (:map evil-normal-state-map
   ("<C-tab>" . centaur-tabs-forward)
   ("<C-iso-lefttab>" . centaur-tabs-backward)))

;; -------- HYDRA MENUS ----------------------------------------------

;; hydra/mode is expected to be personnalized by major mode
(defvar-local hydra/mode (lambda () (interactive) nil))

(use-package hydra
  :ensure t
  :after (evil projectile perspective)
  :config
  (defhydra hydra-themes (:color teal :hint nil)
    "Load a colorless theme"
    ("d"  (change-default-theme 'darkless) "Darkless")
    ("e"  (change-default-theme 'einkless) "Darkless")
    ("l"  (change-default-theme 'lavenderless) "Lavenderless")
    ("n"  (change-default-theme 'nordless) "Nordless")
    ("SPC"  nil "Quit" :exit t))

  (defhydra hydra-main (:color teal :hint nil)
    "
     ^^Global            ^^Buffer             ^^Project           ^^Code
--------------------------------------------------------------------------------
  _m_: Major Mode     _e_: Open file       _g_: Magit          _c_: Comment
  _t_: Load Theme     _q_: Kill window
  _p_: Packages       _x_: Kill buffer
                    ^^_n_: Next error
                    ^^_à_: Navigation
                    ^^_i_: Imenu

"
    ("c"   comment-dwim)
    ("p"   package-list-packages)
    ("q"   delete-window)
    ("x"   kill-this-buffer)
    ("e"   unified-find-file)
    ("t"   hydra-themes/body)
    ("m"   (call-interactively hydra/mode))
    ("i"   counsel-imenu)
    ("n"   flycheck-next-error)
    ("à"   hydra-perspective/body)
    ("g"   hydra-magit/body)
    ("SPC"  nil "Quit" :exit t))

  (defhydra hydra-magit (:color teal :exit t :hint nil)
    "
       ^^Diff                  ^^Commit         ^^Repository
--------------------------------------------------------------------
     _u_: Diff unstaged    _cc_: Commit     _rr_: rebase
     _s_: Diff staged      _cf_: Fixup      _rf_: fetch all
                         ^^_ca_: Amend
"
    ("u"  magit-diff-unstaged)
    ("s"  magit-diff-staged)
    ("cc"  magit-commit-create)
    ("cf"  magit-commit-fixup)
    ("ca"  magit-commit-amend)
    ("rr"  magit-rebase-interactive)
    ("rf"  magit-fetch-all)
    ("g"  magit-dispatch       "Magit menu")
    ("q"  nil "Quit" :exit t))

  (defhydra hydra-perspective (:color teal :hint nil)
    "
       ^^Perspective                ^^Projectile
--------------------------------------------------------------------
    _à_: Change perspective      _s_: Change project
    _k_: Kill perspective        _b_: Change buffer
"
    ("à"  persp-switch)
    ("k"  persp-kill)
    ("s"  projectile-switch-project)
    ("b"  projectile-switch-to-buffer)
    ("q"  nil "Quit" :exit t))

  (define-key dired-mode-map (kbd "SPC") 'hydra-main/body)
  (define-key evil-visual-state-map (kbd "SPC") 'hydra-main/body)
  (define-key evil-normal-state-map (kbd "SPC") 'hydra-main/body))

;; -------- IDE SET-UP -----------------------------------------------

;; Remote edit of files
(use-package tramp)

;; git
(use-package diff-hl
  :ensure t
  :config
  (global-diff-hl-mode +1)
  (diff-hl-flydiff-mode +1))

(use-package git-commit
  :ensure t
  :init
  (defun git-commit-init ()
    (display-fill-column-indicator-mode)
    (flyspell-mode))
  :hook (git-commit-setup . git-commit-init))

(use-package magit
  :ensure t
  :defer t
  :config
  (setq-default magit-diff-refine-hunk 'all)
  (setq-default magit-diff-refine-ignore-whitespace t)
  (add-hook 'magit-post-refresh-hook 'diff-hl-magit-post-refresh))

;; Doc suggestion in the echo area
(use-package eldoc
  :diminish eldoc-mode
  :hook (prog-mode . eldoc-mode))

;; Company
(use-package company
  :ensure t
  :diminish company-mode
  :after evil
  :hook
  (prog-mode . company-mode)
  :bind
  (:map evil-insert-state-map
   ("<C-tab>" . company-complete))
  :config
  (setq company-idle-delay nil)
  (setq company-tooltip-align-annotations t)
  (setq company-minimum-prefix-length 3)
  (setq company-tooltip-minimum-width 50)
  (setq company-tooltip-maximum-width 50)
  (evil-define-key 'insert 'company-active-map (kbd "C-n") 'company-select-next)
  (evil-define-key 'insert 'company-active-map (kbd "C-p") 'company-select-previous))

(use-package flycheck
  :ensure t
  :diminish flycheck-mode
  :hook (prog-mode . flycheck-mode)
  :config
  (define-fringe-bitmap 'flycheck-fringe-bitmap-ball
    (vector #b00000000
            #b00000000
            #b00000000
            #b00000000
            #b00000000
            #b00111000
            #b01111100
            #b11111110
            #b11111110
            #b01111100
            #b00111000
            #b00000000
            #b00000000
            #b00000000
            #b00000000
            #b00000000
            #b00000000))

  (flycheck-define-error-level 'error
    :severity 100
    :compilation-level 2
    :overlay-category 'flycheck-error-overlay
    :fringe-bitmap 'flycheck-fringe-bitmap-ball
    :fringe-face 'flycheck-fringe-error
    :error-list-face 'flycheck-error-list-error)
  (flycheck-define-error-level 'warning
    :severity 100
    :compilation-level 1
    :overlay-category 'flycheck-warning-overlay
    :fringe-bitmap 'flycheck-fringe-bitmap-ball
    :fringe-face 'flycheck-fringe-warning
    :warning-list-face 'flycheck-warning-list-warning)
  (flycheck-define-error-level 'info
    :severity 100
    :compilation-level 0
    :overlay-category 'flycheck-info-overlay
    :fringe-bitmap 'flycheck-fringe-bitmap-ball
    :fringe-face 'flycheck-fringe-info
    :info-list-face 'flycheck-info-list-info))

(use-package company-posframe
  :ensure t
  :diminish company-posframe-mode
  :config
  (setq company-posframe-show-indicator nil)
  :hook (company-mode . company-posframe-mode))

(use-package flycheck-pos-tip
  :ensure t
  :config
  (setq-default flycheck-pos-tip-timeout 30)
  :hook
  (flycheck-mode . flycheck-pos-tip-mode))

;; -------- PROGRAMMING LANGUAGE SET-UP ------------------------------

;; Coq
(defconst opam-switch
  (shell-command-to-string "opam switch show | tr -d '\n'"))

(defun coq-exe (name)
  "Give the absolute path of NAME executable."
  (concat (getenv "HOME")
          "/.opam/"
          opam-switch
          "/bin/"
          name))

(use-package proof-general
  :ensure t
  :mode ("\\.v\\'" . coq-mode)
  :init
  (progn
    (setq-default proof-splash-enable nil)
    (setq-default coq-compile-before-require t)
    (setq-default proof-disappearing-proofs t)
    (setq-default coq-prog-name (coq-exe "coqtop"))
    (setq-default coq-compiler (coq-exe "coqc"))
    (setq-default coq-dependency-analyzer (coq-exe "coqdep"))))

(use-package company-coq
  :ensure t
  :defines coq-one-command-per-line
  :init
  (progn
    (defhydra hydra-coq (:color teal :hint nil)
      "
     ^^Commands               ^^Company-Coq
------------------------------------------------
  _a_: About               _e_: Extract Current Goal
  _p_: Print               _d_: Diff
 _ss_: Search Pattern     _sd_: Show Documentation
  _x_: Exit Coq
"
      ("a"   coq-About)
      ("p"   coq-Print)
      ("ss"  coq-SearchIsos)
      ("x"   proof-shell-exit)
      ("e"   company-coq-lemma-from-goal)
      ("d"   company-coq-diff-dwim)
      ("sd"  company-coq-doc)
      ("q"   nil "Quit" :exit t)))
  :init
  (setq company-coq-disabled-features '(prettify-symbols smart-subscripts))
  (setq coq-one-command-per-line nil)
  :config
  (company-coq-initialize)
  :hook
  (((coq-response-mode coq-goals-mode) . centaur-tabs-local-mode)
   (coq-mode . company-coq-mode)
   (coq-mode . (lambda ()
                 (setq-local lthms-jump-to-definition-handler 'company-coq-jump-to-definition)
                 (setq-local hydra/mode 'hydra-coq/body)))))

;; Rust
(use-package rust-mode
  :defer t
  :ensure t)

(use-package cargo
  :ensure t
  :after rust-mode
  :hook ((rust-mode . cargo-minor-mode)
         (cargo-process-mode . visual-line-mode)))

(use-package racer
  :ensure t
  :hook
  ((rust-mode . racer-mode)
   (racer-mode . (lambda ()
                   (setq-local lthms-jump-to-definition-handler 'racer-find-definition)
                   (setq-local hydra/mode 'hydra-rust/body))))
  :config
  (defhydra hydra-rust (:color teal :hint nil)
    "
     ^^Racer                          ^^Rust
------------------------------------------------
  _d_: Show Documentation          _t_: Run Tests
                                   _c_: Run Clippy
"
    ("d"    racer-describe)
    ("t"    rust-test)
    ("c"    rust-run-clippy)
    ("q"    nil "Quit" :exit t))

  (setq racer-cmd (concat (getenv "HOME") "/.cargo/bin/racer"))
  ;; to be removed once `emacs-racer' is updated
  (setq racer-rust-src-path
        (let* ((sysroot (string-trim
                         (shell-command-to-string "rustc --print sysroot")))
               (lib-path (concat sysroot "/lib/rustlib/src/rust/library"))
               (src-path (concat sysroot "/lib/rustlib/src/rust/src")))
          (or (when (file-exists-p lib-path) lib-path)
              (when (file-exists-p src-path) src-path)))))

(use-package flycheck-rust
  :ensure t
  :hook
  (flycheck-mode . flycheck-rust-setup))

;; Latex
(use-package tex
  :ensure auctex
  :defer t
  :config
  (setq-default font-latex-fontify-script nil)
  (defhydra hydra-tex (:color teal :hint nil)
      "
     ^^Format
------------------------------------------------
 _fp_: Format Paragraph
 _fs_: Format Section
 _fe_: Format Environment
"
    ("fp"   LaTeX-fill-paragraph)
    ("fs"   LaTeX-fill-section)
    ("fe"   LaTeX-fill-environment)
    ("q"    nil "Quit" :exit t))
  :hook
  (TeX-mode . (lambda ()
                (display-fill-column-indicator-mode)
                (setq-local display-fill-column-indicator-column 80)
                (setq-local hydra/mode 'hydra-tex/body))))

;; Emacs Lisp
(use-package package-lint
  :defer t
  :ensure t)

;; Ocaml
(use-package tuareg
  :defer t
  :ensure t)

(use-package ocp-indent
  :ensure t
  :defer t
  :after tuareg)

(use-package utop
  :ensure t
  :defer t)

(use-package merlin
  :ensure t
  :after company
  :config
  (add-to-list 'company-backends 'merlin-company-backend)
  (setq merlin-locate-in-new-window 'never)
  (defhydra hydra-ocaml (:color teal :hint nil)
      "
    ^^Merlin
--------------------------------------------------------------------------------
 _i_: Switch to .mli
 _l_: Switch to .ml
 _o_: Find occurences
 _d_: Show documentation
 _t_: Type under cursor
 _T_: Type of expression
"
      ("i" merlin-switch-to-mli)
      ("l" merlin-switch-to-ml)
      ("o" merlin-occurrences)
      ("t" merlin-type-enclosing)
      ("T" merlin-type-expr)
      ("d" merlin-document)


      ("SPC" nil "Quit" :exit t))
  :hook (((caml-mode tuareg-mode) . merlin-mode)
         (merlin-mode . (lambda ()
                          (setq-local lthms-jump-to-definition-handler 'merlin-locate)
                          (setq-local lthms-pop-stack-handler 'merlin-pop-stack)
                          (setq-local lthms-goto-prev-phrase-handler 'merlin-phrase-prev)
                          (setq-local lthms-goto-next-phrase-handler 'merlin-phrase-next)
                          (setq-local hydra/mode 'hydra-ocaml/body)))))

(use-package flycheck-ocaml
  :ensure t
  :after merlin
  :hook
  (merlin-mode . (lambda ()
                   (setq merlin-error-after-save nil)
                   (flycheck-ocaml-setup))))

;; Haskell
(use-package dante
  :ensure t
  :after haskell-mode
  :hook (((haskell-mode haskell-literate-mode) . dante-mode)))

;; org
(use-package org
  :ensure t
  :mode ("\\.org\\'" . org-mode)
  :config
  (org-babel-do-load-languages
   'org-babel-load-languages
   '((shell . t)))
  (setq org-adapt-indentation nil)
  (setq org-src-preserve-indentation t))

(use-package ox-reveal
  :ensure t
  :after org)

;; Lua
(use-package lua-mode
  :ensure t)

;; SASS
(use-package sass-mode
  :mode ("\\.sass\\'" . sass-mode)
  :hook (sass-mode . rainbow-mode)
  :ensure t)

;; Common Lisp
(use-package slime
  :ensure t
  :defer t
  :config
  (slime-setup)
  (defhydra hydra-slime (:color teal :hint nil)
      "
    ^^Slime              ^^Compile                      ^^Evaluate
--------------------------------------------------------------------------------
 _s_: Start slime    _cf_: Compile function          _d_: Describe symbol
 _x_: Stop slime     _cr_: Compile region           _hd_: HyperSpec Lookup
                   ^^_cc_: Compile file
                   ^^_cC_: Compile and load file
"
    ("s"   slime)
    ("x"   slime-quit-lisp)

    ("cf"  slime-compile-defun)
    ("cr"  slime-compile-region)
    ("cc"  slime-compile-file)
    ("cC"  slime-compile-and-load-file)
    ("be"  slime-eval-buffer)

    ("d"   slime-describe-symbol)
    ("hd"  slime-hyperspec-lookup)
    ("SPC" nil "Quit" :exit t))

  (load (expand-file-name "~/quicklisp/slime-helper.el"))
  (setq-default inferior-lisp-program "/usr/bin/sbcl")
  (setq-default slime-contribs '(slime-fancy))
  :hook
  (slime-mode . (lambda () (setq-local hydra/mode 'hydra-slime/body))))

;; Emails
(add-to-list 'auto-mode-alist '("\\`/tmp/neomutt-" . mail-mode))
(add-hook 'mail-mode-hook
          (lambda ()
            (setq-local display-fill-column-indicator-column 72)))

;; Write custom configuration inside a different file
(setq custom-file "~/.emacs.d/emacs-custom.el")
(unless (file-exists-p custom-file)
  (with-temp-buffer (write-file custom-file)))
(load custom-file)

;;; init.el ends here