Skip to content

Commit d0d77c5

Browse files
committed
Don't get confused by multiline strings that look like imports
1 parent ecfac02 commit d0d77c5

File tree

3 files changed

+26
-2
lines changed

3 files changed

+26
-2
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
unsaved or not visiting a file.
77
* `pyimport-insert-missing` now steps over shebangs when choosing
88
where to insert new imports.
9+
* Fixed an issue with `pyimport-insert-missing` using the contents of
10+
multiline strings that looked like imports.
911

1012
## v1.0
1113

pyimport.el

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,9 +46,22 @@
4646
"Return non-nil if the current line is the last in the buffer."
4747
(looking-at (rx (0+ not-newline) buffer-end)))
4848

49+
(defun pyimport--in-string-p ()
50+
"Return non-nil if point is inside a string."
51+
(nth 3 (syntax-ppss)))
52+
4953
(defun pyimport--buffer-lines (buffer)
50-
(with-current-buffer buffer
51-
(s-split "\n" (buffer-string))))
54+
"Return all the lines in BUFFER, ignoring lines that are within a string."
55+
(let (lines)
56+
(with-current-buffer buffer
57+
(save-excursion
58+
(goto-char (point-min))
59+
(unless (pyimport--in-string-p)
60+
(push (pyimport--current-line) lines))
61+
(while (zerop (forward-line 1))
62+
(unless (pyimport--in-string-p)
63+
(push (pyimport--current-line) lines)))))
64+
(nreverse lines)))
5265

5366
(defun pyimport--import-lines (buffer)
5467
"Return all the lines in this Python BUFFER that look like imports."

test/pyimport-test.el

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,3 +185,12 @@
185185
(equal
186186
(pyimport--extract-simple-import "import foo as bar" "bar")
187187
"import foo as bar")))
188+
189+
(ert-deftest pyimport-buffer-lines ()
190+
"We should ignore multiline strings, as they may not contain valid imports."
191+
(let (lines)
192+
(with-temp-buffer
193+
(insert "x = \"\"\"\nfrom foo\n\"\"\"\n")
194+
(setq lines (pyimport--buffer-lines (current-buffer))))
195+
(should (not
196+
(-contains-p lines "from foo")))))

0 commit comments

Comments
 (0)