Skip to content

Commit 4f40703

Browse files
committed
fix for split cells
1 parent 6607492 commit 4f40703

File tree

2 files changed

+25
-23
lines changed

2 files changed

+25
-23
lines changed

rich/segment.py

+15-18
Original file line numberDiff line numberDiff line change
@@ -129,34 +129,31 @@ def _split_cells(cls, segment: "Segment", cut: int) -> Tuple["Segment", "Segment
129129

130130
cell_size = get_character_cell_size
131131

132-
pos = int((cut / cell_length) * (len(text))) - 1
133-
if pos < 0:
134-
pos = 0
132+
pos = int((cut / cell_length) * len(text))
135133

136-
before = text[:pos]
137-
cell_pos = cell_len(before)
138-
if cell_pos == cut:
139-
return (
140-
_Segment(before, style, control),
141-
_Segment(text[pos:], style, control),
142-
)
143-
while pos < len(text):
144-
char = text[pos]
145-
pos += 1
146-
cell_pos += cell_size(char)
134+
while True:
147135
before = text[:pos]
148-
if cell_pos == cut:
136+
cell_pos = cell_len(before)
137+
out_by = cell_pos - cut
138+
if not out_by:
149139
return (
150140
_Segment(before, style, control),
151141
_Segment(text[pos:], style, control),
152142
)
153-
if cell_pos > cut:
143+
if out_by == -1 and cell_size(text[pos]) == 2:
144+
return (
145+
_Segment(before[:pos] + " ", style, control),
146+
_Segment(" " + text[pos + 1 :], style, control),
147+
)
148+
if out_by == +1 and cell_size(text[pos]) == 2:
154149
return (
155150
_Segment(before[: pos - 1] + " ", style, control),
156151
_Segment(" " + text[pos:], style, control),
157152
)
158-
159-
raise AssertionError("Will never reach here")
153+
if cell_pos < cut:
154+
pos += 1
155+
else:
156+
pos -= 1
160157

161158
def split_cells(self, cut: int) -> Tuple["Segment", "Segment"]:
162159
"""Split segment in to two segments at the specified column.

tests/test_segment.py

+10-5
Original file line numberDiff line numberDiff line change
@@ -288,11 +288,16 @@ def test_split_cells_emoji(text, split, result):
288288
def test_split_cells_mixed() -> None:
289289
"""Check that split cells splits on cell positions."""
290290
# Caused https://github.com/Textualize/textual/issues/4996 in Textual
291-
test = Segment("早乙女リリエル (CV: 徳井青)")
292-
for position in range(1, test.cell_length):
293-
left, right = Segment.split_cells(test, position)
294-
assert cell_len(left.text) == position
295-
assert cell_len(right.text) == test.cell_length - position
291+
tests = [
292+
Segment("早乙女リリエル (CV: 徳井青)"),
293+
Segment("メイド・イン・きゅんクチュアリ☆"),
294+
Segment("TVアニメ「メルクストーリア -無気力少年と瓶の中の少女-」 主題歌CD"),
295+
]
296+
for test in tests:
297+
for position in range(1, test.cell_length):
298+
left, right = Segment.split_cells(test, position)
299+
assert cell_len(left.text) == position
300+
assert cell_len(right.text) == test.cell_length - position
296301

297302

298303
def test_split_cells_doubles() -> None:

0 commit comments

Comments
 (0)