-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathinit.el
5993 lines (5454 loc) · 217 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
;;; init.el --- yiufung's config -*- lexical-binding: t; coding:utf-8; fill-column: 119 -*-
;;; Commentary:
;; My personal config. Use `outshine-cycle-buffer' (<S-Tab>) to navigate through sections, and `counsel-imenu' (C-c i)
;; to locate individual use-package definition.
;;; Code:
(defun make-obsolete (obsolete-name current-name &optional when)
"Make the byte-compiler warn that function OBSOLETE-NAME is obsolete.
OBSOLETE-NAME should be a function name or macro name (a symbol).
The warning will say that CURRENT-NAME should be used instead.
If CURRENT-NAME is a string, that is the `use instead' message
\(it should end with a period, and not start with a capital).
WHEN should be a string indicating when the function
was first made obsolete, for example a date or a release number."
(declare (advertised-calling-convention
;; New code should always provide the `when' argument.
(obsolete-name current-name when) "23.1"))
(put obsolete-name 'byte-obsolete-info
;; The second entry used to hold the `byte-compile' handler, but
;; is not used any more nowadays.
(purecopy (list current-name nil when)))
obsolete-name)
(defmacro define-obsolete-function-alias (obsolete-name current-name
&optional when docstring)
"Set OBSOLETE-NAME's function definition to CURRENT-NAME and mark it obsolete.
\(define-obsolete-function-alias \\='old-fun \\='new-fun \"22.1\" \"old-fun's doc.\")
is equivalent to the following two lines of code:
\(defalias \\='old-fun \\='new-fun \"old-fun's doc.\")
\(make-obsolete \\='old-fun \\='new-fun \"22.1\")
WHEN should be a string indicating when the function was first
made obsolete, for example a date or a release number.
See the docstrings of `defalias' and `make-obsolete' for more details."
(declare (doc-string 4)
(advertised-calling-convention
;; New code should always provide the `when' argument.
(obsolete-name current-name when &optional docstring) "23.1"))
`(progn
(defalias ,obsolete-name ,current-name ,docstring)
(make-obsolete ,obsolete-name ,current-name ,when)))
(defun make-obsolete-variable (obsolete-name current-name &optional when access-type)
"Make the byte-compiler warn that OBSOLETE-NAME is obsolete.
The warning will say that CURRENT-NAME should be used instead.
If CURRENT-NAME is a string, that is the `use instead' message.
WHEN should be a string indicating when the variable
was first made obsolete, for example a date or a release number.
ACCESS-TYPE if non-nil should specify the kind of access that will trigger
obsolescence warnings; it can be either `get' or `set'."
(declare (advertised-calling-convention
;; New code should always provide the `when' argument.
(obsolete-name current-name when &optional access-type) "23.1"))
(put obsolete-name 'byte-obsolete-variable
(purecopy (list current-name access-type when)))
obsolete-name)
(defmacro define-obsolete-variable-alias (obsolete-name current-name
&optional when docstring)
"Make OBSOLETE-NAME a variable alias for CURRENT-NAME and mark it obsolete.
This uses `defvaralias' and `make-obsolete-variable' (which see).
See the Info node `(elisp)Variable Aliases' for more details.
If CURRENT-NAME is a defcustom or a defvar (more generally, any variable
where OBSOLETE-NAME may be set, e.g. in an init file, before the
alias is defined), then the define-obsolete-variable-alias
statement should be evaluated before the defcustom, if user
customizations are to be respected. The simplest way to achieve
this is to place the alias statement before the defcustom (this
is not necessary for aliases that are autoloaded, or in files
dumped with Emacs). This is so that any user customizations are
applied before the defcustom tries to initialize the
variable (this is due to the way `defvaralias' works).
WHEN should be a string indicating when the variable was first
made obsolete, for example a date or a release number.
For the benefit of Customize, if OBSOLETE-NAME has
any of the following properties, they are copied to
CURRENT-NAME, if it does not already have them:
`saved-value', `saved-variable-comment'."
(declare (doc-string 4)
(advertised-calling-convention
;; New code should always provide the `when' argument.
(obsolete-name current-name when &optional docstring) "23.1"))
`(progn
(defvaralias ,obsolete-name ,current-name ,docstring)
;; See Bug#4706.
(dolist (prop '(saved-value saved-variable-comment))
(and (get ,obsolete-name prop)
(null (get ,current-name prop))
(put ,current-name prop (get ,obsolete-name prop))))
(make-obsolete-variable ,obsolete-name ,current-name ,when)))
;;; Bootstrap
;; Speed up bootstrapping
(setq gc-cons-threshold 402653184
gc-cons-percentage 0.6)
(add-hook 'after-init-hook `(lambda ()
(setq gc-cons-threshold 800000
gc-cons-percentage 0.1)
(garbage-collect)) t)
;; (setq comp-deferred-compilation-deny-list '("\\(?:[^z-a]*-autoloads\\.el$\\)"))
;; Always follow symlinks. init files are normally stowed/symlinked.
(setq vc-follow-symlinks t
find-file-visit-truename t
;; Avoid stale compiled code shadow newer source code
load-prefer-newer t)
;; Turn off mouse interface early in startup to avoid momentary display
(if (fboundp 'menu-bar-mode) (menu-bar-mode -1))
(if (fboundp 'tool-bar-mode) (tool-bar-mode -1))
(if (fboundp 'scroll-bar-mode) (scroll-bar-mode -1))
;; Bootstrap `straight.el'
(defvar bootstrap-version)
(let ((bootstrap-file
(expand-file-name "straight/repos/straight.el/bootstrap.el" user-emacs-directory))
(bootstrap-version 5))
(unless (file-exists-p bootstrap-file)
(with-current-buffer
(url-retrieve-synchronously
"https://raw.githubusercontent.com/raxod502/straight.el/develop/install.el"
'silent 'inhibit-cookies)
(goto-char (point-max))
(eval-print-last-sexp)))
(load bootstrap-file nil 'nomessage))
;; Avoid checking for modifications on startup
(setq straight-check-for-modifications '(find-at-startup check-on-save find-when-checking))
;; Bootstrap `use-package'
(setq-default
;; use-package-always-demand t ; Always defer loading package to speed up startup time
use-package-always-defer t
use-package-verbose nil ; Don't report loading details
use-package-expand-minimally t ; make the expanded code as minimal as possible
use-package-enable-imenu-support t) ; Let imenu finds use-package definitions
;; Integration with use-package
(straight-use-package 'use-package)
(setq straight-use-package-by-default t)
;; Early load org-contrib (from 9.4.6+)
(straight-use-package 'org-contrib)
;;; Basic Setup
;;;; Emacs folder setup
;; Emacs configuration, along with many other journals, are synchronized across machines
(setq my-sync-directory "~/Nextcloud")
;; Define configuration directory.
(setq my-emacs-conf-directory (expand-file-name "dotfiles/emacs/" my-sync-directory)
my-private-conf-directory (expand-file-name "private/" my-emacs-conf-directory))
;; For packages not available through MELPA, save it locally and put under load-path
(add-to-list 'load-path (expand-file-name "elisp" my-emacs-conf-directory))
;; Here I also copied core-lib from Doom-Emacs, for some handy macros such as defadvice!
(require 'doom-core-lib)
(use-package auth-source
:straight ivy-pass
;; Setup Credentials
:bind ("H-p" . ivy-pass)
:config
(defun lookup-password (host user port)
(require 'auth-source)
(require 'auth-source-pass)
(let ((auth (auth-source-search :host host :user user :port port)))
(if auth
(let ((secretf (plist-get (car auth) :secret)))
(if secretf
(funcall secretf)
(error "Auth entry for %s@%s:%s has no secret!"
user host port)))
(error "No auth entry found for %s@%s:%s" user host port))))
;; Enable password-store with auth-source
;; auth-source-pass-get is the main entrance.
(auth-source-pass-enable)
;; Need to set allow allow-emacs-pinentry & allow-loopback-pinentry in ~/.gnupg/gpg-agent.conf
(setq epa-pinentry-mode 'loopback)
;; Top debug, set auth-source-debug to t.
(setq auth-source-debug t)
)
;;;; General settings
(setq-default ;; Use setq-default to define global default
;; Who I am
user-mail-address "[email protected]"
user-full-name "Cheong Yiu Fung"
;; Enable all disabled commands
disabled-command-function nil
;; Enable recursive minibuffer edit
enable-recursive-minibuffers t
;; Don't show scratch message, and use fundamental-mode for *scratch*
;; Remove splash screen and the echo area message
inhibit-startup-message t
inhibit-startup-echo-area-message t
initial-scratch-message 'nil
initial-major-mode 'fundamental-mode
;; Emacs modes typically provide a standard means to change the
;; indentation width -- eg. c-basic-offset: use that to adjust your
;; personal indentation width, while maintaining the style (and
;; meaning) of any files you load.
indent-tabs-mode nil ; don't use tabs to indent
tab-width 8 ; but maintain correct appearance
;; Use one space as sentence end
sentence-end-double-space 'nil
;; Newline at end of file
require-final-newline t
;; Don't adjust window-vscroll to view tall lines.
auto-window-vscroll nil
;; Don't create lockfiles.
;; recentf frequently prompts for confirmation.
create-lockfiles nil
;; Leave some rooms when recentering to top, useful in emacs ipython notebook.
recenter-positions '(middle 1 bottom)
;; Move files to trash when deleting
delete-by-moving-to-trash t
;; Show column number
column-number-mode t
;; Don't break lines for me, please
truncate-lines t
;; More message logs
message-log-max 16384
;; Don't prompt up file dialog when click with mouse
use-file-dialog nil
;; Place all auto-save files in one directory.
backup-directory-alist `(("." . ,(concat user-emacs-directory "backups")))
;; more useful frame title, that show either a file or a
;; buffer name (if the buffer isn't visiting a file)
frame-title-format '((:eval (if (buffer-file-name)
(abbreviate-file-name (buffer-file-name))
"%b")))
;; warn when opening files bigger than 100MB
large-file-warning-threshold 100000000
;; Don't create backup files
make-backup-files nil ; stop creating backup~ files
;; Remember my location when the file is last opened
;; activate it for all buffers
save-place-file (expand-file-name "saveplace" user-emacs-directory)
;; smooth scrolling
scroll-conservatively 101
;; Reserve one line when scrolling
scroll-margin 1
;; turn off the bell
ring-bell-function 'ignore
;; Smoother scrolling
mouse-wheel-scroll-amount '(1 ((shift) . 1)) ;; one line at a time
mouse-wheel-progressive-speed nil ;; don't accelerate scrolling
mouse-wheel-follow-mouse 't ;; scroll window under mouse
scroll-step 1 ;; keyboard scroll one line at a time
view-read-only t ;; make read-only buffers in view mode
;; Native comp
package-native-compile t
comp-async-report-warnings-errors nil
;; Ignore 'ad-handle-definition' redefined warnings
ad-redefinition-action 'accept
;; mouse auto follow
mouse-autoselect-window t
focus-follow-mouse 'auto-raise
)
;; Misc
(set-frame-name "emacs")
(fringe-mode 'nil) ;; default (8 . 8) fringe
(save-place-mode t)
(delete-selection-mode 1)
;; enable y/n answers
(fset 'yes-or-no-p 'y-or-n-p)
;; Set paste system
(set-clipboard-coding-system 'utf-16le-dos)
;; Set paste error under linux
(set-selection-coding-system 'utf-8)
;; Allow pasting selection outside of Emacs
(setq x-select-enable-clipboard t
x-select-enable-primary t)
;; Don't blink
(blink-cursor-mode 0)
;; ESC is mapped as metakey by default, very counter-intuitive.
;; Map escape to cancel (like C-g) everywhere
(define-key isearch-mode-map [escape] 'isearch-abort) ;; isearch
(define-key isearch-mode-map "\e" 'isearch-abort) ;; \e seems to work better for terminals
(global-set-key [escape] 'keyboard-escape-quit) ;; everywhere else
;; Let C-g works when cursor is in buffers other than minibuffer
;; https://with-emacs.com/posts/tips/quit-current-context/
(defun keyboard-quit-context+ ()
"Quit current context.
This function is a combination of `keyboard-quit' and
`keyboard-escape-quit' with some parts omitted and some custom
behavior added."
(interactive)
(cond ((region-active-p)
;; Avoid adding the region to the window selection.
(setq saved-region-selection nil)
(let (select-active-regions)
(deactivate-mark)))
((eq last-command 'mode-exited) nil)
(current-prefix-arg
nil)
(defining-kbd-macro
(message
(substitute-command-keys
"Quit is ignored during macro defintion, use \\[kmacro-end-macro] if you want to stop macro definition"))
(cancel-kbd-macro-events))
((active-minibuffer-window)
(when (get-buffer-window "*Completions*")
;; hide completions first so point stays in active window when
;; outside the minibuffer
(minibuffer-hide-completions))
(abort-recursive-edit))
(t
(when completion-in-region-mode
(completion-in-region-mode -1))
(let ((debug-on-quit nil))
(signal 'quit nil)))))
(global-set-key [remap keyboard-quit] #'keyboard-quit-context+)
;; Don't add custom section directly under init.el.
;; https://www.reddit.com/r/emacs/comments/53zpv9/how_do_i_get_emacs_to_stop_adding_custom_fields/
(setq custom-file (expand-file-name "custom.el" my-private-conf-directory))
(when (file-exists-p custom-file)
(load custom-file :noerror))
;; Marking and popping
(setq-default
;; Marking and popping
set-mark-command-repeat-pop t
;; Real emacs knights don't use shift to mark things
shift-select-mode nil)
;; When popping the mark, continue popping until the cursor actually
;; moves Also, if the last command was a copy - skip past all the
;; expand-region cruft.
(defadvice pop-to-mark-command (around ensure-new-position activate)
(let ((p (point)))
(when (eq last-command 'save-region-or-current-line)
ad-do-it
ad-do-it
ad-do-it)
(dotimes (i 10)
(when (= p (point)) ad-do-it))))
;; Confirm when trying to kill frame in emacsclient
;; TODO: Disable for now. It seems to clash with sdcv
;; (define-advice delete-frame (:around (oldfun &rest args) confirm-frame-deletion)
;; "Confirm deleting the frame."
;; (interactive)
;; (when (y-or-n-p "Delete frame? ")
;; (apply oldfun args)))
;; Early unbind keys for customization
(unbind-key "C-s") ; Reserve for search related commands
(unbind-key "C-z") ;; Reserve for hydra related commands
(use-package beacon
;; Highlight the cursor whenever it scrolls
:disabled t
:defer 5
:bind (("C-<f12>" . beacon-blink)) ;; useful when multiple windows
:config
(setq beacon-size 10))
(use-package bug-hunter
:defer 3)
(defun my-rest-pinky ()
"Penalize my impulsive Ctrl syndrome"
(interactive)
(y-or-n-p "Give your pinky some rest!"))
(use-package uniquify
;; unique buffer names dependent on file name
:straight nil
:defer 5
:config
(setq
;; Rename buffers with same name
uniquify-buffer-name-style 'forward
uniquify-separator "/"
;; rename after killing uniquified
uniquify-after-kill-buffer-p t
;; don't muck with special buffers
uniquify-ignore-buffers-re "^\\*"))
(use-package hungry-delete
:defer 3
:config
(setq-default hungry-delete-join-reluctantly t)
(global-hungry-delete-mode))
(use-package autorevert
;; revert buffers when files on disk change
:defer 3
:config
(setq-default
;; Also auto refresh dired, but be quiet about it
global-auto-revert-non-file-buffers t
auto-revert-verbose nil
;; Revert pdf without asking
revert-without-query '("\\.pdf" "\\.png")
;; Auto reverting files in remote machine. Useful for remote plotting.
auto-revert-remote-files t
;; Check revert status every 60s
auto-revert-interval 60)
(global-auto-revert-mode 1) ;; work with auto-save with Org files in Nextcloud
)
(use-package recentf
:defer 5
:preface
(defun recentf-add-dired-directory ()
(if (and dired-directory
(file-directory-p dired-directory)
(not (string= "/" dired-directory)))
(let ((last-idx (1- (length dired-directory))))
(recentf-add-file
(if (= ?/ (aref dired-directory last-idx))
(substring dired-directory 0 last-idx)
dired-directory)))))
:hook (dired-mode . recentf-add-dired-directory)
:config
(setq recentf-save-file "~/.emacs.default/data/recentf"
recentf-max-saved-items 'nil ;; Save the whole list
recentf-max-menu-items 50
;; Cleanup list if idle for 10 secs
recentf-auto-cleanup 60)
;; Suppress "Cleaning up the recentf...done (0 removed)"
(advice-add 'recentf-cleanup :around #'suppress-messages)
(recentf-mode +1)
)
(use-package super-save
:defer 3
:after (eyebrowse ace-window)
:config
;; Auto save
(setq auto-save-default t
auto-save-interval 64 ;; maximum input characters before auto save
auto-save-timeout 2 ;; save every two seconds
auto-save-visited-interval 2 ;; every two seconds
super-save-idle-duration 5 ;; It's okay to set it longer
super-save-auto-save-when-idle t)
(add-to-list 'super-save-triggers 'eyebrowse-previous-window-config)
(add-to-list 'super-save-triggers 'eyebrowse-next-window-config)
(add-to-list 'super-save-triggers 'ace-window)
(add-to-list 'super-save-triggers 'org-agenda-list)
(add-to-list 'super-save-triggers 'org-caldav-sync)
(add-to-list 'super-save-triggers 'magit-status)
(super-save-mode +1)
(auto-save-visited-mode +1)
)
(use-package aggressive-indent
;; Aggressive indent mode
:hook (emacs-lisp-mode . aggressive-indent-mode)
)
(use-package ibuffer
;; Better buffer management
:defer 3
:straight ibuffer-tramp
:bind (("C-x C-b" . ibuffer)
:map ibuffer-mode-map
("M-o" . nil)) ;; unbind ibuffer-visit-buffer-1-window
:config
(add-hook 'ibuffer-hook
(lambda ()
(ibuffer-tramp-set-filter-groups-by-tramp-connection)
(ibuffer-do-sort-by-alphabetic)))
)
(use-package which-key
:defer 3
:config
(setq which-key-idle-delay 1.0)
(which-key-mode)
)
(use-package whole-line-or-region
;; If no region is active, C-w M-w will act on current line
:defer 5
;; Right click to paste: I don't use the popup menu a lot.
:bind ("<mouse-3>" . whole-line-or-region-yank)
:bind (:map whole-line-or-region-local-mode-map ("C-w" . kill-region-or-backward-word)) ;; Reserve for backward-kill-word
:config
(whole-line-or-region-global-mode)
)
(use-package crux
;; A handful of useful functions
:defer 1
:bind (
("C-c b" . 'crux-create-scratch-buffer)
;; ("C-x o" . 'crux-open-with)
("C-x f" . 'crux-recentf-find-file)
("C-x 4 t" . 'crux-transpose-windows)
("C-x C-k" . 'crux-delete-buffer-and-file)
;; ("C-c n" . 'crux-cleanup-buffer-or-region)
;; ("s-<return>" . 'crux-cleanup-buffer-or-region)
("C-M-y" . 'crux-duplicate-and-comment-current-line-or-region)
)
:init
(global-set-key [remap move-beginning-of-line] #'crux-move-beginning-of-line)
(global-set-key [(shift return)] #'crux-smart-open-line)
(global-set-key [remap kill-whole-line] #'crux-kill-whole-line)
:config
;; Retain indentation in these modes.
(add-to-list 'crux-indent-sensitive-modes 'markdown-mode)
)
(use-package direnv
:if (equal system-type 'gnu/linux)
;; Environment switcher to enable project-base environment variables
;; Checks for .envrc file and apply environment variable
:disabled t
:straight flycheck
:straight t
:config
(direnv-mode)
(eval-after-load 'flycheck
'(setq flycheck-executable-find
(lambda (cmd)
(direnv-update-environment default-directory)
(executable-find cmd))))
)
(use-package simple
;; Improvements over simple editing commands
:straight nil
:straight visual-fill-column
:defer 5
:hook ((prog-mode) . auto-fill-mode)
:bind (("<f8>" . (lambda () (interactive) (progn (visual-line-mode) (follow-mode))))
("H-v" . visual-line-mode)
("H-V" . visual-fill-column-mode)
("M-u" . upcase-char)
("M-l" . downcase-char)
("M-SPC" . cycle-spacing)
;; M-backspace to backward-delete-word
("M-S-<backspace>" . backward-kill-sentence)
("M-C-<backspace>" . backward-kill-paragraph)
("C-x C-o" . remove-extra-blank-lines)
;; ("<up>" . scroll-down-line)
;; ("<down>" . scroll-up-line)
)
:init
;; Move more quickly
(global-set-key (kbd "C-S-n")
(lambda ()
(interactive)
(ignore-errors (next-line 5))))
(global-set-key (kbd "C-S-p")
(lambda ()
(interactive)
(ignore-errors (previous-line 5))))
;; Show line num temporarily
(defun goto-line-with-feedback ()
"Show line numbers temporarily, while prompting for the line number input"
(interactive)
(unwind-protect
(progn
(linum-mode 1)
(goto-line (read-number "Goto line: ")))
(linum-mode -1)))
(global-set-key [remap goto-line] 'goto-line-with-feedback)
(defun kill-region-or-backward-word ()
(interactive)
(if (region-active-p)
(kill-region (region-beginning) (region-end))
(backward-kill-word 1)))
(defun remove-extra-blank-lines (&optional beg end)
"If called with region active, replace multiple blank lines
with a single one.
Otherwise, call `delete-blank-lines'."
(interactive)
(if (region-active-p)
(save-excursion
(goto-char (region-beginning))
(while (re-search-forward "^\\([[:blank:]]*\n\\)\\{2,\\}" (region-end) t)
(replace-match "\n")
(forward-char 1)))
(delete-blank-lines)))
(defun countdown ()
"Show a message after timer expires. Based on run-at-time and can understand time like it can."
(interactive)
(let* ((msg-to-show (read-string "Message to show: "))
(time-duration (read-string "Time: ")))
(message time-duration)
(run-at-time time-duration nil #'alert msg-to-show)))
;; Activate `visual-fill-column-mode' in every buffer that uses `visual-line-mode'
;; Disable for now: conflict with olivetti.el
;; (add-hook 'visual-line-mode-hook #'visual-fill-column-mode)
(setq-default visual-fill-column-width 119
visual-fill-column-center-text nil)
)
;;;; Misc defuns
;; Useful functions used by various packages, but not fit to put in anyone.
(defun suppress-messages (func &rest args)
"Suppress message output from FUNC."
;; Some packages are too noisy.
;; https://superuser.com/questions/669701/emacs-disable-some-minibuffer-messages
(cl-flet ((silence (&rest args1) (ignore)))
(advice-add 'message :around #'silence)
(unwind-protect
(apply func args)
(advice-remove 'message #'silence))))
(defun the-the ()
;; https://www.gnu.org/software/emacs/manual/html_node/eintr/the_002dthe.html
"Search forward for for a duplicated word."
(interactive)
(message "Searching for for duplicated words ...")
(push-mark)
;; This regexp is not perfect
;; but is fairly good over all:
(if (re-search-forward
"\\b\\([^@ \n\t]+\\)[ \n\t]+\\1\\b" nil 'move)
(message "Found duplicated word.")
(message "End of buffer")))
(defun sudo-shell-command (command)
"Run COMMAND as root."
(interactive "MShell command (root): ")
(with-temp-buffer
(cd "/sudo::/")
(async-shell-command command)))
;;; Region Manipulation
;; Beautiful command from http://endlessparentheses.com/emacs-narrow-or-widen-dwim.html
(defun narrow-or-widen-dwim (p)
"Widen if buffer is narrowed, narrow-dwim otherwise.
Dwim means: region, org-src-block, org-subtree, or
defun, whichever applies first. Narrowing to
org-src-block actually calls `org-edit-src-code'.
With prefix P, don't widen, just narrow even if buffer
is already narrowed."
(interactive "P")
(declare (interactive-only))
(cond ((and (buffer-narrowed-p) (not p)) (widen))
((region-active-p)
(narrow-to-region (region-beginning)
(region-end)))
((derived-mode-p 'org-mode)
;; `org-edit-src-code' is not a real narrowing
;; command. Remove this first conditional if
;; you don't want it.
(cond ((ignore-errors (org-edit-src-code) t))
((ignore-errors (org-narrow-to-block) t))
(t (org-narrow-to-subtree))))
((derived-mode-p 'latex-mode)
(LaTeX-narrow-to-environment))
(t (narrow-to-defun))))
;; This line actually replaces Emacs' entire narrowing
;; keymap, that's how much I like this command. Only
;; copy it if that's what you want.
(define-key ctl-x-map "n" #'narrow-or-widen-dwim)
(use-package expand-region
;; Incrementally select a region
;; :after org ;; When using straight, er should byte-compiled with the latest Org
:bind (("C-'" . er/expand-region)
("C-M-'" . er/contract-region))
:config
(defun org-table-mark-field ()
"Mark the current table field."
(interactive)
;; Do not try to jump to the beginning of field if the point is already there
(when (not (looking-back "|[[:blank:]]?"))
(org-table-beginning-of-field 1))
(set-mark-command nil)
(org-table-end-of-field 1))
(defun er/add-org-mode-expansions ()
(make-variable-buffer-local 'er/try-expand-list)
(setq er/try-expand-list (append
er/try-expand-list
'(org-table-mark-field))))
(add-hook 'org-mode-hook 'er/add-org-mode-expansions)
(setq expand-region-fast-keys-enabled nil
er--show-expansion-message t))
(use-package wrap-region
;; Wrap selected region
:defer 3
:bind ("H-w" . wrap-region-mode)
:config
(wrap-region-add-wrappers
'(
("$" "$")
("*" "*")
("=" "=")
("`" "`")
("/" "/")
("_" "_")
("~" "~")
("+" "+")
("“" "”")
("#+begin_verse\n" "#+end_verse" "v")
("#+begin_quote\n" "#+end_quote" "q")
("/* " " */" "#" (java-mode javascript-mode css-mode))))
(add-to-list 'wrap-region-except-modes 'ibuffer-mode)
(add-to-list 'wrap-region-except-modes 'magit-mode)
(add-to-list 'wrap-region-except-modes 'magit-todo-mode)
(add-to-list 'wrap-region-except-modes 'magit-popup-mode)
(add-to-list 'wrap-region-except-modes 'help-mode)
(add-to-list 'wrap-region-except-modes 'info-mode)
(add-to-list 'wrap-region-except-modes 'ess-r-mode)
(wrap-region-global-mode +1)
)
(use-package change-inner
:defer 3
:bind (("M-I" . copy-inner)
("M-O" . copy-outer))
)
(use-package selected
;; Run commands on selected region. Very smooth!
:defer 5
:hook (org-mode . selected-minor-mode)
:bind (:map selected-keymap
("q" . selected-off)
;; ("u" . upcase-region)
("d" . downcase-region)
("w" . count-words-region)
;; ("m" . apply-macro-to-region-lines)
("t" . org-table-convert-region)
("o" . open-text-in-firefox)
("i" . org-roam-node-insert)
("b" . (lambda () (interactive) (org-emphasize ?*))) ;; bold
("/" . (lambda () (interactive) (org-emphasize ?/))) ;; italic
("u" . (lambda () (interactive) (org-emphasize ?_))) ;; underscore
("v" . (lambda () (interactive) (org-emphasize ?=))) ;; verbatim
("x" . (lambda () (interactive) (org-emphasize ?+))) ;; cross
("c" . (lambda () (interactive) (org-emphasize ?~))) ;; code
("|" . org-table-create-or-convert-from-region) ;; table
("_" . org-subscript-region-or-point) ;; subscript
("^" . org-superscript-region-or-point) ;; superscript
)
)
;;; Text Editing / Substitution / Copy-Pasting
;; Iterate through CamelCase words
(global-subword-mode +1)
(use-package multiple-cursors
;; Read https://github.com/magnars/multiple-cursors.el for common use cases
:defer 10
:bind
(
;; HOLLLY>>>> Praise Magnars.
;; Useful for org-table-create-or-convert-from-region with some random data from web
("C-<down-mouse-1>" . down-mc/add-cursor-on-click)
;; Common use case: er/expand-region, then add curors.
;; ("C-}" . mc/mark-next-like-this)
;; ("C-{" . mc/mark-previous-like-this)
;; After selecting all, we may end up with cursors outside of view
;; Use C-' to hide/show unselected lines.
;; ("C-*" . mc/mark-all-like-this)
;; highlighting symbols only
;; ("C->" . mc/mark-next-word-like-this)
;; ("C-<" . mc/mark-previous-word-like-this)
;; ("C-M-*" . mc/mark-all-words-like-this)
)
:config
(define-key mc/keymap (kbd "<return>") nil)
(setq mc/list-file (expand-file-name "mc-list.el" my-private-conf-directory))
)
(use-package iedit
;; C-; to start iedit
:defer 3)
(use-package visual-regexp
:straight t
:straight visual-regexp-steroids
:defer 5
:bind (("C-c r" . 'vr/replace)
("C-c %" . 'vr/query-replace))
:config
(global-set-key [remap query-replace] 'vr/query-replace) ; M-%
;; Build up regexp with different backend engine. This supports Emacs, Python, pcre2el. I mostly use it to build up
;; Python regexp but frequently forgot about the name, so an alias is set.
(defalias 'regexp-visualize 'vr/select-replace)
)
(use-package ediff
:hook (ediff-prepare-buffer . outline-show-all) ;; Expand file contents, especially for Org files.
:config
;; Useful functions copied from
;; https://stackoverflow.com/questions/9656311/conflict-resolution-with-emacs-ediff-how-can-i-take-the-changes-of-both-version/29757750#29757750
;; Combined with ~ to swap the order of the buffers you can get A then B or B then A
(defun ediff-copy-both-to-C ()
(interactive)
(ediff-copy-diff ediff-current-difference nil 'C nil
(concat
(ediff-get-region-contents ediff-current-difference 'A ediff-control-buffer)
(ediff-get-region-contents ediff-current-difference 'B ediff-control-buffer))))
(defun add-d-to-ediff-mode-map () (define-key ediff-mode-map "d" 'ediff-copy-both-to-C))
(add-hook 'ediff-keymap-setup-hook 'add-d-to-ediff-mode-map)
;; Do everything in one frame
(setq ediff-window-setup-function 'ediff-setup-windows-plain))
(use-package ztree
;; Compare directories in diff style
:defer 3)
(defun generate-password ()
"Generate a 16-digit password."
(interactive)
(kill-new (s-trim (shell-command-to-string "openssl rand -base64 32 | tr -d /=+ | cut -c -16")))
)
(use-package undo-tree
:defer 3
:config
(setq undo-tree-visualizer-diff t) ;; show diff. wow!
(global-undo-tree-mode))
(use-package undo-propose
:disabled t
:bind (("C-c u" . undo-propose))
)
;; Save undo history across sessions
;; TODO: Annoying prompts in magit
;; (require 'undohist)
;; (undohist-initialize)
(use-package unfill
:bind (("M-Q" . unfill-paragraph)
("M-W" . copy-region-as-kill-unfilled))
:commands (unfill-paragraph unfill-region unfill-toggle)
:config
(defun copy-region-as-kill-unfilled (beg end)
"Copy region, but with all paragraphs unfilled.
Useful when hard line wraps are unwanted (email/sharing article)."
(interactive "r")
(copy-region-as-kill beg end)
(with-temp-buffer
(yank)
(mark-whole-buffer)
(unfill-paragraph)
(kill-region (point-min) (point-max))))
)
(use-package page-break-lines
:defer 3
:config
(global-page-break-lines-mode)
)
(defun reddit-code-indent (reg-beg reg-end)
"Indent region as reddit code style, and copy it."
(interactive "r")
(copy-region-as-kill reg-beg reg-end)
(with-temp-buffer
(yank)
(indent-rigidly (point-min) (point-max) 4)
(copy-region-as-kill (point-min) (point-max)))
)
;;; Completion Framework: Ivy / Swiper / Counsel
(use-package counsel
;; No longer used, moved to vertico
:disabled t
:straight t
:straight ivy-hydra
:straight ivy-rich
:straight counsel-projectile
:straight ivy-posframe
:straight smex
:straight (flx :repo "lewang/flx" :host github :files ("flx.el"))
:straight (pinyinlib :repo "yiufung/pinyinlib.el" :host github) ;; Support for Pinyin searching with Simplified/Traditional Chinese
:straight opencc
:bind (("M-s" . swiper)
("C-c C-r" . ivy-resume)
("<f6>" . ivy-resume)
("C-h V" . counsel-set-variable)
("C-h l" . counsel-find-library)
("C-h u" . counsel-unicode-char)
("C-c j" . counsel-git-grep)
("C-s p" . counsel-git-grep)
("C-c i" . counsel-imenu)
("C-x l" . counsel-locate)
("C-x C-r" . counsel-recentf)
;; Search-replace with ag and rg:
;; C-u prefix to choose search directory
;; C-c C-o opens an occur buffer
;; e to toggle writable state
("C-s C-s" . counsel-rg)
("C-s a" . counsel-ag)
("C-s f" . counsel-file-jump) ;; Jump to a file below the current directory.
("C-s j" . counsel-dired-jump);; Jump to directory under current directory
)
:init
(setq ivy-rich-display-transformers-list
'(ivy-switch-buffer
(:columns
((ivy-rich-candidate (:width 50)) ; return the candidate itself
(ivy-rich-switch-buffer-size (:width 7)) ; return the buffer size
(ivy-rich-switch-buffer-indicators (:width 4 :face error :align right)); return the buffer indicators
(ivy-rich-switch-buffer-major-mode (:width 12 :face warning)) ; return the major mode info
(ivy-rich-switch-buffer-project (:width 15 :face success)) ; return project name using `projectile'
(ivy-rich-switch-buffer-path (:width (lambda (x) (ivy-rich-switch-buffer-shorten-path x (ivy-rich-minibuffer-width 0.3)))))) ; return file path relative to project root or `default-directory' if project is nil
:predicate
(lambda (cand) (get-buffer cand)))
counsel-M-x
(:columns
((counsel-M-x-transformer (:width 40)) ; thr original transformer
(ivy-rich-counsel-function-docstring (:face font-lock-doc-face)))) ; return the docstring of the command
counsel-describe-function
(:columns
((counsel-describe-function-transformer (:width 40)) ; the original transformer
(ivy-rich-counsel-function-docstring (:face font-lock-doc-face)))) ; return the docstring of the function
counsel-describe-variable
(:columns
((counsel-describe-variable-transformer (:width 40)) ; the original transformer
(ivy-rich-counsel-variable-docstring (:face font-lock-doc-face)))) ; return the docstring of the variable
counsel-recentf
(:columns
((ivy-rich-candidate (:width 0.8)) ; return the candidate itself
(ivy-rich-file-last-modified-time (:face font-lock-comment-face)))))) ; return the last modified time of the file
:config
(ivy-mode 1)
(ivy-rich-mode 1)
(counsel-mode 1)
(minibuffer-depth-indicate-mode 1)
(counsel-projectile-mode 1)
(setq smex-save-file (expand-file-name "smex-items" my-private-conf-directory))
(require 'pinyinlib)
(require 'opencc)
(defun re-builder-extended-pattern (str)
"Build regex compatible with pinyin from STR.
If first character is :, search Chinese (regardless of traditional or simplified).
If first character is /, search camelCase."
(let* ((len (length str)))
(cond
;; do nothing
((<= (length str) 0))
;; If the first charater of input in ivy is ":"
;; remaining input is converted into Chinese pinyin regex.
((string= (substring str 0 1) ":")
(setq str (pinyinlib-build-regexp-string (substring str 1 len) t t t t))
;; (ivy--regex-plus str)
)
;; If the first charater of input in ivy is "/",
;; remaining input is converted to pattern to search camel case word
;; For example, input "/ic" match "isController" or "isCollapsed"
((string= (substring str 0 1) "/")
(let* ((rlt "")
(i 0)
(subs (substring str 1 len))
c)
(when (> len 2)
(setq subs (upcase subs))
(while (< i (length subs))
(setq c (elt subs i))
(setq rlt (concat rlt (cond
((and (< c ?a) (> c ?z) (< c ?A) (> c ?Z))
(format "%c" c))
(t
(concat (if (= i 0) (format "[%c%c]" (+ c 32) c)
(format "%c" c))
"[a-z]+")))))
(setq i (1+ i))))
(setq str rlt))))
(ivy--regex-plus str)
;; (orderless-ivy-re-builder str)
;; Use orderless regex engine