wijjit.terminal.ansi.wrap_text

wijjit.terminal.ansi.wrap_text(text, width)[source]

Wrap a single line of text into multiple segments based on width.

This function wraps text to the specified width while preserving ANSI escape codes. It uses smart word boundary detection to break at spaces, hyphens, and punctuation when possible, falling back to hard breaks at width boundaries when no suitable break point is found.

Parameters:
  • text (str) – Text to wrap (may contain ANSI escape codes)

  • width (int) – Maximum width for each segment

Returns:

List of wrapped text segments, preserving ANSI codes

Return type:

list of str

Notes

  • Empty text returns a single empty string segment

  • Text shorter than width returns as-is in a single-element list

  • ANSI escape codes are preserved and don’t count toward visible length

  • Smart word boundary detection prefers breaking at spaces, then hyphens, then punctuation marks

  • Falls back to hard break at width if no boundary found

Examples

Basic wrapping without ANSI codes:

>>> wrap_text("Hello world this is a test", 10)
['Hello ', 'world this', ' is a test']

Wrapping with ANSI codes (codes are preserved):

>>> from wijjit.terminal.ansi import ANSIColor
>>> text = f"{ANSIColor.RED}Hello{ANSIColor.RESET} world"
>>> segments = wrap_text(text, 8)
>>> # ANSI codes preserved, visible length respected

Empty or short text:

>>> wrap_text("", 10)
['']
>>> wrap_text("Short", 10)
['Short']