-
Notifications
You must be signed in to change notification settings - Fork 12
/
traad.el
2209 lines (1866 loc) · 70.9 KB
/
traad.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
;;; traad.el --- emacs interface to the traad refactoring server. -*- lexical-binding: t -*-
;;
;; Copyright (c) 2012-2017 Austin Bingham
;;
;; Author: Austin Bingham <[email protected]>
;; Version: 3.1.1
;; URL: https://github.com/abingham/traad
;; Package-Requires: ((dash "2.13.0") (deferred "0.3.2") (popup "0.5.0") (request "0.2.0") (request-deferred "0.2.0") (virtualenvwrapper "20151123") (f "0.20.0") (bind-map "1.1.1"))
;;
;; This file is not part of GNU Emacs.
;;
;;; Commentary:
;;
;; Description:
;;
;; traad is a JSON+HTTP server built around the rope refactoring library. This
;; file provides an API for talking to that server - and thus to rope - from
;; emacs lisp. Or, put another way, it's another way to use rope from emacs.
;;
;; For more details, see the project page at
;; https://github.com/abingham/traad.
;;
;; Installation:
;;
;; Copy traad.el to some location in your emacs load path. Then add
;; "(require 'traad)" to your emacs initialization (.emacs,
;; init.el, or something).
;;
;; Example config:
;;
;; (require 'traad)
;;
;;; License:
;;
;; Permission is hereby granted, free of charge, to any person
;; obtaining a copy of this software and associated documentation
;; files (the "Software"), to deal in the Software without
;; restriction, including without limitation the rights to use, copy,
;; modify, merge, publish, distribute, sublicense, and/or sell copies
;; of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be
;; included in all copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
;; BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
;; ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
;; CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
;;; Code:
(require 'cl)
(require 'f)
(require 'dash)
(require 'deferred)
(require 'json)
(require 'popup)
(require 'request)
(require 'request-deferred)
(require 'virtualenvwrapper)
(defcustom traad-save-unsaved-buffers 'ask
"What to do when there are unsaved buffers before a refactoring.
Options are:
`ask'
Ask the user if buffers should be saved.
`always'
Always save modified buffers without asking.
`never'
Never save unmodified buffers."
:type '(choice (const :tag "Ask the user" ask)
(const :tag "Always save changes" always)
(const :tag "Never save changes" never))
:risky t)
(defgroup traad nil
"A Python refactoring tool."
:group 'tools
:group 'programming)
(defconst traad-host "127.0.0.1"
"The host on which the traad server is running.")
(defcustom traad-server-program nil
"The name of the traad server program.
If this is nil (default) then the server found in the
`traad-environment-name' virtual environment is used."
:type '(repeat string)
:group 'traad)
(defcustom traad-server-args (list "-V" "2")
"Parameters passed to the traad server before the directory name."
:type '(repeat string)
:group 'traad)
(defcustom traad-debug nil
"Whether debug info should be generated."
:type '(boolean)
:group 'traad)
(defconst traad-required-protocol-version 3
"The required protocol version.")
(defcustom traad-environment-name "traad"
"The name of the Python environment containing the traad server to use.
When `traad-install-server' runs, it uses this variable to
determine where to install the server.
When `traad-server-program' is nil, this variable is used to
determine where the traad server program is installed.
This name is used by `virtualenvwrapper.el' to locate the
virtual environment into which the desired version of traad is
installed. If you have multiple traads in different virtual
environment (e.g. one for Python 2 and one for Python 3) then you
may need to dynamically alter this variable to select the one you
want to use."
:group 'traad)
(defun traad--server-command ()
"Get the command to launch the server."
(or traad-server-program
(venv-with-virtualenv
traad-environment-name
(let ((script (funcall 'executable-find "traad")))
(if script
(list script)
(error "No traad executable found"))))))
;; represents a single server instance. We may be running many for different
;; projects.
(cl-defstruct traad--server
(host "" :read-only t)
(proc nil :read-only t))
(defun traad--open (directory)
"Open a traad server in `directory'.
Returns `traad--server' struct.
"
(let ((proc-buff (get-buffer-create (format "*traad-server: %s*" directory))))
(with-current-buffer proc-buff
(erase-buffer)
(let* ((program (traad--server-command))
(program (if (listp program) program (list program)))
(args (append traad-server-args
(list "-p" "0")
(list directory)))
(program+args (append program args))
(default-directory "~/")
(proc (apply #'start-process "traad-server" proc-buff program+args))
(cont 1)
(server nil))
(while cont
(set-process-query-on-exit-flag proc nil)
(accept-process-output proc 0 100 t)
(cond
((string-match "^Listening on http://.*:\\\([0-9]+\\\)/$" (buffer-string))
(let ((server-host (concat traad-host ":" (match-string 1 (buffer-string)))))
(setq server (make-traad--server :host server-host :proc proc)
cont nil)))
(t
(incf cont)
(when (< 30 cont) ; timeout after 3 seconds
;; Kill the process so we don't accumulate idle processes.
(condition-case nil
;; Just kill the process, not the buffer. The buffer could
;; be useful for diagnostics on why there was a timeout.
(kill-process proc)
(error nil))
(error "Server timeout.")))))
server))))
(defun traad--check-protocol-version (path)
(deferred:$
(traad--deferred-request path "/protocol_version")
(deferred:nextc it
(lambda (req)
(let ((protocol-version (assoc-default
'protocol-version
(request-response-data req))))
(if (eq protocol-version traad-required-protocol-version)
(message "Supported protocol version detected: %s" protocol-version)
(error "Server protocol version is %s, but we require version %s"
protocol-version
traad-required-protocol-version)))))))
; TODO
;; (defun traad-add-cross-project (directory)
;; "Add a cross-project to the traad instance."
;; (interactive
;; (list
;; (read-directory-name "Directory:")))
;; (traad-call 'add_cross_project directory))
; TODO
;; (defun traad-remove-cross-project (directory)
;; "Remove a cross-project from the traad instance."
;; (interactive
;; (list
;; (completing-read
;; "Directory: "
;; (traad-call 'cross_project_directories))))
;; (traad-call 'remove_cross_project directory))
; TODO
;; (defun traad-get-cross-project-directories ()
;; "Get a list of root directories for cross projects."
;; (interactive)
;; (traad-call 'cross_project_directories))
(defun traad--unredo (location idx)
"Common implementation for undo and redo."
(when (traad--all-changes-saved)
(lexical-let ((data (list (cons "index" idx))))
(deferred:$
(traad--deferred-request
(buffer-file-name)
location
:data data
:type "POST")
(deferred:nextc it
(lambda (rsp)
(let* ((response (request-response-data rsp))
(changesets (assoc-default 'changes response)))
(-map
(lambda (changeset)
(dolist (path (traad--change-set-to-paths changeset))
(let* ((root (traad--find-project-root path))
(full-path (expand-file-name (traad--join-path root path)))
(buff (get-file-buffer full-path)))
(if buff
(with-current-buffer buff
(revert-buffer :ignore-auto :no-confirm))))))
changesets)))))))
)
;;;###autoload
(defun traad-undo (idx)
"Undo the IDXth change from the history. \
IDX is the position of an entry in the undo list (see: \
traad-history). This change and all that depend on it will be \
undone. \
Python-like negative indexing works here, so you can \
undo the most recent change by passing `-1' (the default value)."
(interactive
(list
(read-number "Index: " -1)))
(traad--unredo "/history/undo" idx))
;;;###autoload
(defun traad-redo (idx)
"Redo the IDXth change from the history. \
IDX is the position of an entry in the redo list (see: \
traad-history). This change and all that depend on it will be \
redone. \
Python-like negative indexing works here, so you can \
redo the most recent undo by passing `-1' (the default value)."
(interactive
(list
(read-number "Index: " -1)))
(traad--unredo "/history/redo" idx))
(defun traad--update-history-buffer ()
"Update the contents of the history buffer, creating it if \
necessary. Return the history buffer."
(deferred:$
(deferred:parallel
(traad--deferred-request
(buffer-file-name)
"/history/view_undo")
(traad--deferred-request
(buffer-file-name)
"/history/view_redo"))
(deferred:nextc it
(lambda (inputs)
(let* ((undo (assoc-default 'history (request-response-data (elt inputs 0))))
(redo (assoc-default 'history (request-response-data (elt inputs 1))))
(buff (get-buffer-create "*traad-history*")))
(set-buffer buff)
(erase-buffer)
(insert "== UNDO HISTORY ==\n")
(if undo (insert (pp-to-string (traad--enumerate undo))))
(insert "\n")
(insert "== REDO HISTORY ==\n")
(if redo (insert (pp-to-string (traad--enumerate redo))))
buff)))))
;;;###autoload
(defun traad-display-history ()
"Display undo and redo history."
(interactive)
(deferred:$
(traad--update-history-buffer)
(deferred:nextc it
(lambda (buffer)
(switch-to-buffer buffer)))))
(defun traad--history-info-core (location)
"Display information on a single undo/redo operation."
(deferred:$
(traad--deferred-request
(buffer-file-name)
location)
(deferred:nextc it
(lambda (rsp)
(let ((buff (get-buffer-create "*traad-change*"))
(info (assoc-default 'info (request-response-data rsp))))
(switch-to-buffer buff)
(diff-mode)
(erase-buffer)
(insert "Description: " (cdr (assoc 'description info)) "\n"
"Time: " (number-to-string (cdr (assoc 'time info))) "\n"
"Change:\n"
(cdr (assoc 'full_change info))))))))
;;;###autoload
(defun traad-undo-info (i)
"Get info on the I'th undo history."
(interactive
(list
(read-number "Undo index: " -1)))
(traad--history-info-core
(concat "/history/undo_info/" (number-to-string i))))
;;;###autoload
(defun traad-redo-info (i)
"Get info on the I'th redo history."
(interactive
(list
(read-number "Redo index: " -1)))
(traad--history-info-core
(concat "/history/redo_info/" (number-to-string i))))
;;;###autoload
(defun traad-auto-import ()
"Automatically add the necessary import for the current symbol.
Displays a list of potential imports - the user must select the
correct one."
(interactive)
(when (traad--all-changes-saved)
(deferred:$
(traad--deferred-request
(buffer-file-name)
"/auto_import/get_imports"
:type "POST"
:data (list (cons "path" (buffer-file-name))
(cons "offset" (traad--adjust-point (point)))))
(deferred:nextc it
(lambda (rsp)
(let* ((buff (get-buffer-create "*traad-get-imports*"))
(data (request-response-data rsp))
(imports (assoc-default 'imports data))
(location (assoc-default 'location data))
(menu-entries
(sort
(mapcar
(lambda (import)
(format "from %s import %s"
(elt import 1)
(elt import 0)))
imports)
'string-lessp)))
(if menu-entries
(let ((selection (popup-menu*
menu-entries
:margin-left 1
:margin-right 1
)))
(save-excursion
(goto-line location)
(insert selection)
(insert "\n")))
(message "No auto-import candidates (perhaps index is being built)"))))))))
;;;###autoload
(defun* traad-rename (new-name &key (docstrings t) (in-hierarchy t))
"Rename the object at the current location.
Attempts to rename all occurrences of the object in the project.
Optional arguments `DOCSTRINGS' and `IN-HIERARCHY' set renaming
options:
- `DOCSTRINGS' (default `t') specifies whether occurrences in
comments/docstrings should be renamed. For example, let's say
we're renaming a variable, `var_to_rename` and `DOCSTRINGS'
is set to `nil':
| var_to_rename = 'this is a string' # [1]
|
| some_variable = var_to_rename # [2]
|
| # This is an occurrence of `var-to-rename` # [3]
|
| def some_function(input_var):
| '''Docstring that has `var_to_rename` in it.'''# [4]
| return input_var ** 2
|
| some_function(var_to_rename) # [5]
Renaming `var_to_rename` to `new_var_name`, this would
become:
| new_var_name = 'this is a string' # [1]
|
| some_variable = new_var_name # [2]
|
| # This is an occurrence of `var-to-rename` # [3]
|
| def some_function(input_var):
| '''Docstring that has `var_to_rename` in it.'''# [4]
| return input_var ** 2
|
| some_function(new_var_name) # [5]
Note that [1], [2] & [5] were renamed, but [3] &
[4] (occurrences in a comment and a docstring) were not
renamed. If `DOCSTRINGS' were `t', [3] & [4] would have been
renamed.
- `IN-HIERARCHY' (default `t') specifies whether occurrences
higher and lower in the hierarchy should be renamed. (In
practise this means the same method in a subclass or
superclass) For example, let's say you're renaming some
method, `method_to_rename`, and `IN-HIERARCHY' is set to
`nil':
| class BaseClass(object):
| def method_to_rename(): # [1]
| print('This is the super class.')
|
| class DerivedClass(BaseClass):
| def method_to_rename(): # [2]
| print('This is the derived class.')
Renaming `BaseClass.method_to_rename` to
`BaseClass.new_name`, results in:
| class BaseClass(object):
| def new_name(): # [1]
| print('This is the super class.')
|
| class DerivedClass(BaseClass):
| def method_to_rename(): # [2]
| print('This is the derived class.')
The original method, [1], is renamed. Note that the override
method in the subclass, [2], does not get renamed. If
`IN-HIERARCHY' were set to `t', [2] would also be renamed.
Note that unsure occurrences will not be renamed. Rope may find
occurrences that it is unsure about, which are marked as
`unsure`. These will generally be wrong, so you don't want to
include them all. However, this means you may miss some
occurrences of the object. See the Rope documentation for more
details on the `unsure` parameter.
"
(interactive
(list
(read-string (format "Rename `%s' to: " (thing-at-point 'symbol)))))
(traad--fetch-perform-refresh
(buffer-file-name)
"/refactor/rename"
:data (list (cons "name" new-name)
(cons "path" (buffer-file-name))
(cons "offset" (traad--adjust-point (point)))
(cons "in_hierarchy" in-hierarchy)
(cons "docs" docstrings))))
;;;###autoload
(defun traad-rename-advanced (new-name docstrings in-hierarchy)
"Rename the thing at point, with advanced options."
(interactive
(list
(read-string (format "Rename `%s' to: " (thing-at-point 'symbol)))
(y-or-n-p "Rename in docstrings & comments? ")
(y-or-n-p "Rename matching methods in hierarchy (superclass & subclass methods)? ")))
(traad-rename new-name
:docstrings docstrings
:in-hierarchy in-hierarchy))
;;;###autoload
(defun traad-rename-module (new-name)
"Rename the currently opened module.
Note that this renames the module associated with the current
buffer, NOT the module under point."
(interactive
(list
(read-string (format "Rename `%s' to: "
(file-name-sans-extension
(file-name-nondirectory
(buffer-file-name)))))))
(deferred:$
(traad--fetch-perform
(buffer-file-name)
"/refactor/rename"
:data (list (cons "name" new-name)
(cons "path" (buffer-file-name))))
(deferred:nextc it
(lambda (_)
(let* ((dir-name (file-name-directory (buffer-file-name)))
(new-name (expand-file-name (concat dir-name "/" new-name ".py"))))
(kill-buffer (current-buffer))
(switch-to-buffer (find-file new-name)))))))
;;;###autoload
(defun traad-move ()
"Move the current object (DWIM).
Calls the correct form of `move` based on the type of thing at
the point."
(interactive)
(pcase (traad-thing-at (point))
('module (call-interactively 'traad-move-module))
('function (call-interactively 'traad-move-global))
(_ (call-interactively 'traad-move-module))))
;;;###autoload
(defun traad-move-global (dest)
"Move the object at the current location to file `DEST'.
Prompts for a `DEST' when called interactively."
(interactive
(list
(read-file-name "Destination file: " nil nil "confirm")))
(traad--fetch-perform-refresh
(buffer-file-name)
"/refactor/move_global"
:data (list (cons "dest" dest)
(cons "path" (buffer-file-name))
(cons "offset" (traad--adjust-point (point))))))
;;;###autoload
(defun traad-move-module (dest)
"Move the current module to file `DEST'.
Prompts for a `DEST' when called interactively.
Note that this moves the currently *open* module, not the module
under point."
(interactive
(list
(read-directory-name "Destination directory: " nil nil "confirm")))
(deferred:$
(traad--fetch-perform
(buffer-file-name)
"/refactor/move_module"
:data (list (cons "dest" dest)
(cons "path" (buffer-file-name))))
;; Close current buffer, opening new one on moved file.
(deferred:nextc it
(lambda (_)
(let* ((base_name (file-name-nondirectory (buffer-file-name)))
(new_name (expand-file-name (concat dest "/" base_name))))
(kill-buffer (current-buffer))
(switch-to-buffer (find-file new_name)))))))
;;;###autoload
(defun traad-normalize-arguments ()
"Normalize the arguments for the method at point.
This refactors all calls to this function to ensure the variables
are called in the correct order. It also removes explicit
references to keyword arguments whenever possible, replacing them
with positional references. For example, given the following:
| def this_is_a_test(a, b, c=5):
| return [a, b, c]
|
| this_is_a_test(a=10, b=10, c=20)
| this_is_a_test(20, 20, c=10)
| this_is_a_test('a', 'b', 'c')
| this_is_a_test(b='b', c='c', a='a')
| this_is_a_test(a='a', b='b')
Calling `traad-normalize-arguments' on `this_is_a_test`, it would
become:
| def this_is_a_test(a, b, c=5):
| return [a, b, c]
|
| this_is_a_test(10, 10, 20)
| this_is_a_test(20, 20, 10)
| this_is_a_test('a', 'b', 'c')
| this_is_a_test('a', 'b', 'c')
| this_is_a_test('a', 'b')
Note that the arguments in [1] were reordered. A more complex
case would be:
| def longer_function(a, b, c=10, d=20):
| return [a, b, c, d]
|
| longer_function(a='a', b='b', d='d')
Calling `traad-normalize-arguments' on `longer_function`, it
would become:
| def longer_function(a, b, c=10, d=20):
| return [a, b, c, d]
|
| longer_function('a', 'b', d='d')
It cannot remove the keyword reference to `d`, so \"d='d'\" is
retained.
"
(interactive)
(traad--fetch-perform-refresh
(buffer-file-name)
"/refactor/normalize_arguments"
:data (list (cons "path" (buffer-file-name))
(cons "offset" (traad--adjust-point (point))))))
;;;###autoload
(defun traad-remove-argument (index)
"Remove the `INDEX'th argument from the signature at point.
Also attempts to remove it from any calls to this function.
For example, let's say we have the following:
| def some_function(arg1, arg2, arg3=10, arg4='some string'):
| '''Do something to some arbitrary parameters.'''
| first_half = [arg1, arg2]
| second_half = [arg3, arg4]
| return first_half, second_half
|
| some_function(1, 2, arg3=3, arg4='four')
Calling `traad-remove-argument' on `some_function` with an
`INDEX' of 2, this would become:
| def some_function(arg1, arg2, arg4='some string'):
| '''Do something to some arbitrary parameters.'''
| first_half = [arg1, arg2]
| second_half = [arg3, arg4] # [1]
| return first_half, second_half
|
| some_function(1, 2, 'four') # [2]
It has removed the third argument, `arg3`.
Note:
- The index counts from zero, so an index of 0 means the first
argument and an index of 2 means the _third_ argument.
- It does not remove internal references to the argument (e.g.
[1]) in the function logic.
- References to the function also have their function call
normalised. See [2], where the explicit keyword reference was
removed in favour of a positional reference. See
`traad-normalize-arguments' for more information.
"
(interactive
(list
(read-number "Index: ")))
; TODO: Surely there's a
; better way to construct
; these lists...
(traad--fetch-perform-refresh
(buffer-file-name)
"/refactor/remove_argument"
:data (list (cons "arg_index" index)
(cons "path" (buffer-file-name))
(cons "offset" (traad--adjust-point (point))))))
;;;###autoload
(defun traad-add-argument (index name default value)
"Add a new argument at `INDEX' in the signature at point.
Takes the following arguments:
`INDEX' - The index to add the argument at. Note that this
is zero-indexed, so an index of 1 will insert it
as the _second_ argument.
`NAME' - The name of the argument.
`DEFAULT' - The default value of the argument.
`VALUE' - The value to insert for this argument in any
existing calls to this function.
For example, let's say we have the following:
| def some_function(arg1, arg2, arg3=10, arg4='some string'):
| return [arg1, arg2, arg3, arg4]
|
| some_function(1, 2, arg3=3, arg4='four')
Let's call `traad-add-argument' on some_function. We'll supply
the following arguments:
`INDEX' = 3
`NAME' = \"new_arg\"
`DEFAULT' = 30
`VALUE' = 50
This will become:
| def some_function(arg1, arg2, arg3=10, new_arg=30, arg4='some string'):
| return [arg1, arg2, arg3, arg4]
|
| some_function(1, 2, 3, 50, 'four') # [1]
Note that references to the function also have their function
call normalised. See [1], where the explicit keyword reference
was removed in favour of a positional reference. See
`traad-normalize-arguments' for more information.
Arguments are always added as keyword arguments. Rope does not
discriminate based on position, so you can add keyword arguments
out-of-order. For example, back to the original function:
| def some_function(arg1, arg2, arg3=10, arg4='some string'):
| return [arg1, arg2, arg3, arg4]
|
| some_function(1, 2, arg3=3, arg4='four')
Adding the same argument as before at `INDEX' = 1, this will
become:
| def some_function(arg1, new_arg=30, arg2, arg3=10, arg4='some string'):# [1]
| return [arg1, arg2, arg3, arg4]
|
| some_function(1, 50, 2, 3, 'four')
Watch line [1]. Note that the sequence argument `arg2` now
appears after `new_arg`, a keyword argument, so the function
signature is no longer valid.
"
(interactive
(list
(read-number "Index: ")
(read-string "Name: ")
(read-string "Default: ")
(read-string "Value: ")))
(traad--fetch-perform-refresh
(buffer-file-name)
"/refactor/add_argument"
:data (list (cons "arg_index" index)
(cons "name" name)
(cons "default" default)
(cons "value" value)
(cons "path" (buffer-file-name))
(cons "offset" (traad--adjust-point (point))))))
;;;###autoload
(defun traad-inline ()
"Inline this object (replace the object with the thing it represents.)
Inlining can be performed on many objects.
Functions:
Inlining a function replaces calls to a function with the
explicit code the function executes. For example:
| def do_something():
| print sys.version
| return C()
Inlining `do_something`, becomes:
| print sys.version
| return C()
Methods, etc. can also be inlined. For example:
| class C(object):
| var = 1
|
| def f(self, p): # [1]
| result = self.var + pn # [1]
| return result # [1]
|
| c = C()
| x = c.f(1) # [2]
Inlining `C.f`, becomes:
| class C(object):
| var = 1
|
| c = C()
| result = c.var + pn # [2]
| x = result # [2]
Parameters:
Inlning a parameter passes the default value of a keyword
parameter whenever the parameter is not explicitly referenced.
For example:
| def f(p1=1, p2=2):
| pass
|
| f(3, 2)
| f() # [1]
| f(3) # [2]
| f(p1=5, p2=7) # [3]
Inlining `p2`, becomes:
| def f(p1=1, p2=2):
| pass
|
| f(3, 2)
| f(p2=2) # [1]
| f(3, 2) # [2]
| f(5, 7) # [3]
[1] and [2] have had explicit calls to the keyword argument
added. Note that:
- It prefers positional over keyword calls.
- It also normalizes the arguments, so [3] is affected. See
`traad-normalize-arguments' for more information.
"
(interactive)
(traad--fetch-perform-refresh
(buffer-file-name)
"/refactor/inline"
:data (list
(cons "path" (buffer-file-name))
(cons "offset" (traad--adjust-point (point))))))
;;;###autoload
(defun traad-introduce-parameter (parameter)
"Introduce a parameter in a function.
This extracts a hard-coded value in a function, and introduces it
as a parameter. An example may be clearer. Let's say we have:
| def multiply(value):
| result = value * 2
| return result
|
| my_var = multiply(10)
Let's call `traad-introduce-parameter' when the cursor is on '2'
and with `PARAMETER' = \"multiplier\". It will become:
| def multiply(value, multiplier=2):
| result = value * 2
| return result
|
| my_var = multiply(10)
"
(interactive
(list
(read-string "Parameter: ")))
(traad--fetch-perform-refresh
(buffer-file-name)
"/refactor/introduce_parameter"
:data (list
(cons "path" (buffer-file-name))
(cons "offset" (traad--adjust-point (point)))
(cons "parameter" parameter))))
;;;###autoload
(defun traad-encapsulate-field ()
"Introduce getters and setters and use them instad of references.
For example:
| class MyClass(object):
| def __init__(self):
| self.my_var = 1
|
| my_class = MyClass()
| print(my_class.my_var) # [1]
| my_class.my_var = 5 # [2]
Note that [1] is a get operation. [2] is a set operation.
Encapsulating the field `MyClass.my_var` this becomes:
| class MyClass(object):
| def __init__(self):
| self.my_var = 1
|
| def get_my_var(self):
| return self.my_var
|
| def set_my_var(self, value):
| self.my_var = value
|
| my_class = MyClass()
| print(my_class.get_my_var()) # [1]
| my_class.set_my_var(5) # [2]
Note that [1] and [2] have had the getters and setters inserted
automatically.
"
(interactive)
(traad--fetch-perform-refresh
(buffer-file-name)
"/refactor/encapsulate_field"
:data (list
(cons "path" (buffer-file-name))
(cons "offset" (traad--adjust-point (point))))))
;;;###autoload
(defun traad-local-to-field ()
"Turns a local variable into a field variable.
In other words, toggles the 'self' keyword or similar. Some
examples may be clearer.
Let's say we have:
| class MyClass(object):
| def __init__(self):
| some_var = 1
| another_var = some_var * 2
Calling `local-to-field' on `some_var`, it becomes:
| class MyClass(object):
| def __init__(self):
| self.some_var = 1
| another_var = self.some_var * 2
Note that the refactoring is only performed on the variable in
scope, not on other occurrences of the name. For example, if we
have:
| class MyClass(object):
| def __init__(self):
| some_var = 1
| another_var = some_var * 2
|
| def do_something(self):
| some_var = 200
Calling `local-to-field' on `some_var`, it becomes:
| class MyClass(object):
| def __init__(self):
| self.some_var = 1
| another_var = self.some_var * 2
|
| def do_something(self):
| some_var = 200
"
(interactive)
(traad--fetch-perform-refresh
(buffer-file-name)
"/refactor/local_to_field"
:data (list
(cons "path" (buffer-file-name))
(cons "offset" (traad--adjust-point (point))))))
;;;###autoload
(defun traad-use-function ()
"Tries to find the places in which a function can be used and
changes the code to call it instead.
For example, let's say we have the following code:
| def square(p):
| return p ** 2
|
| my_var = 3 ** 2 # [1]
|
| another_var = 4 ** 2 # [2]
Performing 'use function' on `square`, becomes: