diff --git a/Lib/test/test_textwrap.py b/Lib/test/test_textwrap.py index 707aaaa274a..a44184fbc77 100644 --- a/Lib/test/test_textwrap.py +++ b/Lib/test/test_textwrap.py @@ -748,6 +748,11 @@ def test_dedent_preserve_margin_tabs(self): expect = "hello there\n how are you?" self.assertEqual(expect, dedent(text)) + # test margin is smaller than smallest indent + text = " \thello there\n \thow are you?\n \tI'm fine, thanks" + expect = " \thello there\n \thow are you?\n\tI'm fine, thanks" + self.assertEqual(expect, dedent(text)) + # Test textwrap.indent class IndentTestCase(unittest.TestCase): diff --git a/Lib/textwrap.py b/Lib/textwrap.py index 3ad3e18ea89..05e030673a6 100644 --- a/Lib/textwrap.py +++ b/Lib/textwrap.py @@ -444,11 +444,15 @@ def dedent(text): elif margin.startswith(indent): margin = indent - # Current line and previous winner have no common whitespace: - # there is no margin. + # Find the largest common whitespace between current line and previous + # winner. else: - margin = "" - break + for i, (x, y) in enumerate(zip(margin, indent)): + if x != y: + margin = margin[:i] + break + else: + margin = margin[:len(indent)] # sanity check (testing/debugging only) if 0 and margin: diff --git a/Misc/ACKS b/Misc/ACKS index b6089fdaac1..f8fcccf6113 100644 --- a/Misc/ACKS +++ b/Misc/ACKS @@ -847,6 +847,7 @@ Mark Levitt Ivan Levkivskyi William Lewis Akira Li +Robert Li Xuanji Li Robert van Liere Ross Light diff --git a/Misc/NEWS b/Misc/NEWS index 7e7534da507..638964ec361 100644 --- a/Misc/NEWS +++ b/Misc/NEWS @@ -45,6 +45,10 @@ Core and Builtins Library ------- +- Issue #21827: Fixed textwrap.dedent() for the case when largest common + whitespace is a substring of smallest leading whitespace. + Based on patch by Robert Li. + - Issue #25447: The lru_cache() wrapper objects now can be copied and pickled (by returning the original object unchanged).