Show More
@@ -138,6 +138,36 b' def extract_symbols(code, symbols):' | |||
|
138 | 138 | |
|
139 | 139 | return blocks, not_found |
|
140 | 140 | |
|
141 | def strip_initial_indent(lines): | |
|
142 | """For %load, strip indent from lines until finding an unindented line. | |
|
143 | ||
|
144 | https://github.com/ipython/ipython/issues/9775 | |
|
145 | """ | |
|
146 | indent_re = re.compile(r'\s+') | |
|
147 | ||
|
148 | it = iter(lines) | |
|
149 | first_line = next(it) | |
|
150 | indent_match = indent_re.match(first_line) | |
|
151 | ||
|
152 | if indent_match: | |
|
153 | # First line was indented | |
|
154 | indent = indent_match.group() | |
|
155 | yield first_line[len(indent):] | |
|
156 | ||
|
157 | for line in it: | |
|
158 | if line.startswith(indent): | |
|
159 | yield line[len(indent):] | |
|
160 | else: | |
|
161 | # Less indented than the first line - stop dedenting | |
|
162 | yield line | |
|
163 | break | |
|
164 | else: | |
|
165 | yield first_line | |
|
166 | ||
|
167 | # Pass the remaining lines through without dedenting | |
|
168 | for line in it: | |
|
169 | yield line | |
|
170 | ||
|
141 | 171 | |
|
142 | 172 | class InteractivelyDefined(Exception): |
|
143 | 173 | """Exception for interactively defined variable in magic_edit""" |
@@ -341,7 +371,7 b' class CodeMagics(Magics):' | |||
|
341 | 371 | lines = contents.split('\n') |
|
342 | 372 | slices = extract_code_ranges(ranges) |
|
343 | 373 | contents = [lines[slice(*slc)] for slc in slices] |
|
344 | contents = '\n'.join(chain.from_iterable(contents)) | |
|
374 | contents = '\n'.join(strip_initial_indent(chain.from_iterable(contents))) | |
|
345 | 375 | |
|
346 | 376 | l = len(contents) |
|
347 | 377 |
@@ -1000,3 +1000,12 b' def test_ls_magic():' | |||
|
1000 | 1000 | j = json_formatter(lsmagic) |
|
1001 | 1001 | nt.assert_equal(sorted(j), ['cell', 'line']) |
|
1002 | 1002 | nt.assert_equal(w, []) # no warnings |
|
1003 | ||
|
1004 | def test_strip_initial_indent(): | |
|
1005 | def sii(s): | |
|
1006 | lines = s.splitlines() | |
|
1007 | return '\n'.join(code.strip_initial_indent(lines)) | |
|
1008 | ||
|
1009 | nt.assert_equal(sii(" a = 1\nb = 2"), "a = 1\nb = 2") | |
|
1010 | nt.assert_equal(sii(" a\n b\nc"), "a\n b\nc") | |
|
1011 | nt.assert_equal(sii("a\n b\n"), "a\n b\n") |
General Comments 0
You need to be logged in to leave comments.
Login now