Skip to content

gh-158979: Fix textwrap hang when an indent is longer than width - #160559

Closed
devdavidejesus wants to merge 1 commit into
python:mainfrom
devdavidejesus:fix-textwrap-indent-hang
Closed

devdavidejesus wants to merge 1 commit into
python:mainfrom
devdavidejesus:fix-textwrap-indent-hang

Conversation

@devdavidejesus

@devdavidejesus devdavidejesus commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

When initial_indent or subsequent_indent is longer than width, the room left on the line is negative. _handle_long_word() can then leave an empty chunk, which never satisfies cur_len + l <= width, so _wrap_chunks() looped forever. This happens when the text starts with whitespace (long initial_indent), or with drop_whitespace=False (long subsequent_indent). Zero-length chunks are now always accepted; they add nothing to the line, and this matches what already happens when the room is exactly 0.

Tested on macOS with a debug build of main: the new test hangs without the change and passes with it, and test_textwrap passes.

See #160558.

When initial_indent or subsequent_indent was longer than width,
_handle_long_word() could leave an empty chunk that never fit on the
line, and _wrap_chunks() looped forever.  Always accept zero-length
chunks; they add nothing to the line.
@StanFromIreland StanFromIreland changed the title gh-160558: Fix textwrap hang when an indent is longer than width gh-158979: Fix textwrap hang when an indent is longer than width Oct 24, 2026
@devdavidejesus

Copy link
Copy Markdown
Contributor Author

Closing in favor of #158988, which was opened earlier for gh-158979, the same bug as gh-160558. It fixes the cause in _handle_long_word() instead of working around the empty chunk, and it also avoids the extra indent-only last line that this PR still produces: textwrap.wrap('aaaa', 3, subsequent_indent='----', drop_whitespace=False) gives ['aaa', '----a', '----'] here and ['aaa', '----a'] there.

I checked #158988 with the cases from this PR: they all return, and test_textwrap passes. Sorry for the duplicate; I missed the earlier issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant