Get the cell length of a string (length as it appears in the terminal). Args: text: String to measure. unicode_version: Unicode version, `"auto"` to auto detect, `"latest"` for the latest unicode version. Returns: Length of string in terminal cells.
(text: str, unicode_version: str)
| 111 | |
| 112 | |
| 113 | def _cell_len(text: str, unicode_version: str) -> int: |
| 114 | """Get the cell length of a string (length as it appears in the terminal). |
| 115 | |
| 116 | Args: |
| 117 | text: String to measure. |
| 118 | unicode_version: Unicode version, `"auto"` to auto detect, `"latest"` for the latest unicode version. |
| 119 | |
| 120 | Returns: |
| 121 | Length of string in terminal cells. |
| 122 | """ |
| 123 | |
| 124 | if _is_single_cell_widths(text): |
| 125 | return len(text) |
| 126 | |
| 127 | # "\u200d" is zero width joiner |
| 128 | # "\ufe0f" is variation selector 16 |
| 129 | if "\u200d" not in text and "\ufe0f" not in text: |
| 130 | # Simplest case with no unicode stuff that changes the size |
| 131 | return sum( |
| 132 | get_character_cell_size(character, unicode_version) for character in text |
| 133 | ) |
| 134 | |
| 135 | cell_table = load_cell_table(unicode_version) |
| 136 | total_width = 0 |
| 137 | last_measured_character: str | None = None |
| 138 | |
| 139 | SPECIAL = {"\u200d", "\ufe0f"} |
| 140 | |
| 141 | index = 0 |
| 142 | character_count = len(text) |
| 143 | |
| 144 | while index < character_count: |
| 145 | character = text[index] |
| 146 | if character in SPECIAL: |
| 147 | if character == "\u200d": |
| 148 | index += 1 |
| 149 | elif last_measured_character: |
| 150 | total_width += last_measured_character in cell_table.narrow_to_wide |
| 151 | last_measured_character = None |
| 152 | else: |
| 153 | if character_width := get_character_cell_size(character, unicode_version): |
| 154 | last_measured_character = character |
| 155 | total_width += character_width |
| 156 | index += 1 |
| 157 | |
| 158 | return total_width |
| 159 | |
| 160 | |
| 161 | def split_graphemes( |
no test coverage detected