-
Notifications
You must be signed in to change notification settings - Fork 0
/
init.el
1322 lines (1123 loc) · 55 KB
/
init.el
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
;;; -*- lexical-binding: t; -*-
(unless (boundp 'package-archives)
(package-initialize))
(require 'cl-lib)
(unless (fboundp 'use-package)
(defmacro use-package (&rest body)
"Very hacky macro to wrap each statement in a"
`(progn
,@(cl-map 'list
(lambda (stmt)
(message "%s" stmt)
`(ignore-errors ,stmt)
)
body
)
)
)
)
(defun my/vc-git-editor-command (command)
"command is a git subcommand that requires an editor.
example usage: (my/vc-git-editor-command \"rebase -i HEAD~3\")"
(interactive "P")
(unless server-mode (server-force-delete) (server-mode))
(let ((command (if command command (read-string "command: git "))))
(compile (concat "GIT_EDITOR=\"emacsclient\" bash -c \"git " command "\""))))
(defun my/vc-git-rebase-i (&optional branch)
"if branch isn't supplied from arg, prompt for it"
(interactive)
(let ((revision (if branch branch (read-string "revision: "))))
(my/vc-git-editor-command (concat "rebase -i " revision))))
(defun my/vc-git-rebase-abort ()
(interactive)
(compile "git rebase --abort"))
(defun my/vc-git-rebase-continue ()
(interactive)
(compile "git rebase --continue"))
(defun my/vc-git-fetch ()
(interactive)
(compile "git fetch -v"))
(defun my/vc-get-remote ()
(let* ((remote-names (split-string (shell-command-to-string "git remote")))
(remote-urls
(mapcar (lambda (r)
(cons r
(string-trim
(shell-command-to-string (concat "git remote get-url " r)))))
remote-names))
(annotation-fn (lambda (candidate) (cdr (assoc candidate remote-urls))))
(completion-extra-properties `(:annotation-function ,annotation-fn))
(remote (completing-read "Remote: " remote-urls)))
remote))
(defun my/vc-set-remote-url ()
(interactive)
(let* ((remote (my/vc-get-remote))
(curr-url (string-trim
(shell-command-to-string (concat "git remote get-url " remote))))
(new-url (minibuffer-with-setup-hook (lambda () (insert curr-url))
(read-string (concat "Set url for remote <" remote ">: ")))))
(compile (concat "git remote set-url " remote " " new-url))))
(defun my/vc-set-branch-upstream ()
(interactive)
(let* ((remote (my/vc-get-remote))
(curr-branch (car (vc-git-branches)))
(upstream (minibuffer-with-setup-hook
(lambda () (insert remote "/" curr-branch))
(read-string (concat "set branch <" curr-branch "> upstream to: ")))))
(compile (concat "git branch -u " upstream))))
(defun my/vc-add-remote ())
(defun my/vc-delete-remote ())
(defun my/vc-set-remote-url ())
(defun vc-git-common-ancestor-diff (files &optional rev1 rev2 buffer _async)
"Get a difference report using Git between two revisions of FILES."
(let (process-file-side-effects
(command "diff"))
(vc-git--asciify-coding-system)
(if rev2
;; Diffing against the empty tree.
(unless rev1 (setq rev1 "4b825dc642cb6eb9a060e54bf8d69288fbee4904"))
(setq command "diff-index")
(unless rev1 (setq rev1 "HEAD")))
(if vc-git-diff-switches
(apply #'vc-git-command (or buffer "*vc-diff*")
1 ; bug#21969
files
command
"--exit-code"
(append (vc-switches 'git 'diff)
(list "-p" (concat (or rev1 "HEAD") "..." rev2) "--")))
(vc-git-command (or buffer "*vc-diff*") 1 files
"difftool" "--exit-code" "--no-prompt" "-x"
(concat "diff "
(mapconcat #'identity
(vc-switches nil 'diff) " "))
(concat rev1 "..." rev2) "--"))))
(defun vc-git-diff-advice (orig-fun &rest args)
(if (and (eq this-command #'vc-root-version-diff) (not current-prefix-arg))
(apply #'vc-git-common-ancestor-diff args)
(apply orig-fun args))
)
(advice-add #'vc-git-diff :around #'vc-git-diff-advice)
(defalias 'gt #'>)
(defalias 'gt= #'>=)
(defalias 'lt #'<)
(defalias 'lt= #'<=)
(defun neq (obj1 obj2)
"Convenience for not 'eq'"
(not (eq obj1 obj2)))
(use-package ediff :defer t
:config
(advice-remove 'ediff-quit #'disable-y-or-n-p)
(defun disable-y-or-n-p (orig-fun &rest args)
(cl-letf (((symbol-function 'y-or-n-p) (lambda (prompt) t)))
(apply orig-fun args)))
(advice-add 'ediff-quit :around #'disable-y-or-n-p)
(setq ediff-keep-variants nil)
(setq ediff-window-setup-function #'ediff-setup-windows-plain)
(setq ediff-split-window-function #'split-window-horizontally))
(defun vc-ediff-file-at-point ()
(interactive)
(when (eq major-mode 'diff-mode)
(setq my-ediff-prior-window-configuration (current-window-configuration))
(let ((old-revision (first diff-vc-revisions))
(new-revision (second diff-vc-revisions))
(file-to-diff (save-window-excursion
(diff-goto-source)
(buffer-file-name))))
(vc-version-ediff `(,file-to-diff) old-revision new-revision))))
(add-hook 'ediff-quit-hook
(lambda () (when (window-configuration-p my-ediff-prior-window-configuration)
(set-window-configuration my-ediff-prior-window-configuration)))
100)
(when (eq system-type 'gnu/linux)
(setq x-super-keysym 'meta)
(setq x-meta-keysym 'super))
(setq mac-option-modifier 'meta)
(setq mac-command-modifier 'super)
(define-key global-map (kbd "s-/") #'comment-line)
;; terminal stuff, C-/ in case we don't have iterm config
(define-key global-map (kbd "C-/") #'comment-line)
(define-key global-map (kbd "C-_") #'comment-line)
(define-key input-decode-map "\e[1;P9" (kbd "s-/"))
;; mac ligatures
(when (fboundp 'mac-auto-operator-composition-mode)
(mac-auto-operator-composition-mode))
(defun macos-term-select-text-to-clipboard (text)
(unless (eq system-type 'gnu/linux)
(shell-command (concat "echo \"" text "\" | pbcopy" ))))
;; ITERM2 MOUSE SUPPORT
(unless (or window-system (daemonp))
(require 'mouse)
(xterm-mouse-mode t)
(defun track-mouse (e))
(setq mouse-sel-mode t)
(setq interprogram-cut-function #'macos-term-select-text-to-clipboard)) ;; good enough
(winner-mode)
(defun my/set-transparency-in-terminal ()
(interactive)
(unless (string= (face-background 'default) "unspecified-bg")
(setq prev-default-face-bg (face-background 'default)))
(unless (display-graphic-p (selected-frame))
(set-face-background 'default "unspecified-bg" (selected-frame))))
(defun my/unset-transparency-in-terminal ()
(interactive)
(unless (display-graphic-p (selected-frame))
(set-face-background 'default prev-default-face-bg (selected-frame))))
(defun my/set-frame-alpha (&optional arg)
(interactive "sFrame Alpha? ")
(if
(and arg (not (string-empty-p arg)))
(set-frame-parameter nil 'alpha (string-to-number arg))
(set-frame-parameter nil 'alpha 90)))
(defun my/set-frame-alpha-background (&optional arg)
(interactive "sFrame Alpha Background? ")
(if
(and arg (not (string-empty-p arg)))
(set-frame-parameter nil 'alpha-background (string-to-number arg))
(set-frame-parameter nil 'alpha-background 90)))
(setq my-window-map (make-sparse-keymap))
(define-key my-window-map "u" #'winner-undo)
(define-key my-window-map "r" #'winner-redo)
(define-key my-window-map "<"
(lambda (arg) (interactive "P") (shrink-window-horizontally (if arg arg 1))))
(define-key my-window-map ">"
(lambda (arg) (interactive "P") (enlarge-window-horizontally (if arg arg 1))))
(define-key my-window-map "-"
(lambda (arg) (interactive "P") (shrink-window (if arg arg 1))))
(define-key my-window-map "+"
(lambda (arg) (interactive "P") (enlarge-window (if arg arg 1))))
(define-key my-window-map "v" #'split-window-horizontally)
(define-key my-window-map "s" #'split-window-vertically)
(define-key my-window-map "q" #'delete-window)
(define-key my-window-map "\C-w" #'other-window)
(define-key my-window-map "l" #'windmove-right)
(define-key my-window-map "\C-l" #'windmove-right)
(define-key my-window-map "h" #'windmove-left)
(define-key my-window-map "\C-h" #'windmove-left)
(define-key my-window-map "k" #'windmove-up)
(define-key my-window-map "\C-k" #'windmove-up)
(define-key my-window-map "j" #'windmove-down)
(define-key my-window-map "\C-j" #'windmove-down)
(define-key my-window-map "=" #'balance-windows)
(define-key my-window-map "o" #'maximize-window)
(define-key my-window-map "\C-o" #'delete-other-windows)
(define-key global-map (kbd "\C-w") nil)
(define-key global-map (kbd "\C-w") my-window-map)
(setq gc-cons-threshold most-positive-fixnum)
;; Lower threshold back to 8 MiB (default is 800kB)
(add-hook 'emacs-startup-hook
(lambda () (setq gc-cons-threshold (* 1024 1024 16)))) ;; 16MB
(run-with-idle-timer 2 t #'garbage-collect)
(setq inhibit-startup-screen t)
(use-package menu-bar :defer t :config (menu-bar-mode 0))
(use-package tool-bar :defer t :config (tool-bar-mode 0))
(setq viper-mode t)
(require 'viper)
(require 'rect)
(use-package scroll-bar :defer t)
(viper-mode)
(global-hl-line-mode)
(global-auto-revert-mode)
(setq auto-revert-verbose nil)
(global-visual-line-mode)
(when (fboundp #'global-visual-wrap-prefix-mode)
(global-visual-wrap-prefix-mode)
(setq visual-wrap-extra-indent 4))
(when (fboundp #'kill-ring-deindent-mode)
(kill-ring-deindent-mode) )
(add-hook 'prog-mode-hook (lambda () (modify-syntax-entry ?_ "-") (modify-syntax-entry ?_ "_")))
(setq revert-without-query '(".*")) ;; allow reverting without confirm
(setq column-number-mode t)
(setq scroll-margin 8)
(setq visual-bell t)
(setq ring-bell-function 'ignore)
(setq scroll-preserve-screen-position t)
(setq eval-expression-print-level nil)
(setq eval-expression-print-length nil)
(ignore-errors
(make-directory (concat (file-name-directory user-init-file) ".local/"))
(make-directory (concat (file-name-directory user-init-file) ".local/autosave/"))
(make-directory (concat (file-name-directory user-init-file) ".local/backups/")))
(setq auto-save-file-name-transforms
`(("\\`/[^/]*:\\([^/]*/\\)*\\([^/]*\\)\\'" "/Users/jason.z/.emacs.d/.local/cache/autosave/tramp-\\2" t)
(".*" ,(concat (file-name-directory user-init-file) ".local/autosave/\\1") t)))
(setq back-directory-alist `((".*" ,(concat (file-name-directory user-init-file) ".local/backups/"))))
(define-key global-map (kbd "C-S-p") #'yank-from-kill-ring)
(setq auto-save-visited-interval 7)
(auto-save-visited-mode)
(fido-vertical-mode)
(use-package savehist
:init
(savehist-mode))
(if (gt= emacs-major-version 30)
(setq completions-sort 'historical)
(setq completions-sort nil) ;; no sorting makes completion faster
)
(define-key minibuffer-local-completion-map "\t" #'icomplete-force-complete)
(define-key minibuffer-local-completion-map (kbd "C-<return>") #'viper-exit-minibuffer)
(define-key global-map (kbd "C-z") #'viper-mode) ;; C-z to suspend frame is annoying with viper
(setq completion-styles '(partial-completion basic) completion-category-overrides nil completion-category-defaults nil)
;; need this hook otherwise i think fido setup or something overrides the completion which is annoying
(defun my-icomplete-styles () (setq-local completion-styles '(partial-completion basic)))
(add-hook 'icomplete-minibuffer-setup-hook 'my-icomplete-styles)
(defvar my-icomplete-prev-command nil)
(defun my-icomplete-save ()
"save the prvious icomplete session"
(setq my-icomplete-prev-command this-command)
(add-hook 'post-command-hook #'my-icomplete-exit-save-input nil 'local))
(defvar my-icomplete-prev-input "")
(defun my-icomplete-exit-save-input ()
(setq my-icomplete-prev-input (minibuffer-contents-no-properties)))
(add-hook 'icomplete-minibuffer-setup-hook 'my-icomplete-save)
(defun my-icomplete-repeat ()
(interactive)
(when (and (not (equal my-icomplete-prev-command #'my-icomplete-repeat))
(commandp my-icomplete-prev-command))
(minibuffer-with-setup-hook
(lambda () (insert my-icomplete-prev-input))
(call-interactively my-icomplete-prev-command))))
(viper-map! :leader "'" #'my-icomplete-repeat)
;; insert * at the beginning so we don't have to match exactly at the beginning
;; but only in the icomplete minibuffer so we don't clash with viper minibuffer and stuff
;; NOTE: command category can slow down M-x
(defun icomplete-partial-completion-setup ()
(unless (or (eq (icomplete--category) 'file))
(insert "*")))
(add-hook 'icomplete-minibuffer-setup-hook #'icomplete-partial-completion-setup)
;; insert wild card to sorta emulate orderless
(defun icomplete-partial-completion-insert-wildcard ()
(interactive)
(unless (eq last-command 'viper-ex)
(insert "*")))
(define-key icomplete-minibuffer-map " " #'icomplete-partial-completion-insert-wildcard)
;; this allows us to still insert spaces
(define-key icomplete-minibuffer-map (kbd "M-SPC") (lambda () (interactive) (insert " ")))
(add-hook 'minibuffer-setup-hook (lambda () (setq-local icomplete-show-matches-on-no-input nil)) 100)
(advice-add #'viper-search :after
(lambda (string &rest args)
(hi-lock-face-buffer string)))
;; keep highlighting after isearch
(setq lazy-highlight-cleanup nil)
(defun my/ioccur-minibuf-after-edit (beg end len)
(setq my/ioccur-string (buffer-substring-no-properties (1+ (length my/ioccur-prompt-string)) (point-max)))
(when (gt (length (string-replace ".*" "" my/ioccur-string)) 2)
(ignore-errors (occur-1 my/ioccur-string
my/ioccur-nlines-arg
(list my/occur-buffer)))))
(setq my/ioccur-prompt-string "Find: ")
(setq my/ioccur-string "")
(defun my/ioccur (arg)
"Run a pseudo interactive grep, which will incrementally update the xref buffer based on minibuffer input.
With a prefix-arg run normally and specfiy a directory"
(interactive "P")
(setq my/ioccur-string "")
(setq my/occur-buffer (current-buffer))
(setq my/ioccur-nlines-arg (when arg (prefix-numeric-value arg)))
(minibuffer-with-setup-hook
(lambda ()
(local-set-key (kbd "SPC") (lambda () (interactive) (insert ".*")))
(add-hook 'after-change-functions #'my/ioccur-minibuf-after-edit nil 'local))
(occur-1 (read-regexp my/ioccur-prompt-string)
my/ioccur-nlines-arg
(list my/occur-buffer))))
(viper-map! :leader
"ss" #'my/ioccur
;; not sure why but we need to rescan the imenu for our igrep xref buffer
"si" (lambda () (interactive)
(imenu--menubar-select imenu--rescan-item)
(call-interactively 'imenu)))
(defun ripgrep ()
(interactive)
(call-interactively 'grep))
(defun rripgrep ()
(interactive)
(call-interactively 'rgrep))
(defun rripgrep-multiline ()
(interactive)
(call-interactively 'rgrep))
(defun rgrep-multiline ()
(interactive)
(grep-apply-setting 'grep-command "grep -Pazo --color=auto -nH --null -e ")
(call-interactively 'rgrep))
(defun grep-options-advice ()
"A convenient way for us to put different options depending on the grep command being run.
See notes:emacs-notes-and-tips for more details."
(cond ((or (eq this-command 'ripgrep) (eq this-command 'rripgrep))
(progn
(grep-apply-setting 'grep-command "rg -nS --no-heading ") ;; for normal single file grep
(grep-apply-setting 'grep-find-template "find <D> <X> -type f <F> -exec rg <C> -nS --no-heading -H <R> /dev/null {} +"))) ;; for rgrep; uses grep-find-template
((eq this-command 'rripgrep-multiline)
(progn
(grep-apply-setting 'grep-find-template "find <D> <X> -type f <F> -exec rg <C> -nSU --no-heading -H <R> /dev/null {} +")))
((eq this-command 'rgrep-multiline)
(progn
(grep-apply-setting 'grep-find-template "find -H <D> <X> -type f <F> -exec grep -zo <C> -nH --null -e <R> \\{\\} +")))
(t (progn ;; defaults in case I want to change them later to do something different, otherwise don't really need this last case
(grep-apply-setting 'grep-find-template "find -H <D> <X> -type f <F> -exec grep <C> -nH --null -e <R> \\{\\} +")
(grep-apply-setting 'grep-command "grep --color=auto -nH --null -e ")))
)
)
(advice-add #'grep-compute-defaults :before #'grep-options-advice)
(require 'dabbrev)
;; #'dabbrev-completion resets the global variables first so we do the same
(advice-add #'dabbrev-capf :before #'dabbrev--reset-global-variables)
(add-hook 'completion-at-point-functions #'dabbrev-capf 100)
(use-package xref
:config
(setq xref-search-program
(cond ((executable-find "rg") 'ripgrep)
((executable-find "ugrep") 'ugrep)
(t 'grep)))
(setq xref-show-xrefs-function #'xref-show-definitions-completing-read)
(setq xref-show-definitions-function #'xref-show-definitions-completing-read)
(defun search-advice (orig-fun regexp)
(let ((xref-show-xrefs-function #'xref--show-xref-buffer))
(minibuffer-with-setup-hook
(lambda ()
;; for some reason this doesn't apply in xref find apropos but that's honestly ok
;; cause it uses a space separated list of words anyways
(local-set-key (kbd "M-SPC") (lambda () (interactive) (insert " ")))
(local-set-key (kbd "SPC") (lambda () (interactive) (insert ".*"))))
(funcall orig-fun regexp))))
(advice-add 'project-find-regexp :around #'search-advice)
(advice-add 'xref-find-apropos :around #'search-advice)
(advice-add 'previous-history-element :after #'end-of-line) ;; usually we want to go to end of line
(setq my/xref-vi-state-modify-map
(make-composed-keymap
nil
(make-composed-keymap
(list my/viper-vi-basic-motion-keymap
my/viper-vi-motion-g-keymap
my/viper-vi-motion-leader-keymap)
xref--xref-buffer-mode-map)))
(viper-modify-major-mode 'xref--xref-buffer-mode 'vi-state my/xref-vi-state-modify-map))
(setq enable-recursive-minibuffers t)
(setq icomplete-in-buffer t)
(setq minibuffer-visible-completions t)
(global-completion-preview-mode)
;; for default completion behavior in the *completions* buffer, should we decide to use it
(define-key completion-in-region-mode-map (kbd "C-n") #'minibuffer-next-completion)
(define-key completion-in-region-mode-map (kbd "C-p") #'minibuffer-previous-completion)
(define-key minibuffer-visible-completions-map (kbd "C-n") #'minibuffer-next-completion)
(define-key minibuffer-visible-completions-map (kbd "C-p") #'minibuffer-previous-completion)
(setq completions-format 'one-column)
(setq completions-max-height 20)
(setq completions-header-format nil)
(define-error 'no-completions "completing-read-in-region: No completions")
(defun completing-read-in-region (start end collection &optional predicate)
"Prompt for completion of region in the minibuffer if non-unique.
Use as a value for `completion-in-region-function'."
(let* ((initial (buffer-substring-no-properties start end))
(limit (car (completion-boundaries initial collection predicate "")))
(all (completion-all-completions initial collection predicate (length initial)))
;; when the completion candidate list a single one, for some reason completing-read
;; will delete a bunch of lines.
;; to couteract this, we basically undo an atomic change and set the completion variable
(completion (cond
((atom all) nil)
((and (consp all) (atom (cdr all)))
(concat (substring initial 0 limit) (car all)))
(t
(setq completion
(catch 'done
(atomic-change-group
(let ((completion
(completing-read "Completion: " collection predicate nil initial)))
(throw 'done completion)))))))))
(cond (completion (completion--replace start end completion) t)
(t (signal 'no-completions nil)))))
(setq completion-in-region-function #'completing-read-in-region)
;; (setq completion-in-region-function #'completion--in-region)
(setq tab-always-indent 'complete)
(defun indent-current-line ()
"Indent the line. Stolen from the middle section of `indent-for-tab-command'."
(or (not (eq (indent--funcall-widened indent-line-function) 'noindent))
(indent--default-inside-comment)
(when (or (lt= (current-column) (current-indentation))
(not (eq tab-always-indent 'complete)))
(indent--funcall-widened (default-value 'indent-line-function)))))
;; want backtab to undo our indents basically but not do completion
(defun indent-for-backtab-command ()
"Want backtab to reindent the line if we've overintended with tab.
Otheriwse, shift backwards by tab-width."
(interactive)
(if-let ((cmd (ignore-errors
(lookup-key (symbol-value (intern (concat (symbol-name major-mode) "-map")))
[backtab]))))
(call-interactively cmd)
(let ((text-before-pt (buffer-substring-no-properties (line-beginning-position) (point)))
;; get the would be indented column then undo the changes and restore point
(indented-column (catch 'done (save-excursion
(atomic-change-group
(indent-current-line)
(throw 'done (current-column)))))))
;; only deindent if we're equal to or before the would-be indented column
;; otherwise, go back to the intended indented position
(if (lt= (current-column) indented-column)
(indent-rigidly (if (region-active-p) (region-beginning) (line-beginning-position))
(if (region-active-p) (region-end) (line-end-position))
(- tab-width))
(indent-current-line)))))
(defun indent-for-tab-check-empty-before-point (orig-fun &rest args)
"Around advice for `indent-for-tab-command'.
Insert tabs DWIM style if the current position is already indented and
we're at the beginning of the text on the current line.
ORIG-FUN is `indent-for-tab-command' and ARGS is prefix-arg for that."
(let ((text-before-pt (buffer-substring-no-properties (line-beginning-position) (point)))
;; get the would be indented column then undo the changes and restore point
(indented-column (catch 'done (save-excursion
(atomic-change-group
(indent-current-line)
(throw 'done (current-column)))))))
;; only indent if we're equal to or past the would-be indented column
(if (and (gt= (current-column) indented-column)
(string-blank-p text-before-pt))
(insert-tab current-prefix-arg)
(apply orig-fun args))))
(advice-add 'indent-for-tab-command :around #'indent-for-tab-check-empty-before-point)
(define-key viper-insert-basic-map [backtab] #'indent-for-backtab-command)
(use-package vc :config
(setq-default vc-handled-backends '(SVN Git Hg))
(setq vc-git-diff-switches '("--histogram" "--diff-algorithm=histogram"))
)
(use-package speedbar :defer t
:config
(setq speedbar-show-unknown-files t)
(setq speedbar-frame-parameters (delete '(minibuffer) speedbar-frame-parameters))
(setq speedbar-update-flag nil)
(setq my/speedbar-vi-state-modify-map (make-sparse-keymap))
(define-key my/speedbar-vi-state-modify-map (kbd "<tab>") #'speedbar-toggle-line-expansion)
(define-key my/speedbar-vi-state-modify-map (kbd "C-i") #'speedbar-toggle-line-expansion)
(define-key my/speedbar-vi-state-modify-map (kbd "-") #'speedbar-up-directory)
(viper-modify-major-mode 'speedbar-mode 'vi-state my/speedbar-vi-state-modify-map))
(use-package ibuffer :defer t
:config
;; add project level grouping
(defun set-ibuffer-project-groups ()
(setq ibuffer-saved-filter-groups
(list (let ((l (seq-filter #'identity
(cl-mapcar
(lambda (p)
(let* ((project (project--find-in-directory (car p)))
(pname (project-name project))
(pbufs (cl-find-if (lambda (b) (buffer-file-name b)) (project-buffers project))))
(when pbufs
`( ,pname (filename . ,pname)))))
(seq-filter
(lambda (p) (project-buffers (project--find-in-directory (car p))))
project--list)))))
(add-to-list 'l "projects"))))
(ibuffer-switch-to-saved-filter-groups "projects"))
(add-hook 'ibuffer-hook #'set-ibuffer-project-groups))
(setq bookmark-use-annotations t)
(setq bookmark-save-flag 1)
(setq bookmark-automatically-show-annotations nil)
; note the call-interactively does pass the prefix args
(defun my/set-project-bookmark ()
(interactive)
(minibuffer-with-setup-hook
(lambda ()
(let ((prefix (concat (project-name (project-current)) ": ")))
(when (project-name (project-current))
(insert prefix))))
(call-interactively 'bookmark-set)))
(defun my/jump-to-project-bookmark ()
(interactive)
(minibuffer-with-setup-hook
(lambda ()
(let ((prefix (concat (project-name (project-current)) ": ")))
(when (project-name (project-current))
(insert prefix))))
(call-interactively 'bookmark-jump)))
(defun split-string-at-first-match (string regex)
(let ((pos (string-match regex string)))
(if pos
(list (substring string 0 pos)
(substring string (+ pos (length (match-string 0 string)))))
(list string))))
(defun copy-env-vars-from-shell-1 (cmd)
(mapc (lambda (env-var-string)
(let* ((split (split-string-at-first-match env-var-string "="))
(name (cl-first split))
(val (cl-second split)))
(when (and name val)
(setq val (string-replace " " "\\ " val))
(setenv name val)
(when (string-equal "PATH" name)
(setq exec-path (append (parse-colon-path val) (list exec-directory)))
;; eshell path
(setq-default eshell-path-env val)
(when (fboundp 'eshell-set-path) (eshell-set-path val))))))
(split-string (shell-command-to-string cmd) "\n")))
(defun copy-env-vars-from-shell ()
(interactive)
(copy-env-vars-from-shell-1 "bash --login -i -c printenv"))
(defun copy-env-vars-from-shell-virtual-env ()
(interactive)
(let ((venv-name (read-directory-name "venv folder:" nil nil nil nil)))
(copy-env-vars-from-shell-1 (format "bash --login -i -c \". %s && printenv\""
(concat venv-name "bin/activate")))))
(defun get-docker-env-vars ()
"Gets the environment variables set by ENV in dockerfile by looking at /proc/1/environ.
Meant for eshell in mind."
(interactive)
(mapc (lambda (env-var-string)
(let* ((split (split-string env-var-string "="))
(name (cl-first split))
(val (cl-second split)))
(unless (string-equal "TERM" name)
(if (string-equal "PATH" name)
(progn
;; eshell path
(setq eshell-path-env val)
(when (fboundp 'eshell-set-path) (eshell-set-path val)))
(setenv name val)))))
(split-string (shell-command-to-string "tr \'\\0\' \'\\n\' < /proc/1/environ") "\n")))
(use-package tramp :defer t
:config
(add-to-list 'tramp-remote-path 'tramp-own-remote-path)
(setq enable-remote-dir-locals t)
(setq tramp-ssh-controlmaster-options (concat "-o ControlPath=/tmp/ssh-ControlPath-%%r@%%h:%%p " "-o ControlMaster=auto -o ControlPersist=yes"))
(setq tramp-use-ssh-controlmaster-options t)
(defun dired-do-delete-advice-remote (orig-fun &rest args)
;; this way we use the default value as opposed to the alternative of
;; setting delete-by-moving-to-trash to the value of (file-remote-p default-directory)
(if (file-remote-p default-directory)
(let ((delete-by-moving-to-trash nil))
(apply orig-fun args)
)
(apply orig-fun args)
)
)
(advice-add 'dired-internal-do-deletions :around #'dired-do-delete-advice-remote)
)
(with-eval-after-load 'tramp
(add-to-list 'tramp-methods
'("sshx11"
(tramp-login-program "ssh")
(tramp-login-args (("-l" "%u") ("-p" "%p") ("%c")
("-e" "none") ("-X") ("%h")))
(tramp-async-args (("-q")))
(tramp-remote-shell "/bin/sh")
(tramp-remote-shell-login ("-l"))
(tramp-remote-shell-args ("-c"))
(tramp-gw-args (("-o" "GlobalKnownHostsFile=/dev/null")
("-o" "UserKnownHostsFile=/dev/null")
("-o" "StrictHostKeyChecking=yes")
("-o" "ForwardX11=yes")))
(tramp-default-port 22)))
(tramp-set-completion-function "sshx11" tramp-completion-function-alist-ssh))
(add-hook 'prog-mode-hook #'flymake-mode)
(setq treesit-font-lock-level 4)
(setq-default indent-tabs-mode nil)
(which-function-mode)
(setq which-func-display 'header)
(add-hook 'prog-mode-hook
(lambda ()
(unless (eq major-mode 'web-mode)
(electric-pair-local-mode))))
(add-hook 'prog-mode-hook #'hs-minor-mode)
(use-package which-key :defer 2
:config
(which-key-mode))
(defun my/flymake-diagnostics-at-point ()
(interactive)
(let ((diags (flymake-diagnostics (point))))
(if (not (seq-empty-p diags))
(message "%s"
(cl-reduce (lambda (acc d) (concat acc (flymake--diag-text d)))
(flymake-diagnostics (point))
:initial-value ""))
(message "No diagnostics at point."))))
(add-to-list 'display-buffer-alist '((major-mode . compilation-mode)
(display-buffer-in-side-window)))
(add-to-list 'display-buffer-alist
'((or (major-mode . flymake-project-diagnostics-mode)
(major-mode . flymake-diagnostics-buffer-mode))
(display-buffer-in-side-window)))
(add-to-list 'display-buffer-alist
'("\\*eldoc.*\\*"
(display-buffer-in-side-window)))
(add-to-list 'display-buffer-alist
'((major-mode . help-mode)
(display-buffer-in-side-window)
(window-height . 0.35)))
(add-to-list 'display-buffer-alist
'((major-mode . messages-buffer-mode)
(display-buffer-in-side-window)
(window-height . 0.15)))
(define-derived-mode arduino-mode c-mode "arduino"
"My own mode which is a wrapper for c-mode for editing arduino files.")
(use-package eglot :defer t
:config
(add-to-list 'eglot-server-programs '(arduino-mode . ("~/go/1.22.2/bin/arduino-language-server"
"-clangd" "/usr/bin/clangd"
"-cli" "/opt/homebrew/bin/arduino-cli"
"-cli-config" "/Users/jasonzhen/Library/Arduino15/arduino-cli.yaml"
"-fqbn" "arduino:avr:uno"))))
(add-hook 'arduino-mode-hook #'eglot-ensure)
(add-to-list 'auto-mode-alist '("\\.ino\\'" . arduino-mode))
(add-to-list 'auto-mode-alist '("\\.go\\'" . go-ts-mode))
(add-hook 'go-ts-mode-hook #'eglot-ensure)
(use-package go-ts-mode :defer t
:config
(setq go-ts-mode-indent-offset tab-width))
(defun unset-go-env-vars ()
"This is needed so that for example, if one project has a go work file but the other doesn't,
we don't still use the other project's go work file."
(mapc (lambda (env-var-string)
(let* ((split (split-string env-var-string "="))
(name (cl-first split)))
(when (and name (not (string-empty-p name)))
(setenv name ""))))
(split-string (shell-command-to-string "bash --login -c \"go env\"") "\n")))
(defun copy-go-env-vars-from-shell ()
(interactive)
(unset-go-env-vars)
(copy-env-vars-from-shell)
(mapc (lambda (env-var-string)
(let* ((split (split-string env-var-string "="))
(name (cl-first split))
(val (cl-second split)))
(when (and name val (not (string-empty-p name)) (not (string-empty-p val)))
(setenv name (string-trim val "[ '\"]" "[ '\"]")))))
(split-string (shell-command-to-string "bash --login -c \"go env\"") "\n"))
(call-interactively 'eglot-reconnect))
(defvar +go-test-last nil
"The last test run.")
(defun +go--spawn (cmd)
(save-selected-window
(compile cmd)))
(defun +go--run-tests (args)
(let ((cmd (concat "go test -test.v " args)))
(setq +go-test-last (concat "cd " default-directory ";" cmd))
(+go--spawn cmd)))
(defun +go/test-single ()
"Run single test at point."
(interactive)
(if (string-match "_test\\.go" buffer-file-name)
(save-excursion
(re-search-backward "^func[ ]+\\(([[:alnum:]]*?[ ]?[*]?[[:alnum:]]+)[ ]+\\)?\\(Test[[:alnum:]_]+\\)(.*)")
(+go--run-tests (concat "-run" "='^\\Q" (match-string-no-properties 2) "\\E$'")))
(error "Must be in a _test.go file")))
(defun +go/test-file ()
"Run all tests in current file."
(interactive)
(if (string-match "_test\\.go" buffer-file-name)
(save-excursion
(goto-char (point-min))
(let ((func-list))
(while (re-search-forward "^func[ ]+\\(([[:alnum:]]*?[ ]?[*]?[[:alnum:]]+)[ ]+\\)?\\(Test[[:alnum:]_]+\\)(.*)" nil t)
(push (match-string-no-properties 2) func-list))
(+go--run-tests (concat "-run" "='^(" (string-join func-list "|") ")$'"))))
(error "Must be in a _test.go file")))
(use-package go-ts-mode :defer t
:config
(setq my/go-vi-state-modify-map (make-sparse-keymap))
(define-key my/go-vi-state-modify-map " mts" #'+go/test-single)
(define-key my/go-vi-state-modify-map " mtf" #'+go/test-file)
(viper-modify-major-mode 'go-ts-mode 'vi-state my/go-vi-state-modify-map))
(defun copy-pipenv-vars-from-shell ()
(interactive)
(copy-env-vars-from-shell-1 "bash --login -i -c \"pipenv run printenv\""))
(setq-default tab-width 4)
(use-package js :defer t
:config
(setq js-indent-level 4)
(add-hook 'js-mode-hook #'eglot-ensure))
(use-package typescript-ts-mode :defer t
:config
(setq typescript-ts-mode-indent-offset 4)
(add-hook 'typescript-ts-mode-hook #'eglot-ensure))
(add-to-list 'auto-mode-alist '("\\.ts\\'" . typescript-ts-mode))
(add-to-list 'auto-mode-alist '("\\.js\\'" . js-ts-mode))
(use-package elisp-mode :defer t
:config
(require 'advice) ;; for ad-get-orig-definition
(defun +emacs-lisp-highlight-vars-and-faces (end)
"Match defined variables and functions.
Functions are differentiated into special forms, built-in functions and
library/userland functions"
(catch 'matcher
(while (re-search-forward "\\(?:\\sw\\|\\s_\\)+" end t)
(let ((ppss (save-excursion (syntax-ppss))))
(cond ((nth 3 ppss) ; strings
(search-forward "\"" end t))
((nth 4 ppss) ; comments
(forward-line +1))
((let ((symbol (intern-soft (match-string-no-properties 0))))
(and (cond ((null symbol) nil)
((eq symbol t) nil)
((keywordp symbol) nil)
((special-variable-p symbol)
(setq +emacs-lisp--face 'font-lock-variable-name-face))
((and (fboundp symbol)
(eq (char-before (match-beginning 0)) ?\()
(not (memq (char-before (1- (match-beginning 0)))
(list ?\' ?\`))))
(let ((unaliased (indirect-function symbol)))
(unless (or (macrop unaliased)
(special-form-p unaliased))
(let (unadvised)
(while (not (eq (setq unadvised (ad-get-orig-definition unaliased))
(setq unaliased (indirect-function unadvised)))))
unaliased)
(setq +emacs-lisp--face
(if (subrp unaliased)
'font-lock-constant-face
'font-lock-function-name-face))))))
(throw 'matcher t)))))))
nil))
(font-lock-add-keywords 'emacs-lisp-mode `((+emacs-lisp-highlight-vars-and-faces . +emacs-lisp--face)) 'append))
(defun my/eshell-in-bottom-side-window (arg)
(interactive "P")
(let ((eshell-buffer (save-window-excursion (eshell))))
(select-window (display-buffer-in-side-window eshell-buffer '()))))
(defun my/eshell-send-cmd-async ()
(interactive)
(let ((cmd (string-trim (buffer-substring-no-properties eshell-last-output-end (progn (end-of-line) (point))))))
(unless (eshell-head-process)
(delete-region eshell-last-output-end (point))
(insert (format "async-shell-command \"%s\"" cmd)))))
(use-package eshell :defer t
:config
(add-to-list 'eshell-modules-list 'eshell-tramp)
(setq my/eshell-vi-state-modify-map (make-sparse-keymap))
(setq my/eshell-insert-state-modify-map (make-sparse-keymap))
(define-key my/eshell-vi-state-modify-map (kbd "C-<return>") #'my/eshell-send-cmd-async)
(define-key my/eshell-vi-state-modify-map " ma" #'my/eshell-send-cmd-async)
(define-key my/eshell-insert-state-modify-map (kbd "C-<return>") #'my/eshell-send-cmd-async)
(define-key my/eshell-insert-state-modify-map (kbd "M-<return>") #'my/eshell-send-cmd-async)
(defun slurp (f)
(with-temp-buffer
(insert-file-contents f)
(buffer-substring-no-properties (point-min) (point-max))))
(define-key my/eshell-insert-state-modify-map (kbd "C-r")
(lambda ()
(interactive)
(let ((selected (completing-read "History: "
(cl-remove-if-not
(lambda (elem)
(text-properties-at 0 elem))
(ring-elements eshell-history-ring)))))
(when selected
(end-of-line)
(eshell-kill-input)
(insert selected)))))
(viper-modify-major-mode 'eshell-mode 'vi-state my/eshell-vi-state-modify-map)
(viper-modify-major-mode 'eshell-mode 'insert-state my/eshell-insert-state-modify-map))
(use-package eshell :after consult :config
(define-key my/eshell-insert-state-modify-map (kbd "C-r") #'consult-history))
(defun my/shell-in-bottom-side-window (arg)
(interactive "P")
(let ((shell-buffer (save-window-excursion (shell))))
(select-window (display-buffer-in-side-window shell-buffer '()))))
(use-package shell :defer t
:config
(setq my/shell-insert-state-modify-map (make-sparse-keymap))
(define-key my/shell-insert-state-modify-map (kbd "<up>") #'comint-previous-input)
(define-key my/shell-insert-state-modify-map (kbd "<down>") #'comint-next-input)
(define-key my/shell-insert-state-modify-map (kbd "C-r")
(lambda ()
(interactive)
(let ((selected (completing-read "History: "
(cl-remove-if-not
(lambda (elem)
(text-properties-at 0 elem))
(ring-elements comint-input-ring)))))
(when selected
(end-of-line)
(comint-kill-input)
(insert selected)))))
(viper-modify-major-mode 'shell-mode 'insert-state my/shell-insert-state-modify-map))
(use-package shell :after consult :config
(define-key my/shell-insert-state-modify-map (kbd "C-r") #'consult-history))
(when (display-graphic-p) ;; only matter for gui emacs
(setq current-font-height 160)
(defun set-fonts ()
(message "setting fonts")
(cond ((member "FantasqueSansM Nerd Font Propo" (font-family-list))
(ignore-errors (set-face-attribute 'default nil :font "FantasqueSansM Nerd Font Propo" :height current-font-height)))
((member "IosevkaCustom Nerd Font Propo" (font-family-list))
(ignore-errors (set-face-attribute 'default nil :font "FantasqueSansM Nerd Font Propo" :height current-font-height)))