python / python/cpython

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

オープン
#154,686 コメント 1 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

stdlib type-feature
主要言語
Python
スター
77.2k
フォーク
35.9k
PR マージ指標
PR 指標を取得中

説明

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

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

まず PR #152702 の実装と、issue #142035 および #154634 の関連する議論を確認します。textwrap.wrap、fill、shorten、TextWrapper にまたがる提案された text_len パラメーターを比較し、作業完了とみなす前に、表示幅のユースケースと既存の動作がカバーされていることを確認します。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
python
領域
backend
issue の種類
機能追加
難易度
5/5
見積もり時間
1週間以上
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
25/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。