makeover-tui 0.68.0

The terminal renderer for makeover-layout, on ratatui. Colour stops being the constraint above 256 entries; geometry never does, because an edge occupies a whole cell on every side.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
//! Words into cells.
//!
//! One wrap, read by [`height`] and [`draw`] and by their span and line
//! forms, so the rows a paragraph is measured at are the rows it draws in.
//!
//! Width is counted in terminal cells, the way ratatui draws: a CJK glyph or
//! an emoji takes two, a combining mark none. A word too wide for its line is
//! cut on grapheme clusters.

use std::borrow::Cow;

use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::Style;
use ratatui::text::{Line, Span};
use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthStr;

/// The cells `text` takes on a terminal, as this module's wrap measures it.
#[must_use]
pub fn cells(text: &str) -> usize {
    text.width()
}

/// `set_stringn`, where the starting cell lands inside the buffer; a start
/// outside it draws nothing. Past the right edge `set_stringn` clips.
fn put(buf: &mut Buffer, x: u16, y: u16, text: &str, width: usize, style: Style) {
    if buf.area().contains(ratatui::layout::Position { x, y }) {
        buf.set_stringn(x, y, text, width, style);
    }
}

/// The longest prefix of `word` that fits in `width` cells, as its byte
/// length and the cells it takes.
///
/// Cut on grapheme clusters, not `char`s, so a variation selector, a keycap, a
/// ZWJ family or a pair of regional indicators stays whole. With `first`, at
/// least one grapheme, so a glyph wider than the whole line is taken on its
/// own; without, a glyph that does not fit is left for the next row. A
/// zero-width mark after the last glyph that fits stays with it.
fn fitting(word: &str, width: usize, first: bool) -> (usize, usize) {
    let mut used = 0;
    let mut end = 0;
    for grapheme in word.graphemes(true) {
        let wide = grapheme.width();
        if used + wide > width && (end > 0 || !first) {
            break;
        }
        used += wide;
        end += grapheme.len();
    }
    (end, used)
}

/// Where the wrap put one run of text: its row and column, in cells, and the
/// slice and style to draw there.
///
/// Borrowed from the spans the wrap was handed; only [`wrap_spans`], which
/// hands lines back, copies the text.
struct Placed<'s> {
    row: usize,
    column: usize,
    text: &'s str,
    style: Style,
}

/// Walk `spans` as they wrap at `width`, handing each placed run to `place`,
/// and answer how many rows the wrap took.
///
/// Breaks on whitespace, and inside a word only when the word cannot fit on a
/// line of its own; such a word is cut to the width. Every public wrap,
/// measure and draw in this module is this with a different `place`.
///
/// A word is a run of non-whitespace, and it runs on across a span boundary:
/// two spans that adjoin with no whitespace between them draw adjoining, as
/// ratatui draws a [`Line`]. Each word that is not first on its row gets one
/// space before it, styled as the whitespace it replaced. A newline in the
/// whitespace starts a new row.
fn walk<'s>(spans: &'s [Span<'_>], width: u16, mut place: impl FnMut(Placed<'s>)) -> usize {
    if width == 0 {
        return 0;
    }
    let mut wrap = Wrap {
        width: width as usize,
        row: 0,
        column: 0,
        placed: false,
        separator: None,
    };
    // The word being gathered, one piece per span it crosses, and its cells.
    // One buffer for the whole walk, cleared per word.
    let mut word: Vec<(&'s str, Style)> = Vec::new();
    let mut wide = 0usize;

    for span in spans {
        let mut rest: &'s str = span.content.as_ref();
        while !rest.is_empty() {
            let gap = rest
                .find(|c: char| !c.is_whitespace())
                .unwrap_or(rest.len());
            if gap > 0 {
                wrap.word(&word, wide, &mut place);
                word.clear();
                wide = 0;
                // Authored breaks are breaks. A description that put a newline
                // in a string meant it, and rewrapping across it would join two
                // paragraphs.
                let breaks = rest[..gap].matches('\n').count();
                if breaks > 0 {
                    wrap.row += breaks;
                    wrap.column = 0;
                }
                // The style of the whitespace, held until a word turns up to
                // need a separator before it. Kept rather than taken from the
                // word, because the space between `*lean*` and `~~gone~~`
                // belongs to the plain run that held it: a strikethrough that
                // starts one cell early is drawn through a space the author
                // never struck.
                wrap.separator = Some(span.style);
                rest = &rest[gap..];
                continue;
            }
            let end = rest.find(char::is_whitespace).unwrap_or(rest.len());
            let (piece, after) = rest.split_at(end);
            rest = after;
            word.push((piece, span.style));
            wide += cells(piece);
        }
    }
    wrap.word(&word, wide, &mut place);

    // Nothing to say is no rows rather than one blank one, so a node with an
    // empty string costs nothing. A blank line inside a paragraph survives,
    // because that one was authored.
    if wrap.row == 0 && !wrap.placed {
        0
    } else {
        wrap.row + 1
    }
}

/// Where [`walk`] has got to.
struct Wrap {
    width: usize,
    row: usize,
    column: usize,
    /// Whether anything landed on the first row, for the rule at the end.
    placed: bool,
    /// The style of the whitespace last passed over.
    separator: Option<Style>,
}

impl Wrap {
    /// Lay one word, `pieces` in order and `wide` cells in all. An empty word
    /// lays nothing.
    fn word<'s>(
        &mut self,
        pieces: &[(&'s str, Style)],
        mut wide: usize,
        place: &mut impl FnMut(Placed<'s>),
    ) {
        let Some((&(mut head, mut style), mut tail)) = pieces.split_first() else {
            return;
        };

        // A word too long for any line, cut to fit rather than overflowed.
        //
        // The word's width is measured once and each cut's subtracted, so a
        // long unbroken word costs its length and not its length times the
        // number of rows it takes.
        while wide > self.width {
            if self.column > 0 {
                self.row += 1;
                self.column = 0;
            }
            // One glyph wider than the whole line, and nothing after it:
            // placed below like any word that fits, so it does not also leave
            // a blank row behind it.
            if tail.is_empty() && fitting(head, self.width, true).0 == head.len() {
                break;
            }
            let mut used = 0usize;
            loop {
                let (cut, taken) = fitting(head, self.width - used, used == 0);
                if cut > 0 {
                    place(Placed {
                        row: self.row,
                        column: used,
                        text: &head[..cut],
                        style,
                    });
                    used += taken;
                    wide = wide.saturating_sub(taken);
                    head = &head[cut..];
                }
                if !head.is_empty() || used >= self.width {
                    break;
                }
                let Some((&(next, next_style), rest)) = tail.split_first() else {
                    break;
                };
                head = next;
                style = next_style;
                tail = rest;
            }
            self.row += 1;
            if head.is_empty() {
                let Some((&(next, next_style), rest)) = tail.split_first() else {
                    return;
                };
                head = next;
                style = next_style;
                tail = rest;
            }
        }

        // A glyph wider than the whole line leaves `column` past `width`, so
        // the room after it is none rather than a negative.
        let room = self.width.saturating_sub(self.column);
        let wanted = wide + usize::from(self.column > 0);
        if wanted > room && self.column > 0 {
            self.row += 1;
            self.column = 0;
        }
        // Leading whitespace on a line is the wrap's own business and not the
        // author's, so a separator is drawn only between two words that ended
        // up on the same row.
        if self.column > 0 {
            place(Placed {
                row: self.row,
                column: self.column,
                text: " ",
                style: self.separator.unwrap_or(style),
            });
            self.column += 1;
        }
        self.separator = None;
        for (text, style) in std::iter::once((head, style)).chain(tail.iter().copied()) {
            place(Placed {
                row: self.row,
                column: self.column,
                text,
                style,
            });
            self.column += cells(text);
        }
        self.placed = true;
    }
}

/// Break `spans` into lines no wider than `width`, keeping each word under the
/// style it arrived with.
///
/// The wrap collected into lines, for a caller that wants them. Measuring and
/// drawing go through [`spans_height`] and [`draw_spans`], which allocate
/// nothing per word.
pub fn wrap_spans(spans: &[Span<'_>], width: u16) -> Vec<Line<'static>> {
    let mut lines: Vec<Vec<Span<'static>>> = Vec::new();
    let rows = walk(spans, width, |placed| {
        if lines.len() <= placed.row {
            lines.resize_with(placed.row + 1, Vec::new);
        }
        lines[placed.row].push(Span::styled(placed.text.to_string(), placed.style));
    });
    lines.resize_with(rows, Vec::new);
    lines.into_iter().map(Line::from).collect()
}

/// Break `text` into lines no wider than `width`.
///
/// [`wrap_spans`] under one style, flattened back to strings for the callers
/// that have no styles to keep.
pub fn wrap(text: &str, width: u16) -> Vec<String> {
    let mut lines: Vec<String> = Vec::new();
    let spans = [Span::raw(text)];
    let rows = walk(&spans, width, |placed| {
        if lines.len() <= placed.row {
            lines.resize_with(placed.row + 1, String::new);
        }
        lines[placed.row].push_str(placed.text);
    });
    lines.resize_with(rows, String::new);
    lines
}

/// The rows `text` takes at `width`.
pub fn height(text: &str, width: u16) -> u16 {
    spans_height(&[Span::raw(text)], width)
}

/// The rows `spans` take at `width`, wrapped as a block.
pub fn spans_height(spans: &[Span<'_>], width: u16) -> u16 {
    u16::try_from(walk(spans, width, |_| {})).unwrap_or(u16::MAX)
}

/// Draw wrapped text at the top of `area`, and answer the rows it used.
pub fn draw(text: &str, style: Style, area: Rect, buf: &mut Buffer) -> u16 {
    draw_spans(&[Span::styled(text, style)], area, buf)
}

/// Draw wrapped spans at the top of `area`, and answer the rows they used.
///
/// Whitespace between words collapses to one space, styled as the whitespace
/// it replaced; a newline in it starts a new row. Two spans that adjoin with
/// no whitespace between them draw adjoining, as one word. Each run is clipped
/// to `area`.
pub fn draw_spans(spans: &[Span<'_>], area: Rect, buf: &mut Buffer) -> u16 {
    let rows = walk(spans, area.width, |placed| {
        let (Ok(row), Ok(column)) = (u16::try_from(placed.row), u16::try_from(placed.column))
        else {
            return;
        };
        let room = area.width.saturating_sub(column) as usize;
        if row >= area.height || room == 0 {
            return;
        }
        put(
            buf,
            area.x.saturating_add(column),
            area.y.saturating_add(row),
            placed.text,
            room,
            placed.style,
        );
    });
    u16::try_from(rows).unwrap_or(u16::MAX).min(area.height)
}

/// Draw a line of spans at the top of `area`, wrapping onto further rows.
///
/// [`draw_spans`] over `line.spans`, with its spacing: adjoining spans draw
/// adjoining, so `Line::from(vec!["[".into(), "ok".into(), "]".into()])`
/// draws as `[ok]`, the cells ratatui gives the same line.
pub fn draw_line(line: &Line<'_>, area: Rect, buf: &mut Buffer) -> u16 {
    draw_spans(&line.spans, area, buf)
}

/// The rows a line of spans takes at `width`.
pub fn line_height(line: &Line<'_>, width: u16) -> u16 {
    spans_height(&line.spans, width)
}

/// Whether `c` is a bidi control that makes the text after it read backwards.
///
/// U+202A-U+202E are embeddings and overrides, U+2066-U+2069 the isolates, all
/// zero-width.
fn is_bidi(c: char) -> bool {
    matches!(c, '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}')
}

/// [`Line`] with the bidi controls stripped from every span.
///
/// The controls are zero-width, so stripping them changes no width.
pub(crate) fn sanitise(line: Line<'_>) -> Line<'_> {
    let mut line = line;
    for span in &mut line.spans {
        if span.content.chars().any(is_bidi) {
            span.content = Cow::Owned(span.content.chars().filter(|c| !is_bidi(*c)).collect());
        }
    }
    line
}

#[cfg(test)]
mod tests {
    use super::*;
    use ratatui::style::Modifier;

    #[test]
    fn a_paragraph_wraps_on_words_and_counts_the_rows_it_took() {
        // The two halves that have to agree. A height that disagreed with the
        // drawing by one row is a node drawing over the one under it.
        assert_eq!(wrap("the quick brown fox", 10), ["the quick", "brown fox"]);
        assert_eq!(height("the quick brown fox", 10), 2);
    }

    #[test]
    fn nothing_to_say_costs_no_rows_rather_than_one_blank_one() {
        assert_eq!(height("", 10), 0);
        let found = wrap("", 10);
        assert!(found.is_empty(), "{found:?}");
        // A width of zero is a region with no room, not a division to do.
        let found = wrap("anything", 0);
        assert!(found.is_empty(), "{found:?}");
    }

    #[test]
    fn an_authored_break_is_a_break() {
        // A description that put a newline in a string meant it, and rewrapping
        // across it would join two paragraphs.
        assert_eq!(wrap("one\ntwo", 20), ["one", "two"]);
    }

    #[test]
    fn a_word_wider_than_the_region_is_cut_rather_than_overflowed() {
        // The case with no good answer. Cutting is the least bad one: the
        // alternative is a line wider than the region and a buffer that
        // swallows the overflow silently.
        assert_eq!(
            wrap("supercalifragilistic", 6),
            ["superc", "alifra", "gilist", "ic"]
        );
    }

    #[test]
    fn the_space_between_two_runs_belongs_to_the_run_that_held_it() {
        // A strikethrough that starts one cell early is drawn through a space
        // the author never struck. This is why the separator's style is kept
        // rather than taken from the word after it.
        let struck = Style::new().add_modifier(Modifier::CROSSED_OUT);
        let spans = [Span::raw("lean "), Span::styled("gone", struck)];
        let lines = wrap_spans(&spans, 20);
        assert_eq!(lines.len(), 1);
        let separator = lines[0]
            .spans
            .iter()
            .find(|span| span.content.as_ref() == " ")
            .expect("a separator between the two words");
        assert!(!separator.style.add_modifier.contains(Modifier::CROSSED_OUT));
    }

    #[test]
    fn a_drawing_stops_at_the_bottom_of_the_area_it_was_given() {
        // Never below the rect, which is what a terminal does with everything.
        let mut buf = Buffer::empty(Rect::new(0, 0, 10, 2));
        let used = draw(
            "the quick brown fox jumps over",
            Style::new(),
            buf.area,
            &mut buf,
        );
        assert_eq!(used, 2);
    }

    #[test]
    fn a_wide_glyph_takes_two_cells_and_nothing_is_lost() {
        // Fourteen cells. Counted as seven chars it fit in one line of eight,
        // and ratatui then cut the second half off at the edge.
        let lines = wrap("日本語テキスト", 8);
        assert_eq!(lines, ["日本語テ", "キスト"]);
        assert_eq!(height("日本語テキスト", 8), 2);
        assert_eq!(lines.concat(), "日本語テキスト");

        // Drawn, every glyph lands, and nothing is left for set_stringn to cut.
        let area = Rect::new(0, 0, 8, 2);
        let mut buf = Buffer::empty(area);
        assert_eq!(draw("日本語テキスト", Style::default(), area, &mut buf), 2);
        let row = |y: u16| {
            (0..8)
                .map(|x| buf[(x, y)].symbol().to_string())
                .collect::<String>()
        };
        assert_eq!(row(0).replace(' ', ""), "日本語テ");
        assert_eq!(row(1).replace(' ', ""), "キスト");
    }

    #[test]
    fn a_glyph_wider_than_the_line_is_taken_alone_rather_than_looped_on() {
        assert_eq!(wrap("設定", 1), ["設", "定"]);
    }

    #[test]
    fn a_word_after_a_glyph_wider_than_the_line_starts_a_new_one() {
        // The over-wide glyph leaves the column past the width, and the room
        // after it is none: the next word goes below instead of subtracting
        // past zero.
        assert_eq!(wrap("\u{4e2d} a", 1), ["\u{4e2d}", "a"]);
        assert_eq!(height("\u{4e2d} a", 1), 2);
        assert_eq!(
            wrap("\u{4e2d}\u{6587} ab", 1),
            ["\u{4e2d}", "\u{6587}", "a", "b"]
        );
    }

    #[test]
    fn an_accent_is_never_cut_from_its_letter() {
        // `e` and a combining acute: one cell, two chars.
        let accented = "cafe\u{301}s";
        assert_eq!(wrap(accented, 4), ["cafe\u{301}", "s"]);
    }

    #[test]
    fn a_grapheme_cluster_is_cut_as_a_unit_and_not_through_its_chars() {
        // A per-char cut measured each VS16 heart one cell, so three fit a
        // four-cell line: one six-cell line that ratatui clipped. As graphemes
        // they are two cells each, two to a line.
        let hearts = "\u{2764}\u{fe0f}\u{2764}\u{fe0f}\u{2764}\u{fe0f}";
        assert_eq!(
            wrap(hearts, 4),
            ["\u{2764}\u{fe0f}\u{2764}\u{fe0f}", "\u{2764}\u{fe0f}"]
        );
        // A keycap is the same shape: a digit, VS16 and U+20E3 are one two-cell
        // grapheme, not the one cell a per-char count gives them.
        let keys = "1\u{fe0f}\u{20e3}2\u{fe0f}\u{20e3}3\u{fe0f}\u{20e3}";
        assert_eq!(
            wrap(keys, 3),
            [
                "1\u{fe0f}\u{20e3}",
                "2\u{fe0f}\u{20e3}",
                "3\u{fe0f}\u{20e3}"
            ]
        );
        // Counted per char the whole keycap word was three cells, so it went out
        // on one line six cells wide. Every line now fits the region.
        for line in wrap(keys, 3) {
            assert!(cells(&line) <= 3, "line {line:?} is wider than the region");
        }
    }

    #[test]
    fn a_zwj_family_and_a_flag_pair_are_not_split_between_their_chars() {
        // man ZWJ woman ZWJ girl: one two-cell grapheme. A per-char cut broke it
        // mid-cluster, counting each emoji and joiner on its own.
        let family = "\u{1f468}\u{200d}\u{1f469}\u{200d}\u{1f467}";
        let two = format!("{family}{family}");
        assert_eq!(wrap(&two, 3), [family, family]);
        // A family wider than the whole line is taken alone, never split.
        assert_eq!(wrap(family, 1), [family]);
        // A regional-indicator pair is one two-cell grapheme; a lone indicator
        // counted as one cell orphaned the second half of the pair.
        assert_eq!(
            wrap("\u{1f1fa}\u{1f1f8}\u{1f1ec}\u{1f1e7}", 3),
            ["\u{1f1fa}\u{1f1f8}", "\u{1f1ec}\u{1f1e7}"]
        );
    }

    #[test]
    fn spans_after_a_wide_glyph_start_where_it_ends() {
        let area = Rect::new(0, 0, 10, 1);
        let mut buf = Buffer::empty(area);
        // One word across two spans: 設定 is cells 0-3 and `x` cell 4. Counted
        // in chars it landed on cell 2, over the second glyph.
        let spans = [Span::raw("設定"), Span::raw("x")];
        draw_spans(&spans, area, &mut buf);
        assert_eq!(buf[(4, 0)].symbol(), "x");
        // Across whitespace, two words and a separator: `y` takes cell 5.
        let spans = [Span::raw("設定 "), Span::raw("y")];
        draw_spans(&spans, area, &mut buf);
        assert_eq!(buf[(5, 0)].symbol(), "y");
    }

    #[test]
    fn a_word_across_spans_wraps_as_one_word_and_is_cut_as_one() {
        // The word goes below whole rather than leaving its bracket behind.
        let spans = [
            Span::raw("abc "),
            Span::raw("["),
            Span::raw("ok"),
            Span::raw("]"),
        ];
        let lines: Vec<String> = wrap_spans(&spans, 5)
            .iter()
            .map(|line| line.spans.iter().map(|s| s.content.as_ref()).collect())
            .collect();
        assert_eq!(lines, ["abc", "[ok]"]);
        // Too wide for any line, it is cut across its pieces, each keeping
        // its style.
        let bold = Style::new().add_modifier(Modifier::BOLD);
        let spans = [Span::raw("ab"), Span::styled("cdef", bold), Span::raw("g")];
        let lines = wrap_spans(&spans, 3);
        let text: Vec<String> = lines
            .iter()
            .map(|line| line.spans.iter().map(|s| s.content.as_ref()).collect())
            .collect();
        assert_eq!(text, ["abc", "def", "g"]);
        assert_eq!(spans_height(&spans, 3), 3);
        assert_eq!(lines[1].spans[0].style, bold);
        assert_eq!(lines[2].spans[0].style, Style::new());
    }

    #[test]
    fn drawing_outside_the_buffer_loses_the_overshoot_and_not_the_process() {
        let mut buf = Buffer::empty(Rect::new(0, 0, 4, 2));
        for area in [
            Rect::new(0, 1, 4, 5),
            Rect::new(3, 0, 10, 1),
            Rect::new(9, 9, 4, 4),
        ] {
            draw("one two three", Style::default(), area, &mut buf);
            draw_spans(&[Span::raw("one two")], area, &mut buf);
        }
    }

    #[test]
    fn a_bidi_override_is_stripped_from_every_span() {
        // U+202E flips what follows it, so "x\u{202e}" reads as something else
        // in a bidi-aware terminal. The table hands a name straight to
        // ratatui's Table, past the zero-width filter set_stringn applies, so
        // the strip is here and not in the buffer.
        let line = sanitise(Line::from("x\u{202e}"));
        assert_eq!(line.spans[0].content.as_ref(), "x");

        let line = sanitise(Line::from(vec![
            Span::raw("a\u{202a}b"),
            Span::raw("c\u{2069}d"),
        ]));
        assert_eq!(line.spans[0].content.as_ref(), "ab");
        assert_eq!(line.spans[1].content.as_ref(), "cd");
    }

    #[test]
    fn a_line_without_bidi_controls_passes_through_unchanged() {
        // The usual name has nothing to strip and must not pay an allocation
        // for the check: the span keeps its borrowed content.
        let line = sanitise(Line::from("plain"));
        assert!(matches!(
            line.spans[0].content,
            std::borrow::Cow::Borrowed("plain")
        ));
    }

    #[test]
    fn repro_adjoining_spans_get_separator() {
        // A token is three spans, bracket, label, bracket, and takes the label
        // and two cells, as ratatui draws the same line.
        let line = Line::from(vec![Span::raw("["), Span::raw("ok"), Span::raw("]")]);
        let area = Rect::new(0, 0, 10, 1);
        let mut buf = Buffer::empty(area);
        assert_eq!(draw_line(&line, area, &mut buf), 1);
        let row: String = (0..10).map(|x| buf[(x, 0)].symbol().to_string()).collect();
        assert_eq!(row.trim_end(), "[ok]");
        assert_eq!(cells(row.trim_end()), line.width());
        // Each piece keeps its own style.
        let bold = Style::new().add_modifier(Modifier::BOLD);
        let line = Line::from(vec![
            Span::raw("["),
            Span::styled("ok", bold),
            Span::raw("]"),
        ]);
        let mut buf = Buffer::empty(area);
        draw_line(&line, area, &mut buf);
        assert!(buf[(1, 0)].modifier.contains(Modifier::BOLD));
        assert!(!buf[(0, 0)].modifier.contains(Modifier::BOLD));
        assert!(!buf[(3, 0)].modifier.contains(Modifier::BOLD));
    }
}