edamame 0.1.6

A Terminal Markdown editor that stays rendered while you edit
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
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
//! Per-frame table layout snapshots plus the row/column-button rendering behind mouse-driven
//! reorder, resize, and delete.
//!
//! There is deliberately **no** standalone `StatefulWidget` for tables: the rendered lines keep
//! flowing through `ParsedDoc`'s pre-rendered line list, so scroll, wrap, and cell-scoped raw
//! reveal work unchanged.  What lives here is the mouse-facing half — [`build_snapshots`] scans the
//! visible lines, [`hit_test`](TableLayoutSnapshot::hit_test) maps a click onto one, and
//! [`paint_handles`] overlays the glyphs after the line-render pass.
//!
//! Snapshots are stored on the `RenderedViewState` so the next frame's mouse handling can hit-test
//! against them.

use std::ops::Range;

use ratatui::buffer::Buffer as TuiBuf;
use ratatui::layout::Rect;
use ratatui::style::Style;

use crate::config::Theme;
use crate::document::row_map::{self, TablePart};
use crate::editor::{table_edit_ops, EditorState};
use crate::markdown::table_layout;

/// Reorder-handle glyph, for both row-reorder (in the external left gutter) and column-reorder
/// (centered on each column's top border cell).  The "dot grip" convention reads as "drag me".
pub const REORDER_HANDLE_GLYPH: char = '⠿';
/// Highlights the destination separator during a row-handle drag; the heavier weight reads against
/// the table's standard `─`.
pub const DROP_ROW_GLYPH: char = '━';
/// Column-drag counterpart, reading against the standard `│` border.
pub const DROP_COL_GLYPH: char = '┃';
/// Column-resize glyph, painted on each interior `│` of the header row as a visible target;
/// clicks anywhere within the border's `±1` tolerance still resize.
pub const COLUMN_RESIZE_GLYPH: char = '⇔';
/// Delete-handle glyph, painted on the outer right `│` for each data row and on the bottom border
/// for each column.  A click deletes outright; undo restores.  Gated by `config.table.show_buttons`
/// like the other handles.
pub const DELETE_HANDLE_GLYPH: char = '✕';

/// Rows preceding the first data row (header, then alignment), so data row `i` is at
/// `HEADER_ROWS + i`.
pub const HEADER_ROWS: usize = 2;

/// Per-frame snapshot of one visible table's layout.  Every coordinate is in terminal cells
/// relative to the document area's origin, and valid only for the frame it was built on.
#[derive(Debug, Clone)]
pub struct TableLayoutSnapshot {
    /// Byte offset of this table's first row in the source buffer.
    pub table_byte_start: usize,
    /// Byte offset just past the last newline of the final row.
    pub table_byte_end: usize,
    /// Number of columns (`info.col_count`).
    pub col_count: usize,
    /// Number of TableInfo rows (header + alignment + data).
    pub row_count: usize,
    /// Per-column cell ranges inside a row's content area: `start` is just after the opening `│`,
    /// `end` is the closing `│` itself.
    pub col_ranges: Vec<Range<u16>>,
    /// Per-data-row vertical ranges; `row_ranges[i]` spans `info.rows[HEADER_ROWS + i]`.  Only
    /// data rows carry a drag handle, so the header and alignment rows are skipped.
    pub row_ranges: Vec<Range<u16>>,
    /// Where the `⠿` row-reorder glyph is painted: ON the outer left `│`, overlaying the border for
    /// each data row, wherever the table sits (top-level, or behind a quote's bar or an item's
    /// indent), as `✕` does on the right.  `None` when handles are disabled.
    pub row_handle_col: Option<u16>,
    /// The `┌─┬─┐` top border, carrying one column-reorder glyph per column.  `None` when handles
    /// are disabled or the border scrolled off.
    pub top_border_row: Option<u16>,
    /// The header row, carrying the `⇔` resize glyphs.  `None` when it scrolled off.
    pub header_row: Option<u16>,
    /// Where the `✕` row-delete glyph is painted: ON the outer right `│`, overlaying the border
    /// for each data row.  Resize on a data row therefore shifts to one cell inside the border;
    /// non-data rows have no delete hit and still fall through to `ColumnBorder`.
    pub delete_row_handle_col: Option<u16>,
    /// The `└─┴─┘` bottom border, carrying the column-delete glyphs.  `None` when handles are
    /// disabled or the border scrolled off.
    pub bottom_border_row: Option<u16>,
}

/// What a `(col, row)` click lands on inside a table.  Every `row_idx` is a **TableInfo** row
/// index (`HEADER_ROWS + data_index`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TableHit {
    /// Click inside a data cell's content area.
    Cell { row_idx: usize, col_idx: usize },
    /// Click on a vertical `│` border; `col_idx` is `0..=col_count`, with 0 and `col_count` the
    /// outer borders.  Only the interior ones drive resize.
    ColumnBorder { col_idx: usize },
    /// Click on the `≡` row-drag glyph next to a data row.
    RowHandle { row_idx: usize },
    /// Click on the `⇔` column-drag glyph above a column.
    ColumnHandle { col_idx: usize },
    /// Click on the `✕` row-delete glyph.  `row_idx` is ≥ `HEADER_ROWS`: header and alignment
    /// can't be deleted, so that border cell stays a resize target on those rows.
    DeleteRowHandle { row_idx: usize },
    /// Click on the `✕` column-delete glyph.  Only emitted when the table has more than one
    /// column.
    DeleteColumnHandle { col_idx: usize },
}

impl TableLayoutSnapshot {
    /// `TableInfo` row index of the data row nearest `row`, or `None` outside the data-row band.
    ///
    /// Consecutive `row_ranges` entries are separated by a one-row gap (the `├─┼─┤` rule, or the
    /// blank stripe line), and a strict range test answered `None` on every one — which made
    /// grabbing the `⠿` handle a coin flip and stalled the drop indicator mid-crossing.  Snapping
    /// to the nearest row closes the gaps.  The band stops at the separators bounding the first and
    /// last data rows, so the header stays un-grabbable and a pointer leaving the table below stops
    /// moving the hover.
    pub fn data_row_at_y(&self, row: u16) -> Option<usize> {
        let first = self.row_ranges.first()?;
        let last = self.row_ranges.last()?;
        if row < first.start.saturating_sub(1) || row > last.end {
            return None;
        }
        let idx = self
            .row_ranges
            .iter()
            .enumerate()
            .min_by_key(|(_, r)| range_distance(r, row))
            .map(|(i, _)| i)?;
        Some(HEADER_ROWS + idx)
    }

    /// 0-indexed column nearest `col`, or `None` outside the table's horizontal extent.  Same
    /// snapping rationale as [`Self::data_row_at_y`]: the `│` / `┬` vertices between `col_ranges`
    /// entries are exactly where a user aiming at a column handle tends to press.
    pub fn column_at_x(&self, col: u16) -> Option<usize> {
        let first = self.col_ranges.first()?;
        let last = self.col_ranges.last()?;
        if col < first.start.saturating_sub(1) || col > last.end {
            return None;
        }
        self.col_ranges
            .iter()
            .enumerate()
            .min_by_key(|(_, r)| range_distance(r, col))
            .map(|(i, _)| i)
    }

    /// Hit-test document-area-relative `(col, row)` against this snapshot.
    ///
    /// Precedence: delete handle → row handle → column handle → column border → cell.  Delete wins
    /// over `ColumnBorder` because the row-delete glyph sits ON the outer right `│`; resize on a
    /// data row stays reachable one cell either side, and non-data rows have no delete hit at all.
    /// Borders are hit within `±1` of their `│` column.
    pub fn hit_test(&self, col: u16, row: u16) -> Option<TableHit> {
        // Checked before ColumnBorder so the `✕` cell wins over the right border's ±1 window.
        if let Some(handle_col) = self.delete_row_handle_col {
            if col == handle_col {
                for (i, y_range) in self.row_ranges.iter().enumerate() {
                    if row >= y_range.start && row < y_range.end {
                        return Some(TableHit::DeleteRowHandle {
                            row_idx: HEADER_ROWS + i,
                        });
                    }
                }
            }
        }

        // Deliberately ±1 of the glyph rather than the column's whole width: this is the one
        // destructive hit on the border rows, so aiming at a border must not drop a column.
        if let Some(bot_y) = self.bottom_border_row {
            if row == bot_y {
                for (c, x_range) in self.col_ranges.iter().enumerate() {
                    if let Some(glyph_x) = column_glyph_x(x_range) {
                        if col.abs_diff(glyph_x) <= 1 {
                            return Some(TableHit::DeleteColumnHandle { col_idx: c });
                        }
                    }
                }
            }
        }

        // Anywhere across the data rows' vertical band, separators included.
        if let Some(handle_col) = self.row_handle_col {
            if col == handle_col {
                if let Some(row_idx) = self.data_row_at_y(row) {
                    return Some(TableHit::RowHandle { row_idx });
                }
            }
        }

        // A `┬` vertex resolves to the adjacent column: clicking exactly on one would otherwise
        // miss the handle and silently start a resize.
        if let Some(top_y) = self.top_border_row {
            if row == top_y {
                if let Some(col_idx) = self.column_at_x(col) {
                    return Some(TableHit::ColumnHandle { col_idx });
                }
            }
        }

        // Within ±1 of a `│`, provided the row is part of the table.  The header's `⇔` glyph is
        // just a highlighted sub-region of this same area.
        if self.row_count > 0 && self.row_on_table(row) {
            if let Some(first) = self.col_ranges.first() {
                let left_border = first.start.saturating_sub(1);
                if col.abs_diff(left_border) <= 1 {
                    return Some(TableHit::ColumnBorder { col_idx: 0 });
                }
            }
            for (c, x_range) in self.col_ranges.iter().enumerate() {
                let border_col = x_range.end;
                if col.abs_diff(border_col) <= 1 {
                    return Some(TableHit::ColumnBorder { col_idx: c + 1 });
                }
            }
        }

        // Data cell.
        for (i, y_range) in self.row_ranges.iter().enumerate() {
            if row >= y_range.start && row < y_range.end {
                for (c, x_range) in self.col_ranges.iter().enumerate() {
                    if col >= x_range.start && col < x_range.end {
                        return Some(TableHit::Cell {
                            row_idx: HEADER_ROWS + i,
                            col_idx: c,
                        });
                    }
                }
            }
        }
        None
    }

    fn row_on_table(&self, row: u16) -> bool {
        let first_y = self
            .top_border_row
            .or_else(|| self.row_ranges.first().map(|r| r.start.saturating_sub(2)))
            .unwrap_or(0);
        let last_y = self
            .row_ranges
            .last()
            .map(|r| r.end + 1) // include the bottom border
            .unwrap_or(first_y);
        row >= first_y && row <= last_y
    }
}

/// Distance from `v` to `range` (0 when inside), for snapping a pointer that landed on one of the
/// box-drawing cells between two ranges.
fn range_distance(range: &Range<u16>, v: u16) -> u16 {
    if v < range.start {
        range.start - v
    } else if v >= range.end {
        v - range.end + 1
    } else {
        0
    }
}

/// Center of a column's content span — where its border-cell glyph is painted.  Shared by
/// `paint_handles` and the column-delete hit-test so the glyph and the live cell can't drift apart.
fn column_glyph_x(x_range: &Range<u16>) -> Option<u16> {
    if x_range.end <= x_range.start {
        return None;
    }
    Some(x_range.start + (x_range.end - x_range.start) / 2)
}

/// Per-frame instruction for `paint_drop_indicator`.  The caller distills `mouse_ops::DragTarget`
/// into one of these so the UI layer doesn't import the editor-side enum.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DropIndicator {
    /// Row drag: highlight the separator that would receive the drop — above `hover_row_idx` when
    /// dropping upward, below when downward, as derived from `src_row_idx`.
    Row {
        table_byte_start: usize,
        src_row_idx: usize,
        hover_row_idx: usize,
    },
    /// Column drag; same drop-side semantics as `Row`.
    Column {
        table_byte_start: usize,
        src_col_idx: usize,
        hover_col_idx: usize,
    },
    /// Resize guideline at the pointer's X.  Driven only by `tests/ui.rs` today; the live
    /// column-border drag paints through a different path.
    #[allow(dead_code)]
    ColumnBorder { table_byte_start: usize, x: u16 },
}

// ── Snapshot construction ───────────────────────────────────────────────────

/// Refresh `snapshots` in place when the cache key (`scroll`, `area`, `parsed_version`,
/// `show_handles`) changed, mirroring the image and link snapshot caches.  `show_handles` is part
/// of the key because it changes the snapshot contents.
pub fn build_snapshots_cached(
    state: &EditorState,
    area: Rect,
    show_handles: bool,
    snapshots: &mut Vec<TableLayoutSnapshot>,
    cache_key: &mut Option<(usize, Rect, u64, bool)>,
) {
    let key = (state.scroll, area, state.parsed_version, show_handles);
    if *cache_key == Some(key) {
        return;
    }
    *snapshots = build_snapshots(state, area, show_handles);
    *cache_key = Some(key);
}

/// Build a snapshot for every table fully or partially on screen.
///
/// `show_handles` controls whether snapshots carry the handle coordinates, and therefore whether
/// hit-testing classifies clicks on those cells as handle hits.
pub fn build_snapshots(
    state: &EditorState,
    area: Rect,
    show_handles: bool,
) -> Vec<TableLayoutSnapshot> {
    let mut out: Vec<TableLayoutSnapshot> = Vec::new();
    if area.height == 0 {
        return out;
    }
    let lines = &state.parsed.lines;
    let total = lines.len();
    let width = area.width as usize;

    let (mut virtual_idx, mut first_sub_row) =
        state.rendered_line_at_visual_row(state.scroll, width);
    let mut vis_y: usize = 0;
    let height = area.height as usize;

    // The open snapshot stays open through border / separator rows so a multi-row table merges
    // into one snapshot; it closes only when the rendered line leaves the table.
    let mut open_table: Option<TableLayoutSnapshot> = None;
    // The source line of the open snapshot's table's header.
    let mut open_table_line: Option<usize> = None;
    // Per-data-row span accumulator: opened by a row's first `DataRow` sub-line, extended by its
    // continuations, pushed onto `snap.row_ranges` when a separator closes the row.
    let mut current_data_row_y: Option<(usize, Range<u16>)> = None;
    // The block last read, its first rendered line, and its rows' table parts with the header
    // lines made absolute: one read per block, not per line.
    let mut block_parts: Option<(usize, usize, row_map::TableParts)> = None;

    while vis_y < height && virtual_idx < total {
        let Some(line) = lines.get(virtual_idx) else {
            break;
        };
        let full_rows_used = state
            .parsed
            .visual_rows_for_line_at(virtual_idx, width)
            .max(1);
        let rows_used = full_rows_used.saturating_sub(first_sub_row).max(1);

        // Which table this rendered line belongs to, at any depth, by the parse's row origins:
        // the source line of its header, and the part it draws.
        let mut part: Option<(usize, TablePart)> = None;
        if let Some(block) = state.parsed.source_map.block_for_rendered_line(virtual_idx) {
            if block_parts.as_ref().is_none_or(|(b, ..)| *b != block) {
                let map = &state.parsed.source_map;
                let first_line = map
                    .original_range_for_block(block)
                    .map_or(0, |r| state.parsed.byte_to_line(r.start));
                let mut parts = row_map::table_parts(&state.parsed, block);
                for (header, _) in parts.iter_mut().flatten() {
                    *header += first_line;
                }
                block_parts = Some((block, map.rendered_lines_for_block(block).start, parts));
            }
            if let Some((_, first_row, parts)) = block_parts.as_ref() {
                part = parts
                    .get(virtual_idx.saturating_sub(*first_row))
                    .copied()
                    .flatten();
            }
        }
        let current_table = part.map(|(header, _)| header);
        let sub_kind = part.map(|(_, p)| p);

        // Close the open snapshot if we've moved off its table.
        if current_table != open_table_line {
            if let Some(mut prev) = open_table.take() {
                if let Some((_, range)) = current_data_row_y.take() {
                    prev.row_ranges.push(range);
                }
                out.push(prev);
            }
            open_table_line = None;
            current_data_row_y = None;
        }

        if let Some(header_line) = current_table {
            // Open a new snapshot if we aren't already tracking this table.
            if open_table.is_none() {
                // By line: the parse's bytes drift from the buffer's while an in-line edit
                // defers the re-parse, its lines don't.
                let rope = state.buffer.rope();
                let line = header_line.min(rope.len_lines());
                if let Some(info) = table_edit_ops::locate_table(state, rope.line_to_byte(line)) {
                    open_table = Some(TableLayoutSnapshot {
                        table_byte_start: info.start,
                        table_byte_end: info.end,
                        col_count: info.col_count,
                        row_count: info.rows.len(),
                        col_ranges: Vec::new(),
                        row_ranges: Vec::new(),
                        row_handle_col: None,
                        top_border_row: None,
                        header_row: None,
                        delete_row_handle_col: None,
                        bottom_border_row: None,
                    });
                    open_table_line = Some(header_line);
                }
            }

            if let Some(snap) = open_table.as_mut() {
                // Fill col_ranges from the first row carrying `│` characters.  Screen
                // geometry, so pipe *cells*: a wide glyph to the left takes two.
                if snap.col_ranges.is_empty() {
                    let pipes = table_layout::rendered_pipe_cells(line);
                    if pipes.len() == snap.col_count + 1 {
                        for i in 0..snap.col_count {
                            let start = pipes[i] as u16 + 1;
                            let end = pipes[i + 1] as u16;
                            snap.col_ranges.push(Range { start, end });
                        }
                    }
                }

                let y = vis_y as u16;
                let y_end = y + rows_used as u16;

                match sub_kind {
                    Some(TablePart::TopBorder) => {
                        if show_handles && snap.top_border_row.is_none() {
                            snap.top_border_row = Some(y);
                        }
                    }
                    Some(TablePart::Header { sub: 0 }) => {
                        // Anchor the column-resize glyph row on the header's first sub-line.
                        if show_handles && snap.header_row.is_none() {
                            snap.header_row = Some(y);
                        }
                    }
                    Some(TablePart::Header { .. }) => {
                        // A wrapped header's continuation lines anchor nothing new.
                    }
                    Some(TablePart::HeavyRule)
                    | Some(TablePart::Separator)
                    | Some(TablePart::BottomBorder) => {
                        // A separator closes the current data row's span.
                        if let Some((_, range)) = current_data_row_y.take() {
                            snap.row_ranges.push(range);
                        }
                        if matches!(sub_kind, Some(TablePart::BottomBorder))
                            && show_handles
                            && snap.bottom_border_row.is_none()
                            && snap.col_count > 1
                        {
                            // A single-column table can't lose its last column.
                            snap.bottom_border_row = Some(y);
                        }
                    }
                    Some(TablePart::DataRow { row, .. }) => match current_data_row_y.as_mut() {
                        Some((existing_row, range)) if *existing_row == row => {
                            range.end = y_end;
                        }
                        _ => {
                            if let Some((_, prev_range)) = current_data_row_y.take() {
                                snap.row_ranges.push(prev_range);
                            }
                            current_data_row_y = Some((row, y..y_end));
                        }
                    },
                    None => {}
                }

                // ON the outer left `│`.
                if show_handles && snap.row_handle_col.is_none() && !snap.col_ranges.is_empty() {
                    snap.row_handle_col = Some(snap.col_ranges[0].start.saturating_sub(1));
                }
                // ON the outer right `│`, overlaying the border for each data row; `hit_test`
                // checks delete before `ColumnBorder`, so non-data rows still resize here.
                if show_handles
                    && snap.delete_row_handle_col.is_none()
                    && !snap.col_ranges.is_empty()
                {
                    let outer_right = snap.col_ranges.last().unwrap().end;
                    snap.delete_row_handle_col = Some(outer_right);
                }
            }
        }

        vis_y += rows_used;
        virtual_idx += 1;
        first_sub_row = 0;
    }

    if let Some(mut prev) = open_table.take() {
        if let Some((_, range)) = current_data_row_y.take() {
            prev.row_ranges.push(range);
        }
        out.push(prev);
    }
    out
}

// ── Handle rendering ────────────────────────────────────────────────────────

/// Overlay the row/column-button glyphs on top of already-rendered table lines.
///
/// `cursor_table_start` limits painting to the table the cursor is inside; `None` paints on every
/// visible table (used by tests).
pub fn paint_handles(
    snapshots: &[TableLayoutSnapshot],
    area: Rect,
    buf: &mut TuiBuf,
    theme: &Theme,
    cursor_table_start: Option<usize>,
) {
    // Reorder and resize glyphs share the interactive accent; delete uses the louder
    // `table_handle_delete` so the destructive affordance stands out.
    let move_style: Style = theme.table_handle;
    let delete_style: Style = theme.table_handle_delete;
    for snap in snapshots {
        if let Some(start) = cursor_table_start {
            if snap.table_byte_start != start {
                continue;
            }
        } else {
            // No cursor table — skip painting handles entirely.
            return;
        }
        // One glyph per logical data row, at its first sub-line: one per wrapped sub-line reads
        // as noise, and the hit-test covers the row's full y-range anyway.
        if let Some(col) = snap.row_handle_col {
            if col < area.width {
                for y_range in &snap.row_ranges {
                    let y = y_range.start;
                    if y < area.height {
                        if let Some(cell) = buf.cell_mut((area.x + col, area.y + y)) {
                            cell.set_char(REORDER_HANDLE_GLYPH);
                            cell.set_style(move_style);
                        }
                    }
                }
            }
        }

        // Centered within each column's content span, so they overlay the `─` and leave the
        // `┌`/`┬` corners intact.
        if let Some(y) = snap.top_border_row {
            if y < area.height {
                for x_range in &snap.col_ranges {
                    let Some(x) = column_glyph_x(x_range) else {
                        continue;
                    };
                    if x < area.width {
                        if let Some(cell) = buf.cell_mut((area.x + x, area.y + y)) {
                            cell.set_char(REORDER_HANDLE_GLYPH);
                            cell.set_style(move_style);
                        }
                    }
                }
            }
        }

        // Every interior border plus the rightmost outer one (which resizes the last column).
        // Not the leftmost: there is no column to its left.
        if let Some(y) = snap.header_row {
            if y < area.height {
                for x_range in &snap.col_ranges {
                    let border_x = x_range.end;
                    if border_x < area.width {
                        if let Some(cell) = buf.cell_mut((area.x + border_x, area.y + y)) {
                            cell.set_char(COLUMN_RESIZE_GLYPH);
                            cell.set_style(move_style);
                        }
                    }
                }
            }
        }

        // One per data row, at its first sub-line, like the reorder gutter.  `row_ranges` only
        // tracks data rows, so the undeletable header and alignment rows are skipped for free.
        if let Some(col) = snap.delete_row_handle_col {
            if col < area.width {
                for y_range in &snap.row_ranges {
                    let y = y_range.start;
                    if y < area.height {
                        if let Some(cell) = buf.cell_mut((area.x + col, area.y + y)) {
                            cell.set_char(DELETE_HANDLE_GLYPH);
                            cell.set_style(delete_style);
                        }
                    }
                }
            }
        }

        // Mirrors the column-reorder glyphs on the top border.  `bottom_border_row` is `None` for
        // a single-column table, so nothing paints there.
        if let Some(y) = snap.bottom_border_row {
            if y < area.height {
                for x_range in &snap.col_ranges {
                    let Some(x) = column_glyph_x(x_range) else {
                        continue;
                    };
                    if x < area.width {
                        if let Some(cell) = buf.cell_mut((area.x + x, area.y + y)) {
                            cell.set_char(DELETE_HANDLE_GLYPH);
                            cell.set_style(delete_style);
                        }
                    }
                }
            }
        }
    }
}

// ── Drop-indicator painter ──────────────────────────────────────────────────

/// Highlight every valid drop separator for an in-progress drag — the hover target at the bright
/// accent, the other candidates dimmer.  Runs after `paint_handles` so it overlays the border
/// glyphs.  No-op when no snapshot matches the indicator's table.
pub fn paint_drop_indicator(
    snapshots: &[TableLayoutSnapshot],
    indicator: &DropIndicator,
    area: Rect,
    buf: &mut TuiBuf,
    theme: &Theme,
) {
    let active_style: Style = theme.table_drop_indicator;
    let candidate_style: Style = theme.table_drop_target;
    match *indicator {
        DropIndicator::Row {
            table_byte_start,
            src_row_idx,
            hover_row_idx,
        } => {
            let Some(snap) = snapshots
                .iter()
                .find(|s| s.table_byte_start == table_byte_start)
            else {
                return;
            };
            if src_row_idx < 2 || snap.row_ranges.is_empty() {
                return;
            }
            // The separator on the side of the hover row matching the drag direction.
            let active_y = active_row_drop_y(snap, src_row_idx, hover_row_idx);

            // Paint every valid drop dimly so the user sees the full set.  The two separators
            // bounding the source row are excluded — dropping there is a no-op.
            let src_data_idx = src_row_idx - 2;
            let Some(first) = snap.col_ranges.first() else {
                return;
            };
            let Some(last) = snap.col_ranges.last() else {
                return;
            };
            let x_start = first.start.saturating_sub(1);
            let x_end = last.end;
            let x_max = area.width;
            for (i, y_range) in snap.row_ranges.iter().enumerate() {
                // Separator above this data row.
                let above = y_range.start.saturating_sub(1);
                // Separator below this data row.
                let below = y_range.end;
                for &y in &[above, below] {
                    if y >= area.height {
                        continue;
                    }
                    // A drop on the source row's own separators is a no-op.
                    if (i == src_data_idx && (y == above || y == below))
                        || (i + 1 == src_data_idx && y == below)
                        || (i == src_data_idx + 1 && y == above)
                    {
                        continue;
                    }
                    let style = if Some(y) == active_y {
                        active_style
                    } else {
                        candidate_style
                    };
                    paint_horizontal_drop(
                        buf,
                        area.x + x_start,
                        area.x + x_end,
                        area.x + x_max,
                        area.y + y,
                        style,
                    );
                }
            }
        }
        DropIndicator::Column {
            table_byte_start,
            src_col_idx,
            hover_col_idx,
        } => {
            let Some(snap) = snapshots
                .iter()
                .find(|s| s.table_byte_start == table_byte_start)
            else {
                return;
            };
            if snap.col_ranges.is_empty() {
                return;
            }
            let active_x = active_column_drop_x(snap, src_col_idx, hover_col_idx);
            // Vertical span shared across every candidate.
            let y_top = snap
                .top_border_row
                .or_else(|| snap.row_ranges.first().map(|r| r.start.saturating_sub(2)))
                .unwrap_or(0);
            let y_bot = snap
                .row_ranges
                .last()
                .map(|r| r.end)
                .unwrap_or(area.height.saturating_sub(1));
            let y_max = area.height;
            // Every border is a candidate except the two flanking the source column.
            let mut borders: Vec<u16> = Vec::with_capacity(snap.col_ranges.len() + 1);
            if let Some(first) = snap.col_ranges.first() {
                borders.push(first.start.saturating_sub(1));
            }
            for r in &snap.col_ranges {
                borders.push(r.end);
            }
            for (i, &x) in borders.iter().enumerate() {
                if x >= area.width {
                    continue;
                }
                // Skip borders adjacent to the source column.
                if i == src_col_idx || i == src_col_idx + 1 {
                    continue;
                }
                let style = if Some(x) == active_x {
                    active_style
                } else {
                    candidate_style
                };
                paint_vertical_drop(
                    buf,
                    area.y + y_top,
                    area.y + y_bot,
                    area.y + y_max,
                    area.x + x,
                    style,
                );
            }
        }
        DropIndicator::ColumnBorder {
            table_byte_start,
            x,
        } => {
            let Some(snap) = snapshots
                .iter()
                .find(|s| s.table_byte_start == table_byte_start)
            else {
                return;
            };
            if x >= area.width {
                return;
            }
            let y_top = snap
                .top_border_row
                .or_else(|| snap.row_ranges.first().map(|r| r.start.saturating_sub(2)))
                .unwrap_or(0);
            let y_bot = snap
                .row_ranges
                .last()
                .map(|r| r.end)
                .unwrap_or(area.height.saturating_sub(1));
            let y_max = area.height;
            for y in y_top..=y_bot {
                if y >= y_max {
                    break;
                }
                if let Some(cell) = buf.cell_mut((area.x + x, area.y + y)) {
                    cell.set_char(DROP_COL_GLYPH);
                    cell.set_style(active_style);
                }
            }
        }
    }
}

/// Y of the active drop separator for a row drag; `None` over the source row itself.
fn active_row_drop_y(
    snap: &TableLayoutSnapshot,
    src_row_idx: usize,
    hover_row_idx: usize,
) -> Option<u16> {
    if hover_row_idx < 2 || hover_row_idx == src_row_idx {
        return None;
    }
    let data_idx = hover_row_idx - 2;
    let y_range = snap.row_ranges.get(data_idx)?;
    if src_row_idx > hover_row_idx {
        Some(y_range.start.saturating_sub(1))
    } else {
        Some(y_range.end)
    }
}

/// X of the active drop separator for a column drag; `None` on the source column.
fn active_column_drop_x(
    snap: &TableLayoutSnapshot,
    src_col_idx: usize,
    hover_col_idx: usize,
) -> Option<u16> {
    if hover_col_idx == src_col_idx {
        return None;
    }
    if src_col_idx > hover_col_idx {
        snap.col_ranges
            .get(hover_col_idx)
            .map(|r| r.start.saturating_sub(1))
    } else {
        snap.col_ranges.get(hover_col_idx).map(|r| r.end)
    }
}

/// Heavy horizontal rule across `[x_start, x_end]` at row `y`, clipped at `x_max`.
fn paint_horizontal_drop(
    buf: &mut TuiBuf,
    x_start: u16,
    x_end: u16,
    x_max: u16,
    y: u16,
    style: Style,
) {
    for x in x_start..=x_end {
        if x >= x_max {
            break;
        }
        if let Some(cell) = buf.cell_mut((x, y)) {
            cell.set_char(DROP_ROW_GLYPH);
            cell.set_style(style);
        }
    }
}

/// Heavy vertical rule down `[y_top, y_bot]` at column `x`, clipped at `y_max`.
fn paint_vertical_drop(buf: &mut TuiBuf, y_top: u16, y_bot: u16, y_max: u16, x: u16, style: Style) {
    for y in y_top..=y_bot {
        if y >= y_max {
            break;
        }
        if let Some(cell) = buf.cell_mut((x, y)) {
            cell.set_char(DROP_COL_GLYPH);
            cell.set_style(style);
        }
    }
}

// ── Tests ───────────────────────────────────────────────────────────────────

#[cfg(test)]
#[allow(clippy::single_range_in_vec_init)]
mod tests {
    use super::*;

    fn snap(col_ranges: Vec<Range<u16>>, row_ranges: Vec<Range<u16>>) -> TableLayoutSnapshot {
        TableLayoutSnapshot {
            table_byte_start: 0,
            table_byte_end: 100,
            col_count: col_ranges.len(),
            row_count: HEADER_ROWS + row_ranges.len(),
            col_ranges,
            row_ranges,
            row_handle_col: None,
            top_border_row: None,
            header_row: None,
            delete_row_handle_col: None,
            bottom_border_row: None,
        }
    }

    #[test]
    fn hit_test_returns_cell_for_click_in_content() {
        let s = snap(vec![1..4, 5..8], vec![3..4, 4..5]);
        let hit = s.hit_test(2, 3).unwrap();
        assert_eq!(
            hit,
            TableHit::Cell {
                row_idx: 2,
                col_idx: 0
            }
        );
    }

    #[test]
    fn hit_test_returns_border_for_click_on_pipe() {
        let s = snap(vec![1..4, 5..8], vec![3..4, 4..5]);
        // Interior border sits at col_ranges[0].end == 4.
        let hit = s.hit_test(4, 3).unwrap();
        assert_eq!(hit, TableHit::ColumnBorder { col_idx: 1 });
    }

    #[test]
    fn hit_test_border_tolerates_one_cell_miss() {
        // Col 5 is both within the border's ±1 window and `col_ranges[1].start`; borders win.
        let s = snap(vec![1..4, 5..8], vec![3..4, 4..5]);
        let hit = s.hit_test(5, 3).unwrap();
        assert!(matches!(
            hit,
            TableHit::ColumnBorder { col_idx: 1 } | TableHit::Cell { col_idx: 1, .. }
        ));
    }

    #[test]
    fn hit_test_row_handle_when_handles_enabled() {
        let mut s = snap(vec![5..8], vec![3..4]);
        s.row_handle_col = Some(2);
        let hit = s.hit_test(2, 3).unwrap();
        assert_eq!(hit, TableHit::RowHandle { row_idx: 2 });
    }

    #[test]
    fn hit_test_column_handle_when_handles_enabled() {
        let mut s = snap(vec![5..8, 9..12], vec![3..4]);
        s.top_border_row = Some(1);
        let hit = s.hit_test(6, 1).unwrap();
        assert_eq!(hit, TableHit::ColumnHandle { col_idx: 0 });
    }

    #[test]
    fn hit_test_border_in_header_row_when_resize_glyphs_on() {
        // Header at y=2, interior border at col_ranges[0].end=8.
        let mut s = snap(vec![5..8, 9..12], vec![3..4]);
        s.top_border_row = Some(1);
        s.header_row = Some(2);
        let hit = s.hit_test(8, 2).unwrap();
        assert_eq!(hit, TableHit::ColumnBorder { col_idx: 1 });
    }

    /// Regression: a gutter click on the separator between two data rows used to classify as
    /// nothing, which made grabbing the `⠿` handle a coin flip.
    #[test]
    fn hit_test_row_handle_covers_the_separator_between_rows() {
        let mut s = snap(vec![5..8], vec![3..4, 5..6]);
        s.row_handle_col = Some(2);
        // y=4 is the separator between data row 0 (y=3) and row 1 (y=5).
        assert_eq!(s.hit_test(2, 4), Some(TableHit::RowHandle { row_idx: 2 }));
        // The bounding separators count too.
        assert_eq!(s.hit_test(2, 2), Some(TableHit::RowHandle { row_idx: 2 }));
        assert_eq!(s.hit_test(2, 6), Some(TableHit::RowHandle { row_idx: 3 }));
        // …but the header / alignment rows above the band do not.
        assert_eq!(s.hit_test(2, 1), None);
    }

    /// A `┬` vertex — where a user aiming at a column handle tends to press — must resolve to an
    /// adjacent column, not fall through to `ColumnBorder` and silently start a resize.
    #[test]
    fn hit_test_column_handle_covers_the_border_vertices() {
        let mut s = snap(vec![5..8, 9..12], vec![3..4]);
        s.top_border_row = Some(1);
        // `┌` at x=4, `┬` at x=8, `┐` at x=12.
        assert_eq!(
            s.hit_test(4, 1),
            Some(TableHit::ColumnHandle { col_idx: 0 })
        );
        assert_eq!(
            s.hit_test(8, 1),
            Some(TableHit::ColumnHandle { col_idx: 0 })
        );
        assert_eq!(
            s.hit_test(12, 1),
            Some(TableHit::ColumnHandle { col_idx: 1 })
        );
        // Past the right edge the handle band ends and the border's ±1 window takes over.
        assert_eq!(
            s.hit_test(13, 1),
            Some(TableHit::ColumnBorder { col_idx: 2 })
        );
    }

    /// The destructive `✕` gets a glyph ±1 hitbox, not the column's whole width, so the bottom
    /// border stays usable as a resize target.
    #[test]
    fn hit_test_column_delete_is_scoped_to_the_glyph() {
        let mut s = snap(vec![1..8, 9..16], vec![3..4]);
        s.bottom_border_row = Some(5);
        // Glyph centre of column 0 is x = 1 + 7/2 = 4.
        assert_eq!(
            s.hit_test(4, 5),
            Some(TableHit::DeleteColumnHandle { col_idx: 0 })
        );
        assert_eq!(
            s.hit_test(5, 5),
            Some(TableHit::DeleteColumnHandle { col_idx: 0 })
        );
        // Well away from the glyph: the interior border resizes.
        assert_eq!(
            s.hit_test(8, 5),
            Some(TableHit::ColumnBorder { col_idx: 1 })
        );
    }

    #[test]
    fn hit_test_returns_none_outside_any_region() {
        let s = snap(vec![1..4, 5..8], vec![3..4]);
        assert!(s.hit_test(100, 100).is_none());
    }

    #[test]
    fn hit_test_returns_delete_row_handle_when_handle_set() {
        // The delete column sits ON the outer right `│`, so a data-row click there deletes while
        // the header / alignment rows fall through to ColumnBorder.
        let mut s = snap(vec![1..4, 5..8], vec![3..4, 4..5]);
        s.delete_row_handle_col = Some(8);
        let hit = s.hit_test(8, 3).unwrap();
        assert_eq!(hit, TableHit::DeleteRowHandle { row_idx: 2 });
        let hit = s.hit_test(8, 4).unwrap();
        assert_eq!(hit, TableHit::DeleteRowHandle { row_idx: 3 });
    }

    /// With `✕` painted ON the right border, the cell just inside it is the data-row resize
    /// target, via the `ColumnBorder ±1` tolerance.
    #[test]
    fn hit_test_cell_just_inside_right_border_still_resizes() {
        let mut s = snap(vec![1..4, 5..8], vec![3..4]);
        s.delete_row_handle_col = Some(8); // same as last.end
                                           // x=7 is one cell inside the right `│` at x=8 — within the ColumnBorder ±1 window.
        let hit = s.hit_test(7, 3).unwrap();
        assert_eq!(hit, TableHit::ColumnBorder { col_idx: 2 });
    }

    /// On a non-data row the delete glyph's x has no `row_range` match, so the click falls
    /// through to `ColumnBorder` and the right column stays resizable.
    #[test]
    fn hit_test_right_border_on_non_data_row_still_resizes() {
        let mut s = snap(vec![1..4, 5..8], vec![5..6]); // single data row at y=5
        s.delete_row_handle_col = Some(8);
        // y=3 is in the header / alignment region, outside `row_ranges`.
        assert_eq!(
            s.hit_test(8, 3),
            Some(TableHit::ColumnBorder { col_idx: 2 })
        );
    }

    /// What `config.table.show_buttons = false` guarantees: with no delete handle the right border
    /// on a data row is a plain `ColumnBorder`.
    #[test]
    fn hit_test_falls_through_when_delete_handles_disabled() {
        let s = snap(vec![1..4, 5..8], vec![3..4]);
        assert_eq!(
            s.hit_test(8, 3),
            Some(TableHit::ColumnBorder { col_idx: 2 })
        );
    }

    #[test]
    fn hit_test_returns_delete_column_handle_on_bottom_border() {
        let mut s = snap(vec![1..4, 5..8], vec![3..4]);
        s.bottom_border_row = Some(5);
        let hit = s.hit_test(2, 5).unwrap();
        assert_eq!(hit, TableHit::DeleteColumnHandle { col_idx: 0 });
        let hit = s.hit_test(6, 5).unwrap();
        assert_eq!(hit, TableHit::DeleteColumnHandle { col_idx: 1 });
    }

    /// `row_ranges` tracks only data rows, so the delete check can't fire outside one.
    #[test]
    fn hit_test_delete_row_handle_skips_header_and_alignment() {
        let mut s = snap(vec![1..4, 5..8], vec![5..6]); // single data row at y=5
        s.delete_row_handle_col = Some(8);
        // The contract: y=2 gives ColumnBorder, not DeleteRowHandle.
        assert_ne!(
            s.hit_test(8, 2),
            Some(TableHit::DeleteRowHandle { row_idx: 2 })
        );
    }

    /// An unchanged cache key must leave `snapshots` untouched.
    #[test]
    fn build_snapshots_cached_reuses_output_when_key_matches() {
        use crate::config::Theme;
        use crate::document::Buffer;
        use crate::editor::EditorState;

        let theme: &'static Theme = Box::leak(Box::new(Theme::default()));
        let src = "| a | b |\n|---|---|\n| 1 | 2 |\n";
        let state = EditorState::new(Buffer::from_str(src), theme);
        let area = Rect::new(0, 0, 40, 10);

        let mut snapshots: Vec<TableLayoutSnapshot> = Vec::new();
        let mut key: Option<(usize, Rect, u64, bool)> = None;
        build_snapshots_cached(&state, area, false, &mut snapshots, &mut key);
        let first_len = snapshots.len();
        assert!(first_len > 0, "expected at least one snapshot");

        // Tag the snapshots so a rebuild is detectable.
        snapshots[0].col_count = 999;
        build_snapshots_cached(&state, area, false, &mut snapshots, &mut key);
        assert_eq!(
            snapshots[0].col_count, 999,
            "snapshots must not be rebuilt when cache key matches",
        );

        // Changing show_handles busts the cache.
        build_snapshots_cached(&state, area, true, &mut snapshots, &mut key);
        assert_ne!(
            snapshots[0].col_count, 999,
            "snapshots must be rebuilt when show_handles changes",
        );
    }
}