File tree Expand file tree Collapse file tree 2 files changed +45
-2
lines changed Expand file tree Collapse file tree 2 files changed +45
-2
lines changed Original file line number Diff line number Diff line change @@ -79,6 +79,24 @@ To terminate the loop early, throw 'break."
79
79
(string= keyword2 " from" )
80
80
(string= mod1 mod2))))
81
81
82
+ (defun pyimport--insert-from-symbol (symbol )
83
+ " When point is a on an import line, add SYMBOL."
84
+ ; ; Assumes the current line is of the form 'from foo import bar, baz'.
85
+
86
+ ; ; Step past the 'from '.
87
+ (goto-char (line-beginning-position ))
88
+ (while (not (looking-at " import " ))
89
+ (forward-char 1 ))
90
+ (forward-char (length " import " ))
91
+
92
+ (insert
93
+ (->> (delete-and-extract-region (point ) (line-end-position ))
94
+ (s-split " , " )
95
+ (cons symbol)
96
+ (-sort #'string< )
97
+ (-uniq)
98
+ (s-join " , " ))))
99
+
82
100
(defun pyimport--insert-import (line )
83
101
" Insert LINE, a python import statement, in the current buffer."
84
102
(let* ((current-lines (pyimport--import-lines (current-buffer )))
@@ -87,9 +105,8 @@ To terminate the loop early, throw 'break."
87
105
; ; Find the first matching line, and append there
88
106
(pyimport--for-each-line
89
107
(when (pyimport--same-module (pyimport--current-line) line)
90
- (goto-char (point-at-eol ))
91
108
(-let [(_ _module _ name) (s-split " " line)]
92
- (insert " , " name))
109
+ (pyimport-- insert-from-symbol name))
93
110
; ; Break from this loop.
94
111
(throw 'break nil )))
95
112
Original file line number Diff line number Diff line change 117
117
(setq result-lines (nreverse result-lines))
118
118
(should
119
119
(equal result-lines '(" a" " b" " c" " d" )))))
120
+
121
+ (ert-deftest insert-import-simple ()
122
+ " Test inserting an import."
123
+ (with-temp-buffer
124
+ (pyimport--insert-import " from foo import x" )
125
+ (should
126
+ (equal (buffer-string )
127
+ " from foo import x\n " ))))
128
+
129
+ (ert-deftest insert-import-with-existing ()
130
+ " Test inserting an import when we already have imports from that module."
131
+ (with-temp-buffer
132
+ (insert " from foo import x\n " )
133
+ (pyimport--insert-import " from foo import y" )
134
+ (should
135
+ (equal (buffer-string )
136
+ " from foo import x, y\n " ))))
137
+
138
+ (ert-deftest insert-import-duplicate ()
139
+ " Test inserting an import when we already have that symbol imported"
140
+ (with-temp-buffer
141
+ (insert " from foo import x\n " )
142
+ (pyimport--insert-import " from foo import x" )
143
+ (should
144
+ (equal (buffer-string )
145
+ " from foo import x\n " ))))
You can’t perform that action at this time.
0 commit comments