-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathdotEmacs
4876 lines (4407 loc) · 184 KB
/
dotEmacs
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
(require 'package)
(setq package-quickstart t)
;; This can fix some troubles with native compilation
;; (setq load-no-native t)
;;; Before everything else
;; (defvar old--file-name-handler-alist file-name-handler-alist)
(setq file-name-handler-alist nil)
;; (add-hook 'emacs-startup-hook
;; #'(lambda () (setq ;; gc-cons-threshold 16777216 ; 16mb
;; gc-cons-threshold 104857600 ; 100MB
;; gc-cons-percentage 0.1
;; file-name-handler-alist old--file-name-handler-alist)
;; ;; (my/set-font)
;; ))
;;; Package setup
; If we run package-initialize, then add-to-list melpa, the
; package-install invocation will fail. We need the package-archives
; list setup before calling package-initialize.
(setq package-archives '(("org" . "http://orgmode.org/elpa/")
("melpa" . "http://melpa.milkbox.net/packages/")
("gnu" . "http://elpa.gnu.org/packages/")))
;; (package-initialize)
(require 'use-package)
;; (eval-when-compile
;; (add-to-list 'load-path "~/src/use-package")
;; (require 'use-package))
;; (require 'bind-key)
;; Show a message whenever a package takes longer than 0.1s to load
(setq use-package-verbose t)
(setq use-package-compute-statistics t)
;;; benchmark-init
(use-package benchmark-init
:disabled
:config
(require 'benchmark-init)
;; To disable collection of benchmark data after init is done.
(add-hook 'after-init-hook (lambda ()
(benchmark-init/deactivate)
(require 'benchmark-init-modes)))
(benchmark-init/activate))
;;; Font setup
;; It would be nice to include this logic in early-init.el, but
;; `window-system' is not set up by the time that file is run during
;; emacs startup.
(defun my/preferred-font-size ()
(cond
((memq window-system '(mac ns)) 15)
((file-exists-p "/etc/nixos") 11)
((file-exists-p "/etc/lsb-release") 18)
(t 11)))
(defun my/set-font ()
(if (and nil (memq window-system '(mac ns)))
(set-frame-font "Monaco 14" nil t)
(let ((size (my/preferred-font-size)))
(set-face-font 'default (format "Victor Mono-%d:weight=demi" size))
(set-frame-font (format "Victor Mono-%d:weight=demi" size) nil t))
;; (if (or (memq window-system '(mac ns))
;; ;; (file-exists-p "/etc/lsb-release")
;; )
;; (set-frame-font "Victor Mono-15:weight=demi")
;; (set-frame-font "Victor Mono-11:weight=demi"))
))
(my/set-font)
(defvar yanone-font-name "Yanone Kaffeesatz")
(use-package info
:commands (info info-apropos)
:config
;; (set-face-attribute 'info-title-1 nil :family "Yanone Kaffeesatz" :weight 'light :height 200 :foreground "#E1BEE7")
;; (set-face-attribute 'info-title-2 nil :family "Yanone Kaffeesatz" :weight 'light :height 175)
;; (set-face-attribute 'info-title-3 nil :family "Yanone Kaffeesatz" :weight 'light :height 160)
;; (set-face-attribute 'info-title-4 nil :family "Yanone Kaffeesatz" :weight 'light :height 150)
;; (set-face-attribute 'info-menu-header nil :family "Yanone Kaffeesatz" :weight 'light :height 175 :foreground "#E1BEE7")
(set-face-attribute 'info-title-1 nil :font yanone-font-name :weight 'light :height 200 :foreground "#E1BEE7")
(set-face-attribute 'info-title-2 nil :font yanone-font-name :weight 'light :height 175)
(set-face-attribute 'info-title-3 nil :font yanone-font-name :weight 'light :height 160)
(set-face-attribute 'info-title-4 nil :font yanone-font-name :weight 'light :height 150)
(set-face-attribute 'info-menu-header nil :font yanone-font-name :weight 'light :height 175 :foreground "#E1BEE7"))
(use-package hl-line
:commands (hl-line-mode)
:custom-face
(hl-line ((t (:background "gray20")))))
;;;; Support ligatures
;; See https://github.com/tonsky/FiraCode/wiki/Emacs-instructions#user-content-using-composition-char-table
;; (let ((alist '((33 . ".\\(?:\\(?:==\\|!!\\)\\|[!=]\\)")
;; (35 . ".\\(?:###\\|##\\|_(\\|[#(?[_{]\\)")
;; (36 . ".\\(?:>\\)")
;; (37 . ".\\(?:\\(?:%%\\)\\|%\\)")
;; (38 . ".\\(?:\\(?:&&\\)\\|&\\)")
;; (42 . ".\\(?:\\(?:\\*\\*/\\)\\|\\(?:\\*[*/]\\)\\|[*/>]\\)")
;; ;; This one interferes with formatting of hlines in org-mode tables
;; ;; (43 . ".\\(?:\\(?:\\+\\+\\)\\|[+>]\\)")
;; (45 . ".\\(?:\\(?:-[>-]\\|<<\\|>>\\)\\|[<>}~-]\\)")
;; (46 . ".\\(?:\\(?:\\.[.<]\\)\\|[.=-]\\)")
;; (47 . ".\\(?:\\(?:\\*\\*\\|//\\|==\\)\\|[*/=>]\\)")
;; (48 . ".\\(?:x[a-zA-Z]\\)")
;; (58 . ".\\(?:::\\|[:=]\\)")
;; (59 . ".\\(?:;;\\|;\\)")
;; ;; This one interferes with org-mode tables
;; ;; (60 . ".\\(?:\\(?:!--\\)\\|\\(?:~~\\|->\\|\\$>\\|\\*>\\|\\+>\\|--\\|<[<=-]\\|=[<=>]\\||>\\)\\|[*$+~/<=>|-]\\)")
;; (60 . ".\\(?:\\(?:!--\\)\\|\\(?:~~\\|->\\|\\$>\\|\\*>\\|\\+>\\|<[<=]\\|=[<=>]\\||>\\)\\|[*$+~/<=>|]\\)")
;; (61 . ".\\(?:\\(?:/=\\|:=\\|<<\\|=[=>]\\|>>\\)\\|[<=>~]\\)")
;; (62 . ".\\(?:\\(?:=>\\|>[=>-]\\)\\|[=>-]\\)")
;; (63 . ".\\(?:\\(\\?\\?\\)\\|[:=?]\\)")
;; (91 . ".\\(?:]\\)")
;; (92 . ".\\(?:\\(?:\\\\\\\\\\)\\|\\\\\\)")
;; (94 . ".\\(?:=\\)")
;; (119 . ".\\(?:ww\\)")
;; (123 . ".\\(?:-\\)")
;; (124 . ".\\(?:\\(?:|[=|]\\)\\|[=>|]\\)")
;; (126 . ".\\(?:~>\\|~~\\|[>=@~-]\\)")
;; )
;; ))
;; (dolist (char-regexp alist)
;; (set-char-table-range composition-function-table (car char-regexp)
;; `([,(cdr char-regexp) 0 font-shape-gstring]))))
(use-package ligature
:disabled
:config
;; Enable the "www" ligature in every possible major mode
(ligature-set-ligatures 't '("www"))
;; Enable traditional ligature support in eww-mode, if the
;; `variable-pitch' face supports it
(ligature-set-ligatures 'eww-mode '("ff" "fi" "ffi"))
;; Enable all Cascadia Code ligatures in programming modes
(ligature-set-ligatures 'prog-mode '("|||>" "<|||" "<==>" "<!--" "####" "~~>" "***" "||=" "||>"
":::" "::=" "=:=" "===" "==>" "=!=" "=>>" "=<<" "=/=" "!=="
"!!." ">=>" ">>=" ">>>" ">>-" ">->" "->>" "-->" "---" "-<<"
"<~~" "<~>" "<*>" "<||" "<|>" "<$>" "<==" "<=>" "<=<" "<->"
"<--" "<-<" "<<=" "<<-" "<<<" "<+>" "</>" "###" "#_(" "..<"
"..." "+++" "/==" "///" "_|_" "www" "&&" "^=" "~~" "~@" "~="
"~>" "~-" "**" "*>" "*/" "||" "|}" "|]" "|=" "|>" "|-" "{|"
"[|" "]#" "::" ":=" ":>" ":<" "$>" "==" "=>" "!=" "!!" ">:"
">=" ">>" ">-" "-~" "-|" "->" "--" "-<" "<~" "<*" "<|" "<:"
"<$" "<=" "<>" "<-" "<<" "<+" "</" "#{" "#[" "#:" "#=" "#!"
"##" "#(" "#?" "#_" "%%" ".=" ".-" ".." ".?" "+>" "++" "?:"
"?=" "?." "??" ";;" "/*" "/=" "/>" "//" "__" "~~" "(*" "*)"
"\\\\" "://"))
;; Enables ligature checks globally in all buffers. You can also do it
;; per mode with `ligature-mode'.
(global-ligature-mode t))
;; This has to be very early in initialization.
(defvar outline-minor-mode-prefix "\M-#")
;; (add-to-list 'load-path "/Users/acowley/.nix-profile/share/emacs/site-lisp")
;;; General emacs configuration
;;;; Elisp Helpers
(require 'subr-x)
(defun path-up-one-level ()
"Remove the trailing directory component of a path at point"
(interactive)
(let ((path (thing-at-point 'filename t)))
(when path
(goto-char (point-min))
(let ((end (search-forward path)))
(when end
(let ((start (search-backward path)))
(when start
(let ((new-path (file-name-directory (directory-file-name path))))
(kill-region start end)
(insert new-path)))))))))
(bind-key "C-l" #'path-up-one-level minibuffer-local-map)
(defun my/eval-last-sexp (raw-prefix)
"A wrapper around `eval-last-sexp' that modifies the behavior when called with a prefix argument to insert the result of evaluating the sexp before point after inserting an arrow. The result is the original sexp is left in the buffer, followed by an arrow, followed by the result of evaluation. If no prefix is given, the result is shown in the minibuffer as with `eval-last-sexp'."
(interactive "P")
(if (null raw-prefix)
(eval-last-sexp raw-prefix)
(let ((val (eval (macroexpand-all
(eval-sexp-add-defvars (elisp--preceding-sexp)))
lexical-binding)))
(insert (format " ⇒ %s" val)))))
(global-set-key (kbd "C-x C-e") 'my/eval-last-sexp)
(defun backward-skip-alpha (&optional pt)
"Move point backward until the last contiguous alpha character
Used as part of yas-key-syntaxes to expand snippets immediately
preceded by a dollar sign character `$' as encountered when
entering LaTeX math mode."
(re-search-backward (rx (not (any alpha))))
(when (not (null (match-beginning 0)))
(right-char)))
(defun split-third ()
"Split the frame into two windows split vertically with the one
on the left taking up 2/3rds of the width."
(interactive)
(delete-other-windows)
(split-window-horizontally)
(split-window-horizontally)
(balance-windows)
(delete-window))
(defun go-fullscreen ()
"If the current frame is not already full screen, disable the
menu bar, set the frame to full screen, and vertically split the
window into a 2:1 ratio."
(interactive)
(unless (eq (frame-parameter nil 'fullscreen) 'fullboth)
(menu-bar-mode -1)
(toggle-frame-fullscreen)
(split-third)))
(defun increment-number-aux (offset)
"Increment the number point is in or adjacent to. If a prefix
argument is given, its numeric value is added to the number
rather than the default of 1."
(interactive "P")
(let ((n (number-at-point)))
(when n
(replace-match (format "%d" (+ n (or offset 1)))))))
(defun increment-number (offset)
"Increment the number point is in or adjacent to. If a prefix
argument is given, its numeric value is added to the number
rather than the default of 1. This is a wrapper for
`increment-number-aux' that is multiple-cursor aware.
If you are using helm, ensure that `helm-M-x' is in your
`mc/cmds-to-run-once' list (often set in ~/.mc-lists.el)."
(interactive "P")
(if (> (or (mc/num-cursors) 1) 1)
(mc/execute-command-for-all-cursors #'increment-number-aux)
(funcall #'increment-number-aux offset)))
(defun insert-after (x y xs)
"`(insert-after x y list)` inserts `y` after `x` in `list`. If
`x` is not found, `list` is returned unchanged. This is a
non-destructive operation."
(let ((rest xs)
(result))
(while rest
(cond
((eq (car rest) x)
(setq result (append (reverse (cons (car rest) result))
(cons y (cdr rest))))
(setq rest nil))
((null (cdr rest))
(setq rest nil)
(setq result xs))
(t (setq result (cons (car rest) result))
(setq rest (cdr rest)))))
result))
(defun fill-list (xs &optional separator prefix suffix)
"Format a list to respect the fill column.
List elements are separated by SEPARATOR. The formatted list is
prefixed by PREFIX, and terminated by SUFFIX. If the list is
wrapped across multiple lines, lines after the first are indented
by a number of spaces equal to the length of PREFIX."
(require 'cl-lib)
(let ((sep (or separator ", "))
(prefix-len (if prefix (length prefix) 0)))
(with-temp-buffer
(when prefix (insert prefix))
(insert (string-join xs sep))
(when suffix (insert suffix))
(goto-char (point-min))
(setq fill-prefix (cl-loop repeat prefix-len concat " "))
(fill-paragraph)
(buffer-string))))
(defun parse-time-span (s)
"Parse a time span string representing hours, minutes and seconds
of the form \"3h2m48.293s\" into a number of seconds."
(let* ((hours (pcase (split-string s "h")
(`(,h ,rest) (cons (* 60 60 (string-to-number h)) rest))
(_ (cons 0 s))))
(mins (pcase (split-string (cdr hours) "m")
(`(,m ,rest) (cons (* 60 (string-to-number m)) rest))
(_ `(0 . ,(cdr hours)))))
(secs (pcase (split-string (cdr mins) "s")
(`(,s ,_) (string-to-number s))
(_ (error "No seconds component")))))
(+ (car hours) (car mins) secs)))
;; Based on http://emacs.stackexchange.com/a/11067/6537
(defun my-transpose-sexps ()
"If point is at or just after certain chars (comma, space, or
dash) transpose chunks around that. Otherwise transpose sexps."
(interactive "*")
(if (not (or (looking-at "[, -]*")
(looking-back "[, -]*" (point-at-bol))))
(progn (transpose-sexps 1) (forward-sexp -1))
(while (looking-at "[, -]") (forward-char))
(let ((beg (point)) end rhs lhs)
(while (and (not (eobp))
(not (looking-at "\\s-*\\([,]\\|\\s)\\)")))
(forward-sexp 1))
(setq rhs (buffer-substring beg (point)))
(delete-region beg (point))
(re-search-backward "[,]\\s-*" nil t)
(setq beg (point))
(while (and (not (bobp))
(not (looking-back "\\([,]\\|\\s(\\)\\s-*" (point-at-bol))))
(forward-sexp -1))
(setq lhs (buffer-substring beg (point)))
(delete-region beg (point))
(insert rhs)
(re-search-forward "[,]\\s-*" nil t)
(save-excursion
(insert lhs)))))
(defun my/today ()
"Return a string with today's date in Year-Month-Day (YYYY-MM-DD) format."
(format-time-string "%Y-%m-%d" (current-time)))
(defun insert-include-guard ()
"Insert a C/C++-style ‘#ifndef‘ include guard in the current buffer."
(interactive)
(let* ((fname (buffer-file-name))
(ext (upcase (file-name-extension fname)))
(base (upcase (file-name-sans-extension (file-name-nondirectory fname))))
(guard (concat "__" base "_" ext)))
(save-excursion
(goto-char (point-min))
(insert (concat "#ifndef " guard "\n#define " guard "\n\n\n"))
(goto-char (point-max))
(insert "\n#endif"))
(forward-line 4)))
(defun serve-project-path (fname)
"Transform a file name into a path relative to a project root."
(let ((project-root (expand-file-name
(or (locate-dominating-file fname "WORKSPACE")
(locate-dominating-file fname "run-container.sh")))))
(string-remove-prefix project-root (expand-file-name fname))))
(defun insert-serve-include-guard ()
"Insert a C/C++-style '#ifndef' include guard using Serve conventions"
(interactive)
(let* (;; (fname (serve-project-path (buffer-file-name)))
;; (ext (upcase (file-name-extension fname)))
;; (base (upcase (file-name-sans-extension (file-name-nondirectory fname))))
;; (path (upcase (file-name-directory fname)))
;; (guard (string-replace "/" "_" (concat path base "_" ext "_")))
(copyright "/**
* Copyright 2022 Serve Robotics Inc.
*/\n\n"))
(save-excursion
(goto-char (point-min))
(insert (concat copyright "#pragma once\n"))
;; (insert (concat copyright "#ifndef " guard "\n#define " guard "\n\n\n"))
;; (goto-char (point-max))
;; (insert (concat "\n#endif // " guard))
)
(forward-line 5)))
(require 'dash)
(defun start-of-week ()
"Return a date triple of (MONTH DAY YEAR) for the Sunday that starts the current week."
(-find (-compose #'zerop #'calendar-day-of-week)
(-map #'calendar-current-date (-iterate #'1- 0 7))))
(defun till-start-of-week ()
"Return a list of dates going back to the most recent Sunday."
(let ((res (-split-with (-compose #'not #'zerop #'calendar-day-of-week)
(-map #'calendar-current-date (-iterate #'1- 0 7)))))
(append (car res) (caadr res))))
(defun time-to-date (time)
"Convert a time as returned by `parse-time-string' to a date as returned by `calendar-current-date'."
(pcase time
(`(,_ ,_ ,_ ,day ,mon ,year ,_ ,_ ,_) (list mon day year))))
(defun count-completed-tasks ()
"Count up all tasks completed this week and this month.
Considers entries in the current buffer whose headlines match `* DONE' and have a `:completed:' property with a date."
(interactive)
(let* ((days-of-week (till-start-of-week))
(this-month (car (calendar-current-date))))
(let* ((res (org-map-entries
(lambda ()
(let* ((props (org-entry-properties))
(completed (assoc "COMPLETED" props))
(date (and completed
(time-to-date
(parse-time-string (cdr completed)))))
(month (and date (car date))))
(if completed
(cons (if (= month this-month) 1 0)
(if (-any-p (-partial #'equal date) days-of-week)
1 0))
'(0 . 0))
))
"* DONE"))
(sums (-reduce (lambda (acc x)
(pcase (cons acc x)
(`((,acc-m . ,acc-w) . (,m . ,w))
(cons (+ acc-m m) (+ acc-w w)))))
res)))
(pcase sums
(`(,month-count . ,week-count)
(message "%d tasks completed this week; %d this month" week-count month-count))))))
(defun shuffle (xs)
"Construct a new list with all the elements of XS at random positions."
(let ((lst ())
(n (length xs)))
(while (> n 1)
(pcase (-split-at (random n) xs)
(`(,hd ,tl) (progn
(push (car tl) lst)
(setf n (- n 1))
(setf xs (append hd (cdr tl)))))))
(cons (car xs) lst)))
(defun quote-shell-string (str)
"Safely embed a string in single-quotes.
We can pass single-quoted strings to shell commands, but single
quotes within those strings need to be escaped. We use the
technique of ending the quoted string, concatenating a literal
single-quote character, and concatenating the remaining
single-quoted string."
(concat "'" (replace-regexp-in-string "'" "'\\\\''" str) "'"))
(defun parenthesize-negatives ()
"Wrap negative numeric literals in parentheses.
Parentheses are required with negative numeric literals Haskell.
This helper makes it slightly easier to paste numbers into
Haskell programs as it may be applied to all numbers in region."
(interactive)
(if (region-active-p)
(save-excursion
(let ((regexp (rx "-" (+ (or digit ?.))))
(start (region-beginning))
(end (region-end)))
(goto-char start)
(while (re-search-forward regexp end t)
(message "Found match: %s" (match-string 0))
(replace-match "(\\&)" nil nil)
(set 'end (+ end 2)))))
(message "Select a region first")))
;;;; Miscellaneous Settings
;; A short mode line that is going to be tweaked with moody
;; (setq-default mode-line-format
;; '("%e"
;; mode-line-modified
;; mode-line-buffer-identification
;; " "
;; mode-line-position
;; (vc-mode vc-mode)
;; " "
;; mode-line-modes
;; mode-line-misc-info
;; mode-line-end-spaces))
(when (display-graphic-p)
(global-unset-key (kbd "C-z"))
(global-unset-key (kbd "C-x C-z")))
(setq confirm-kill-emacs #'y-or-n-p)
(setq frame-resize-pixelwise t)
(setq warning-suppress-types '((comp)))
(put 'narrow-to-region 'disabled nil)
(setq inhibit-compacting-font-caches t)
(column-number-mode 1)
(set-scroll-bar-mode 'right)
;; (tool-bar-mode -1)
;; (when (and window-system (not (memq window-system '(mac ns))))
;; (set-frame-size (selected-frame) 80 56))
;; Enable ligatures for fonts that provide them (e.g. hæck)
;; This may cause slowdown
;; (add-hook 'prog-mode-hook #'mac-auto-operator-composition-mode)
;; (add-hook 'prog-mode-hook (lambda () (auto-composition-mode -1)))
;; (add-hook 'text-mode-hook (lambda () (auto-composition-mode -1)))
(setq tab-always-indent 'complete)
(setq display-line-numbers-type 'relative)
;; Let us use a minibuffer command (as with a package like consult)
;; while using another command in the minibuffer
(setq enable-recursive-minibuffers t)
(minibuffer-depth-indicate-mode 1)
;; Disable electric-quote-mode everywhere
(add-hook 'after-change-major-mode-hook
(lambda () (electric-quote-mode -1)))
(electric-quote-mode -1)
;; This was causing some odd behavior for me where the first quote I
;; hit wouldn't create a closing quote, then when I manually added the
;; closing quote electric-pair-mode would add a third quote which I'd
;; have to delete!
(setq electric-pair-preserve-balance nil
;; A non-nil value can make it hard to insert a quote on a
;; newline if the first character of the next line is a
;; quotation mark.
electric-pair-skip-whitespace nil)
;; I had this problem where if I have a line that starts with a double
;; quote character, and I want to insert a new line before it that
;; also starts with a double quote, when I type the new double quote
;; character, point moves to just past the starting double quote on
;; the next line. This is unhelpful in programming situations.
(setq electric-pair-skip-self
(lambda (c)
(unless (and (char-equal c ?\") (eolp))
(electric-pair-default-skip-self c))))
(electric-pair-mode +1)
(add-hook 'prog-mode-hook #'electric-indent-mode)
;; Cause use-package to install packages automatically if not already
;; present
; (setq use-package-always-ensure t)
;; Clean trailing whitespace when saving a buffer.
;; This is too dangerous: it makes producing minimal diffs harder than
;; necessary, and can break things that expect a trailing whitespace
;; (e.g. with a regex). It may be fine for my own code, but judgment
;; should be applied before invoking it.
;; (setq before-save-hook #'whitespace-cleanup)
;; Keep ediff UI in a single frame
(setq ediff-window-setup-function #'ediff-setup-windows-plain)
;; Disable ligatures in ediff buffers
(add-hook 'ediff-mode-hook
(lambda ()
(setq auto-composition-mode nil)))
;; Use the exec-path-from-shell package to set the PATH
;; (use-package exec-path-from-shell
;; :if (memq window-system '(mac ns))
;; :config
;; (setq exec-path-from-shell-arguments (list "-l"))
;; (exec-path-from-shell-initialize))
;; Move point to farthest possible position when scrolling the window
;; has reached the beginning or end of the buffer
(setq scroll-error-top-bottom t)
;; Support Cmd-up/down for top/bottom of buffer
(global-set-key (kbd "<s-up>") 'beginning-of-buffer)
(global-set-key (kbd "<s-down>") 'end-of-buffer)
(global-set-key (kbd "C-x C-k") #'kill-buffer)
;; Make bookmark jumping easier
(global-set-key (kbd "C-c b") #'bookmark-jump)
;; Don't undo undo operations by default
(global-set-key (kbd "C-/") #'undo-only)
(global-set-key (kbd "C-_") #'undo-redo)
;; More convenient binding for going to a line
(global-set-key (kbd "C-c g") #'goto-line)
;; Use Shift+ArrowKey to move the cursor between windows.
;; This means you lose shift select.
;; (windmove-default-keybindings)
;; (setq windmove-wrap-around t)
;; Highlight matching parentheses
(show-paren-mode 1)
;; Speed up tramp from
;; https://emacs.stackexchange.com/a/37855
(setq vc-ignore-dir-regexp
(format "%s\\|%s"
vc-ignore-dir-regexp
tramp-file-name-regexp))
;; Display PDFs inline
(add-to-list 'image-type-file-name-regexps '("\\.pdf\\'" . imagemagick))
(add-to-list 'image-file-name-extensions "pdf")
(setq imagemagick-types-inhibit (remove 'PDF imagemagick-types-inhibit))
(add-to-list 'imagemagick-enabled-types 'PDF)
(add-hook 'emacs-startup-hook (lambda ()
(imagemagick-register-types)))
;; (use-package session
;; :commands (session-initialize)
;; :init
;; ;; Preserve history between sessions
;; (add-hook 'after-init-hook 'session-initialize)
;; ;; Don't interfere with helm-show-kill-ring
;; (setq session-save-print-spec '(t nil 40000)))
; yank will replace the active region's contents
(delete-selection-mode 1)
(setq c-default-style "bsd"
c-basic-offset 2)
(setq-default indent-tabs-mode nil)
(setq default-directory "~/")
(setq mac-option-modifier 'meta)
;; Keyboard shortcut for aligning a region on a regexp
(global-set-key (kbd "C-x a r") 'align-regexp)
;; Start the emacs server if possible
;; (when (fboundp 'server-mode) (funcall 'server-mode 1))
;; Revert buffers whose files have changed on disk
(global-auto-revert-mode t)
;; Disable the alarm bell on Quit (C-g)
(setq ring-bell-function 'ignore)
;; Turn off electric-indent-mode everywhere
(when (fboundp 'electric-indent-mode) (electric-indent-mode -1))
(put 'downcase-region 'disabled nil)
;; (setq TeX-command-extra-options "-shell-escape")
(put 'dired-find-alternate-file 'disabled nil)
(setq wdired-allow-to-change-permissions t)
(use-package dired
:config
(setq dired-listing-switches "-alh"
dired-du-size-format t
dired-dwim-target t)
(add-hook 'dired-mode-hook (lambda () (recentf-add-file default-directory))))
;; When `'which-function` output is too long, it can interfere with
;; modeline rendering
(defun truncate-function-name (s)
"Truncates a string to 20 characters. If the name has one or more
double colons (\"::\") in it, the part of the string after the
last double colon is truncated to 20 characters."
(unless (null s)
(if (> (length s) 20)
(truncate-string-to-width
(car (last (split-string s "::")))
20 nil nil "...")
s)))
(advice-add 'which-function :filter-return #'truncate-function-name)
;; From https://emacs.stackexchange.com/a/24658
(defun advice-unadvice (sym)
"Remove all advices from symbol SYM."
(interactive "aFunction symbol: ")
(advice-mapc (lambda (advice _props) (advice-remove sym advice)) sym))
;(load-theme 'monokai t)
;(load-theme 'darktooth t)
(use-package recentf
:init
(setq
;; This is an attempt to prevent recentf (that keeps track of recent
;; files) from stat'ing remote files.
;; recentf-keep '(file-remote-p file-readable-p)
recentf-keep '(recentf-keep-default-predicate)
recentf-exclude
`("/\\(\\(\\(COMMIT\\|NOTES\\|PULLREQ\\|TAG\\)_EDIT\\|MERGE_\\|\\)MSG\\|BRANCH_DESCRIPTION\\)\\'"
,(regexp-quote "/.emacs.d/elpa/")
,(regexp-quote "/var/folders/")
,(regexp-quote "/.emacs.d/bookmarks")
,(regexp-quote "/.emacs.d/recentf")))
(defun recent-buffer (b &rest _)
(let ((file (buffer-file-name (get-buffer b))))
(unless (null file) (recentf-add-file file))))
(advice-add 'switch-to-buffer :after #'recent-buffer)
:config
(setq recentf-max-saved-items 200))
;; Another options is
;; (require 'recentf)
;; (setq recentf-auto-cleanup 'never) ;; disable before we start recentf!
;; (recentf-mode 1)
;; John Wiegley's ANSI colors hook for compiler output
(defun compilation-ansi-color-process-output ()
(ansi-color-process-output nil)
(set (make-local-variable 'comint-last-output-start)
(point-marker)))
(add-hook 'compilation-filter-hook #'compilation-ansi-color-process-output)
(defun sort-words ()
(interactive)
(sort-regexp-fields nil "\\w+" "\\&" (region-beginning) (region-end)))
(defun browse-url-safari (uri &args)
"Open a URI in Safari using AppleScript. This preserves anchors."
(let ((script (format "
tell application \"Safari\"
open location \"%s\"
activate
end tell" uri)))
(do-applescript script)))
(if (memq window-system '(mac ns))
(setq browse-url-browser-function #'browse-url-safari)
(setq browse-url-browser-function #'browse-url-firefox))
;; From http://emacsredux.com/blog/2013/06/21/eval-and-replace/
(defun eval-and-replace ()
"Replace the preceding sexp with its value."
(interactive)
(backward-kill-sexp)
(condition-case nil
(prin1 (eval (read (current-kill 0)))
(current-buffer))
(error (message "Invalid expression")
(insert (current-kill 0)))))
(global-set-key (kbd "C-c e") 'eval-and-replace)
;(setq visual-line-fringe-indicators '(left-curly-arrow nil))
;; Stefan Monnier <foo at acm.org>. It is the opposite of fill-paragraph
(defun unfill-paragraph (&optional region)
"Takes a multi-line paragraph and makes it into a single line of text."
(interactive (progn (barf-if-buffer-read-only) '(t)))
(let ((fill-column (point-max)))
(fill-paragraph nil region)))
;; Handy key definition
(define-key global-map "\M-Q" 'unfill-paragraph)
;; From Joao Tavora http://stackoverflow.com/a/18034042/277078
;; Kill a process in the *Process List* buffer created by
;; `list-processes`.
(defun joaot/delete-process-at-point ()
(interactive)
(let ((process (get-text-property (point) 'tabulated-list-id)))
(cond ((and process
(processp process))
(delete-process process)
(revert-buffer))
(t
(error "no process at point!")))))
(define-key process-menu-mode-map (kbd "C-k") #'joaot/delete-process-at-point)
(use-package visual-fill-column :defer t)
;; Put the visited file name in the frame title
;; (setq-default frame-title-format '("%f [%m]"))
(setq-default frame-title-format
'("emacs - "
(:eval (file-name-nondirectory (or (buffer-file-name) "")))
" [%m]"))
;; (customize-set-variable pixel-scroll-precision-mode t)
;; Kills the whole line (incuding the newline) if at column zero.
;; Note: this is killing the whole line even when not at column zero.
;; (setq kill-whole-line t)
;; Add Byte as a unit to `calc`
;; From /u/politza https://www.reddit.com/r/emacs/comments/31xezm/common_byte_units_in_calc/cq6ef06?utm_source=share&utm_medium=web2x
(setq math-additional-units '(
(GiB "1024 * MiB" "Giga Byte")
(MiB "1024 * KiB" "Mega Byte")
(KiB "1024 * B" "Kilo Byte")
(B nil "Byte")
(Gib "1024 * Mib" "Giga Bit")
(Mib "1024 * Kib" "Mega Bit")
(Kib "1024 * b" "Kilo Bit")
(b "B / 8" "Bit")
(FLOP nil "FLOP")))
;; Reset calc's cache
(setq math-units-table nil)
;;;; variable-pitch-mode
(defun my/text-mode-hook ()
(flyspell-mode)
(turn-on-visual-line-mode)
(variable-pitch-mode)
(setq left-margin-width 2
right-margin-width 2)
;; (setq buffer-face-mode-face '(:family "Helvetica Neue" :weight thin))
;; (setq buffer-face-mode-face '(:family "Avenir Next"))
;; (setq variable-pitch-face '(:family "Avenir Next"))
;; (setq buffer-face-mode-face '(:family "Montserrat"))
;; (buffer-face-mode)
;; (text-scale-adjust 1.5)
;; (text-mode-hook-identify)
)
(add-hook 'text-mode-hook #'my/text-mode-hook)
;;;; Ignored extensions
(add-to-list 'completion-ignored-extensions ".hi")
(add-to-list 'completion-ignored-extensions ".o")
;; (add-hook 'ido-setup-hook (setq ido-ignore-extensions t))
;; (add-hook 'ido-setup-hook (lambda ()
;; (add-to-list 'ido-ignore-files "\\.hi")
;; (add-to-list 'ido-ignore-files "\\.o")))
;;;; Spell checking
;; brew install hunspell
;; Download the OpenOffice dictionary for the language you want. The
;; `.oxt' file is a zip archive. Put the `.aff' and `.dic' files from
;; that archive in `~/Library/Spelling/'. Then create symlinks from,
;; for example, `en_US.aff' to `default.aff' in that directory, and
;; likewise for the `.dic' file. Try running `hunspell -D' to see what
;; dictionaries hunspell is using. The "personal dictionary" is just a
;; word list.
(when (memq window-system '(mac ns))
(progn
(setq ispell-program-name "hunspell")
(setq ispell-local-dictionary "en_US")
(setq ispell-personal-dictionary "~/.hunspell_en_US")))
;; (setq ispell-local-dictionary-alist
;; '(("en_US" "[[:alpha:]]" "[^[:alpha:]]" "[']" nil
;; ("-d" "en_US"))
;; nil utf-8))
;(setq ispell-extra-args '("-a" "-i" "utf-8"))
(add-to-list 'process-coding-system-alist '("hunspell" . utf-8))
;; hunspell hacking to get ispell to actually use utf-8
;; See: http://stackoverflow.com/questions/3961119/working-setup-for-hunspell-in-emacs
(add-hook 'emacs-startup-hook
(lambda ()
(eval-after-load "ispell" '(defun ispell-get-coding-system () 'utf-8))
(add-hook 'prog-mode-hook 'flyspell-prog-mode)
(add-hook 'text-mode-hook 'flyspell-mode)))
;;;; Copy and comment
(defun copy-and-comment ()
(interactive)
(kill-ring-save (region-beginning) (region-end))
(comment-dwim nil)
(goto-char (region-end))
(end-of-line)
(newline-and-indent))
;;;; Tramp with sudo
;; We hardly ever want to actually ssh into a host as root. Instead,
;; we want to ssh into the host using your account name, and then
;; switches to root on the host. This lets us use paths like
;; `/sudo:remotehost:/etc/hdparm.conf`. Remember that there has been a
;; history of projectile-global-mode interfering with such file
;; operations, so you may need to disable that temporarly.
;; See the manual: https://www.gnu.org/software/tramp/#Multi_002dhops
;; (add-to-list 'tramp-default-proxies-alist
;; '(nil "\\`root\\'" "/ssh:%h:"))
;; (add-to-list 'tramp-default-proxies-alist
;; '((regexp-quote (system-name)) nil nil))
;;;; cparens
(defun cparens ()
"Parenthesize the C expression in region"
(interactive)
(if (region-active-p)
(let* ((exp (buffer-substring (region-beginning) (region-end)))
(tmp (make-temp-file "cparens-input")))
(unwind-protect
(progn
(write-region (region-beginning) (region-end) tmp)
(let ((res (with-temp-buffer
(cons
(call-process "cparens" tmp (current-buffer) nil)
(buffer-substring-no-properties
(point-min) (point-max))))))
(if (eq (car res) 0)
(progn
(delete-region (region-beginning) (region-end))
(insert (cdr res)))
(error (cdr res)))))
(delete-file tmp)))))
;;;; Firefox (or Chromium) session save/load
;; From https://acidwords.com/posts/2019-12-04-handle-chromium-and-firefox-sessions-with-org-mode.html
;; with more discussion on reddit https://www.reddit.com/r/emacs/comments/e6fxrf/handle_chromium_firefox_sessions_with_orgmode/
(require 'cl-lib)
(defun save-firefox-session ()
"Reads chromium current session and generates an org-mode heading with items."
(interactive)
(save-excursion
(let* ((dir "~/.mozilla/firefox/")
(dirs (directory-files dir))
(unique-dir (cl-find-if (lambda (x)
(and (string-match "\\.default" x)
(file-accessible-directory-p (concat dir x))))
dirs))
(path (concat dir unique-dir "/sessionstore-backups/recovery.jsonlz4"))
(cmd (concat "nix run nixpkgs.lz4json -c lz4jsoncat " path
" | nix run nixpkgs.jq -c jq '.windows[].tabs[] | .entries[-1] | .url'"
" | sed 's/\"//g' | sort | uniq"))
(ret (shell-command-to-string cmd)))
(insert
(concat "* "
(format-time-string "[%Y-%m-%d %H:%M:%S]")
"\n"
(mapconcat (lambda (x) (concat " - " x))
(cl-remove-if (lambda (x) (or (null x)
(string-blank-p x)
(string= "null" x)))
(split-string ret "\n"))
"\n"))))))
(defun restore-firefox-session ()
"Restore web browser session by opening each link with `browse-url`.
Make sure to put cursor on date heading that contains a list of urls."
(interactive)
(save-excursion
(beginning-of-line)
(when (looking-at "^\\*")
(forward-line 1)
(while (looking-at "^[ ]+-[ ]+\\(http.?+\\)$")
(let* ((ln (thing-at-point 'line t))
(ln (replace-regexp-in-string "^[ ]+-[ ]+" "" ln))
(ln (replace-regexp-in-string "\n" "" ln)))
(browse-url ln))
(forward-line 1)))))
;;;; Offer diff on killing buffer with unsaved changes
;; From https://www.reddit.com/r/emacs/comments/13b2z5z/add_a_diff_to_the_yesnosave_and_quit_choices/jj9jcrt/
(defun my-ask-kill-buffer ()
"Ask to diff, save or kill buffer"
(if (and (buffer-file-name) (buffer-modified-p))
(cl-loop for ch = (read-event "(K)ill buffer, (D)iff buffer, (S)ave buffer, (N)othing?")
if (or (eq ch ?k) (eq ch ?K))
return t
if (or (eq ch ?d) (eq ch ?D))
do (diff-buffer-with-file)
if (or (eq ch ?s) (eq ch ?S))
return (progn (save-buffer) t)
if (or (eq ch ?n) (eq ch ?N))
return nil)
t))
(add-to-list 'kill-buffer-query-functions #'my-ask-kill-buffer)
;;; Diminish
(use-package diminish :disabled t)
;;; Themes
;; (use-package darkokai-theme :defer t)
;; (use-package monokai-theme :defer t)
(use-package apropospriate-theme
:config
(load-theme 'apropospriate-dark t)
:custom-face
(region ((t (:background "gray22"))))
(helm-match ((t (:foreground "gold"))))
;; (company-tooltip-selection ((t (:background "SteelBlue"))))
;; (company-tooltip-annotation-selection ((t (:background "SteelBlue"))))
;; (company-tooltip-common-selection ((t (:foreground "black" :background "DeepSkyBlue"))))
;; (company-tooltip-common ((t (:foreground "DeepSkyBlue"))))
(lsp-ui-peek-selection ((t (:background "DeepSkyBlue"))))
(lsp-ui-peek-highlight ((t (:foreground "gold"))))
(mode-line-inactive ((t (:background "gray16" :box nil)))))
;;; emacs server
(use-package server
:config (and (fboundp 'server-mode)
(add-hook 'emacs-startup-hook
(lambda ()
(or (server-running-p) (server-mode))))))
;;; company-mode
(use-package company