From ded0fb172c89c4532b4d9c168b588a1a890d5d4b 2019-05-10 22:37:40 From: Robin Gustafsson Date: 2019-05-10 22:37:40 Subject: [PATCH] Remove leading empty lines When running a cell, the leading indentation on the first line is removed from all of the cell's lines. This causes indentation errors on subsequent lines in case the first line consists entirely of whitespace matching a valid level of indentation that is greater than the least indented line. This change avoids the issue by first removing any leading, whitespace-only lines. Closes #11594 --- diff --git a/IPython/core/inputtransformer2.py b/IPython/core/inputtransformer2.py index 0bf22a1..04f4232 100644 --- a/IPython/core/inputtransformer2.py +++ b/IPython/core/inputtransformer2.py @@ -18,6 +18,19 @@ import warnings _indent_re = re.compile(r'^[ \t]+') +def leading_empty_lines(lines): + """Remove leading empty lines + + If the leading lines are empty or contain only whitespace, they will be + removed. + """ + if not lines: + return lines + for i, line in enumerate(lines): + if line and not line.isspace(): + return lines[i:] + return lines + def leading_indent(lines): """Remove leading indentation. @@ -510,6 +523,7 @@ class TransformerManager: """ def __init__(self): self.cleanup_transforms = [ + leading_empty_lines, leading_indent, classic_prompt, ipython_prompt, diff --git a/IPython/core/tests/test_inputtransformer2_line.py b/IPython/core/tests/test_inputtransformer2_line.py index 13a18d2..102f449 100644 --- a/IPython/core/tests/test_inputtransformer2_line.py +++ b/IPython/core/tests/test_inputtransformer2_line.py @@ -86,3 +86,31 @@ def test_leading_indent(): for sample, expected in [INDENT_SPACES, INDENT_TABS]: nt.assert_equal(ipt2.leading_indent(sample.splitlines(keepends=True)), expected.splitlines(keepends=True)) + +LEADING_EMPTY_LINES = ("""\ + \t + +if True: + a = 3 + +b = 4 +""", """\ +if True: + a = 3 + +b = 4 +""") + +ONLY_EMPTY_LINES = ("""\ + \t + +""", """\ + \t + +""") + +def leading_empty_lines(): + for sample, expected in [LEADING_EMPTY_LINES, ONLY_EMPTY_LINES]: + nt.assert_equal( + ipt2.leading_empty_lines(sample.splitlines(keepends=True)), + expected.splitlines(keepends=True))