-
Notifications
You must be signed in to change notification settings - Fork 27
/
emr-elisp.el
1600 lines (1350 loc) · 53 KB
/
emr-elisp.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
;;; emr-elisp.el --- Refactoring commands for Emacs Lisp -*- lexical-binding: t; -*-
;; Copyright (C) 2013 Chris Barrett
;; Copyright (C) 2018 Wilfred Hughes
;; Author: Chris Barrett <[email protected]>
;; This file is not part of GNU Emacs.
;; This program is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; Refactoring commands for Emacs Lisp
;;; Code:
(require 's)
(require 'list-utils)
(require 'dash)
(require 'thingatpt)
(require 'compile)
(require 'emr)
(require 'emr-lisp)
(autoload 'paredit-splice-sexp-killing-backward "paredit")
(defcustom emr-el-definition-macro-names
'(defun defun* cl-defun defmacro defmacro* cl-defmacro defcustom
defvar defvar-local defconst defsubst defsubst* cl-defsubst)
"Lists the function, macro and variable definition forms in Elisp.
Used when searching for usages across the whole buffer."
:group 'emr)
(defun emr-el:safe-read (sexp)
"A wrapper around `read' that return nil immediately if SEXP is null.
If sexp is nil, `read' would prompt the user for input from stdin.
Bad."
(and sexp (read sexp)))
(defun emr-el:print (form)
"Print FORM as a Lisp expression."
(let (
;; Print forms to any depth.
(print-quoted t)
(print-level nil)
(print-length nil)
(print-escape-newlines t)
)
(prin1-to-string form)))
;;;; Navigation commands
(defun emr-el:goto-first-match (regex)
"Move point to the first match in the buffer for REGEX."
(save-match-data
(when (string-match regex (buffer-string) 0)
(goto-char (match-beginning 0)))))
(defun emr-el:looking-at-decl? ()
(-contains? '(interactive declare) (car-safe (list-at-point))))
;;;; Formatting commands
(defun emr-el:symbol-file-name (fn)
"Find the name of the file that declares function FN."
(-when-let (file (find-lisp-object-file-name fn (symbol-function fn)))
(and (stringp file)
(file-name-nondirectory (file-name-sans-extension file)))))
(defvar emr-el:special-symbols
'(--cl-rest-- &rest &optional &key &allow-other-keys \,\@ \,)
"A list of symbols that should be ignored by variable searches.")
(cl-defun emr-el:bindings-in-lambda ((_lam arglist &rest body))
"Return all bound variables within a lambda form."
(let ((bs (-difference arglist emr-el:special-symbols)))
(-concat bs (emr-el:bound-variables body))))
(cl-defun emr-el:bindings-in-let ((_let bindings &rest body))
"Return the list of bound values in the given `let' or `let*' expression."
(-concat (emr-el:let-binding-list-symbols bindings)
(emr-el:bound-variables body)))
(cl-defun emr-el:bindings-in-defalias ((_def (_quote sym) func))
"Return the bindings in a defalias form, including the named alias."
(cons sym (emr-el:bound-variables func)))
(defun emr-el:bound-variables (form)
"Find the list of let- or lambda-bound variables in FORM."
;; Form traversal can recur infinitely in some quotation scenarios. In
;; such cases it is not a problem to bail and unwind the stack.
(ignore-errors
(-uniq
(let* (
;; Handle errors in expansion. Expansion errors are common with syntax
;; quotes, for example.
(form (or (ignore-errors (macroexpand-all form))
(ignore-errors (macroexpand form))
form))
(hd (car-safe form)))
(cond
((equal 'lambda hd) (emr-el:bindings-in-lambda form))
((equal 'let hd) (emr-el:bindings-in-let form))
((equal 'let* hd) (emr-el:bindings-in-let form))
((equal 'defalias hd) (emr-el:bindings-in-defalias form))
;; `function' is the quotation form for function objects.
;; Do not bail if the next item is not a lambda.
((equal 'function hd) (condition-case _err
(-mapcat 'emr-el:bindings-in-lambda (cdr form))
(error
(-mapcat 'emr-el:bound-variables (cdr form)))))
;; FORM is probably a value if we're not looking at a list, and can be
;; ignored.
((listp form)
(->> form
;; Handle improper lists.
(list-utils-make-proper-copy)
(-mapcat 'emr-el:bound-variables))))))))
(defun emr-el:unquoted-symbols (form)
"Return a list of every unquoted symbol in FORM."
(let (syms
(forms-remaining (list form)))
(while (not (null forms-remaining))
(let ((subform (pop forms-remaining)))
(cond
;; Skip quoted symbols.
((and (consp subform) (eq (car subform) 'quote)))
;; Iterate on the subforms for lists.
((consp subform)
(push (cdr subform) forms-remaining)
(push (car subform) forms-remaining))
;; If this node is a symbol, add it to our list.
((and subform (symbolp subform))
(push subform syms)))))
syms))
(defun emr-el:free-variables (form &optional context)
"Try to find the symbols in FORM that do not have variable bindings.
CONTEXT is the top level form that encloses FORM."
;; Macro-expand FORM and find the list of bound symbols. Diff this with the
;; other symbols in FORM. Figure out which ones are not functions, keywords,
;; special vars, etc. This should give a pretty good idea of which symbols are
;; 'free'.
(let ((bound-vars (emr-el:bound-variables form))
(ctx-bound (emr-el:bound-variables context))
(form-syms (emr-el:unquoted-symbols form)))
(->> (or (ignore-errors (macroexpand-all form)) form)
;; Get all symbols from FORM's macro-expansion.
(list)
(list-utils-make-proper-inplace)
(-flatten)
(-filter 'symbolp)
(-distinct)
;; Only use symbols present in the original form. This prevents free vars
;; from the macro-expansion leaking in.
(--filter (-contains? form-syms it))
;; Finally, reduce the candidates.
(--remove (or (-contains? bound-vars it)
(-contains? emr-el:special-symbols it)
(booleanp it)
(keywordp it)
;; Remove special vars and function names, unless they've
;; been bound in the enclosing form.
(unless (-contains? ctx-bound it)
(or
(special-variable-p it)
(ignore-errors
(symbol-function it)))))))))
;;;; Definition site tests
(defun emr-el:macro-definition? (form)
"Return t if FORM expands to a macro definition."
(ignore-errors
(let* ((exp (macroexpand-all form))
;; Skip surrounding `prog1'. This will exist if the macro has
;; `declare' specs.
(exp (if (equal 'prog1 (car exp))
(cdr exp)
exp)))
;; A macro expands to a defalias.
(cl-destructuring-bind (&optional def _sym binding &rest rest) exp
;; The binding is a call to `cons'. The first arg is the quoted
;; symbol `macro'.
(cl-destructuring-bind (&optional _cons mac &rest lambda) binding
(and (equal 'defalias def)
;; NB quoted symbol 'macro must be quoted twice for comparison.
(equal ''macro mac)))))))
(defun emr-el:function-definition? (form)
"Return t if FORM expands to a function definition."
(ignore-errors
(let ((exp (macroexpand-all form)))
(and (equal 'defalias (car exp))
(equal 'function (caaddr exp))))))
(defun emr-el:variable-definition? (form)
(ignore-errors
(-contains? '(defconst defvar defcustom)
(car (macroexpand-all form)))))
(defun emr-el:definition? (form)
"Return non-nil if FORM is a definition."
(or (emr-el:variable-definition? form)
(emr-el:macro-definition? form)
(emr-el:function-definition? form)))
(defun emr-el:looking-at-definition? ()
"Non-nil if point is at a definition form."
(ignore-errors (emr-el:definition? (list-at-point))))
;;;; Refactoring commands
(defun emr-el:extract-var-values (sexp)
"Return the name and initializing value of SEXP if it is a variable definition."
(let ((exp (macroexpand-all sexp)))
(when (emr-el:variable-definition? exp)
(cl-destructuring-bind (_def sym &rest forms) exp
(cons sym (car forms))))))
(cl-defun emr-el:replace-usages ((sym . value))
"Replace all instances of SYM with VALUE in the current buffer.
Returns a list of lines where changes were made."
(save-excursion
(goto-char (point-min))
(save-match-data
(let ((match-sym
(rx-to-string
`(seq (not (any "(")) (* space)
(group symbol-start ,(symbol-name sym)
symbol-end))))
(lines))
;; Check for "(" since we don't want to replace function calls.
(while (and (search-forward-regexp match-sym nil t)
(match-data))
(setq lines (cons (line-number-at-pos) lines))
;; Perform replacement.
(replace-match (emr-el:print value) t nil nil 1)
(emr-lisp-reindent-defun))
(nreverse lines)))))
;;;###autoload
(defun emr-el-inline-variable ()
"Inline the variable defined at point.
Uses of the variable in the current buffer are replaced with the
initvalue in the variable definition.
EXAMPLE:
(emr-el-inline-variable)
BEFORE:
(defvar x| value)
(usage x)
AFTER:
(usage value)"
(interactive "*")
(save-excursion
(emr-lisp-back-to-open-round)
(-if-let (def (emr-el:extract-var-values (list-at-point)))
(if (or (consp def) (> (length def) 1))
(emr-lisp-extraction-refactor () "Inlining applied at"
;; Clean up line spacing.
(while (emr-blank-line?)
(kill-line))
;; Perform inlining.
;;
;; emr-lisp-extraction-refactor will report the first insertion. If
;; there are none or more than one insertion, override this report.
(-if-let (lines (-map 'int-to-string (emr-el:replace-usages def)))
(when (> (length lines) 1)
(message "Inlining applied at lines %s" (s-join ", " lines)))
(user-error "No usages found")))
(user-error "No value to inline for %s" (car def)))
(user-error "Not a variable definition"))))
; ------------------
(defun emr-el:eval-and-print-progn (prog)
"Eval and print each form in sexp PROG."
(->> (macroexp-unprogn prog)
(-map 'eval)
(-remove 'null)
(-map 'emr-el:print)))
;;;###autoload
(defun emr-el-eval-and-replace ()
"Replace the current region or the form at point with its value.
EXAMPLE:
(emr-el-eval-and-replace)
BEFORE:
(+ (+ 1 2)| 3)
AFTER:
(+ 3 3)"
(interactive "*")
(emr-lisp-extraction-refactor (sexp) "Replacement at"
(-if-let (form (emr-el:safe-read sexp))
(progn
(insert (->> form (emr-el:eval-and-print-progn) (s-join "\n")))
(indent-for-tab-command)
(emr-lisp-reindent-defun))
(user-error "Unable to read the given form"))))
; ------------------
(defun emr-el:read-with-default (prompt value)
"Prompt for user input, showing PROMPT with an inline default VALUE."
(let ((val (s-trim (format "%s" value))))
(s-trim
(if (s-blank? val)
(read-string (format "%s: " prompt))
(read-string (format "%s (default: %s): " prompt val) nil nil val)))))
(defun emr-el:format-submitted-arglist (arglist)
"Format a user-submitted ARGLIST, raising an error if it is malformed."
(unless (or (s-blank? arglist)
(s-matches? (rx (or "()" "nil")) arglist))
(condition-case _err
(emr-el:safe-read (format "(%s)" arglist))
(error
;; Rethrow reader errors as something more informative.
(user-error "Malformed arglist")))))
(defun emr-el:read-args (form context)
"Read an arglist from the user, using FORM to generate a suggestion.
CONTEXT is the top level form that encloses FORM."
(let ((input
;; Generate suggested arglist for prompt.
(->> (emr-el:free-variables form context)
(-map 'symbol-name)
(s-join " ")
(s-trim)
;; Read user input, supplying default arglist.
(emr-el:read-with-default "Arglist" )))
)
(emr-el:format-submitted-arglist input)))
(defun emr-el:format-defun (defun-str)
"Format DEFUN-STR to a prettier defun representation."
(replace-regexp-in-string
(rx bol "(" (* nonl) "def" (* nonl) (group "nil" (* space)) eol)
"()"
defun-str t nil 1))
(defun emr-el:form-extent-for-extraction ()
"Return either the current region or the list at point."
(if (region-active-p)
(emr-line-str)
(list-at-point)))
(defun emr-el:unprogn (str)
(with-temp-buffer
(save-excursion (insert str))
(forward-word)
(when (thing-at-point-looking-at "progn")
(ignore-errors
(paredit-splice-sexp-killing-backward)))
(buffer-string)))
;;;###autoload
(defun emr-el-extract-function (name arglist)
"Extract a function, using the current region or form at point as the body.
NAME is the name of the new function.
ARGLIST is its argument list.
EXAMPLE:
(emr-el-extract-function \"extracted\" '(x))
BEFORE:
(defun orig (x)
(application| x))
AFTER:
(defun extracted (x)
(application x))
(defun orig (x)
(extracted x))"
(interactive
(list
;; Function name.
(read-string "Name: ")
;; Prompt user with default arglist.
(emr-el:read-args (emr-el:form-extent-for-extraction)
(thing-at-point 'defun))))
(when (s-blank? name)
(user-error "Name must not be blank"))
(emr-lisp-extraction-refactor (sexp) "Extracted to"
(let ((name (intern name))
;; Extract to a `cl-defun' if given a Common Lisp-style arglist.
(defun-form (if (-any? 'listp arglist) 'cl-defun 'defun))
(body (emr-el:unprogn sexp)))
;; Insert usage at point.
(insert (emr-el:print (cl-list* name arglist)))
;; Insert defun.
(->> (format "(%s %s %s\n %s)" defun-form name arglist body)
(emr-el:format-defun)
(emr-lisp-insert-above-defun)))))
; ------------------
(defun emr-el:infer-arglist-for-usage (form)
"Suggest a suitable arglist for the given function application FORM."
(->> form
;; Anything that isn't a symbol becomes 'argn'.
(--map-indexed (if (symbolp it) it (intern (format "arg%s" it-index))))
;; Drop function name.
(-drop 1)))
;;;###autoload
(defun emr-el-implement-function (name arglist)
"Create a function definition for the symbol at point.
The function will be called NAME and have the given ARGLIST.
EXAMPLE:
(emr-el-implement-function \"hello\" '(x y))
BEFORE:
|(hello x y)
AFTER:
(defun hello (x y)
)
(hello x y)"
(interactive (list
(emr-el:safe-read
(emr-el:read-with-default "Name" (symbol-at-point)))
;; Infer arglist from usage.
(->> (list-at-point)
(emr-el:infer-arglist-for-usage)
(-map 'symbol-name)
(s-join " ")
(s-trim)
(emr-el:read-with-default "Arglist")
(emr-el:format-submitted-arglist))))
;; Determine which defun form to use.
(let ((defun-form (if (-any? 'listp arglist) 'cl-defun 'defun))
pos)
;; Insert usage and defun, then move to the point to the body of the defun.
(save-excursion
;; Mark whole list at point.
(beginning-of-thing 'sexp)
(mark-sexp)
(emr-lisp-extraction-refactor () "Defined function"
;; Insert reference. Quote the symbol if it's not in the funcall
;; position.
(if (thing-at-point-looking-at "(")
(insert (format "%s" name))
(insert (format "#'%s" name)))
;; Insert definition.
(setq pos (->> (format "(%s %s %s\n )" defun-form name arglist)
(emr-el:format-defun)
(emr-lisp-insert-above-defun)))))
;; Move to end of inserted form.
(goto-char pos)
;; Move to body position.
(beginning-of-defun)
(forward-line 1)
(indent-for-tab-command)))
; ------------------
;;;###autoload
(defun emr-el-extract-variable (name)
"Extract the current region or form at point to a special variable.
The variable will be called NAME.
EXAMPLE:
(emr-el-extract-variable \"x\")
BEFORE:
(usage (+ 1 2)|)
AFTER:
(defvar x (+ 1 2))
(usage x)"
(interactive "*sName: ")
(when (s-blank? name)
(user-error "Name must not be blank"))
(emr-lisp-extraction-refactor (sexp) "Extracted to"
;; Insert usage.
(insert (s-trim name))
;; Insert definition.
(emr-lisp-insert-above-defun (format "(defvar %s %s)" name sexp))))
;;;###autoload
(defun emr-el-extract-constant (name)
"Extract the current region or form at point to a constant special variable.
The variable will be called NAME.
EXAMPLE:
(emr-el-extract-constant \"x\")
BEFORE:
(usage (+ 1 2)|)
AFTER:
(defconst x (+ 1 2))
(usage x)"
(interactive "*sName: ")
(when (s-blank? name)
(user-error "Name must not be blank"))
(emr-lisp-extraction-refactor (sexp) "Extracted to"
;; Insert usage
(insert (s-trim name))
;; Insert definition.
(emr-lisp-insert-above-defun (format "(defconst %s %s)" name sexp))))
; ------------------
(defun emr-el:autoload-exists? (function str)
"Return non-nil if an autoload for FUNCTION exists in string STR."
(s-contains? (format "(autoload '%s " function) str))
(defun emr-el:beginning-of-defun ()
"A safe version of `beginning-of-defun'.
Attempts to find an enclosing defun form first, rather than
relying on indentation."
(or
;; Search for known defun form enclosing point.
(cl-loop
while (ignore-errors (backward-up-list) t)
do (when (thing-at-point-looking-at
(rx-to-string `(seq "(" (or ,@(-map 'symbol-name emr-el-definition-macro-names)))))
(cl-return (point))))
;; Fall back to using indentation.
(ignore-errors
(beginning-of-thing 'defun))))
(defun emr-el:autoload-directive-exsts-above-defun? ()
"Non-nil if the current defun is preceeded by an autoload directive."
(save-excursion
(emr-el:beginning-of-defun)
(forward-line -1)
(emr-line-matches? (rx bol (* space) ";;;###autoload" (* space) eol))))
;;;###autoload
(defun emr-el-insert-autoload-directive ()
"Insert an autoload directive above the current defun, macro or keymap.
EXAMPLE:
(emr-el-insert-autoload-directive)
BEFORE:
(defun hello| ())
AFTER:
;;;###autoload
(defun hello ())"
(interactive "*")
(unless (emr-el:autoload-directive-exsts-above-defun?)
(emr-reporting-buffer-changes "Inserted autoload"
(save-excursion
(beginning-of-thing 'defun)
(open-line 1)
(insert ";;;###autoload")))))
(defun emr-el:sort-autoloads (autoloads)
(let ((file-grouping (->> autoloads (--group-by (nth 1 it)))))
;; Order by file name...
(->> (sort file-grouping (lambda (L R) (string< (car L) (car R))))
;; ...then by function name.
(-mapcat (lambda (assoc)
(sort (cdr assoc) (lambda (L R) (string< (car L) (car R))))))
;; Trim all components.
(-map (lambda (xs) (--map (s-trim it) xs)))
;; ;; Recombine and insert into buffer.
(--map (cl-destructuring-bind (fname file &optional rest) it
(if (not (s-blank? rest))
(format "(autoload %s %s %s)" fname file rest)
(format "(autoload %s %s)" fname file)))))))
;;;###autoload
(defun emr-el-tidy-autoloads ()
"Consolidate and reorder autoloads in the current buffer.
Order autoloads alphabetically by their file, then by their function name."
(interactive "*")
(let (autoloads
(rx-autoload (rx bol (* space) "(autoload" (+ space)
(group-n 1 (+ (not space)))
(+ space)
(group-n 2 (+ (not space)))
(* space)
(group-n 3 (*? nonl))
")")))
(save-excursion
(when (emr-el:goto-first-match rx-autoload)
(beginning-of-line)
(forward-line)
;; Collect autoloads in buffer.
(save-excursion
(goto-char (point-min))
(while (search-forward-regexp rx-autoload nil t)
(push (list (match-string 1) (match-string 2) (match-string 3))
autoloads)
(replace-match "")
(when (emr-blank-line?)
(ignore-errors
(kill-line)))))
(->> (emr-el:sort-autoloads autoloads)
(-distinct)
(s-join "\n")
(s-append "\n")
(insert))))))
;;;###autoload
(defun emr-el-extract-autoload (function file)
"Create an autoload for FUNCTION and insert it into the buffer.
FILE is the file that declares FUNCTION. See `autoload' for
details.
* If there are no autoloads in the buffer, the new autoload will
be inserted above the current toplevel form.
* If other autoloads exist in the buffer, the new autoload will
be inserted near them."
(interactive
(let* ((sym (intern (or (thing-at-point 'symbol) (read-string "Function: "))))
(file (or (emr-el:symbol-file-name sym)
(read-string "File: "))))
(list sym file)))
(let ((form `(autoload ',function ,file)))
(save-excursion
(emr-reporting-buffer-changes "Extracted to"
;; Put the extraction next to existing autoloads if any, otherwise
;; insert above top-level form.
(if (emr-el:goto-first-match "^(autoload ")
(progn (forward-line 1) (end-of-line) (newline)
(insert (emr-el:print form)))
(emr-lisp-insert-above-defun
(emr-el:print form)))))
(emr-el-tidy-autoloads)))
; ------------------
(defun emr-el:first-atom (form)
"Return the first atom the car of FORM, at any level of nesting."
(if (listp form)
(car-safe (-flatten form))
form))
(defun emr-el:let-binding-list-symbols (binding-forms)
"Return the symbols defined in the given let BINDING-FORMS."
(->> binding-forms
(--map (or (car-safe it) it))
(-remove 'null)))
(defconst emr-el:scope-boundary-forms
'(lambda defun cl-defun defun* defmacro cl-defmacro defmacro*
let let* save-excursion unwind-protect
flet cl-flet cl-flet* cl-labels labels
ert-deftest)
"A list of forms that define some kind of scope or context.
They will bound upward searches when looking for places to insert let forms.")
(defun emr-lisp-peek-back-upwards ()
"Return the car of the enclosing form."
(save-excursion
(when (ignore-errors (backward-up-list) t)
(forward-char 1)
(sexp-at-point))))
(defun emr-el:simplify-let-form-at-point ()
"Tidy the let form at point.
If it has no bindings, splice its contents into the surrounding
form or replace with `progn'."
(save-excursion
(emr-el:goto-start-of-let-binding)
;; Move into list.
(forward-char 1)
(-let (((let-keyword bindings . body) (list-at-point)))
;; Move to position after bindings list.
(forward-list 1)
(cond
;; If there are no bindings, splice the body forms into the
;; surrounding context if any of the following are true:
;;
;; 1. the let body has only a single form
;;
;; 2. the let expression is an &body or &rest argument to the
;; enclosing form.
;;
((and (null bindings)
(or (>= 1 (length body))
(-contains? (cons 'progn emr-el:scope-boundary-forms)
(emr-lisp-peek-back-upwards))))
(paredit-splice-sexp-killing-backward))
;; Replace `let*' with `let' if there's only a single binding form.
((equal 1 (length bindings))
(when (eq let-keyword 'let*)
(emr-el-toggle-let*)))
;; Otherwise replace `let' with `progn'.
((null bindings)
(backward-kill-sexp 2)
(insert "progn"))))
(emr-lisp-reindent-defun)))
(defun emr-el:join-line-after-let-binding-kill ()
"Tidy up newlines after modifiying a let-form binding list."
(when (or (emr-blank-line?)
(emr-line-matches? (rx "(" (* space) eol))
(emr-line-matches? (rx bol (* space) ")" (* space) eol)))
(forward-char 1)
(join-line)))
;;;###autoload
(defun emr-el-delete-let-binding-form ()
"Delete the let binding around point."
(interactive "*")
(cl-assert (emr-el:looking-at-let-binding-symbol?))
(let ((kr kill-ring))
(unwind-protect
(save-excursion
;; Delete binding.
(emr-lisp-back-to-open-round)
(kill-sexp)
;; Reformat after kill.
(emr-el:join-line-after-let-binding-kill)
;; Ensure whole form is correctly reindented.
(mark-defun)
(indent-region (region-beginning) (region-end)))
;; Restore kill-ring.
(setq kill-ring kr)
(emr-el:simplify-let-form-at-point))))
; ------------------
(defun emr-el:goto-containing-body-form ()
"Search upwards for the first function or macro declaration enclosing point.
Move to that body form that encloses point."
;; Ensure we're at the start of the current symbol.
(when (looking-at (rx symbol-end))
(backward-sexp))
(catch 'found
(while t
(when (-contains-p emr-el:scope-boundary-forms (emr-lisp-peek-back-upwards))
(throw 'found (point)))
(condition-case nil
(backward-up-list)
(error
;; Outer sexp, can't go up any further. We didn't find any
;; body form.
(throw 'found nil))))))
(defun emr-el:let-start-pos ()
"Search upward form point to find the start position of the innermost let."
(let ((positions
(list
(emr-lisp-find-upwards 'let)
(emr-lisp-find-upwards 'let*)
(emr-lisp-find-upwards '-let)
(emr-lisp-find-upwards '-let*))))
(setq positions (-non-nil positions))
(when positions
(-max positions))))
;; TODO: the example is redundant here.
(defun emr-el-toggle-let* ()
"Toggle between let and let* in the enclosing let form.
EXAMPLE:
(emr-el-toggle-let*)
BEFORE:
(let* ((x 1))
(+| x 1))
AFTER:
(let ((x 1))
(+ x 1))"
(interactive)
(save-excursion
(goto-char (emr-el:let-start-pos))
(forward-char 1)
(forward-sexp)
;; TODO: reindent afterwards
(if (eq (char-before (point)) ?*)
(delete-char -1)
(insert "*"))))
(defun emr-el:wrap-body-form-at-point-with-let ()
"Wrap the form with a let statement at a sensible place."
(emr-el:goto-containing-body-form)
(let ((start-pos (point)))
(forward-sexp)
(insert ")")
(goto-char start-pos))
(insert "(let ()\n ")
(emr-lisp-reindent-defun))
;; https://github.com/Wilfred/emacs-refactor/issues/35
(defun emr-el:add-let-binding (var val)
"Add a binding for symbol VAR assigned to VAL to the innermost let form.
Ensures that VAR is inserted before point.
VAL should be a string of elisp source code."
(-let* ((let-form-start (emr-el:let-start-pos))
;; Read the whole let form.
((let-keyword let-vars . _)
(save-excursion
(goto-char let-form-start)
(read (current-buffer))))
(let-paren-depth
(save-excursion
(nth 0 (syntax-ppss let-form-start))))
(vars-end
(save-excursion
(goto-char let-form-start)
;; Step over opening paren.
(forward-char)
;; Step over let keyword.
(forward-sexp)
;; Step over the vars.
(forward-sexp)
(point))))
(save-excursion
(let ((var-start-depth (+ let-paren-depth 2))
vars-after-p)
(if (> (point) vars-end)
;; We're extracting a let binding from the body, so we'll insert
;; this new var after all the existing vars.
(progn
(goto-char vars-end)
(backward-char)
(when let-vars
(newline-and-indent)))
;; Move up s-expressions until we're at the beginning of the
;; variable declaration.
;; (let (|(x foo)) ...)
(setq vars-after-p t)
(while (not (eq (nth 0 (syntax-ppss)) var-start-depth))
(goto-char (nth 1 (syntax-ppss))))
;; Move to the end of the previous sexp, if present.
(if (> (length let-vars) 1)
(progn
(backward-sexp)
(forward-sexp)))
;; Convert let to let* if we only had a single binding.
(when (and (= (length let-vars) 1)
(eq let-keyword 'let))
(emr-el-toggle-let*)))
(insert (format "(%s %s)" var val))
(when vars-after-p
(newline-and-indent))))))
;;;###autoload
(defun emr-el-extract-to-let (symbol)
"Extract the region or expression at point to a let-binding named SYMBOL.
* extracts the list at or around point
* if there is no enclosing let-form, inserts one at the top of
the current context (e.g. the enclosing `defun' or `lambda' form)."
(interactive "*SVariable name: ")
(atomic-change-group
(let (val-start-pos
val-end-pos
val)
;; Get the position of the expression that will be the value
;; for our extrcted var.
(if (use-region-p)
(progn
(setq val-start-pos (region-beginning))
(setq val-end-pos (region-end))
(deactivate-mark))
(save-excursion
(emr-lisp-back-to-open-round)
(setq val-start-pos (point))
(setq val-end-pos (progn (forward-sexp) (point)))))
(setq val
(buffer-substring-no-properties val-start-pos val-end-pos))
;; Replace the expression with our new variable.
(goto-char val-start-pos)
(delete-region val-start-pos val-end-pos)
(insert (symbol-name symbol))
;; If we're not inside a let, add one.
(save-excursion
(unless (emr-el:let-start-pos)
(emr-el:wrap-body-form-at-point-with-let)))
;; Insert the new var in the let form.
(emr-el:add-let-binding symbol val))))
; ------------------
(defun emr-el:goto-start-of-let-binding ()
"Move to the opening paren of the let-expression at point.
Otherwise move to the previous one in the current top level form."
(-when-let (pos (emr-el:let-start-pos))
(when (< 0 pos)
(goto-char pos)
(point))))
(defun emr-el:find-in-tree (elt tree)
"Return non-nil if ELT is in TREE."
(cond ((equal elt tree) elt)
((listp tree)
(--reduce-from (or acc (emr-el:find-in-tree elt it))
nil tree))))
(defun emr-el:point-sexp-index ()
"Return the position of point in the current sexp.
For example:
(foo| foo) => 0
(foo fo|o) => 1"
(let ((init-pos (point))
(result 0)
sexp-start sexp-end)
(save-excursion
;; Find the boundaries of the containing sexp.
(backward-up-list)
(setq sexp-start (point))
(forward-sexp)
(setq sexp-end (point))
;; Move over the opening paren of the containing sexp.
(goto-char (1+ sexp-start))
;; Move forward, counting subitems until we pass the original
;; point position.
(while (and