Skip to content

Comments

Fix infinite loop when ANSI escape sequences appear at string start#3963

Closed
veeceey wants to merge 1 commit intoTextualize:masterfrom
veeceey:fix/issue-3958-ansi-infinite-loop
Closed

Fix infinite loop when ANSI escape sequences appear at string start#3963
veeceey wants to merge 1 commit intoTextualize:masterfrom
veeceey:fix/issue-3958-ansi-infinite-loop

Conversation

@veeceey
Copy link

@veeceey veeceey commented Feb 8, 2026

Summary

Fixes #3958

When strings with ANSI escape sequences at the start were printed using console.print(), the program would hang in an infinite loop. This was a critical bug introduced in version 14.3.2.

Root Cause

The issue was in split_graphemes() in rich/cells.py:

  1. ANSI escape characters (\x1b) have zero cell width
  2. Zero-width characters are normally associated with the previous character
  3. When no previous character exists (at string start), the index wasn't incremented
  4. This caused an infinite loop in the while loop at line 182

Changes

  • Added an else clause to handle zero-width characters when spans is empty
  • When there's no previous character to associate with, skip the zero-width character
  • Added test test_ansi_at_start() to verify the fix

Test plan

  • Added regression test that verifies no infinite loop occurs
  • All existing cell tests pass
  • Manual testing with the exact strings from the issue report confirms they now print without hanging

Before

from rich.console import Console

Console().print('\x1b[38;5;249mi\x1b[0m')  # Hangs forever

After

from rich.console import Console

Console().print('\x1b[38;5;249mi\x1b[0m')  # Prints successfully

When strings with ANSI escape sequences at the start were printed, split_graphemes()
would enter an infinite loop. This happened because:

1. ANSI escape characters (\x1b) have zero cell width
2. Zero-width characters are normally associated with the previous character
3. When no previous character exists (at string start), the index wasn't incremented
4. This caused an infinite loop in the while loop

Fixed by adding an else clause to skip zero-width characters when there is no
previous character to associate them with.

Fixes Textualize#3958
@TomJGooding
Copy link
Contributor

I notice you also opened #3959 for the same issue. Was this PR created by mistake?

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] Strings with ANSI escape sequences can cause Console.print() to hang

2 participants