quadraui 0.6.0

Cross-platform Rust UI toolkit: write one AppLogic and run it unmodified on TUI, GTK4 (Linux), macOS, and Windows backends
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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
//! TUI rasteriser for the [`Editor`] primitive.
//!
//! Handles every editor paint category: backgrounds (active /
//! cursorline / DAP-stopped / diff), gutter (BP / git / diagnostics /
//! lightbulb / line numbers), syntax-highlighted text, indent guides,
//! color columns, ghost continuation, diagnostic + spell underlines,
//! bracket-match, selections (primary / multi-cursor / yank-flash),
//! cursor (Block via fg/bg swap, Bar/Underline returned to host),
//! secondary cursors, and AI ghost text.
//!
//! ## Scrollbars
//!
//! The rasteriser internally calls [`super::draw_scrollbar`] for both
//! vertical and horizontal scrollbars when overflow is present.
//! [`draw_editor_with_reserve`] additionally accepts `right_reserve_w`
//! so a host can reserve a strip (a minimap, say) between the text and
//! the vertical scrollbar without moving the scrollbar off the
//! viewport's true right edge.
//!
//! ## Status line
//!
//! The per-window status line is **not** painted by this rasteriser.
//! The host is responsible for reserving a row at the bottom of `area`
//! if `Editor.status_line` would be drawn there. The host should shrink
//! `area` by 1 if a status line is present, call `draw_editor`, then
//! paint the status line at the reserved row.
//!
//! ## Cursor side-effect
//!
//! The TUI [`Frame`](ratatui::Frame) cursor (used by Bar / Underline
//! shapes) is set by calling `Frame::set_cursor_position`. To keep this
//! rasteriser pure-paint, the Bar / Underline cursor *position* is
//! returned via [`EditorPaintResult::cursor_position`]; the host calls
//! `set_cursor_position` after this function returns. Block cursors are
//! painted directly by inverting the buffer cell's fg/bg.

use crate::primitives::editor::{
    CursorShape, DiagnosticSeverity, DiffLine, Editor, EditorLine, EditorSelection, GitLineStatus,
};
use crate::primitives::scrollbar::Scrollbar;
use crate::text_util::{char_col_to_visual, snap_to_char_boundary};
use crate::theme::Theme;
use crate::types::Color;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::{Color as RColor, Modifier};

use super::{qc, set_cell, set_cell_styled};

/// Output of [`draw_editor`] — carries side-effects the host needs
/// to apply *after* the buffer paint completes.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct EditorPaintResult {
    /// Screen-space `(x, y)` for `Frame::set_cursor_position` when the
    /// cursor shape is `Bar` or `Underline`. `None` when the cursor is
    /// off-screen, missing, or in `Block` mode (Block is painted
    /// directly into the buffer via fg/bg inversion).
    pub cursor_position: Option<(u16, u16)>,
}

/// Paint an [`Editor`] into `buf`. See module docs for paint-category
/// inventory and exclusions (status line stays with the host).
///
/// Equivalent to [`draw_editor_with_reserve`] with `right_reserve_w: 0`
/// — the common case: no reserved trailing strip, so the paint stops
/// short of only the vertical scrollbar column (when one is present).
pub fn draw_editor(
    buf: &mut Buffer,
    area: Rect,
    editor: &Editor,
    theme: &Theme,
) -> EditorPaintResult {
    draw_editor_with_reserve(buf, area, editor, theme, 0)
}

/// [`draw_editor`], plus a fixed-width strip (in `buf` cells) a caller
/// can reserve between the buffer text and the vertical scrollbar —
/// mirroring [`Editor::layout_with_options_and_reserve`]'s
/// `right_reserve_w`, the paint-side half of that layout parameter.
///
/// A host that wants to dock something (a minimap strip, for example)
/// between the text and the scrollbar would otherwise have to narrow
/// `area` itself, which drags the vertical scrollbar left with it —
/// flush against the text instead of anchored at the viewport's true
/// right edge. `right_reserve_w` decouples the two: it is trimmed off
/// the *trailing* edge of `area` before the gutter/text/scrollbar
/// layout is derived, so the background fill, per-row text (and
/// everything derived from it — row highlight, indent guides, color
/// columns, ghost continuation, diagnostic/spell underlines,
/// bracket-match), selection overlays, the block cursor, secondary
/// cursors, AI ghost text and the horizontal scrollbar track all stop
/// short of the reserved strip, while the vertical scrollbar keeps
/// hugging `area.x + area.width - 1` regardless.
///
/// The strip is left untouched for a caller to paint something else
/// into without that content being overwritten on the next repaint; a
/// caller derives its bounds as the gap between the narrowed text area
/// and the vertical scrollbar column (or the area's right edge when
/// there is no vertical scrollbar). `right_reserve_w: 0` reproduces
/// [`draw_editor`] exactly.
pub fn draw_editor_with_reserve(
    buf: &mut Buffer,
    area: Rect,
    editor: &Editor,
    theme: &Theme,
    right_reserve_w: u16,
) -> EditorPaintResult {
    let mut result = EditorPaintResult::default();

    // Bounds-check overlay writes against the buffer's *actual* allocated
    // extent, not the caller-supplied `area`. The two can diverge across
    // a resize: the host computes `area` from a layout pass against one
    // terminal size, and by the time this paint runs `buf` may already
    // have been reallocated for a smaller size. Indexing against a stale,
    // larger `area` panics with "index outside of buffer"; indexing
    // against `buf.area` is always safe.
    let buf_area = buf.area;

    let window_bg = qc(if editor.show_active_bg {
        theme.editor_active_background
    } else {
        theme.background
    });
    let default_fg = qc(theme.foreground);
    let gutter_w = editor.gutter_char_width as u16;
    let viewport_lines = area.height as usize;
    let has_scrollbar = editor.total_lines > viewport_lines
        && area.width > gutter_w.saturating_add(right_reserve_w).saturating_add(1);
    let viewport_cols = (area.width as usize).saturating_sub(
        gutter_w as usize + right_reserve_w as usize + if has_scrollbar { 1 } else { 0 },
    );
    let has_h_scrollbar = editor.max_col > viewport_cols && area.height > 1;
    // Width shared by the background fill, the per-row text and the
    // horizontal scrollbar track: `area.width` minus the gutter, minus
    // `right_reserve_w`, minus the vertical scrollbar's own column —
    // i.e. everything up to (but not including) the reserved trailing
    // strip.
    let text_width = area
        .width
        .saturating_sub(gutter_w)
        .saturating_sub(right_reserve_w)
        .saturating_sub(if has_scrollbar { 1 } else { 0 });
    let bg_width = area
        .width
        .saturating_sub(right_reserve_w)
        .saturating_sub(if has_scrollbar { 1 } else { 0 });

    // ── Background fill ─────────────────────────────────────────
    for row in 0..area.height {
        for col in 0..bg_width {
            set_cell(buf, area.x + col, area.y + row, ' ', default_fg, window_bg);
        }
    }

    for (row_idx, line) in editor.lines.iter().enumerate() {
        let screen_y = area.y + row_idx as u16;
        if screen_y >= area.y + area.height {
            break;
        }

        // Cursorline / Diff / DAP stopped-line background.
        let line_bg = if line.is_dap_current {
            qc(theme.dap_stopped_bg)
        } else {
            match line.diff_status {
                Some(DiffLine::Added) => qc(theme.diff_added_bg),
                Some(DiffLine::Removed) => qc(theme.diff_removed_bg),
                Some(DiffLine::Padding) => qc(theme.diff_padding_bg),
                _ if line.is_current_line && editor.is_active && editor.cursorline => {
                    qc(theme.cursorline_bg)
                }
                _ => window_bg,
            }
        };
        if line_bg != window_bg {
            // Stop short of the vertical scrollbar column and the
            // reserved trailing strip (`bg_width`, computed above) — the
            // row highlight must not bleed into either.
            for col in 0..bg_width {
                set_cell(buf, area.x + col, screen_y, ' ', default_fg, line_bg);
            }
        }

        // ── Gutter ──────────────────────────────────────────────
        if gutter_w > 0 {
            let line_num_fg = qc(if line.is_current_line {
                theme.line_number_active_fg
            } else {
                theme.line_number_fg
            });
            // The bp column offset: 1 when has_breakpoints, else 0.
            // The git column offset: bp_offset + 1 when has_git_diff, else bp_offset.
            let bp_offset = if editor.has_breakpoints { 1 } else { 0 };
            let git_offset = if editor.has_git_diff {
                bp_offset + 1
            } else {
                bp_offset
            };
            for (i, ch) in line.gutter_text.chars().enumerate() {
                let gx = area.x + i as u16;
                if gx >= area.x + gutter_w {
                    break;
                }
                let fg = if editor.has_breakpoints && i == 0 {
                    if line.is_dap_current || line.is_breakpoint {
                        qc(theme.diagnostic_error)
                    } else {
                        line_num_fg
                    }
                } else if editor.has_git_diff && i == bp_offset {
                    qc(match line.git_diff {
                        Some(GitLineStatus::Added) => theme.git_added,
                        Some(GitLineStatus::Modified) => theme.git_modified,
                        Some(GitLineStatus::Deleted) => theme.git_deleted,
                        None => theme.line_number_fg,
                    })
                } else {
                    let _ = git_offset;
                    line_num_fg
                };
                set_cell(buf, gx, screen_y, ch, fg, line_bg);
            }
            // Diagnostic gutter icon is painted at column `bp_offset` to
            // keep the breakpoint marker visible when both are present.
            let diag_x = area.x + bp_offset as u16;
            if let Some(severity) = editor.diagnostic_gutter.get(&line.line_idx) {
                let (diag_ch, diag_color) = match severity {
                    DiagnosticSeverity::Error => ('●', qc(theme.diagnostic_error)),
                    DiagnosticSeverity::Warning => ('●', qc(theme.diagnostic_warning)),
                    DiagnosticSeverity::Information => ('●', qc(theme.diagnostic_info)),
                    DiagnosticSeverity::Hint => ('●', qc(theme.diagnostic_hint)),
                };
                set_cell(buf, diag_x, screen_y, diag_ch, diag_color, line_bg);
            } else if !line.is_wrap_continuation
                && editor.code_action_lines.contains(&line.line_idx)
                && editor.lightbulb_glyph != '\0'
            {
                set_cell(
                    buf,
                    diag_x,
                    screen_y,
                    editor.lightbulb_glyph,
                    qc(theme.lightbulb),
                    line_bg,
                );
            }
        }

        // ── Text (narrowed by the scrollbar column and any reserve) ─
        let text_area_x = area.x + gutter_w;
        render_text_line(
            buf,
            text_area_x,
            screen_y,
            text_width,
            line,
            editor.scroll_left,
            theme,
            line_bg,
            editor.tabstop,
        );

        // ── Indent guides ───────────────────────────────────────
        if !line.indent_guides.is_empty() {
            let guide_fg = qc(theme.indent_guide_fg);
            let active_fg = qc(theme.indent_guide_active_fg);
            for &guide_col in &line.indent_guides {
                if guide_col < editor.scroll_left {
                    continue;
                }
                let vis_col = (guide_col - editor.scroll_left) as u16;
                if vis_col >= text_width {
                    break;
                }
                let cx = text_area_x + vis_col;
                if cx < buf_area.x + buf_area.width && screen_y < buf_area.y + buf_area.height {
                    let cell = &mut buf[(cx, screen_y)];
                    if cell.symbol() == " " {
                        let is_active = editor.active_indent_col == Some(guide_col);
                        let fg = if is_active { active_fg } else { guide_fg };
                        cell.set_char('│');
                        cell.set_fg(fg);
                    }
                }
            }
        }

        // ── Color columns ───────────────────────────────────────
        if !line.colorcolumns.is_empty() {
            let cc_bg = qc(theme.colorcolumn_bg);
            for &cc_col in &line.colorcolumns {
                if cc_col < editor.scroll_left {
                    continue;
                }
                let vis_col = (cc_col - editor.scroll_left) as u16;
                if vis_col >= text_width {
                    break;
                }
                let cx = text_area_x + vis_col;
                if cx < buf_area.x + buf_area.width && screen_y < buf_area.y + buf_area.height {
                    let cell = &mut buf[(cx, screen_y)];
                    cell.set_bg(cc_bg);
                }
            }
        }

        // ── Ghost continuation lines ────────────────────────────
        if line.is_ghost_continuation {
            if let Some(ghost) = &line.ghost_suffix {
                let ghost_fg = qc(theme.ghost_text_fg);
                for (i, ch) in ghost.chars().enumerate() {
                    let gx = text_area_x + i as u16;
                    if gx >= text_area_x + text_width {
                        break;
                    }
                    set_cell(buf, gx, screen_y, ch, ghost_fg, line_bg);
                }
            }
        }

        // ── Diagnostic underlines ───────────────────────────────
        for dm in &line.diagnostics {
            let diag_fg = qc(match dm.severity {
                DiagnosticSeverity::Error => theme.diagnostic_error,
                DiagnosticSeverity::Warning => theme.diagnostic_warning,
                DiagnosticSeverity::Information => theme.diagnostic_info,
                DiagnosticSeverity::Hint => theme.diagnostic_hint,
            });
            let vis_start = char_col_to_visual(&line.raw_text, dm.start_col, editor.tabstop);
            let vis_end = char_col_to_visual(&line.raw_text, dm.end_col, editor.tabstop);
            for vcol in vis_start..vis_end {
                if vcol < editor.scroll_left {
                    continue;
                }
                let vis_col = (vcol - editor.scroll_left) as u16;
                if vis_col >= text_width {
                    break;
                }
                let cx = text_area_x + vis_col;
                if cx < buf_area.x + buf_area.width && screen_y < buf_area.y + buf_area.height {
                    let cell = &mut buf[(cx, screen_y)];
                    cell.set_fg(diag_fg);
                    cell.modifier |= Modifier::UNDERLINED;
                    cell.underline_color = diag_fg;
                }
            }
        }

        // ── Spell error underlines ──────────────────────────────
        let spell_fg = qc(theme.spell_error);
        for sm in &line.spell_errors {
            let vis_start = char_col_to_visual(&line.raw_text, sm.start_col, editor.tabstop);
            let vis_end = char_col_to_visual(&line.raw_text, sm.end_col, editor.tabstop);
            for vcol in vis_start..vis_end {
                if vcol < editor.scroll_left {
                    continue;
                }
                let vis_col = (vcol - editor.scroll_left) as u16;
                if vis_col >= text_width {
                    break;
                }
                let cx = text_area_x + vis_col;
                if cx < buf_area.x + buf_area.width && screen_y < buf_area.y + buf_area.height {
                    let cell = &mut buf[(cx, screen_y)];
                    cell.set_fg(spell_fg);
                    cell.modifier |= Modifier::UNDERLINED;
                    cell.underline_color = spell_fg;
                }
            }
        }

        // ── Bracket match highlighting ──────────────────────────
        let bracket_bg = qc(theme.bracket_match_bg);
        for &(view_line, col) in &editor.bracket_match_positions {
            if view_line == row_idx {
                let vis = char_col_to_visual(&line.raw_text, col, editor.tabstop);
                if vis < editor.scroll_left {
                    continue;
                }
                let vis_col = (vis - editor.scroll_left) as u16;
                if vis_col >= text_width {
                    continue;
                }
                let cx = text_area_x + vis_col;
                if cx < buf_area.x + buf_area.width && screen_y < buf_area.y + buf_area.height {
                    let cell = &mut buf[(cx, screen_y)];
                    cell.set_bg(bracket_bg);
                }
            }
        }
    }

    // ── Selection overlays ──────────────────────────────────────
    if let Some(sel) = &editor.selection {
        render_selection(buf, area, editor, sel, theme, theme.selection, text_width);
    }
    for esel in &editor.extra_selections {
        render_selection(buf, area, editor, esel, theme, theme.selection, text_width);
    }
    if let Some(yh) = &editor.yank_highlight {
        render_selection(
            buf,
            area,
            editor,
            yh,
            theme,
            theme.yank_highlight_bg,
            text_width,
        );
    }

    // ── Vertical scrollbar ──────────────────────────────────────
    if has_scrollbar {
        let track_h = if has_h_scrollbar {
            area.height.saturating_sub(1)
        } else {
            area.height
        };
        if track_h > 0 {
            let track = crate::event::Rect::new(
                (area.x + area.width - 1) as f32,
                area.y as f32,
                1.0,
                track_h as f32,
            );
            let scrollbar = Scrollbar::vertical(
                "tui:editor:v_scrollbar",
                track,
                editor.scroll_top as f32,
                editor.total_lines as f32,
                viewport_lines as f32,
                1.0,
            );
            super::draw_scrollbar(buf, &scrollbar, theme, theme.background);
        }
    }

    // ── Horizontal scrollbar ────────────────────────────────────
    if has_h_scrollbar && editor.max_col > 0 && viewport_cols > 0 {
        let cell_bg = if editor.show_active_bg {
            theme.editor_active_background
        } else {
            theme.background
        };
        let sb_y = area.y + area.height - 1;
        let track_x = area.x + gutter_w;
        // Same width as the text columns above — the h-scrollbar spans
        // exactly the text region, stopping short of both the vertical
        // scrollbar column and the reserved trailing strip.
        let track_w = text_width;
        if track_w > 0 {
            let track = crate::event::Rect::new(track_x as f32, sb_y as f32, track_w as f32, 1.0);
            let scrollbar = Scrollbar::horizontal(
                "tui:editor:h_scrollbar",
                track,
                editor.scroll_left as f32,
                editor.max_col as f32,
                viewport_cols as f32,
                1.0,
            );
            super::draw_scrollbar(buf, &scrollbar, theme, cell_bg);

            // Corner cell (intersection of v-scrollbar column and h-scrollbar row).
            if has_scrollbar {
                set_cell(
                    buf,
                    area.x + area.width - 1,
                    sb_y,
                    '┘',
                    qc(theme.separator),
                    qc(cell_bg),
                );
            }
        }
    }

    // Exclusive right bound (in screen columns) of the text region the
    // cursor / ghost text / secondary cursors are allowed to paint into:
    // the gutter plus `text_width`, i.e. up to but not including the
    // reserved trailing strip and the vertical scrollbar column.
    let text_right = area.x + gutter_w + text_width;

    // ── Cursor ──────────────────────────────────────────────────
    if let Some(cursor) = &editor.cursor {
        let cursor_screen_y = area.y + cursor.pos.view_line as u16;
        let raw = editor
            .lines
            .get(cursor.pos.view_line)
            .map(|l| l.raw_text.as_str())
            .unwrap_or("");
        let vis_col = char_col_to_visual(raw, cursor.pos.col, editor.tabstop)
            .saturating_sub(editor.scroll_left) as u16;
        let cursor_screen_x = area.x + gutter_w + vis_col;

        let buf_area = buf.area;
        match cursor.shape {
            CursorShape::Block => {
                if cursor_screen_x < text_right.min(buf_area.x + buf_area.width)
                    && cursor_screen_y < buf_area.y + buf_area.height
                {
                    let cell = &mut buf[(cursor_screen_x, cursor_screen_y)];
                    cell.set_bg(qc(theme.cursor)).set_fg(qc(theme.background));
                }
            }
            CursorShape::Bar | CursorShape::Underline => {
                result.cursor_position = Some((cursor_screen_x, cursor_screen_y));
            }
        }
    }

    // ── AI ghost text (after cursor on cursor line) ─────────────
    if let Some(cursor) = &editor.cursor {
        if let Some(rl) = editor.lines.get(cursor.pos.view_line) {
            if let Some(ghost) = &rl.ghost_suffix {
                let ghost_screen_y = area.y + cursor.pos.view_line as u16;
                let vis_col = char_col_to_visual(&rl.raw_text, cursor.pos.col, editor.tabstop)
                    .saturating_sub(editor.scroll_left) as u16;
                let ghost_start_x = area.x + gutter_w + vis_col;
                let ghost_fg = qc(theme.ghost_text_fg);
                for (i, ch) in ghost.chars().enumerate() {
                    let gx = ghost_start_x + i as u16;
                    if gx >= text_right {
                        break;
                    }
                    set_cell(buf, gx, ghost_screen_y, ch, ghost_fg, window_bg);
                }
            }
        }
    }

    // ── Secondary cursors (multi-cursor) ────────────────────────
    let cursor_color = qc(theme.cursor);
    let bg_color = qc(theme.background);
    let has_extra_sels = !editor.extra_selections.is_empty();
    for extra_pos in &editor.extra_cursors {
        let sy = area.y + extra_pos.view_line as u16;
        let col = if has_extra_sels {
            extra_pos.col + 1
        } else {
            extra_pos.col
        };
        let raw = editor
            .lines
            .get(extra_pos.view_line)
            .map(|l| l.raw_text.as_str())
            .unwrap_or("");
        let vis_col =
            char_col_to_visual(raw, col, editor.tabstop).saturating_sub(editor.scroll_left) as u16;
        let sx = area.x + gutter_w + vis_col;
        let buf_area = buf.area;
        if sx < text_right.min(buf_area.x + buf_area.width) && sy < buf_area.y + buf_area.height {
            let cell = &mut buf[(sx, sy)];
            cell.set_bg(cursor_color).set_fg(bg_color);
        }
    }

    result
}

// ─── Private helpers ────────────────────────────────────────────────────

/// Convert a UTF-8 byte offset into a character index. Returns the
/// total char count if the offset is past the end. Snaps to the
/// nearest char boundary at or before `byte_offset` (via
/// [`snap_to_char_boundary`]) so non-boundary inputs don't panic.
/// Mirrors `vimcode::tui_main::byte_to_char_idx`.
fn byte_to_char_idx(text: &str, byte_offset: usize) -> usize {
    text[..snap_to_char_boundary(text, byte_offset)]
        .chars()
        .count()
}

/// Paint one [`EditorLine`]'s text spans into `buf`, scrolled by
/// `scroll_left`, expanding tabs to `tabstop` and applying syntax
/// foreground / background / bold / italic from each [`StyledSpan`].
/// Inline annotations (virtual text) paint in `theme.annotation_fg`
/// after the line content. Mirrors
/// `vimcode::tui_main::render_impl::render_text_line`.
#[allow(clippy::too_many_arguments)]
fn render_text_line(
    buf: &mut Buffer,
    x_start: u16,
    y: u16,
    max_width: u16,
    line: &EditorLine,
    scroll_left: usize,
    theme: &Theme,
    window_bg: RColor,
    tabstop: usize,
) {
    let raw = &line.raw_text;
    let chars: Vec<char> = raw.chars().filter(|&c| c != '\n' && c != '\r').collect();

    let mut char_fgs: Vec<Color> = vec![theme.foreground; chars.len()];
    let mut char_bgs: Vec<Option<Color>> = vec![None; chars.len()];
    let mut char_mods: Vec<Modifier> = vec![Modifier::empty(); chars.len()];

    for span in &line.spans {
        let start = byte_to_char_idx(raw, span.start_byte);
        let end = byte_to_char_idx(raw, span.end_byte).min(chars.len());
        for i in start..end {
            char_fgs[i] = span.style.fg;
            char_bgs[i] = span.style.bg;
            let mut m = Modifier::empty();
            if span.style.bold {
                m |= Modifier::BOLD;
            }
            if span.style.italic {
                m |= Modifier::ITALIC;
            }
            char_mods[i] = m;
        }
    }

    let tabstop = tabstop.max(1);
    let mut vis_col: usize = 0;
    let mut cells: Vec<(usize, char, usize)> = Vec::with_capacity(chars.len());
    for (i, &ch) in chars.iter().enumerate() {
        if ch == '\t' {
            let next_stop = ((vis_col / tabstop) + 1) * tabstop;
            while vis_col < next_stop {
                cells.push((vis_col, ' ', i));
                vis_col += 1;
            }
        } else {
            cells.push((vis_col, ch, i));
            vis_col += 1;
        }
    }
    let total_vis_cols = vis_col;

    for &(vcol, ch, ci) in &cells {
        if vcol < scroll_left {
            continue;
        }
        let col = (vcol - scroll_left) as u16;
        if col >= max_width {
            break;
        }
        let fg = qc(char_fgs[ci]);
        let bg = char_bgs[ci].map(qc).unwrap_or(window_bg);
        if char_mods[ci].is_empty() {
            set_cell(buf, x_start + col, y, ch, fg, bg);
        } else {
            set_cell_styled(buf, x_start + col, y, ch, fg, bg, char_mods[ci], None);
        }
    }

    // Inline annotation / virtual text (e.g. git blame).
    if let Some(ann) = &line.annotation {
        let visible_cols = total_vis_cols.saturating_sub(scroll_left);
        let ann_start = x_start + visible_cols.min(max_width as usize) as u16;
        let ann_fg = qc(theme.annotation_fg);
        for (i, ch) in ann.chars().enumerate() {
            let col = ann_start + i as u16;
            if col >= x_start + max_width {
                break;
            }
            set_cell(buf, col, y, ch, ann_fg, window_bg);
        }
    }
}

/// Paint one selection range overlay onto `buf`. Walks the editor's
/// visible lines, calling [`EditorSelection::cols_on`] to map each
/// buffer-coordinate selection row to segment-local visual columns (so
/// wrapped lines highlight only the segment that overlaps the selection
/// range, and ghost-continuation / diff-padding rows are skipped
/// entirely). Sets each touched cell's bg to `color`, preserving the
/// cell's existing fg unless that fg equals the window background (in
/// which case the cell would be invisible against the new bg, so it's
/// swapped to the theme's default foreground). Mirrors
/// `vimcode::tui_main::render_impl::render_selection`.
fn render_selection(
    buf: &mut Buffer,
    area: Rect,
    editor: &Editor,
    sel: &EditorSelection,
    theme: &Theme,
    color: Color,
    text_width: u16,
) {
    let window_bg = qc(if editor.show_active_bg {
        theme.editor_active_background
    } else {
        theme.background
    });
    let default_fg = qc(theme.foreground);
    let sel_bg = qc(color);
    let gutter_w = editor.gutter_char_width as u16;
    let text_area_x = area.x + gutter_w;
    let text_width = text_width as usize;

    for (row_idx, line) in editor.lines.iter().enumerate() {
        let Some(cols) = sel.cols_on(line) else {
            continue;
        };
        let screen_y = area.y + row_idx as u16;

        let vis_start = char_col_to_visual(&line.raw_text, cols.start, editor.tabstop);
        let vis_end = char_col_to_visual(&line.raw_text, cols.end, editor.tabstop);

        for vis in vis_start..vis_end {
            if vis < editor.scroll_left {
                continue;
            }
            let screen_col = (vis - editor.scroll_left) as u16;
            if screen_col >= text_width as u16 {
                break;
            }
            let sx = text_area_x + screen_col;
            let buf_area = buf.area;
            if sx < buf_area.x + buf_area.width && screen_y < buf_area.y + buf_area.height {
                let cell = &mut buf[(sx, screen_y)];
                let old_fg = cell.fg;
                cell.set_bg(sel_bg);
                if old_fg == window_bg {
                    cell.set_fg(default_fg);
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::primitives::editor::{DiagnosticMark, SelectionKind, SpellMark};
    use ratatui::buffer::Buffer;
    use ratatui::layout::Rect as RtRect;

    /// Minimal one-line [`EditorLine`] carrying decoration-overlay
    /// categories at the given columns. All columns land past `raw_text`'s
    /// own length — none of the paint sites require character content under
    /// them to safely index `buf[(cx, screen_y)]`.
    fn decorated_line(line_idx: usize, col: usize) -> EditorLine {
        EditorLine {
            raw_text: "x".repeat(col + 2),
            gutter_text: String::new(),
            spans: vec![],
            line_idx,
            is_current_line: false,
            is_fold_header: false,
            folded_line_count: 0,
            git_diff: None,
            diff_status: None,
            diagnostics: vec![DiagnosticMark {
                start_col: col,
                end_col: col + 1,
                severity: DiagnosticSeverity::Error,
                message: String::new(),
            }],
            spell_errors: vec![SpellMark {
                start_col: col,
                end_col: col + 1,
            }],
            is_breakpoint: false,
            is_conditional_bp: false,
            is_dap_current: false,
            is_wrap_continuation: false,
            segment_col_offset: 0,
            annotation: None,
            ghost_suffix: None,
            is_ghost_continuation: false,
            indent_guides: vec![col],
            colorcolumns: vec![col],
        }
    }

    fn test_editor(lines: Vec<EditorLine>, bracket_match_positions: Vec<(usize, usize)>) -> Editor {
        Editor {
            id: crate::types::WidgetId::new("editor"),
            rect: crate::event::Rect::new(0.0, 0.0, 20.0, 5.0),
            lines,
            cursor: None,
            extra_cursors: vec![],
            selection: None,
            extra_selections: vec![],
            yank_highlight: None,
            scroll_top: 0,
            scroll_left: 0,
            total_lines: 2,
            max_col: 20,
            gutter_char_width: 0,
            is_active: true,
            show_active_bg: false,
            has_git_diff: false,
            has_breakpoints: false,
            diagnostic_gutter: Default::default(),
            code_action_lines: Default::default(),
            bracket_match_positions,
            active_indent_col: None,
            tabstop: 4,
            cursorline: false,
            lightbulb_glyph: '\0',
        }
    }

    /// `draw_editor` must bounds-check every overlay write against
    /// `buf.area` (the buffer's real, already-resized extent), not the
    /// caller-supplied `area`. A resize between layout computation and
    /// `ratatui::Terminal::draw` can leave `area` describing a larger
    /// region than `buf` actually has. This test reproduces that gap:
    /// `area` is wider and taller than `buf`, and the overlay categories
    /// (indent guides, color columns, diagnostics, spell errors, bracket
    /// match) target cells inside `area` but outside `buf.area` both
    /// horizontally and vertically. The function must silently skip the
    /// off-buffer writes and return normally.
    #[test]
    fn draw_editor_does_not_panic_when_area_outlives_buf() {
        let lines = vec![
            decorated_line(0, 15), // triggers the *horizontal* guard
            decorated_line(1, 2),  // triggers the *vertical* guard
        ];
        let editor = test_editor(lines, vec![(0, 15), (1, 2)]);
        let theme = Theme::default();

        // `buf` is the real, already-shrunk buffer (10x1); `area` is the
        // stale, larger layout rect (20x5) from before a terminal resize.
        let mut buf = Buffer::empty(RtRect::new(0, 0, 10, 1));
        let area = RtRect::new(0, 0, 20, 5);

        // Must not panic.
        let _ = draw_editor(&mut buf, area, &editor, &theme);
    }

    /// `right_reserve_w` must carve out a strip at the trailing edge of
    /// `area` that the background fill and text paint leave untouched,
    /// while the vertical scrollbar still hugs the true right edge of
    /// `area` — unaffected by the reserve, per this function's doc.
    #[test]
    fn draw_editor_right_reserve_w_leaves_strip_untouched_and_keeps_scrollbar_at_edge() {
        let lines = vec![sel_test_line(0, "hi", 0, false, None)];
        let mut editor = test_editor(lines, vec![]);
        // > viewport_lines (area.height below) so a v-scrollbar is drawn.
        editor.total_lines = 100;
        let theme = Theme::default();

        let area = RtRect::new(0, 0, 20, 5);
        let mut buf = Buffer::empty(area);
        let right_reserve_w: u16 = 3;

        // Sentinel: mark the whole buffer with a glyph/style the paint
        // never produces, so any cell still carrying it afterward proves
        // this function skipped writing there.
        for y in 0..area.height {
            for x in 0..area.width {
                set_cell(&mut buf, x, y, '?', RColor::Reset, RColor::Reset);
            }
        }

        let _ = draw_editor_with_reserve(&mut buf, area, &editor, &theme, right_reserve_w);

        let scrollbar_x = area.x + area.width - 1;
        for y in 0..area.height {
            let scrollbar_cell = &buf[(scrollbar_x, y)];
            assert_ne!(
                scrollbar_cell.symbol(),
                "?",
                "vertical scrollbar must hug the true right edge regardless of right_reserve_w"
            );

            // Every column inside the reserved strip (between the text
            // area and the scrollbar column) must still carry the
            // sentinel — untouched by background fill or text paint.
            for x in (scrollbar_x - right_reserve_w)..scrollbar_x {
                let cell = &buf[(x, y)];
                assert_eq!(
                    cell.symbol(),
                    "?",
                    "column {x} is inside the right_reserve_w strip and must be left untouched"
                );
            }
        }

        // A column inside the text area (left of the reserved strip)
        // must have been painted over by the background fill.
        let painted_cell = &buf[(0, 0)];
        assert_ne!(
            painted_cell.symbol(),
            "?",
            "columns left of the reserve strip must still be painted"
        );
    }

    // ── Selection column math via `EditorSelection::cols_on` ────────────

    fn sel_test_line(
        line_idx: usize,
        raw_text: &str,
        segment_col_offset: usize,
        is_ghost_continuation: bool,
        diff_status: Option<DiffLine>,
    ) -> EditorLine {
        EditorLine {
            raw_text: raw_text.into(),
            gutter_text: String::new(),
            spans: vec![],
            line_idx,
            is_current_line: false,
            is_fold_header: false,
            folded_line_count: 0,
            git_diff: None,
            diff_status,
            diagnostics: vec![],
            spell_errors: vec![],
            is_breakpoint: false,
            is_conditional_bp: false,
            is_dap_current: false,
            is_wrap_continuation: segment_col_offset > 0,
            segment_col_offset,
            annotation: None,
            ghost_suffix: is_ghost_continuation.then(|| "ai suggestion".to_string()),
            is_ghost_continuation,
            indent_guides: vec![],
            colorcolumns: vec![],
        }
    }

    /// One `Char` selection spanning buffer lines `[0, 2]` painted
    /// across a plain row, a wrapped-segment row, a ghost-continuation
    /// row, and a diff-padding row — same matrix
    /// `tests/conformance/editor.rs` proves against
    /// `EditorSelection::cols_on` directly, proven again here through a
    /// real `draw_editor` paint so this backend's own call site is
    /// covered too.
    #[test]
    fn draw_editor_selection_respects_wrapped_ghost_and_diff_padding_rows() {
        let lines = vec![
            // Row 0: buffer line 0, plain, selection's own start line.
            sel_test_line(0, "0123456789", 0, false, None),
            // Row 1: a wrap-continuation segment of buffer line 1,
            // starting at buffer column 5 — its own text is only 5
            // chars, entirely inside the selection.
            sel_test_line(1, "abcde", 5, false, None),
            // Row 2: the AI-ghost continuation of buffer line 1 — same
            // `line_idx` as row 1, but virtual, must never be selected.
            sel_test_line(1, "", 0, true, None),
            // Row 3: buffer line 2 (the selection's own end line), but a
            // diff-padding filler row — must never be selected either.
            sel_test_line(2, "", 0, false, Some(DiffLine::Padding)),
        ];
        let mut editor = test_editor(lines, vec![]);
        // `test_editor`'s fixed `max_col: 20` would otherwise overflow
        // this 10-wide buffer and reserve the bottom row (row 3, exactly
        // the diff-padding row this test samples) for a horizontal
        // scrollbar track — unrelated to selection paint, and would
        // clobber the very background this test asserts on.
        editor.max_col = 0;
        editor.total_lines = 4;
        editor.selection = Some(EditorSelection {
            kind: SelectionKind::Char,
            start_line: 0,
            start_col: 0,
            end_line: 2,
            end_col: 10,
        });
        let theme = Theme::default();

        let mut buf = Buffer::empty(RtRect::new(0, 0, 10, 4));
        let area = RtRect::new(0, 0, 10, 4);
        let _ = draw_editor(&mut buf, area, &editor, &theme);

        let sel_bg = qc(theme.selection);
        let window_bg = qc(theme.background);
        let diff_padding_bg = qc(theme.diff_padding_bg);

        assert_eq!(
            buf[(0, 0)].bg,
            sel_bg,
            "row 0 (plain, selection's start line) should be tinted"
        );
        assert_eq!(
            buf[(0, 1)].bg,
            sel_bg,
            "row 1 (wrapped segment of a fully-selected line) should be tinted"
        );
        assert_eq!(
            buf[(0, 2)].bg,
            window_bg,
            "row 2 (ghost continuation) must never be tinted by a selection"
        );
        assert_eq!(
            buf[(0, 3)].bg,
            diff_padding_bg,
            "row 3 (diff padding) must show only its diff background, not a selection tint"
        );
    }

    /// `draw_editor_with_reserve(..., 0)` must reproduce `draw_editor`
    /// cell-for-cell — the convenience wrapper is a thin forward, not an
    /// independent code path that could silently drift from it.
    #[test]
    fn draw_editor_with_reserve_zero_matches_draw_editor() {
        let lines = vec![sel_test_line(0, "0123456789", 0, false, None)];
        let mut editor = test_editor(lines, vec![]);
        editor.total_lines = 10;
        editor.max_col = 20;
        let theme = Theme::default();

        let area = RtRect::new(0, 0, 10, 4);
        let mut buf_a = Buffer::empty(area);
        let mut buf_b = Buffer::empty(area);
        let result_a = draw_editor(&mut buf_a, area, &editor, &theme);
        let result_b = draw_editor_with_reserve(&mut buf_b, area, &editor, &theme, 0);

        assert_eq!(result_a, result_b);
        for y in 0..area.height {
            for x in 0..area.width {
                let a = &buf_a[(x, y)];
                let b = &buf_b[(x, y)];
                assert_eq!(a.symbol(), b.symbol(), "symbol diverged at ({x}, {y})");
                assert_eq!(a.fg, b.fg, "fg diverged at ({x}, {y})");
                assert_eq!(a.bg, b.bg, "bg diverged at ({x}, {y})");
            }
        }
    }

    /// `right_reserve_w` narrows the per-row background highlight (the
    /// cursorline tint here, a different code path from the whole-area
    /// background fill covered by
    /// `draw_editor_right_reserve_w_leaves_strip_untouched_and_keeps_scrollbar_at_edge`),
    /// but the vertical scrollbar stays anchored to `area`'s true right
    /// edge — the whole point of a paint-side reserve: a host can dock a
    /// strip (a minimap, say) between the narrowed text and the
    /// scrollbar without the scrollbar sliding left to hug the text.
    #[test]
    fn draw_editor_with_reserve_keeps_scrollbar_at_area_right_edge() {
        let mut line = sel_test_line(0, "0123456789ABCDEF", 0, false, None);
        line.is_current_line = true;
        let mut editor = test_editor(vec![line], vec![]);
        editor.cursorline = true;
        editor.total_lines = 10; // forces has_scrollbar
        editor.max_col = 0; // no horizontal scrollbar — keep this test focused

        let theme = Theme::default();
        let area = RtRect::new(0, 0, 10, 4);
        let mut buf = Buffer::empty(area);

        // Sentinel the whole buffer with a glyph/style the paint never
        // produces, so a cell still carrying it afterwards proves the
        // paint skipped writing there.
        for y in 0..area.height {
            for x in 0..area.width {
                set_cell(&mut buf, x, y, '?', RColor::Reset, RColor::Reset);
            }
        }

        let right_reserve_w = 2;
        let _ = draw_editor_with_reserve(&mut buf, area, &editor, &theme, right_reserve_w);

        let cursorline_bg = qc(theme.cursorline_bg);

        // bg_width = area.width(10) - has_scrollbar(1) - right_reserve_w(2) = 7:
        // the cursorline tint covers columns 0..7 and stops there.
        assert_eq!(
            buf[(6, 0)].bg,
            cursorline_bg,
            "column 6 is inside the narrowed cursorline highlight"
        );
        for x in 7..9 {
            let cell = &buf[(x, 0)];
            assert_eq!(
                cell.symbol(),
                "?",
                "column {x} is inside the reserved strip: no glyph may spill into it"
            );
            assert_eq!(
                cell.bg,
                RColor::Reset,
                "column {x} is inside the reserved strip: the cursorline tint must stop short of it"
            );
        }

        // The vertical scrollbar track still hugs area's true right
        // edge (column 9 = area.x + area.width - 1), undisturbed by the
        // reserve — it must not have slid left to column 7 or 8.
        assert_ne!(
            buf[(9, 0)].symbol(),
            "?",
            "scrollbar track at area's right edge (column 9) must be painted"
        );
    }
}