-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdefuns.el
2372 lines (2116 loc) · 87.9 KB
/
defuns.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
;;; defuns.el -*- coding: utf-8; lexical-binding: t; -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Key binding utilities
(defun basis/define-prefix-command (command &optional key doc)
"Define COMMAND as a prefix command, optionally bound to KEY."
(declare (indent 2) (doc-string 3))
(define-prefix-command command)
(when key (global-set-key key command))
(when doc (put command 'variable-documentation doc))
command)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Editing utilities
(defvar-local basis/beginning-of-buffer-function #'ignore
"Function to move to the logical beginning of a buffer.")
(defvar-local basis/end-of-buffer-function #'ignore
"Function to move to the logical end of a buffer.")
(defun basis/beginning-of-buffer (&optional arg)
(interactive "^P")
(if (null arg)
(let ((pos (point)))
(or (region-active-p) (push-mark))
(funcall basis/beginning-of-buffer-function)
(and (eq (point) pos) (goto-char (point-min))))
(call-interactively #'beginning-of-buffer)))
(defun basis/end-of-buffer (&optional arg)
(interactive "^P")
(if (null arg)
(let ((pos (point)))
(or (region-active-p) (push-mark))
(funcall basis/end-of-buffer-function)
(and (eq (point) pos) (goto-char (point-max))))
(call-interactively #'end-of-buffer)))
(defun basis/next-line ()
"Move point to the next line.
Wrapper around `next-line' to let-bind `next-line-add-newlines'
to nil if a keyboard macro is executing. Also let-bind
`deactivate-mark' so that the mark isn't deactivated when
newlines are entered."
(interactive)
(let ((next-line-add-newlines
(and next-line-add-newlines
(not executing-kbd-macro)))
(deactivate-mark))
(call-interactively #'next-line)))
(defun basis/beginning-of-line ()
"Smarter `move-beginning-of-line'.
Go back to the first non-whitespace character or, if already
there, to the beginning of the line."
(interactive)
(let ((start (point)))
(back-to-indentation)
(when (= (point) start)
(move-beginning-of-line nil))))
(defvar basis/blank-line-regexp "^[[:blank:]]*$"
"Regexp matching a blank line.")
(defun basis/next-blank-line (n)
"Move point to the Nth next blank line."
(interactive "p")
(let* ((back (< n 0))
(count (abs n)))
(while (and (> count 0) (not (if back (bobp) (eobp))))
(and (save-excursion (beginning-of-line)
(looking-at basis/blank-line-regexp))
(forward-line (if back -1 1)))
(or (and (funcall (if back #'re-search-backward #'re-search-forward)
basis/blank-line-regexp nil t)
(goto-char (match-end 0)))
(goto-char (if back (point-min) (point-max))))
(setq count (1- count)))))
(defun basis/previous-blank-line (n)
"Move point to the Nth previous blank line."
(interactive "p")
(basis/next-blank-line (- n)))
(defun basis/comment-or-uncomment (beg end)
"Comment or uncomment the active region or current line."
(interactive
(if (use-region-p)
(list (region-beginning) (region-end))
(list (line-beginning-position) (line-end-position))))
(comment-or-uncomment-region beg end))
(defun basis/comment-region-lines (beg end &optional arg)
"Comment out the lines from BEG to END.
With optional prefix ARG, uncomment instead."
(interactive "*r\nP")
(pcase-let ((`(,beg . ,end) ; Rotate if "upside-down"
(if (> beg end)
(cons end beg)
(cons beg end))))
;; Always comment whole lines
(let ((beg (save-excursion (goto-char beg)
(line-beginning-position)))
(end (save-excursion (goto-char end)
(if (bolp)
(point)
(line-end-position)))))
(comment-region beg end arg))))
(defvar basis/whitespace-chars "\f\r\n[:blank:]"
"Whitespace characters, for e.g. `skip-chars-forward'.")
(defun basis/uncomment-sexp (&optional n)
"Uncomment the sexp at point."
(interactive "*p")
(let* ((start (point-marker))
(pos nil)
(end (save-excursion
(when (nth 4 (syntax-ppss))
(re-search-backward comment-start-skip
(line-beginning-position)
t))
(setq pos (point-marker))
(comment-forward (point-max))
(point-marker)))
(beg (save-excursion
(forward-line 0)
(while (= end (save-excursion
(comment-forward (point-max))
(point)))
(forward-line -1))
(goto-char (line-end-position))
(re-search-backward comment-start-skip
(line-beginning-position)
t)
(while (looking-at-p comment-start-skip)
(forward-char -1))
(point-marker))))
(unless (= beg end)
(uncomment-region beg end))
(goto-char pos)
;; Identify the "top-level" sexp inside the comment
(while (and (ignore-errors (backward-up-list) t)
(>= (point) beg))
(skip-chars-backward (rx (syntax expression-prefix)))
(set-marker pos (point)))
;; Re-comment everything before it
(ignore-errors (comment-region beg pos))
;; And everything after it
(goto-char pos)
(forward-sexp (or n 1))
(skip-chars-forward basis/whitespace-chars)
(if (< (point) end)
(ignore-errors (comment-region (point) end))
;; If this is a closing delimiter, pull it up
(goto-char end)
(skip-chars-forward basis/whitespace-chars)
(when (= (car (syntax-after (point))) 5)
(delete-indentation)))
;; Without a prefix, it's more useful to leave point where it was
(prog1 (unless n (goto-char start))
(set-marker start nil)
(set-marker beg nil)
(set-marker end nil)
(set-marker pos nil))))
(defun basis/comment-sexp-raw ()
"Comment the sexp at point and move over it."
(pcase (or (bounds-of-thing-at-point 'sexp)
(save-excursion
(skip-chars-forward basis/whitespace-chars)
(bounds-of-thing-at-point 'sexp)))
(`(,beg . ,end)
(goto-char end)
(skip-chars-forward basis/whitespace-chars)
(comment-region beg end)
(skip-chars-forward basis/whitespace-chars))))
(defun basis/comment-or-uncomment-sexp (&optional n)
"Comment or uncomment the sexp at point.
When commenting, a prefix argument N means comment that many
sexps. When uncommenting, a prefix argument N means move forward
that many sexps before uncommenting."
(interactive "*p")
(if (or (nth 4 (syntax-ppss))
(< (save-excursion
(skip-chars-forward basis/whitespace-chars)
(point))
(save-excursion
(comment-forward 1)
(point))))
(basis/uncomment-sexp n)
(dotimes (_ (or n 1))
(basis/comment-sexp-raw))))
(defun basis/open-line-maybe-reindent (n)
"Insert a newline and leave point before it.
Like `open-line' but, if in a `prog-mode' buffer with a
non-relative `indent-line-function', reindent the text following
the newline."
(interactive "*p")
(call-interactively #'open-line)
(when (and (derived-mode-p 'prog-mode)
(not (memq indent-line-function
'(indent-relative
indent-relative-maybe
python-indent-line-function
haskell-indentation-indent-line))))
(save-excursion
(forward-line n)
(indent-according-to-mode))))
(defun basis/open-line-below (&optional arg)
"Open a new line below the current one."
(interactive "*p")
(let ((arg (or arg 1)))
(if (< arg 0)
(basis/open-line-above (- arg))
(end-of-line)
(newline arg)
(indent-according-to-mode))))
(defun basis/open-line-above (&optional arg)
"Open a new line above the current one."
(interactive "*p")
(let ((arg (or arg 1)))
(if (< arg 0)
(basis/open-line-below (- arg))
(beginning-of-line)
(newline arg)
(forward-line (- arg))
(indent-according-to-mode))))
(defun basis/electric-return ()
"Typical \"electric\" return, similar to that in CC Mode."
(interactive)
(when (memq (char-after) '(?\) ?\] ?}))
(save-excursion (newline-and-indent)))
(newline-and-indent))
(defun basis/eol-maybe-semicolon ()
"Move to the end of the line and insert a semicolon."
(interactive)
(end-of-line)
(delete-horizontal-space t)
(unless (eq (char-before) ?\;)
(insert ";")))
(defun basis/wrap-in-curlies (beg end)
"Wrap the current line with curly braces."
(interactive
(if (use-region-p)
(list (region-beginning) (region-end))
(list (line-beginning-position) (line-end-position))))
(save-excursion
(goto-char beg)
(forward-line -1)
(end-of-line)
(delete-horizontal-space)
(insert " {")
(goto-char end)
(end-of-line)
(newline-and-indent)
(insert "}")
(indent-for-tab-command)))
(defvar-local basis/smart-hyphen-code-only t
"If non-nil, do not perform substitutions in strings or comments.")
(defvar-local basis/smart-hyphen-style 'snake
"The substitution style to use (`snake', `camel', or nil).")
(defun basis/smart-hyphen (n)
"Conditionally insert a hyphen or upcase the next char."
(interactive "*p")
(unless (memq basis/smart-hyphen-style '(snake camel nil))
(error "Unknown smart-hyphen style: `%s'" basis/smart-hyphen-style))
(if (or (not basis/smart-hyphen-style)
(and basis/smart-hyphen-code-only
(let ((state (syntax-ppss)))
(or (nth 3 state)
(nth 4 state)))))
(self-insert-command n)
(insert "-")
(let ((command (key-binding (vector (read-event)))))
(if (eq command 'self-insert-command)
(insert (let ((next (elt (this-command-keys) 1)))
(if (and (memq (char-syntax next) '(?w ?_))
;; Don't perform the replacement if the preceding
;; expression is a literal number or simple numeric
;; expression (e.g. arithmetic)
(save-excursion
(skip-chars-backward "[:digit:][:punct:]()")
(not (looking-at-p "\\_<\\|("))))
(pcase basis/smart-hyphen-style
(`camel
(delete-char -1)
(upcase next))
(`snake
(delete-char -1)
(format "_%c" next)))
next)))
(call-interactively command)))))
(defun basis/next-long-line (&optional threshold message)
"Move forward to the next overly-long line.
With a prefix arg, read the THRESHOLD to use. Otherwise use
`whitespace-line-column' if `whitespace-mode' is enabled, or 80
if not."
(interactive (list (and current-prefix-arg (read-number "Threshold: "))
t))
(let ((threshold (or threshold
(and (bound-and-true-p whitespace-mode)
whitespace-line-column)
(and (bound-and-true-p auto-fill-function)
fill-column)
80))
(start (point))
(line (line-number-at-pos))
result)
(when (eolp)
(forward-line 1)
(setq line (1+ line)))
(while (not (or result (eobp)))
(end-of-line)
(let ((column (current-column)))
(if (> column threshold)
(let ((chars (- (point) (line-beginning-position))))
(when message
(message "Line %d is %d columns (%d chars) long"
line column chars))
(setq result (cons line column)))
(forward-line 1)
(setq line (1+ line)))))
(unless result
(goto-char start)
(when message (message "No long lines found")))
result))
(defun basis/kill-something (arg)
"Kill the region, or one or more words backward."
(interactive "*p")
(if (use-region-p)
(kill-region (region-beginning) (region-end))
(backward-kill-word arg)))
(defun basis/selectrum-delete-something (arg)
(interactive "*p")
(if (use-region-p)
(delete-region (region-beginning) (region-end))
(delete-region (point) (progn (forward-word (- arg)) (point)))))
(defun basis/smart-kill-whole-line (&optional arg)
"Variant of `kill-whole-line'.
Kill the current line and move point to the first non-whitespace
character of the next line."
(interactive "*P")
(kill-whole-line arg)
(back-to-indentation))
(defun basis/duplicate-line (n)
"Duplicate the line at point.
With an argument N, duplicate that many lines."
(interactive "*p")
(let ((col (current-column))
(beg (line-beginning-position))
(end (progn (forward-line n) (point))))
(insert-buffer-substring (current-buffer) beg end)
(forward-line (- n))
(move-to-column col)))
(defun basis/kill-ring-save-something (beg end &optional indent-by)
"Save the contents of the active region or the current line."
(interactive
(pcase-let ((`(,beg . ,end)
(if (use-region-p)
(cons (region-beginning) (region-end))
(cons (line-beginning-position)
(save-excursion (forward-line 1) (point)))))
(arg current-prefix-arg))
(list beg end (and arg (prefix-numeric-value arg)))))
(if indent-by
;; It arguably makes more sense to add indentation on yank, but adding it
;; on save has two upsides: the indented code or text can then be pasted
;; into another program, and `yank' already takes an argument.
(let ((buffer (current-buffer)))
(with-temp-buffer
(insert-buffer-substring buffer beg end)
(indent-rigidly (point-min) (point-max) indent-by)
(kill-ring-save (point-min) (point-max)))
(setq deactivate-mark t))
(kill-ring-save beg end)))
(defun basis/kill-ring-save-as-fenced-code-block (beg end &optional indent)
"Save the region from BEG to END as a fenced code block."
(interactive
(pcase-let* ((`(,beg . ,end)
(if (use-region-p)
(cons (region-beginning) (region-end))
(cons (point-min) (point-max))))
(indent
(cond ((integerp current-prefix-arg)
current-prefix-arg)
((consp current-prefix-arg)
(- (indent-rigidly--current-indentation beg end))))))
(list beg end indent)))
(let* ((buffer (current-buffer))
(mode-name (symbol-name major-mode))
(language (replace-regexp-in-string "-mode\\'" "" mode-name)))
(with-temp-buffer
(insert-buffer-substring buffer beg end)
(goto-char (point-min))
(when indent
(indent-rigidly (point-min) (point-max) indent))
(when (looking-at "^\\(\\([[:blank:]]*\n\\)+\\)")
(delete-region (match-beginning 1) (match-end 1)))
(insert "```" language "\n")
(if (re-search-forward "^\\([[:blank:]\n]+\\)\\'" nil t)
(delete-region (match-beginning 1) (match-end 1))
(goto-char (point-max)))
(unless (eq (char-before) ?\n)
(insert "\n"))
(insert "```")
(kill-ring-save (point-min) (point-max)))
(setq deactivate-mark t)))
(defun basis/kill-ring-save-buffer-file-name (&optional arg)
"Save BUFFER's associated file name to the kill ring.
Abbreviate the file name, unless called with prefix ARG."
(interactive "P")
(if-let* ((file (buffer-file-name)))
(kill-new (message "%s" (if arg file (abbreviate-file-name file))))
(user-error "Current buffer is not visiting a file")))
(defun basis/clipboard-save-string (str)
"Save STR directly to the system clipboard.
Do not save the string to the the kill ring."
(funcall interprogram-cut-function str))
(defun basis/clipboard-save-something (beg end &optional thing)
"Save the region or buffer to the system clipboard."
(interactive
(if (use-region-p)
(list (region-beginning) (region-end) 'region)
(list (point-min) (point-max) 'buffer)))
(basis/clipboard-save-string (buffer-substring-no-properties beg end))
(setq deactivate-mark t)
(when thing (message "Copied %s to clipboard" thing)))
(defun basis/downcase-almost-everything (arg)
"Downcase everything not in a string or comment."
(interactive "P")
(let ((start (point))
(count 0)
(case-fold-search nil))
(and arg (goto-char (point-min)))
(while (re-search-forward "[[:upper:]]+" nil t)
(let ((state (syntax-ppss)))
(cond ((nth 3 state) ; Inside a string
(goto-char (nth 8 state))
(forward-sexp 1))
((nth 4 state) ; Inside a comment
(goto-char (nth 8 state))
(forward-comment (buffer-size)))
(t
(replace-match (downcase (match-string 0)) t t)
(setq count (1+ count))))))
(and (zerop count) (goto-char start))
(message "Made %d replacements" count)))
(defun basis/pop-to-mark-ensure-new-pos (original)
"Advice for `pop-to-mark-command' to repeat until point moves."
(let ((p (point))
(n 0))
(while (and (= p (point))
(< (prog1 n (setq n (1+ n)))
10))
(funcall original))))
(defun basis/untabify-buffer ()
"Untabify the current buffer."
(interactive)
(save-excursion (untabify (point-min) (point-max))))
(defun basis/indent-buffer ()
"Indent the current buffer."
(interactive)
(save-excursion (indent-region (point-min) (point-max))))
(defun basis/cleanup-buffer-safe ()
"Clean up the whitespace content of a buffer conservatively."
(interactive)
(basis/untabify-buffer)
(delete-trailing-whitespace)
(set-buffer-file-coding-system 'utf-8))
(defun basis/cleanup-buffer ()
"Clean up and indent the current buffer."
(interactive)
(basis/cleanup-buffer-safe)
(basis/indent-buffer))
(defun basis/count-words ()
"Count the lines, words, and characters in the active region.
Like `count-words-region', but operate on the current buffer if
the region isn't active."
(interactive)
(let ((current-prefix-arg (not (use-region-p))))
(call-interactively #'count-words-region)))
(defun basis/count-sloc (beg end)
"Count the \"SLOC\" between BEG and END.
If no region is active, examine the full buffer."
(interactive
(if (use-region-p)
(list (region-beginning) (region-end))
(list (point-min) (point-max))))
(save-excursion
(goto-char beg)
(let ((count 0))
(while (< (point) end)
(if (nth 4 (syntax-ppss))
(let ((pos (point)))
(goto-char (nth 8 (syntax-ppss)))
(forward-comment (point-max))
(when (< (point) pos) (goto-char pos)))
(forward-comment (point-max)))
(setq count (1+ count))
(forward-line))
(when (called-interactively-p 'interactive)
(message "SLOC: %d" count)))))
(defun basis/cycle-spacing-fast (&optional n)
"Invoke `cycle-spacing' in `fast' MODE."
(interactive "*p")
(cycle-spacing n nil 'fast))
(defun basis/fill-or-unfill-paragraph ()
"Fill or un-fill the paragraph at or after point."
(interactive)
(let ((fill-column (if (eq last-command 'basis/fill-or-unfill-paragraph)
(progn (setq this-command nil)
(point-max))
fill-column)))
(call-interactively #'fill-paragraph)))
(defun basis/quote-thing (beg end open close)
"Surround the region from BEG to END in OPEN and CLOSE quotes."
(interactive
(pcase-let* ((`(,beg . ,end)
(let (bounds)
(cond ((use-region-p)
(cons (region-beginning) (region-end)))
((setq bounds (bounds-of-thing-at-point 'symbol))
bounds)
(t
(cons (point) (point))))))
(`(,open . ,close)
(let ((char (read-char "Quote type: ")))
(if current-prefix-arg
(cons char char)
(pcase char
(?\` '(?\` . ?\'))
(?\' '(?\‘ . ?\’))
(?\" '(?\“ . ?\”))
(c `(,c . ,c)))))))
(list beg end open close)))
(if (eq beg end)
(progn (goto-char beg)
(insert open close)
(forward-char -1))
(let ((end (copy-marker end)))
(goto-char beg)
(insert open)
(goto-char end)
(insert close)
(set-marker end nil))))
(defun basis/delete-some-whitespace ()
"Delete whitespace around point."
(interactive)
(let* ((pos (point))
(tab (progn (skip-chars-backward "[:blank:]\f")
(and indent-tabs-mode (eq (char-after) ?\t))))
(beg (constrain-to-field nil pos))
(end (progn (skip-chars-forward "[:blank:]\f")
(constrain-to-field nil pos t)))
(cnt (- end beg)))
(cond ((> cnt 1)
(delete-region beg end)
(insert (if tab ?\t ?\s)))
((= cnt 1)
(delete-region beg end)
(when tab (insert ?\s)))
((or (bolp) (eolp))
(let* ((beg (if (re-search-backward "[^[:blank:]\f\r\n]" nil t)
(progn (forward-line 1)
(point))
(point-min)))
(end (progn (or (re-search-forward "[^[:blank:]\f\r\n]" nil t)
(goto-char (point-max)))
(beginning-of-line)
(max (point) beg)))
(cnt (count-lines beg end))
(pos (copy-marker pos (= pos end))))
(delete-region beg end)
(when (> cnt 1) (insert ?\n))
(goto-char pos)
(prog1 nil (set-marker pos nil)))))))
(defun basis/delete-indentation (&optional arg)
"Augmented version of `delete-indentation'.
Like `delete-indentation', but also delete redundant comment
characters and, if joining to an empty line, re-indent."
(interactive "*P")
(if arg (forward-line) (beginning-of-line))
(let ((pos (point-marker)))
(when comment-start
(comment-normalize-vars)
(let* ((beg-blk (or (and (derived-mode-p 'sql-mode)
"/\\*")
(and (boundp 'c-block-comment-start-regexp)
c-block-comment-start-regexp)))
(end-blk (or (and (derived-mode-p 'sql-mode)
"\\*/")
(and (boundp 'c-block-comment-ender-regexp)
c-block-comment-ender-regexp)))
(beg-rxp (concat "\\(\\s<+\\|"
comment-start-skip
(and beg-blk (concat "\\|" beg-blk))
"\\)"))
(con-str (or (and (> (length comment-continue) 0)
comment-continue)
(and (derived-mode-p 'sql-mode)
" * ")
(and (boundp 'c-block-comment-prefix)
(stringp c-block-comment-prefix)
c-block-comment-prefix)))
(con-rxp (and con-str (regexp-quote con-str)))
(end-rxp (concat "\\(\\s>+\\|"
comment-end-skip
(and end-blk (concat "\\|" end-blk))
"\\)")))
(cond ((and (progn (skip-chars-forward " \t")
(looking-at beg-rxp))
(save-excursion
(save-match-data
(let ((bol (progn (forward-line -1) (point)))
(eol (progn (end-of-line) (point))))
(or (and (progn (skip-chars-backward " \t")
(looking-back end-rxp bol))
(progn (delete-region (match-beginning 0)
eol)
t))
(progn (goto-char bol)
(looking-at beg-rxp)))))))
(delete-region pos (match-end 0)))
((let ((beg (and con-rxp (nth 8 (syntax-ppss)))))
(when (and beg (> (point) beg))
(progn (skip-chars-forward " \t")
(let ((n (length con-str))
(i 0))
(while (and (< i n)
(not (bolp))
(memq (aref con-str i) '(?\s ?\t)))
(forward-char -1)
(setq i (1+ i))))
(looking-at con-rxp))))
(delete-region pos (match-end 0))))))
(delete-indentation)
(when (bolp) (indent-according-to-mode))
(prog1 nil (set-marker pos nil))))
(defun basis/delete-empty-lines (beg end &optional arg)
"Delete empty lines between BEG and END.
If prefix ARG is non-nil, lines are considered empty and deleted
if they contain (only) tabs and spaces. Otherwise, lines are only
deleted if they are completely empty."
(interactive
(pcase-let ((`(,beg ,end)
(if (use-region-p)
(list (region-beginning) (region-end))
(list (point-min) (point-max)))))
(list beg end current-prefix-arg)))
(let ((regexp (if arg "^[[:blank:]]*$" "^$")))
(save-restriction
(narrow-to-region beg end)
(goto-char (point-min))
(while (and (re-search-forward regexp nil t)
(not (eobp)))
(let ((beg (match-beginning 0))
(end (min (1+ (match-end 0)) (point-max))))
(delete-region beg end))))))
(defun basis/narrow-or-widen-dwim (arg)
"Widen if buffer is narrowed, otherwise narrow.
When narrowing, narrow to the region if active, otherwise to the
current defun. With prefix ARG, never widen; narrow even if the
buffer is already narrowed."
(interactive "P")
(cond ((and (buffer-narrowed-p) (not arg))
(widen))
((region-active-p)
(narrow-to-region (region-beginning) (region-end)))
(t
(narrow-to-defun))))
(defun basis/next-trailing-whitespace ()
"Move point to the next occurrence of trailing whitespace."
(interactive)
(let ((start (point)))
(skip-chars-forward "[:blank:]")
(if (re-search-forward "[[:blank:]]+$" nil t)
(goto-char (match-beginning 0))
(goto-char start)
(message "No trailing whitespace"))))
(defun basis/find-non-text-character ()
"Find a non-text character, if any, in the current buffer.
\"Non-text\" is not a well-defined term, but in this case it
means anything that's not a printing character, a whitespace
character, or newline."
(interactive)
(if (re-search-forward "[^[:print:][:space:]\n]" nil t)
(forward-char -1)
(message "No non-text characters found")))
(defun basis/abbrev-insert-undo-boundary (&rest _)
"Advice for `abbrev-insert'.
When triggered by `self-insert-command', insert an undo boundary
after inserting the character."
(when (eq this-command 'self-insert-command)
(let ((abbrev-mode nil))
(call-interactively #'self-insert-command)
(undo-boundary))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Movement
(defun basis/ace-window-kludge (original arg)
"Advice for `ace-window'.
Ensure it always works with two windows, even when one (or both)
is read-only and empty."
(if (and (eq aw-scope 'frame)
(= (length (window-list)) 2))
(pcase arg
(4 (basis/transpose-windows 1))
(16 (delete-other-windows))
(_ (other-window 1)))
(funcall original arg)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Search
(defun basis/isearch-meta-del-char ()
"Delete non-matching text or the last character."
(interactive)
(let ((pos (isearch-fail-pos)))
(isearch-del-char (or (and pos (- (length isearch-string) pos))
1))))
(defun basis/isearch-cancel ()
"Cancel the current interactive search.
Unlike `isearch-abort' and `isearch-exit', always cancel the
current search, with no context-dependent behavior."
(interactive)
(discard-input)
(setq isearch-success nil)
(isearch-cancel))
(defun basis/isearch-yank-something ()
"Pull the current region or symbol into the search string."
(interactive)
(isearch-yank-string
(if (use-region-p)
(progn (setq deactivate-mark t)
(buffer-substring (region-beginning) (region-end)))
(or (current-word t) ""))))
(defun basis/occur-beginning-of-buffer ()
(interactive)
(goto-char (point-min))
(occur-next 1))
(defun basis/occur-end-of-buffer ()
(interactive)
(goto-char (point-max))
(occur-prev 1))
(defun basis/occur-dwim (regexp nlines)
"Like `occur', but use the symbol at point as the default REGEXP."
(interactive
(let* ((history nil)
(default (cond ((use-region-p)
(buffer-substring (region-beginning) (region-end)))
((current-word t))
(t (setq history 'regexp-history-last)
(car regexp-history)))))
(list (read-regexp (if default
(format "Occur (default %s): " default)
"Occur: ")
default
history)
(prefix-numeric-value current-prefix-arg))))
(occur regexp nlines))
(defvar basis/occur-show-notes-regexp
(regexp-opt '("TODO" "DONE" "NOTE" "KLUDGE" "FIXME" "FAIL" "XXX" "???") t)
"Regexp for `basis/occur-show-notes'.")
(defun basis/occur-show-notes ()
"Search for common \"TODO\"-style notes."
(interactive)
(occur basis/occur-show-notes-regexp))
(defun basis/push-mark-noactivate (&rest _)
"Push the mark without activating it.
Used as :after advice for `avy-push-mark'."
(push-mark nil t nil))
(defun basis/grep-use-bash (original &rest args)
"Advice for `lgrep'.
Invoke grep via bash, since zsh signals an error if there are any
non-matching patterns. See bug #23590."
(let ((shell-file-name (or (executable-find "bash")
shell-file-name)))
(apply original args)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Completion
(defun basis/describe-function (function)
"Display the full documentation of FUNCTION."
(interactive
(let ((default (function-called-at-point))
(enable-recursive-minibuffers t))
(list (intern (completing-read "Describe function: "
obarray
(lambda (sym)
(or (get sym 'function-documentation)
(fboundp sym)))
t nil nil
(and (symbolp default)
(not (null default))
(symbol-name default)))))))
(describe-function function))
(defun basis/describe-variable (variable &optional buffer frame)
"Display the full documentation of VARIABLE."
(interactive
(let ((default (variable-at-point))
(enable-recursive-minibuffers t))
(list (intern (completing-read "Describe variable: "
obarray
(lambda (sym)
(or (get sym 'variable-documentation)
(and (boundp sym)
(not (keywordp sym)))))
t nil nil
(and (symbolp default)
(not (keywordp default))
(symbol-name default)))))))
(describe-variable variable buffer frame))
(defun basis/describe-face (face &optional frame)
"Display the properties of face FACE on FRAME."
(interactive
(let ((default (symbol-at-point))
(enable-recursive-minibuffers t))
(list (intern (completing-read "Describe face: "
obarray #'facep t nil nil
(and (symbolp default)
(symbol-name default)))))))
(describe-face face frame))
(defun basis/company-maybe-block-completion (&rest _)
"Prevent `company-auto-begin' from running in some circumstances."
;; Used as `:before-until' advice, so returning non-nil prevents completion.
(pcase major-mode
(`python-mode
(nth 3 (syntax-ppss)))
(`sh-mode
(save-excursion
(forward-char -2)
(looking-at-p "\\_<fi\\_>")))))
(defun basis/maybe-enable-company-clang ()
"Conditionally enable `company-clang' for the current buffer."
(when (and (buffer-file-name)
(not (file-remote-p (buffer-file-name)))
(bound-and-true-p company-clang-executable))
(add-to-list 'company-backends #'company-clang)))
(defvar basis/ivy-format-selection-text
(propertize "> " 'face 'font-lock-function-name-face)
"Text to place before the selection during `ivy' completion.")
(defun basis/insert-file-name (file)
"Read FILE completion and insert it in the current buffer."
(interactive "f")
(insert (abbreviate-file-name (if (file-directory-p file)
(file-name-as-directory file)
file))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Programming modes
(defun basis/eval-something ()
"Eval the active region, if any; otherwise eval the toplevel form."
(interactive)
(if (use-region-p)
(prog1 (call-interactively #'eval-region)
(setq deactivate-mark t))
(call-interactively #'eval-defun)))
(defun basis/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)))))
(defun basis/scheme-send-something ()
(interactive)
(call-interactively
(if (use-region-p) #'scheme-send-region #'scheme-send-definition)))
(defun basis/geiser-eval-something ()
(interactive)
(call-interactively
(if (use-region-p) #'geiser-eval-region #'geiser-eval-definition)))
(defun basis/geiser-eval-something-and-go ()
(interactive)
(call-interactively (if (use-region-p)
#'geiser-eval-region-and-go
#'geiser-eval-definition-and-go)))
(defun basis/geiser-expand-something ()
(interactive)
(call-interactively
(if (use-region-p) #'geiser-expand-region #'geiser-expand-last-sexp)))
(defun basis/python-send-something ()
"Send the active region or the current defun."
(interactive)
(call-interactively
(if (use-region-p) #'python-shell-send-region #'python-shell-send-defun)))
(defun basis/python-nav-backward-sexp (&optional arg)
"Move backward by one sexp."
(interactive "^p")
(python-nav-forward-sexp (- arg)))
(defun basis/jedi-installed-p ()
"Return non-nil if Python, Jedi, and EPC are installed."
(condition-case nil
(with-temp-buffer
(let ((inhibit-message t)
(message-log-max nil))
(zerop (call-process python-shell-interpreter nil nil nil
"-c" "import epc; import jedi; exit()"))))
(file-error nil)))
(defun basis/python-insert-triple-quotes ()
"Insert Python triple-quotes and move point to the center."
(interactive)
(let* ((keys (this-command-keys))
(char (elt keys (1- (length keys)))))
(insert-char char 6)
(forward-char -3)))
(defun basis/python-find-virtual-env (&optional dir)
(when-let* ((dir (or dir (ignore-errors (projectile-project-root))))
(env (expand-file-name "env" dir)))
(and (or (file-exists-p (expand-file-name "bin/activate" env))
(file-exists-p (expand-file-name "Scripts/activate" env)))
env)))
(defun basis/python-activate-virtual-env (dir)
"Like `pyvenv-activate' but try to guess the directory."
(interactive
(list (read-directory-name
"Activate virtual environment: "
(when-let* ((root (ignore-errors (projectile-project-root))))
(or (basis/python-find-virtual-env root)
root)))))
(if (eq major-mode 'python-mode)
(pyvenv-activate dir)