-
Notifications
You must be signed in to change notification settings - Fork 52
/
setup-editing.el
executable file
·897 lines (793 loc) · 35.4 KB
/
setup-editing.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
;; Time-stamp: <2016-01-22 23:48:17 kmodi>
;; Functions related to editing text in the buffer
;; Contents:
;;
;; Time stamps
;; Insert time-stamp + user name
;; Duplicate current line or region
;; Managing white spaces and empty newlines
;; Untabify
;; Align
;; Eval and replace last sexp
;; Toggle comment on current line or selected region
;; My modified basic functions
;; Kill Line
;; Open Line
;; Pull Up Line
;; Enable the disabled functions
;; Narrowing
;; Setting Goal Column
;; Upper/lower case conversion
;; zop-to-char
;; Kill with line numbers
;; Rectangle
;; Cycle Letter Case
;; Sort Words
;; Unfill
;; Gplusify
;; Replace identical strings with incremental number suffixes
;; Delete Blank Lines
;; Space Adjustment After Word Kills
;; Whole Buffer If Not Region
;; Mark Management
;; Popping marks
;; Smart Mark
;; Tweaking `region-extract-function'
;; Bindings
;; Comment Commander
;;; Time stamps
;; Write time stamps when saving files
;; http://www.emacswiki.org/emacs/TimeStamp
;; You can arrange to put a time stamp in a file, so that it is updated
;; automatically each time you edit and save the file. The time stamp must be
;; in the first few N lines of the file (where N is set by the variable
;; `time-stamp-line-limit', and you should insert it like this:
;; Time-stamp: <2013-11-28 02:08:29 KModi>
;; or like this:
;; Time-stamp: " "
(setq time-stamp-line-limit 20)
(add-hook 'before-save-hook #'time-stamp)
;;;; Insert time-stamp + user name
;; http://emacs.stackexchange.com/a/17358/115
(defun modi/insert-time-stamp (option)
"Insert time-stamp with user name - DWIM.
If the point is not in a comment or string,
time-stamp + user name is inserted prefixed with `comment-start' characters.
If the point is in a comment or string immediately after `comment-start' chars,
or if the buffer's major-mode has `comment-start' set to nil,
time-stamp + user name is inserted without any prefix.
If the point is in a comment or string, but *not* immediately after
`comment-start' chars,
time-stamp + user name is inserted with `--' prefix.
Additional control:
C-u -> Prefix (`comment-start' or `--') is not auto-inserted.
C-u C-u -> User name is not inserted.
C-u C-u C-u -> All of the above."
(interactive "p")
(let ((current-date-time-format "%a %b %d %H:%M:%S %Z %Y")
(no-prefix (or (= option 4) ; C-u or C-u C-u C-u
(= option 64)))
(no-user-name (or (= option 16) ; C-u C-u or C-u C-u C-u
(= option 64))))
;; Insert a space if there is no space to the left of the current point
;; and it's not at the beginning of a line
(when (and (not (looking-back "^ *"))
(not (looking-back " ")))
(insert " "))
;; Insert prefix only if `comment-start' is defined for the major mode
(when (stringp comment-start)
(if (or (nth 3 (syntax-ppss)) ; string
(nth 4 (syntax-ppss))) ; comment
;; If the point is in a comment or string
(progn
;; If the point is not immediately after `comment-start' chars
;; (followed by optional space)
(when (and (not no-prefix)
(not (looking-back (concat comment-start " *")))
(not (looking-back "^ *")))
(insert "--")))
;; If the point is NOT in a comment or string
(progn
(when (not no-prefix)
(insert comment-start)))))
;; Insert a space if there is no space to the left of the current point
;; and it's not at the beginning of a line
(when (and (not (looking-back "^ *"))
(not (looking-back " ")))
(insert " "))
(insert (format-time-string current-date-time-format (current-time)))
(when (not no-user-name)
(insert (concat " - " (getenv "USER"))))
;; Insert a space after the time stamp if not at the end of the line
(when (not (looking-at " *$"))
(insert " "))))
(bind-key "C-c D" #'modi/insert-time-stamp modi-mode-map)
;;; Duplicate current line or region
;; http://tuxicity.se/emacs/elisp/2010/03/11/duplicate-current-line-or-region-in-emacs.html
(defun duplicate-current-line-or-region (arg)
"Duplicates the current line or region ARG times.
If there's no region, the current line will be duplicated. However, if
there's a region, all lines that region covers will be duplicated."
(interactive "p")
(let (beg end (origin (point)))
(if (and mark-active (> (point) (mark)))
(exchange-point-and-mark))
(setq beg (line-beginning-position))
(if mark-active
(exchange-point-and-mark))
(setq end (line-end-position))
(let ((region (buffer-substring-no-properties beg end)))
(dotimes (i arg)
(goto-char end)
(newline)
(insert region)
(setq end (point)))
(goto-char (+ origin (* (length region) arg) arg)))))
;;; Managing white spaces and empty newlines
(setq require-final-newline t)
;; Delete trailing white space in lines and empty new lines at the end of file
;; when saving files.
;; This is very useful for macro definitions in Verilog as for multi-line
;; macros, NO space is allowed after line continuation character "\"
(defvar do-not-delete-trailing-whitespace nil
"If nil, `delete-trailing-whitespace' function will be executed in the
`write-file-functions' hook.
Usage: If you do not want to automatically delete the trailing whitespace in
any of the files in a given sub-directory, create a `.dir-locals.el' file in
that sub-directory will the below contents:
((\"sub-dir-name\"
. ((nil . ((do-not-delete-trailing-whitespace . t))))))
")
(make-variable-buffer-local 'do-not-delete-trailing-whitespace)
(defun modi/delete-trailing-whitespace-maybe (&rest args)
"Return nil if `do-not-delete-trailing-whitespace' is unbound or nil."
(bound-and-true-p do-not-delete-trailing-whitespace))
;; Call the `delete-trailing-whitespace' function only if
;; `modi/delete-trailing-whitespace-maybe' returns nil.
(advice-add 'delete-trailing-whitespace :before-until #'modi/delete-trailing-whitespace-maybe)
(add-hook 'before-save-hook #'delete-trailing-whitespace)
;;; Untabify
(setq-default indent-tabs-mode nil) ; Use spaces instead of tabs for indentation
(defun modi/untabify-buffer ()
"Untabify the current buffer.
http://www.veripool.org/issues/345-Verilog-mode-can-t-get-untabify-on-save-to-work
Note that the function's return value is set to nil because if this function is
added to `write-file-functions' hook, emacs will stay stuck at at the
\"Saving file ..\" message and the file won't be saved if any function added to
`write-file-functions' returned a non-nil value.
As per the suggestion in https://debbugs.gnu.org/cgi/bugreport.cgi?bug=21492,
for this purpose, it makes a better sense to use `before-save-hook' (a normal
hook) instead of `write-file-functions' (an abnormal hook that relies on stuff
like the function return values).
So below would be a recommended way of using this function:
(defun my/verilog-mode-customizations ()
(add-hook 'before-save-hook #'modi/untabify-buffer nil :local))
(add-hook 'verilog-mode-hook #'my/verilog-mode-customizations)
Note that it is suggested to add this function to the `before-save-hook'
*locally* within a hook for a major mode which does not require the use of
tabs instead of spaces. Do NOT add this function to the hook globally,
because it can cause issues with files like Makefiles that rely on the use of
tabs explicitly."
(interactive)
(untabify (point-min) (point-max))
;; Return nil for the benefit of `write-file-functions'.
nil)
;;; Align
;; http://stackoverflow.com/questions/6217153/aligning-or-prettifying-code-in-emacs
;; http://stackoverflow.com/questions/3633120/emacs-hotkey-to-align-equal-signs
(defun modi/align-to-equals (begin end)
"Align region to equal signs"
(interactive "r")
;; align-regexp syntax: align-regexp (beg end regexp &optional group spacing repeat)
;; beg and end are the begin and end of the selected region
;; regexp is the default 'group' for deletion/expansion
;; group is to specify the parenthesis group that is desired to be deleted/expanded (default=1)
;; spacing is the number of spaces that replaces specified parenthesis group (default=0)
;; repeat set to t/nil tells whether the alignment needs to be done multiple times per line (default=nil)
(align-regexp begin end "\\(\\s-*\\)=" 1 1 nil))
;; To do it manually do `M-x align-regexp`, type `=` and hit Enter
;; To perform align-regexp WITHOUT the default values of regexp, group, spacing, repeat
;; do `C-u M-x align-regexp`
(defun modi/align-columns (begin end)
"Align text columns"
(interactive "r")
;; align-regexp syntax: align-regexp (beg end regexp &optional group spacing repeat)
(align-regexp begin end "\\(\\s-+\\)[a-zA-Z0-9=(),?':`\.{}]" 1 1 t)
(indent-region begin end)) ; indent the region correctly after alignment
;;; Eval and replace last sexp
;; http://stackoverflow.com/a/3035574/1219634
(defun eval-and-replace-last-sexp ()
"Replace an emacs lisp expression (s-expression aka sexp) with its result.
How to use: Put the cursor at the end of an expression like (+ 1 2) and call
this command."
(interactive)
(let ((value (eval (preceding-sexp))))
(kill-sexp -1)
(insert (format "%s" value))))
(bind-to-modi-map "x" #'eval-and-replace-last-sexp)
;;; Toggle comment on current line or selected region
;; http://stackoverflow.com/questions/9688748/emacs-comment-uncomment-current-line
;; http://endlessparentheses.com/implementing-comment-line.html
(defun endless/comment-line-or-region (n)
"Comment or uncomment current line and proceed to the next line.
With positive prefix, apply to N lines including current one.
With negative prefix, apply to -N lines above.
If region is active, apply to active region instead."
(interactive "p")
(if (use-region-p)
(comment-or-uncomment-region
(region-beginning) (region-end))
(let ((range
(list (line-beginning-position)
(goto-char (line-end-position n)))))
(comment-or-uncomment-region
(apply #'min range)
(apply #'max range)))
(forward-line 1)
(back-to-indentation)))
;;; My modified basic functions
;;;; Kill Line
(defun modi/kill-line (&optional arg)
"Kill line.
If ARG is nil, kill line from the current point to the end of the line, not
including the trailing newline. But if the point is at the beginning of the
line or at indentation, kill the whole line including the trailing newline
and move back to the indentation.
If ARG < 0, kill lines backward.
If ARG == 0, kill text before point on the current line.
If ARG > 0, kill that many lines from point."
(interactive "P")
(when (and arg (listp arg)) ; to handle universal prefix cases
(setq arg (car arg)))
(let* ((kill-whole-line t)
(bol-point (save-excursion
(beginning-of-line)
(point)))
(bol-or-at-indentation-p (looking-back "^ *" bol-point)))
(when bol-or-at-indentation-p
(beginning-of-line))
(kill-line arg)
(when bol-or-at-indentation-p
(back-to-indentation))))
;;;; Open Line
(defun modi/smart-open-line (&optional n)
"Move the current line down if there are no word chars between the start of
line and the cursor. Else, insert empty line after the current line."
(interactive "p")
(if (derived-mode-p 'org-mode)
(dotimes (cnt n)
(org-open-line 1))
;; Get the substring from start of line to current cursor position
(let ((str-before-point (buffer-substring (line-beginning-position) (point))))
;; (message "%s" str-before-point)
(if (not (string-match "\\w" str-before-point))
(progn
(dotimes (cnt n)
(newline-and-indent))
;; (open-line 1)
(previous-line n)
(indent-relative-maybe))
(progn
(move-end-of-line nil)
(dotimes (cnt n)
(newline-and-indent))
(previous-line (- n 1)))))))
;;;; Pull Up Line
;; http://emacs.stackexchange.com/q/7519/115
(defun modi/pull-up-line ()
"Join the following line onto the current one (analogous to `C-e', `C-d') or
`C-u M-^' or `C-u M-x join-line'.
If the current line is a comment and the pulled-up line is also a comment,
remove the comment characters from that line."
(interactive)
(join-line -1)
;; If the current line is a comment
(when (nth 4 (syntax-ppss))
;; Remove the comment prefix chars from the pulled-up line if present
(save-excursion
;; Delete all comment-start and space characters
(while (looking-at (concat "\\s<" ; comment-start char as per syntax table
"\\|" (substring comment-start 0 1) ; first char of `comment-start'
"\\|" "\\s-")) ; extra spaces
(delete-forward-char 1))
(insert-char ? )))) ; insert space
;;; Enable the disabled functions
;;;; Narrowing
(put 'narrow-to-region 'disabled nil)
(put 'narrow-to-defun 'disabled nil)
(put 'narrow-to-page 'disabled nil)
;;;; Setting Goal Column
;; http://emacsblog.org/2007/03/17/quick-tip-set-goal-column/
(put 'set-goal-column 'disabled nil)
;; C-x C-n <- Set goal column
;; C-u C-x C-n <- Unset goal column
;;;; Upper/lower case conversion
(put 'upcase-region 'disabled nil)
(put 'downcase-region 'disabled nil)
;;; zop-to-char
;; https://github.com/thierryvolpiatto/zop-to-char
(use-package zop-to-char
:config
(progn
(setq zop-to-char-kill-keys '(?\r ?\C-k))
(setq zop-to-char-copy-keys '(?\M-w ?\C-c))
(setq zop-to-char-next-keys '(?\C-n ?\C-f))
(setq zop-to-char-prec-keys '(?\C-p ?\C-b))
(setq zop-to-char-quit-at-pos-keys '(?\C-g ?\e)) ; quit to original pos
(setq zop-to-char-quit-at-point-keys '(?\C-q nil)) ; quit to current pos
(setq zop-to-char-erase-keys '(?\d ?\C-d))
(bind-keys
:map modi-mode-map
("M-z" . zop-up-to-char)
("M-Z" . zop-to-char))))
;;; Kill with line numbers
;; http://stackoverflow.com/q/12165205/1219634
(defun kill-with-linenum (beg end unicode)
"Copy the selected region with file name, starting and ending
line numbers, date and user name.
When called with a prefix like `C-u', it will use unicode characters
instead of ASCII characters for adorning the copied snippet."
(interactive "r\nP")
(save-excursion
(goto-char end)
(skip-chars-backward "\n \t")
(setq end (point))
(let ((chars-start-of-code-block (if unicode "╭────────" ",--------"))
(chars-end-of-code-block (if unicode "╰────────" "`--------"))
(chars-n-dash (if unicode "─" "--" ))
(chars-m-dash (if unicode "──" "---" ))
(chars-pipe (if unicode "│" "|" ))
(chunk (buffer-substring beg end))
(buffer-or-file-name (or (buffer-file-name) (buffer-name)))
(user (getenv "USER")))
(setq chunk (concat
(format "%s #%-d %s %s %s\n%s "
chars-start-of-code-block
(line-number-at-pos beg)
chars-n-dash
(replace-regexp-in-string
(concat "_" user) "_${USER}" buffer-or-file-name)
chars-m-dash
chars-pipe)
(replace-regexp-in-string
"\n" (format "\n%s " chars-pipe) chunk)
(format "\n%s #%-d %s %s %s %s"
chars-end-of-code-block
(line-number-at-pos end)
chars-n-dash
(format-time-string "%Y/%m/%d")
chars-n-dash
user)))
(kill-new chunk)))
(deactivate-mark))
(defun kill-with-linenum-unicode (beg end)
(interactive "r")
(kill-with-linenum beg end :unicode))
(when (featurep 'region-bindings-mode)
(bind-keys
:map region-bindings-mode-map
;; When region is selected, pressing `c' will copy the region
;; with ASCII character adornment.
;; Pressing `C-u c' or `C' will copy with Unicode character adornment.
("c" . kill-with-linenum)
("C" . kill-with-linenum-unicode)))
;;; Rectangle
;; How to position the cursor after the end of line; useful for copying/killing
;; rectangles have lines of varying lengths.
;; http://emacs.stackexchange.com/a/3661/115
(use-package rectangle-utils
:commands (extend-rectangle-to-end)
:init
(progn
(when (featurep 'region-bindings-mode)
(bind-keys
:map region-bindings-mode-map
("|" . extend-rectangle-to-end)))))
(defun modi/kill-rectangle-replace-with-space (start end)
"Kill the rectangle and replace it with spaces."
(interactive "r")
(setq killed-rectangle (extract-rectangle start end))
(clear-rectangle start end)
(setq deactivate-mark t)
(if (called-interactively-p 'interactive)
(indicate-copied-region (length (car killed-rectangle)))))
;; http://oremacs.com/2015/02/25/rectangle-hydra/
(defun ora-ex-point-mark ()
(interactive)
(if rectangle-mark-mode
(exchange-point-and-mark)
(let ((mk (mark)))
(rectangle-mark-mode 1)
(goto-char mk))))
(defhydra hydra-rectangle (:body-pre (rectangle-mark-mode 1)
:color pink
:post (deactivate-mark)
:hint nil)
"
Rectangle:
^_p_^ _d_ delete _s_tring _c_/_C_ (delete/kill) and replace with space
_b_ _f_ _k_ cut _r_eset _o_pen (create blank rectangle and push text in region to the right)
^_n_^ _w_ copy e_x_change _X_ delete whitespace starting from the left edge of the rectangle
^^^^ _y_ paste _e_xtend Prefix rectangle lines with _N_umbers
"
("b" backward-char)
("f" forward-char)
("p" previous-line)
("n" next-line)
("d" delete-rectangle)
("k" kill-rectangle)
("w" copy-rectangle-as-kill)
("y" yank-rectangle)
("s" string-rectangle)
("t" string-rectangle)
("r" (if (region-active-p)
(deactivate-mark)
(rectangle-mark-mode 1)))
("x" ora-ex-point-mark)
("e" extend-rectangle-to-end)
("c" clear-rectangle)
("C" modi/kill-rectangle-replace-with-space)
("o" open-rectangle)
("X" delete-whitespace-rectangle)
("N" rectangle-number-lines)
("q" nil "cancel" :color blue))
(bind-key "C-x SPC" #'hydra-rectangle/body modi-mode-map)
;;; Cycle Letter Case
;; http://ergoemacs.org/emacs/modernization_upcase-word.html
(defun xah-cycle-letter-case (arg)
"Cycle the letter case of the selected region or the current word.
Cycles from 'lower' -> 'Capitalize' -> 'UPPER' -> 'lower' -> ..
C-u M-x xah-cycle-letter-case -> Force convert to upper case.
C-u C-u M-x xah-cycle-letter-case -> Force convert to lower case.
C-u C-u C-u M-x xah-cycle-letter-case -> Force capitalize."
(interactive "p")
(let (p1 p2
(deactivate-mark nil)
(case-fold-search nil))
(if (use-region-p)
(setq p1 (region-beginning)
p2 (region-end))
(let ((bds (bounds-of-thing-at-point 'word)))
(setq p1 (car bds)
p2 (cdr bds))))
(cl-case arg
(4 (put this-command 'next-state "UPPER")) ; Force convert to upper case
(16 (put this-command 'next-state "lower")) ; Force convert to lower case
(64 (put this-command 'next-state "Capitalize")) ; Force capitalize
(t (when (not (eq last-command this-command))
(save-excursion
(goto-char p1)
(cond
;; lower -> Capitalize
((looking-at "[[:lower:]]") (put this-command 'next-state "Capitalize"))
;; Capitalize -> UPPER
((looking-at "[[:upper:]][[:lower:]]") (put this-command 'next-state "UPPER"))
;; Default: UPPER -> lower
(t (put this-command 'next-state "lower")))))))
(cl-case (string-to-char (get this-command 'next-state)) ; `string-to-char' returns first character in string
(?U (upcase-region p1 p2)
;; UPPER -> lower
(put this-command 'next-state "lower"))
(?l (downcase-region p1 p2)
;; lower -> Capitalize
(put this-command 'next-state "Capitalize"))
(t (upcase-initials-region p1 p2)
;; Capitalize -> UPPER
(put this-command 'next-state "UPPER")))))
(defun modi/upcase () (interactive) (xah-cycle-letter-case 4))
(defun modi/downcase () (interactive) (xah-cycle-letter-case 16))
(defun modi/capitalize () (interactive) (xah-cycle-letter-case 64))
(when (featurep 'region-bindings-mode)
(bind-keys
:map region-bindings-mode-map
("~" . xah-cycle-letter-case)))
(defhydra hydra-change-case (:color blue
:hint nil)
"
_C_apitalize _U_PCASE _d_owncase _<SPC>_ →Cap→UP→down→
"
("C" modi/capitalize)
("c" modi/capitalize)
("U" modi/upcase)
("u" modi/upcase)
("d" modi/downcase)
("l" modi/downcase)
("<SPC>" xah-cycle-letter-case :color red)
("M-c" xah-cycle-letter-case :color red)
("q" nil "cancel" :color blue))
(bind-keys
:map modi-mode-map
("C-x C-u" . modi/upcase)
("C-x C-l" . modi/downcase)
("M-c" . hydra-change-case/body))
;;; Sort Words
;; http://www.emacswiki.org/emacs/SortWords
;; http://emacs.stackexchange.com/a/7550/115
(defun sort-words (reverse beg end)
"Sort words in region alphabetically, in REVERSE if negative.
Prefixed with negative \\[universal-argument], sorts in reverse.
The variable `sort-fold-case' determines whether alphabetic case
affects the sort order. See `sort-regexp-fields'.
Temporarily consider - and _ characters as part of the word when sorting."
(interactive "*P\nr")
(let ((temp-table (copy-syntax-table text-mode-syntax-table)))
(with-syntax-table temp-table
(modify-syntax-entry ?- "w" temp-table)
(modify-syntax-entry ?_ "w" temp-table)
(sort-regexp-fields reverse "\\w+" "\\&" beg end))))
;;; Unfill
;; Forked version of https://github.com/purcell/unfill
(use-package unfill
:load-path "elisp/unfill")
;;; Gplusify
;; Copy region with formatting for G+ comments
;; https://github.com/jorgenschaefer/gplusify
(use-package gplusify
:commands (gplusify-region-as-kill)
:init
(progn
(when (featurep 'region-bindings-mode)
(bind-keys
:map region-bindings-mode-map
("G" . gplusify-region-as-kill)))))
;;; Replace identical strings with incremental number suffixes
(defvar modi/rwins-max 100
"Default maximum number of replacements.")
(defvar modi/rwins-incr 1
"Default number by which the number suffixes will increment in the
replacements.")
(defun modi/replace-with-incr-num-suffix (start)
"Replace selected region/symbol at point with incrementing number suffixes.
If START is non-nil, the replacements will be suffixes with the START number
and increment by 1 on each replacement.
If START is nil and if the selected region or symbol already ends in a number,
the replacements will use that number as the START number.
If START is nil and if the selected region or symbol does NOT end in a number,
the replacements will use 1 as the START number.
`modi/rwins-max' controls the maximum number till which the suffix number
increments. After the max number is reached, the suffixes will restart from
START (behavior of `map-query-replace-regexp').
`modi/rwins-incr' controls the increments between the number suffixes in
consecutive replacements.
Example:
Initial text:
Here3 Here3 Here3 Here3 Here3
After replacement text:
Here3 Here4 Here5 Here6 Here7
Note that the selected region cannot contain any spaces."
(interactive "p")
(let (raw-str beg non-number-str to-strings)
(cond ((use-region-p)
(setq raw-str (buffer-substring-no-properties
(region-beginning) (region-end)))
(setq beg (region-beginning)))
((symbol-at-point)
(setq raw-str (substring-no-properties
(symbol-name (symbol-at-point))))
(setq beg (car (bounds-of-thing-at-point 'symbol)))))
(if (string-match "\\b\\(\\w*?\\)\\([0-9]+\\)$" raw-str)
(progn
(setq non-number-str (match-string-no-properties 1 raw-str))
(when (null current-prefix-arg)
(setq start (string-to-number (match-string-no-properties 2 raw-str)))))
(setq non-number-str raw-str))
;; http://www.gnu.org/software/emacs/manual/html_node/elisp/Mapping-Functions.html
(setq to-strings (mapconcat (lambda (x) (concat non-number-str (number-to-string x)))
(number-sequence
start
(+ start (* modi/rwins-incr (1- modi/rwins-max)))
modi/rwins-incr)
" "))
(goto-char beg) ; Go to the start of the selection/symbol
(map-query-replace-regexp (regexp-quote raw-str) to-strings)))
;;; Delete Blank Lines
;; http://www.masteringemacs.org/article/removing-blank-lines-buffer
;; If a region is selected, delete all blank lines in that region.
;; Else, call `delete-blank-lines'.
(defun modi/delete-blank-lines-in-region ()
(let ((do-not-run-orig-fn (use-region-p)))
(when do-not-run-orig-fn
(flush-lines "^\\s-*$" (region-beginning) (region-end)))
do-not-run-orig-fn))
(advice-add 'delete-blank-lines :before-until #'modi/delete-blank-lines-in-region)
;;; Space Adjustment After Word Kills
(defun modi/just-one-space-post-kill-word (&rest _)
"Function to manage white space after `kill-word' operations.
1. If point is at the beginning of the line after possibly some white space,
remove that white space and re-indent that line.
2. If there is space before or after the point, ensure that there is only
one white space around the point.
3. Otherwise, do nothing.
During the whole operation do not change the point position with respect to the
surrounding white space.
abc| def ghi <-- point on the left of white space after 'abc'
abc| ghi <-- point still before white space after calling this function
abc |def ghi <-- point on the right of white space before 'def'
abc |ghi <-- point still after white space after calling this function."
(save-excursion ; maintain the initial position of the pt with respect to space
(cond ((looking-back "^ *") ; remove extra space at beginning of line
(just-one-space 0)
(indent-according-to-mode))
((or (looking-at " ")
(looking-back " ")) ; adjust space only if it exists
(just-one-space 1))
(t ; do nothing otherwise, includes case where the point is at EOL
))))
;; Delete extra horizontal white space after `kill-word' and `backward-kill-word'
(advice-add 'kill-word :after #'modi/just-one-space-post-kill-word)
;;; Whole Buffer If Not Region
(defvar modi/whole-buffer-if-not-region-fns '(indent-region
eval-region)
"List of functions to advice so that they act on the whole buffer if a
region is not selected.")
(defvar modi/whole-buffer-if-not-region-adv-fn-name-format
"modi/adv-%s--whole-buffer-if-not-region"
"Format for naming the auto generated advice functions for the functions
listed in `modi/whole-buffer-if-not-region-fns'.")
(defun modi/gen-whole-buffer-if-not-region-adv-fn (symbol)
"Function to generate a function that applies the function represented by
SYMBOL to the whole buffer if region is not selected."
(let ((fn-name (intern
(format
modi/whole-buffer-if-not-region-adv-fn-name-format symbol))))
`(defun ,fn-name (orig-fn &rest args)
(save-excursion
;; Execute the original SYMBOL function if it is called indirectly.
;; Example: We do not want to trigger this advice if `eval-region'
;; is called via `eval-defun'.
(if (or (not (eq ',symbol this-command))
(use-region-p))
(apply orig-fn args)
(progn
(apply orig-fn (list (point-min) (point-max)))
(message "Executed %s on the whole buffer."
(propertize (symbol-name ',symbol)
'face 'font-lock-function-name-face))))))))
(defmacro modi/add-whole-buffer-if-not-region-advice ()
"Generate advice functions for each fn in `modi/whole-buffer-if-not-region-fns'."
`(progn ,@(mapcar
(lambda (x) (modi/gen-whole-buffer-if-not-region-adv-fn x))
modi/whole-buffer-if-not-region-fns)))
(modi/add-whole-buffer-if-not-region-advice)
;; Advice functions (that originally act on a region) to act on the whole
;; buffer if a region is not selected.
(dolist (fn modi/whole-buffer-if-not-region-fns)
(let ((adv-fn (intern
(format
modi/whole-buffer-if-not-region-adv-fn-name-format fn))))
(advice-add fn :around adv-fn)))
;;; Mark Management
;;;; Popping marks
;; http://endlessparentheses.com/faster-pop-to-mark-command.html
;; https://github.com/magnars/expand-region.el/issues/159#issuecomment-83538021
(defun modi/multi-pop-to-mark (orig-fun &rest args)
"When popping the mark, continue popping until the cursor actually moves.
Try the repeated popping up to 10 times."
(let ((p (point)))
(dotimes (i 10)
(when (= p (point))
(apply orig-fun args)))))
(advice-add 'pop-to-mark-command :around #'modi/multi-pop-to-mark)
;; Ensure that we can quickly pop the mark several times by typing
;; C-u C-SPC C-SPC, instead of having to type C-u C-SPC C-u C-SPC.
(setq set-mark-command-repeat-pop t)
;;;; Smart Mark
;; C-g after `mark-whole-buffer' brings the point back to where it originally was.
(use-package smart-mark
:config
(progn
(smart-mark-mode 1)))
;;; Tweaking `region-extract-function'
(defconst modi/enable-region-extract-function-tweak t
"Enable my customization of `region-extract-function' if non-nil.")
(defun modi/region-extract-function (delete)
"Function to get the region's content.
If DELETE is `bounds', then don't delete, but just return the
boundaries of the region as a list of (START . END) positions.
If DELETE is `delete-only', then only delete the region and the return value
is undefined.
If `modi/enable-region-extract-function-tweak' is non-nil and if
\\[universal-argument] is used before \\[kill-ring-save] or \\[kill-region],
kill the region with all trailing whitespace removed and also replace 2 or more
spaces with single spaces.
If DELETE is nil, just return the content as a string.
If anything else, delete the region and return its content as a string,
after filtering it with `filter-buffer-substring'."
(when (region-beginning)
(cond
;; Below condition was added in emacs 25.0+
;; http://git.savannah.gnu.org/cgit/emacs.git/commit/?h=emacs-25&id=31f6e939334180add7bc11240343615a2e6350f6
((eq delete 'bounds)
(list (cons (region-beginning) (region-end))))
;; `delete' is set to `'delete-only' in `delete-backward-char' and
;; `delete-forward-char' functions.
((eq delete 'delete-only)
(delete-region (region-beginning) (region-end)))
;; When doing `C-u M-w` or `C-u C-w', kill the region.
((and modi/enable-region-extract-function-tweak
(eq 4 (prefix-numeric-value current-prefix-arg)))
(let ((sel (filter-buffer-substring (region-beginning) (region-end) delete)))
(with-temp-buffer
(insert sel)
;; Removing trailing whitespace from the whole temp buffer
(delete-trailing-whitespace)
(goto-char (point-min))
(while (re-search-forward "\\s-\\{2,\\}" nil :noerror)
(replace-match " "))
(buffer-string))))
;; `delete' is set to `'delete' in `kill-region' function.
;; `delete' is set to `nil' in `copy-region-as-kill' and `deactivate-mark'
;; functions.
(t
(filter-buffer-substring (region-beginning) (region-end) delete)))))
(setq region-extract-function #'modi/region-extract-function)
;;; Bindings
(bind-keys
:map modi-mode-map
;; override the binding of `M-;' for `comment-dwim'
("M-;" . endless/comment-line-or-region)
("C-x d" . delete-region)
("C-S-d" . duplicate-current-line-or-region)
("C-x \\" . align-regexp) ; align selected region to the entered regexp
;; align multiple columns in the selected region. Of course all the selected
;; lines must have the same number of columns of groups of non-space characters
("C-x |" . modi/align-columns)
("C-k" . modi/kill-line)
;; override the binding of `C-o' for `open-line'
("C-o" . modi/smart-open-line)
("C-j" . modi/pull-up-line)
("M-=" . count-words) ; count words in buffer if no region selected
("<f9>" . eval-region)
;; override M-backspace to always do `backward-kill-word' using `modi-mode-map'.
;; Below is required so that `verilog-mode' does not bind it to `kill-word'.
("<M-delete>" . backward-kill-word))
(bind-to-modi-map "=" #'modi/align-to-equals)
;;; Comment Commander
;; Usage: Quickly pressing `j' twice will toggle comment on the current line or
;; region and proceed the cursor to the next line.
;; Now each consecutive pressing of `j', will toggle the comment on that
;; line and proceed to the next line. Pressing `p' or `n' will simply
;; navigate the cursor to the next or previous line without commenting
;; or uncommenting anything.
;;
;; jj j j j j j n n n j j p j n
;;
;; Numeric prefixes are supported too:
;;
;; jj 5j 7j 2j j 7n n n j j p j n
(defhydra hydra-comment (:color red
:columns 4)
"comment"
("j" endless/comment-line-or-region "toggle comment")
(";" endless/comment-line-or-region "toggle comment")
("p" previous-line "prev line")
("n" next-line "next line")
("{" backward-paragraph "backward para")
("P" backward-paragraph "backward para")
("}" forward-paragraph "forward para")
("N" forward-paragraph "forward para")
("m" set-mark-command "set mark")
("d" mark-defun "mark defun")
("k" kill-whole-line "kill whole line")
("b" backward-sexp "backward sexp")
("f" forward-sexp "forward sexp")
("q" nil "cancel" :color blue))
(key-chord-define-global "jj" #'hydra-comment/body)
(bind-key "C-c ;" #'hydra-comment/body modi-mode-map)
(provide 'setup-editing)
;; (1) Commented new line
;; `M-j'/`C-M-j' - `indent-new-comment-line' (aliased to `comment-indent-new-line')
;; This creates a commented new line; useful when writing multiline comments
;; like this one without having to manually type in the comment characters.
;; (2) Undo
;; `C-_' or `C-/'
;; (3) Toggle read-only-mode; toggles buffers between editable and read-only states.
;; `C-x C-q' or `M-x read-only-mode'
;; (4) Backups using prefix args to `save-buffer' (C-x C-s)
;; C-x C-s -> Makes the prev version into a backup file if
;; previously requested or if this is the first save.
;; C-u C-x C-s -> Marks this version to become a backup when the
;; next save is done.
;; C-u C-u C-x C-s -> Unconditionally makes the previous version into
;; a backup file.
;; C-u C-u C-u C-x C-s -> Does both of what C-u prefix and C-u C-u prefix do.