Truncate text to fit within max_width, adding ellipsis if needed. Args: text: Text to truncate (ANSI codes are preserved but not counted) max_width: Maximum visible width in terminal columns ellipsis: Ellipsis character to use (default: "…") Returns: Truncat
(text: str, max_width: int, ellipsis: str = "…")
| 69 | |
| 70 | |
| 71 | def truncate_with_ellipsis(text: str, max_width: int, ellipsis: str = "…") -> str: |
| 72 | """Truncate text to fit within max_width, adding ellipsis if needed. |
| 73 | |
| 74 | Args: |
| 75 | text: Text to truncate (ANSI codes are preserved but not counted) |
| 76 | max_width: Maximum visible width in terminal columns |
| 77 | ellipsis: Ellipsis character to use (default: "…") |
| 78 | |
| 79 | Returns: |
| 80 | Truncated text with ellipsis if needed |
| 81 | |
| 82 | Examples: |
| 83 | >>> truncate_with_ellipsis("Hello World", 8) |
| 84 | 'Hello W…' |
| 85 | >>> truncate_with_ellipsis("你好世界", 5) |
| 86 | '你好…' |
| 87 | """ |
| 88 | if max_width <= 0: |
| 89 | return "" |
| 90 | |
| 91 | current_width = calculate_display_width(text) |
| 92 | |
| 93 | # No truncation needed |
| 94 | if current_width <= max_width: |
| 95 | return text |
| 96 | |
| 97 | # Remove ANSI codes for truncation (we'll lose color, but that's expected) |
| 98 | plain_text = ANSI_ESCAPE_RE.sub("", text) |
| 99 | |
| 100 | # If max_width is too small for ellipsis |
| 101 | ellipsis_width = calculate_display_width(ellipsis) |
| 102 | if max_width <= ellipsis_width: |
| 103 | return plain_text[:max_width] |
| 104 | |
| 105 | # Find truncation point |
| 106 | available_width = max_width - ellipsis_width |
| 107 | truncated = "" |
| 108 | current_width = 0 |
| 109 | |
| 110 | for char in plain_text: |
| 111 | char_width = calculate_display_width(char) |
| 112 | if current_width + char_width > available_width: |
| 113 | break |
| 114 | truncated += char |
| 115 | current_width += char_width |
| 116 | |
| 117 | return truncated + ellipsis |
| 118 | |
| 119 | |
| 120 | def pad_to_width(text: str, target_width: int, align: str = "left", fill_char: str = " ") -> str: |