abstracttui 0.3.7

A reactive, compositor-grade terminal UI engine: fine-grained signals, layered rendering with damage tracking, images (kitty/iTerm2/sixel/mosaic), software-rasterized 3D (GLB), themes and animation.
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
//! CodeView: a read-only, syntax-highlighted code pane — and the ONE
//! place lexer token kinds become theme colors.
//!
//! ```ignore
//! use abstracttui::widgets::CodeView;
//! let view = CodeView::new(source_text)
//!     .lang("rust")
//!     .scroll_offset(top_line.get())
//!     .element(&t)
//!     .build();
//! ```
//!
//! [`code_token_color`] maps `text::TokenKind` onto the theme's derived
//! `syntax_*` inks (doc §1.4a): lexers never mint colors, themes never
//! know lexers. `Ident` deliberately renders as body `text` — the
//! built-in lexer cannot split types from functions; the `syntax_type` /
//! `syntax_func` inks stand ready for richer lexers (mapping documented
//! there, not invented per widget).
//!
//! [`diff_token_color`] is the diff twin (backlog 0140's additive
//! slice): `text::DiffKind` onto the SEMANTIC inks — added `ok`,
//! removed `error`, hunk headers `info`, chrome `text_muted` — so a
//! patch scans red/green in every theme without any theme knowing diff.
//! `CodeView::lang("diff")` and diff-labeled markdown fences both route
//! through it (one mapping, no drift).
//!
//! Chrome: code sits on `surface_raised` (the audited code ground), line
//! numbers right-aligned in `text_faint` with a `border` separator.
//!
//! OWNER: DESIGN.

use std::rc::Rc;

use crate::base::{Point, Rgba};
use crate::layout::Style as LayoutStyle;
use crate::render::rich::{RichLine, Span};
use crate::render::{Attrs, Style};
use crate::text::{
    CLikeLexer, DataKind, DiffKind, DiffLexer, Highlighter, JsonLexer, TokenKind, YamlLexer,
};
use crate::theme::TokenSet;
use crate::ui::Element;

/// The theming of syntax: token kind -> derived theme ink (§1.4a).
pub fn code_token_color(kind: TokenKind, t: &TokenSet) -> Rgba {
    match kind {
        TokenKind::Keyword => t.syntax_keyword,
        TokenKind::String => t.syntax_string,
        TokenKind::Number => t.syntax_number,
        TokenKind::Comment => t.syntax_comment,
        TokenKind::Punct => t.syntax_punct,
        // Identifiers are body ink: the C-like lexer cannot tell types
        // from functions; syntax_type/syntax_func await a lexer that can.
        TokenKind::Ident => t.text,
    }
}

/// The theming of diffs: diff line kind -> theme ink, beside
/// [`code_token_color`] so kinds become colors in exactly one place.
/// Semantic inks, not syntax inks: added/removed are *state* ("this
/// changed"), so they ride `ok`/`error` — the tokens every theme already
/// audits — never a hue a diff invents.
pub fn diff_token_color(kind: DiffKind, t: &TokenSet) -> Rgba {
    match kind {
        DiffKind::Added => t.ok,
        DiffKind::Removed => t.error,
        DiffKind::HunkHeader => t.info,
        DiffKind::FileHeader => t.text,
        DiffKind::Meta => t.text_muted,
        DiffKind::Context => t.text,
        // DiffKind is #[non_exhaustive]; in-crate this match stays
        // exhaustive so the compiler walks every new kind through here,
        // but FOREIGN matches need a `_` arm — document theirs as body
        // text (never invisible).
    }
}

/// The theming of structured data (wave 13): [`DataKind`] -> theme
/// ink, beside its two siblings so kinds become colors in exactly one
/// place. Keys ride `syntax_func` (a key is a member NAME — the ink
/// [`code_token_color`]'s docs held ready for a richer lexer) and YAML
/// tags/anchors ride `syntax_type` (type annotations by grammar);
/// literals are the grammar's reserved words (`syntax_keyword`);
/// strings/numbers/comments/punctuation match the code mapping.
/// `DataKind` is `#[non_exhaustive]`; FOREIGN matches need a `_` arm —
/// render unknown kinds as body text (never invisible).
pub fn data_token_color(kind: DataKind, t: &TokenSet) -> Rgba {
    match kind {
        DataKind::Key => t.syntax_func,
        DataKind::String => t.syntax_string,
        DataKind::Number => t.syntax_number,
        DataKind::Literal => t.syntax_keyword,
        DataKind::Comment => t.syntax_comment,
        DataKind::Punct => t.syntax_punct,
        DataKind::Tag => t.syntax_type,
        // In-crate the match stays exhaustive so the compiler walks
        // every new kind through here.
    }
}

/// One diff line -> themed spans: the crate-shared recipe both
/// `CodeView` (lang "diff") and diff-labeled markdown fences render
/// through, mirroring `RichLine::from_highlighted`'s gap-filling
/// contract. File
/// headers additionally carry BOLD (the anchor a reader scans for);
/// everything else is ink-only.
pub(crate) fn diff_rich_line(line: &str, lexer: &DiffLexer, base: Style, t: &TokenSet) -> RichLine {
    let mut out = RichLine::new();
    let mut cursor = 0;
    for (range, kind) in lexer.spans(line) {
        if range.start > cursor {
            out.push(Span::new(&line[cursor..range.start], base));
        }
        let mut style = Style::new().fg(diff_token_color(kind, t));
        if kind == DiffKind::FileHeader {
            style = style.attrs(Attrs::BOLD);
        }
        out.push(Span::new(&line[range.clone()], style));
        cursor = range.end;
    }
    if cursor < line.len() {
        out.push(Span::new(&line[cursor..], base));
    }
    out
}

/// One JSON/YAML line -> themed spans (the gap-filling recipe, data
/// vocabulary): the crate-shared path for `CodeView` lang
/// `"json"`/`"yaml"` and the same-labeled markdown fences.
pub(crate) fn data_rich_line(
    line: &str,
    spans: Vec<(std::ops::Range<usize>, DataKind)>,
    base: Style,
    t: &TokenSet,
) -> RichLine {
    let mut out = RichLine::new();
    let mut cursor = 0;
    for (range, kind) in spans {
        if range.start > cursor {
            out.push(Span::new(&line[cursor..range.start], base));
        }
        out.push(Span::new(
            &line[range.clone()],
            Style::new().fg(data_token_color(kind, t)),
        ));
        cursor = range.end;
    }
    if cursor < line.len() {
        out.push(Span::new(&line[cursor..], base));
    }
    out
}

/// How a `CodeView` tints lines: a token lexer behind the
/// [`Highlighter`] seam, the line-oriented diff lexer, or a
/// structured-data lexer (different span vocabularies, so different
/// arms — see `text::diff` and `text::data`).
enum Tinter {
    Syntax(Rc<dyn Highlighter>),
    Diff(DiffLexer),
    Json(JsonLexer),
    Yaml(YamlLexer),
}

/// A syntax-tinted code block on the raised code ground: line-lexed
/// highlighting through the theme's `syntax_*` tokens, with optional
/// line numbers and wrap-or-clip control.
///
/// [`lang`](CodeView::lang) picks the lexer by name — including
/// `"diff"` (added/removed/hunk/meta lines onto `ok`/`error`/`info`/
/// muted inks — the review surface) and `"json"`/`"yaml"` (the
/// structured-data lexers: keys/literals/strings/numbers/comments onto
/// the `syntax_*` inks through [`data_token_color`]). The view carries
/// an intrinsic measure (lines × gutter+longest-line), so
/// `Scroll::new(view)` scrolls the true extent on both axes out of the
/// box. The canonical build is `.view(cx)`; see the
/// [module docs](crate::widgets::code).
pub struct CodeView {
    source: String,
    tinter: Tinter,
    line_numbers: bool,
    scroll_offset: i32,
    layout: Option<LayoutStyle>,
}

impl CodeView {
    pub fn new(source: impl Into<String>) -> CodeView {
        CodeView {
            source: source.into(),
            tinter: Tinter::Syntax(Rc::new(CLikeLexer::default())),
            line_numbers: true,
            scroll_offset: 0,
            layout: None,
        }
    }

    /// Swap the lexer (language modes; the default is the C-like demo
    /// lexer).
    pub fn lexer(mut self, lexer: impl Highlighter + 'static) -> CodeView {
        self.tinter = Tinter::Syntax(Rc::new(lexer));
        self
    }

    /// Pick the built-in lexer by language label (best effort, the same
    /// labels markdown fences carry): `"diff"`/`"patch"`/`"udiff"` route
    /// to the diff lexer ([`diff_token_color`] inks),
    /// `"json"`/`"jsonc"`/`"json5"`/`"jsonl"`/`"ndjson"` and
    /// `"yaml"`/`"yml"` route to the structured-data lexers
    /// ([`data_token_color`] inks, wave 13), `"c"` picks the C
    /// [`CLikeLexer`] preset, anything else keeps the default C-like
    /// lexer — unknown labels never change today's rendering.
    pub fn lang(mut self, label: &str) -> CodeView {
        let first = label.split_whitespace().next().unwrap_or("");
        self.tinter = if DiffLexer::matches_lang(first) {
            Tinter::Diff(DiffLexer::new())
        } else if JsonLexer::matches_lang(first) {
            Tinter::Json(JsonLexer::new())
        } else if YamlLexer::matches_lang(first) {
            Tinter::Yaml(YamlLexer::new())
        } else if first.eq_ignore_ascii_case("c") {
            Tinter::Syntax(Rc::new(CLikeLexer::c()))
        } else {
            // "rust"/"rs" and unknown labels: the rust-preset default.
            Tinter::Syntax(Rc::new(CLikeLexer::default()))
        };
        self
    }

    pub fn line_numbers(mut self, on: bool) -> CodeView {
        self.line_numbers = on;
        self
    }

    /// First visible source line (app-managed scrolling, clamped).
    pub fn scroll_offset(mut self, lines: i32) -> CodeView {
        self.scroll_offset = lines.max(0);
        self
    }

    pub fn layout(mut self, layout: LayoutStyle) -> CodeView {
        self.layout = Some(layout);
        self
    }

    /// Total source lines — the app's scroll clamp.
    pub fn line_count(source: &str) -> usize {
        source.lines().count()
    }

    /// Canonical one-call build: tokens resolve from the app's theme
    /// context (a tracked read — building inside a `dyn_view`
    /// re-renders on theme switch). `element(&tokens)` remains the
    /// explicit-theming door.
    pub fn view(self, cx: crate::reactive::Scope) -> crate::ui::View {
        let t = crate::widgets::theme_tokens(cx);
        self.element(&t).build()
    }

    pub fn element(self, t: &TokenSet) -> Element {
        let tokens = *t;
        let ground = t.surface_raised;
        let gutter_fg = t.text_faint;
        let rule_fg = t.border;
        let base = Style::new().fg(t.text);
        let tinter = self.tinter;
        let line_numbers = self.line_numbers;
        let offset = self.scroll_offset as usize;
        let lines: Vec<String> = self.source.lines().map(|s| s.to_string()).collect();
        // basis 0 beside grow: leftover space in definite flex parents,
        // exactly the pre-measure geometry (the 0240 modal-overflow
        // class; same default as `Scroll` and `MarkdownView`).
        let layout = self.layout.unwrap_or_else(|| {
            LayoutStyle::default()
                .grow(1.0)
                .basis(crate::layout::Dimension::Cells(0))
        });

        // The measure seam (wave 13): code never wraps, so the
        // intrinsic answer is static — height = source lines, width =
        // gutter + the longest line (char-per-cell, the draw's v1 width
        // model). `Scroll::new(view)` reads the true extent on both
        // axes (horizontal panning of long lines included).
        let total = lines.len();
        let natural_w = {
            let gutter = if line_numbers { digits(total) + 3 } else { 0 };
            let longest = lines
                .iter()
                .map(|l| l.chars().count() as i32)
                .max()
                .unwrap_or(0);
            gutter + longest
        };

        Element::new()
            .style(layout)
            .measure(move |avail| {
                if avail.w <= 0 {
                    return crate::base::Size::ZERO;
                }
                crate::base::Size::new(natural_w.min(avail.w), total as i32)
            })
            .draw(move |canvas, rect| {
                if rect.w <= 0 || rect.h <= 0 {
                    return;
                }
                canvas.fill(rect, ' ', tokens.text, ground);
                let total = lines.len();
                let gutter_w = if line_numbers {
                    (digits(total) + 1).min(rect.w - 2)
                } else {
                    0
                };
                let offset = offset.min(total.saturating_sub(1));
                for (row, line) in lines.iter().skip(offset).enumerate() {
                    let y = rect.y + row as i32;
                    if y >= rect.bottom() {
                        break;
                    }
                    let mut x = rect.x;
                    if gutter_w > 0 {
                        let num = format!("{:>w$} ", offset + row + 1, w = (gutter_w - 1) as usize);
                        x += canvas.print(Point::new(x, y), &num, gutter_fg, ground);
                        canvas.put(Point::new(x, y), '│', rule_fg, ground);
                        x += 2;
                    }
                    let rich = match &tinter {
                        Tinter::Syntax(lexer) => {
                            RichLine::from_highlighted(line, &**lexer, base, |kind| {
                                Style::new().fg(code_token_color(kind, &tokens))
                            })
                        }
                        Tinter::Diff(lexer) => diff_rich_line(line, lexer, base, &tokens),
                        Tinter::Json(lexer) => {
                            data_rich_line(line, lexer.spans(line), base, &tokens)
                        }
                        Tinter::Yaml(lexer) => {
                            data_rich_line(line, lexer.spans(line), base, &tokens)
                        }
                    };
                    for span in &rich.spans {
                        x += crate::widgets::richtext::print_span_clipped(
                            canvas,
                            x,
                            y,
                            rect.right(),
                            &span.text,
                            &span.style,
                        );
                        if x >= rect.right() {
                            break;
                        }
                    }
                }
            })
    }
}

fn digits(n: usize) -> i32 {
    n.max(1).ilog10() as i32 + 1
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::base::Size;
    use crate::theme::default_theme;
    use crate::widgets::test_util::{draw_into, row};

    const SRC: &str = "fn main() {\n    // greet\n    print(\"hi\", 42);\n}";

    /// Cell column of `needle` in a row string — `str::find` returns
    /// BYTE offsets, and gutter glyphs (`│`) are multi-byte: cells are
    /// chars (the bug this helper exists to prevent).
    fn cell_of(row: &str, needle: &str) -> i32 {
        let byte = row.find(needle).unwrap();
        row[..byte].chars().count() as i32
    }

    #[test]
    fn token_kinds_map_to_syntax_inks() {
        let t = default_theme().tokens;
        assert_eq!(code_token_color(TokenKind::Keyword, &t), t.syntax_keyword);
        assert_eq!(code_token_color(TokenKind::String, &t), t.syntax_string);
        assert_eq!(code_token_color(TokenKind::Number, &t), t.syntax_number);
        assert_eq!(code_token_color(TokenKind::Comment, &t), t.syntax_comment);
        assert_eq!(code_token_color(TokenKind::Punct, &t), t.syntax_punct);
        assert_eq!(code_token_color(TokenKind::Ident, &t), t.text);
    }

    #[test]
    fn renders_highlighted_cells_on_the_code_ground() {
        let t = default_theme().tokens;
        let c = draw_into(CodeView::new(SRC).element(&t), Size::new(28, 4));
        // Gutter: right-aligned number in faint + rule.
        assert!(row(&c, 0).starts_with("1 │ fn main"), "{:?}", row(&c, 0));
        assert_eq!(c.cell(Point::new(0, 0)).unwrap().1, t.text_faint);
        assert_eq!(c.cell(Point::new(2, 0)).unwrap().1, t.border);
        // `fn` keyword ink at its cell; ground is surface_raised.
        let (ch, fg, bg) = c.cell(Point::new(4, 0)).unwrap();
        assert_eq!(ch, 'f');
        assert_eq!(fg, t.syntax_keyword);
        assert_eq!(bg, t.surface_raised);
        // Comment line ink.
        let comment_x = cell_of(&row(&c, 1), "//");
        assert_eq!(
            c.cell(Point::new(comment_x, 1)).unwrap().1,
            t.syntax_comment
        );
        // String + number inks on line 3.
        let quote_x = cell_of(&row(&c, 2), "\"");
        assert_eq!(c.cell(Point::new(quote_x, 2)).unwrap().1, t.syntax_string);
        let num_x = cell_of(&row(&c, 2), "42");
        assert_eq!(c.cell(Point::new(num_x, 2)).unwrap().1, t.syntax_number);
    }

    #[test]
    fn scroll_clamps_and_numbers_track() {
        let t = default_theme().tokens;
        let c = draw_into(
            CodeView::new(SRC).scroll_offset(2).element(&t),
            Size::new(24, 2),
        );
        assert!(row(&c, 0).starts_with("3 │"), "{:?}", row(&c, 0));
        // Absurd offset clamps to the last line instead of blanking.
        let c = draw_into(
            CodeView::new(SRC).scroll_offset(999).element(&t),
            Size::new(24, 2),
        );
        assert!(row(&c, 0).starts_with("4 │"), "{:?}", row(&c, 0));
        assert_eq!(CodeView::line_count(SRC), 4);
    }

    const DIFF: &str = "diff --git a/x.rs b/x.rs\n@@ -1,2 +1,2 @@ fn main() {\n-let a = 0;\n+let a = 1;\n context\n\\ No newline at end of file";

    #[test]
    fn diff_kinds_map_to_semantic_inks() {
        let t = default_theme().tokens;
        assert_eq!(diff_token_color(DiffKind::Added, &t), t.ok);
        assert_eq!(diff_token_color(DiffKind::Removed, &t), t.error);
        assert_eq!(diff_token_color(DiffKind::HunkHeader, &t), t.info);
        assert_eq!(diff_token_color(DiffKind::FileHeader, &t), t.text);
        assert_eq!(diff_token_color(DiffKind::Meta, &t), t.text_muted);
        assert_eq!(diff_token_color(DiffKind::Context, &t), t.text);
    }

    #[test]
    fn lang_diff_renders_added_removed_inks_through_the_real_draw_path() {
        let t = default_theme().tokens;
        let c = draw_into(
            CodeView::new(DIFF).lang("diff").element(&t),
            Size::new(36, 6),
        );
        // Meta chrome (diff --git) in muted ink on the code ground.
        let (ch, fg, bg) = c.cell(Point::new(4, 0)).unwrap();
        assert_eq!(ch, 'd');
        assert_eq!(fg, t.text_muted);
        assert_eq!(bg, t.surface_raised);
        // Hunk header in info; its trailing function context in body ink.
        let hunk_x = cell_of(&row(&c, 1), "@@");
        assert_eq!(c.cell(Point::new(hunk_x, 1)).unwrap().1, t.info);
        let fn_x = cell_of(&row(&c, 1), "fn main");
        assert_eq!(c.cell(Point::new(fn_x, 1)).unwrap().1, t.text);
        // Removed line in error ink, added line in ok ink — whole line.
        let minus_x = cell_of(&row(&c, 2), "-let");
        assert_eq!(c.cell(Point::new(minus_x, 2)).unwrap().1, t.error);
        assert_eq!(c.cell(Point::new(minus_x + 6, 2)).unwrap().1, t.error);
        let plus_x = cell_of(&row(&c, 3), "+let");
        assert_eq!(c.cell(Point::new(plus_x, 3)).unwrap().1, t.ok);
        // Context body ink; no-newline marker muted.
        let ctx_x = cell_of(&row(&c, 4), "context");
        assert_eq!(c.cell(Point::new(ctx_x, 4)).unwrap().1, t.text);
        let nn_x = cell_of(&row(&c, 5), "\\ No newline");
        assert_eq!(c.cell(Point::new(nn_x, 5)).unwrap().1, t.text_muted);
    }

    /// Wave 13: the structured-data mapping — kinds become colors in
    /// exactly one place, and the json/yaml lang routes render through
    /// the real draw path with key/value/literal distinction.
    #[test]
    fn data_kinds_map_to_syntax_inks() {
        let t = default_theme().tokens;
        assert_eq!(data_token_color(DataKind::Key, &t), t.syntax_func);
        assert_eq!(data_token_color(DataKind::String, &t), t.syntax_string);
        assert_eq!(data_token_color(DataKind::Number, &t), t.syntax_number);
        assert_eq!(data_token_color(DataKind::Literal, &t), t.syntax_keyword);
        assert_eq!(data_token_color(DataKind::Comment, &t), t.syntax_comment);
        assert_eq!(data_token_color(DataKind::Punct, &t), t.syntax_punct);
        assert_eq!(data_token_color(DataKind::Tag, &t), t.syntax_type);
    }

    #[test]
    fn lang_json_and_yaml_render_key_value_inks_through_the_draw_path() {
        let t = default_theme().tokens;
        let json = "{\n  \"name\": \"Ada\",\n  \"age\": 36\n}";
        let c = draw_into(
            CodeView::new(json)
                .lang("json")
                .line_numbers(false)
                .element(&t),
            Size::new(24, 4),
        );
        let kx = cell_of(&row(&c, 1), "\"name\"");
        let (_, fg, bg) = c.cell(Point::new(kx, 1)).unwrap();
        assert_eq!(fg, t.syntax_func, "json keys ride the member ink");
        assert_eq!(bg, t.surface_raised);
        let vx = cell_of(&row(&c, 1), "\"Ada\"");
        assert_eq!(c.cell(Point::new(vx, 1)).unwrap().1, t.syntax_string);
        let nx = cell_of(&row(&c, 2), "36");
        assert_eq!(c.cell(Point::new(nx, 2)).unwrap().1, t.syntax_number);

        let yaml = "service: web # edge\nready: true\ntag: !!str x";
        let c = draw_into(
            CodeView::new(yaml)
                .lang("yaml")
                .line_numbers(false)
                .element(&t),
            Size::new(26, 3),
        );
        let kx = cell_of(&row(&c, 0), "service");
        assert_eq!(c.cell(Point::new(kx, 0)).unwrap().1, t.syntax_func);
        let cx = cell_of(&row(&c, 0), "# edge");
        assert_eq!(c.cell(Point::new(cx, 0)).unwrap().1, t.syntax_comment);
        let lx = cell_of(&row(&c, 1), "true");
        assert_eq!(c.cell(Point::new(lx, 1)).unwrap().1, t.syntax_keyword);
        let tx = cell_of(&row(&c, 2), "!!str");
        assert_eq!(c.cell(Point::new(tx, 2)).unwrap().1, t.syntax_type);
    }

    #[test]
    fn lang_labels_route_and_unknown_labels_keep_todays_rendering() {
        let t = default_theme().tokens;
        // "rust" and an unknown label both render the keyword ink (the
        // default C-like path — unknown labels change nothing).
        for label in ["rust", "elixir"] {
            let c = draw_into(CodeView::new(SRC).lang(label).element(&t), Size::new(28, 4));
            assert_eq!(c.cell(Point::new(4, 0)).unwrap().1, t.syntax_keyword);
        }
        // A diff label with fence-style extra words still routes.
        let c = draw_into(
            CodeView::new("+x")
                .lang("diff filename=a.patch")
                .line_numbers(false)
                .element(&t),
            Size::new(8, 1),
        );
        assert_eq!(c.cell(Point::new(0, 0)).unwrap().1, t.ok);
    }

    /// Theme honesty for the diff mapping: the inks it borrows (`ok`,
    /// `error`, `info`, `text_muted`) must stay readable on
    /// `surface_raised`, the declared code ground — measured across
    /// every built-in theme, not assumed from the `bg`-anchored audit.
    /// The floor matches the semantic-state class (3.0:1); the failure
    /// message names the theme and measured value.
    #[test]
    fn diff_inks_clear_contrast_on_the_code_ground_in_every_theme() {
        use crate::theme::{contrast_ratio, themes};
        for theme in themes() {
            let t = &theme.tokens;
            for (name, ink) in [
                ("ok", t.ok),
                ("error", t.error),
                ("info", t.info),
                ("text_muted", t.text_muted),
            ] {
                let ratio = contrast_ratio(ink, t.surface_raised);
                assert!(
                    ratio >= 3.0,
                    "{}: diff ink `{name}` measures {ratio:.2}:1 on surface_raised",
                    theme.id
                );
            }
        }
    }

    #[test]
    fn no_gutter_mode_and_tiny_rects() {
        let t = default_theme().tokens;
        let c = draw_into(
            CodeView::new(SRC).line_numbers(false).element(&t),
            Size::new(16, 2),
        );
        assert!(row(&c, 0).starts_with("fn main"), "{:?}", row(&c, 0));
        for size in [Size::new(0, 0), Size::new(2, 1), Size::new(5, 1)] {
            let _ = draw_into(CodeView::new(SRC).element(&t), size);
        }
    }
}