diff --git a/IPython/lib/pretty.py b/IPython/lib/pretty.py index 36d7824..2fee84c 100644 --- a/IPython/lib/pretty.py +++ b/IPython/lib/pretty.py @@ -229,7 +229,17 @@ class PrettyPrinter(_PrettyPrinterBase): self.buffer.append(Breakable(sep, width, self)) self.buffer_width += width self._break_outer_groups() - + + def break_(self): + """ + Explicitly insert a newline into the output, maintaining correct indentation. + """ + self.flush() + self.output.write(self.newline) + self.output.write(' ' * self.indentation) + self.output_width = self.indentation + self.buffer_width = 0 + def begin_group(self, indent=0, open=''): """ @@ -478,8 +488,12 @@ def _default_pprint(obj, p, cycle): """ klass = getattr(obj, '__class__', None) or type(obj) if getattr(klass, '__repr__', None) not in _baseclass_reprs: - # A user-provided repr. - p.text(repr(obj)) + # A user-provided repr. Find newlines and replace them with p.break_() + output = repr(obj) + for idx,output_line in enumerate(output.splitlines()): + if idx: + p.break_() + p.text(output_line) return p.begin_group(1, '<') p.pretty(klass) diff --git a/IPython/lib/tests/test_pretty.py b/IPython/lib/tests/test_pretty.py index 689ae48..2e0aaab 100644 --- a/IPython/lib/tests/test_pretty.py +++ b/IPython/lib/tests/test_pretty.py @@ -58,6 +58,23 @@ class NoModule(object): NoModule.__module__ = None +class Breaking(object): + def _repr_pretty_(self, p, cycle): + with p.group(4,"TG: ",":"): + p.text("Breaking(") + p.break_() + p.text(")") + +class BreakingRepr(object): + def __repr__(self): + return "Breaking(\n)" + +class BreakingReprParent(object): + def _repr_pretty_(self, p, cycle): + with p.group(4,"TG: ",":"): + p.pretty(BreakingRepr()) + + def test_indentation(): """Test correct indentation in groups""" @@ -118,3 +135,19 @@ def test_pprint_nomod(): """ output = pretty.pretty(NoModule) nt.assert_equal(output, 'NoModule') + +def test_pprint_break(): + """ + Test that p.break_ produces expected output + """ + output = pretty.pretty(Breaking()) + expected = "TG: Breaking(\n ):" + nt.assert_equal(output, expected) + +def test_pprint_break_repr(): + """ + Test that p.break_ is used in repr + """ + output = pretty.pretty(BreakingReprParent()) + expected = "TG: Breaking(\n ):" + nt.assert_equal(output, expected) \ No newline at end of file