python / python/cpython

Add `text_len` to `TextWrapper` for ANSI and variable character width awareness

Open
#154,686 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

stdlib type-feature
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

Description

Feature or enhancement

Proposal:

This is a proposal to add a text_len parameter to textwrap.wrap, textwrap.fill, textwrap.shorten and textwrap.TextWrapper.

That way we can teach these functions how to measure the length of visible text.

The main use-case is ignoring ANSI sequences like so:

>>> import re, textwrap
>>> visible_len = lambda s: len(re.sub(r'\x1b\[[0-9;]*m', '', s))
>>> colored = 'normal \x1b[31mcolored\x1b[0m words here'
>>> lines = textwrap.wrap(colored, width=14, text_len=visible_len)
>>> [re.sub(r'\x1b\[[0-9;]*m', '', line) for line in lines]
['normal colored', 'words here']

This allow flexibility without having to maintain or introduce full ANSI awareness to all the string-manipulating utilities.

And I am pretty sure some users can come up with creative usage other than ANSI, and it provides a future escape-hatch.

An implementation is available at #152702

Has this already been discussed elsewhere?

I have already discussed this feature proposal on Discourse

Links to previous discussion of this feature:

This is a direct follow up on https://github.com/python/cpython/issues/142035 , which introduced a local patch in _split_lines via https://github.com/python/cpython/pull/154634 to address that bug. A new issue has been requested by a project member to track the generalization of that local patch.

Linked PRs
  • gh-152702

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reviewing the implementation in PR #152702 and the related discussion in issues #142035 and #154634. Compare the proposed text_len parameter across textwrap.wrap, fill, shorten, and TextWrapper, then verify that the visible-width use case and existing behavior are covered before considering the work done.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
backend
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.