Skip to content

[BUG] set_cell_size returns incorrect result for negative total with narrow text #4211

Description

@DaerenKim

Describe the bug

set_cell_size() returns incorrectly truncated text when total is negative and the input consists entirely of single-cell-width characters.

For example:

from rich.cells import set_cell_size

print(repr(set_cell_size("ab", -1)))
print(repr(set_cell_size("abc", -1)))
print(repr(set_cell_size("abcdef", -1)))

Currently this produces:

'a'
'ab'
'abcde'

Expected:

''
''
''

The issue is caused by the total <= 0 guard being placed after the single-cell-width fast path:

if _is_single_cell_widths(text):
    size = len(text)
    if size < total:
        return text + " " * (total - size)
    return text[:total]

if total <= 0:
    return ""

For single-cell-width strings, negative slicing is therefore reached before the guard. Python's negative slicing causes part of the string to be returned.

For comparison, strings containing wide characters correctly return an empty string because they do not take the single-cell-width fast path.

The fix is to move the total <= 0 check before the _is_single_cell_widths() fast path.

I have also added regression tests covering negative total values.

Platform

  • macOS
  • Python 3.13.6

The issue is reproducible independently of terminal software.

I have already implemented the fix and added regression tests in my fork. I would be happy to submit the changes as a pull request if I can be granted contributor access, or I can follow whatever contribution process you prefer.

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions