tinynote 0.6.2

A minimal, local-first markdown notes TUI over plain files
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
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
//! Markdown → styled cells for the full-page preview (^P).
//!
//! Block structure comes from pulldown-cmark here; the live-preview editor is
//! line-based instead. Both share the palette in [`crate::md::theme`].
//!
//! The preview keeps more than text: every cell remembers whether it belongs to
//! a link, every line remembers which source line it came from, and checkbox and
//! image lines are tagged. That is what makes the preview clickable — open a
//! link, toggle a checkbox, or click anywhere else to land in the editor at the
//! same place.

use crate::config::TableStyle;
use crate::md::theme;
use pulldown_cmark::{Alignment, Event, Options, Parser, Tag, TagEnd};
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};

/// One rendered character: what to draw, which link (if any) it belongs to, and
/// where in the source it came from — `None` for scaffolding the renderer added
/// itself (bullets, table padding, code-block indents, image labels).
#[derive(Clone, Debug, PartialEq)]
pub struct PCell {
    pub ch: char,
    pub style: Style,
    pub link: Option<usize>,
    /// (source line, source column in chars) this character was drawn from.
    pub src: Option<(usize, usize)>,
}

/// An inline image the preview would like to draw.
#[derive(Clone, Debug, PartialEq)]
pub struct ImageSpec {
    pub alt: String,
    pub url: String,
}

/// One rendered line, plus what a click on it should do.
#[derive(Clone, Debug, Default)]
pub struct PLine {
    pub cells: Vec<PCell>,
    /// Source line to toggle when this line's checkbox is clicked.
    pub checkbox: Option<usize>,
    /// Index into [`Rendered::images`] when this line stands in for an image.
    pub image: Option<usize>,
    /// Source line this rendered line came from, for click → cursor.
    pub src_line: Option<usize>,
    /// This line is deliberately wider than the page and must not be
    /// soft-wrapped: it is one row of a scrolling table, and the page pans
    /// sideways across it instead.
    pub wide: bool,
}

/// Merge equal-styled cells into a ratatui line.
pub fn to_line(cells: &[PCell]) -> Line<'static> {
    let mut spans: Vec<Span<'static>> = Vec::new();
    let mut text = String::new();
    let mut current: Option<Style> = None;
    for cell in cells {
        if current != Some(cell.style) {
            if let Some(s) = current {
                spans.push(Span::styled(std::mem::take(&mut text), s));
            }
            current = Some(cell.style);
        }
        text.push(cell.ch);
    }
    if let Some(s) = current {
        spans.push(Span::styled(text, s));
    }
    Line::from(spans)
}

impl PLine {
    /// The plain text of the line, for tests and debugging.
    #[cfg(test)]
    pub fn text(&self) -> String {
        self.cells.iter().map(|c| c.ch).collect()
    }
}

/// A whole rendered page.
#[derive(Clone, Debug, Default)]
pub struct Rendered {
    pub lines: Vec<PLine>,
    pub urls: Vec<String>,
    pub images: Vec<ImageSpec>,
}

impl Rendered {
    pub fn url(&self, i: usize) -> Option<&str> {
        self.urls.get(i).map(String::as_str)
    }
}

/// Options: GitHub-flavoured enough for notes.
fn options() -> Options {
    Options::ENABLE_STRIKETHROUGH | Options::ENABLE_TASKLISTS | Options::ENABLE_TABLES
}

/// Unbounded-width render, for tests that don't care about the page width.
#[cfg(test)]
pub fn render(markdown: &str) -> Rendered {
    render_wide(markdown, usize::MAX)
}

/// Render for a page `width` columns wide, with the default table shape.
#[cfg(test)]
pub fn render_wide(markdown: &str, width: usize) -> Rendered {
    render_page(markdown, width, TableStyle::default())
}

/// Render for a page `width` columns wide, drawing wide tables the way the
/// settings ask for.
pub fn render_page(markdown: &str, width: usize, tables: TableStyle) -> Rendered {
    let mut r = Ren::new(markdown, width, tables);
    r.run(markdown);
    r.finish()
}

/// Where cells are currently going: the page, or a table cell being measured.
enum Sink {
    Page,
    Table,
}

#[derive(Default)]
struct Table {
    aligns: Vec<Alignment>,
    rows: Vec<Vec<Vec<PCell>>>,
    in_head: bool,
    row: Vec<Vec<PCell>>,
}

struct Ren {
    /// The source, kept so cells can remember the column they came from.
    src: String,
    out: Rendered,
    cells: Vec<PCell>,
    cell_buf: Vec<PCell>,
    sink: Sink,
    styles: Vec<Style>,
    link: Option<usize>,
    prefix: String,
    list_depth: usize,
    in_code_block: bool,
    table: Option<Table>,
    /// How a table wider than the page is drawn.
    tables: TableStyle,
    /// Page width in columns, used to size tables.
    width: usize,
    /// Byte offset of the start of each source line.
    line_starts: Vec<usize>,
    /// Source line for the line currently being built.
    src_line: Option<usize>,
    pending_checkbox: Option<usize>,
    done_item: bool,
    image_alt: Option<(String, String)>,
}

impl Ren {
    fn new(markdown: &str, width: usize, tables: TableStyle) -> Ren {
        let mut line_starts = vec![0usize];
        for (i, b) in markdown.bytes().enumerate() {
            if b == b'\n' {
                line_starts.push(i + 1);
            }
        }
        Ren {
            src: markdown.to_string(),
            out: Rendered::default(),
            cells: Vec::new(),
            cell_buf: Vec::new(),
            sink: Sink::Page,
            styles: vec![Style::default()],
            link: None,
            prefix: String::new(),
            list_depth: 0,
            in_code_block: false,
            table: None,
            tables,
            width,
            line_starts,
            src_line: None,
            pending_checkbox: None,
            done_item: false,
            image_alt: None,
        }
    }

    fn style(&self) -> Style {
        *self.styles.last().unwrap()
    }

    fn buf(&mut self) -> &mut Vec<PCell> {
        match self.sink {
            Sink::Page => &mut self.cells,
            Sink::Table => &mut self.cell_buf,
        }
    }

    /// Push scaffolding the renderer invented: it maps back to no source column.
    fn push(&mut self, text: &str, style: Style, link: Option<usize>) {
        self.push_at(text, style, link, None);
    }

    /// Push text, optionally carrying the source byte offset of its first
    /// character so each cell remembers where it came from.
    fn push_at(&mut self, text: &str, style: Style, link: Option<usize>, off: Option<usize>) {
        let mut off = off;
        let mut cells: Vec<PCell> = Vec::with_capacity(text.len());
        for ch in text.chars() {
            cells.push(PCell {
                ch,
                style,
                link,
                src: off.map(|o| self.pos_of(o)),
            });
            if let Some(o) = off.as_mut() {
                *o += ch.len_utf8();
            }
        }
        self.buf().extend(cells);
    }

    fn line_of(&self, offset: usize) -> usize {
        match self.line_starts.binary_search(&offset) {
            Ok(i) => i,
            Err(i) => i.saturating_sub(1),
        }
    }

    /// Source byte offset → (line, column in chars).
    fn pos_of(&self, offset: usize) -> (usize, usize) {
        let line = self.line_of(offset);
        let start = self.line_starts.get(line).copied().unwrap_or(0);
        let offset = offset.min(self.src.len());
        let col = self.src.get(start..offset).map_or(0, |s| s.chars().count());
        (line, col)
    }

    fn flush(&mut self) {
        if self.cells.is_empty() {
            return;
        }
        let cells = std::mem::take(&mut self.cells);
        self.out.lines.push(PLine {
            cells,
            checkbox: self.pending_checkbox.take(),
            image: None,
            src_line: self.src_line,
            wide: false,
        });
    }

    fn blank(&mut self) {
        self.flush();
        if !self
            .out
            .lines
            .last()
            .map(|l| l.cells.is_empty())
            .unwrap_or(true)
        {
            self.out.lines.push(PLine::default());
        }
    }

    /// Start a line inside a blockquote with its `▌ ` bars. Continuation lines
    /// get theirs at the soft break; this is the first line of each block.
    fn line_prefix(&mut self) {
        if self.prefix.is_empty() || !matches!(self.sink, Sink::Page) || !self.cells.is_empty() {
            return;
        }
        let p = self.prefix.clone();
        self.push(&p, theme::marker(), None);
    }

    fn indent(&self) -> String {
        format!(
            "{}{}",
            self.prefix,
            "  ".repeat(self.list_depth.saturating_sub(1))
        )
    }

    /// Text from the document: scan for `==highlight==` and bare URLs.
    /// `off` is the source byte offset of `text`, when it is a verbatim slice.
    fn emit_text(&mut self, text: &str, off: Option<usize>) {
        let base = self.style();
        let link = self.link;
        let chars: Vec<char> = text.chars().collect();
        // byte offset of each char, so every run knows where it started
        let mut byte_at: Vec<usize> = Vec::with_capacity(chars.len() + 1);
        let mut b = 0;
        for ch in &chars {
            byte_at.push(b);
            b += ch.len_utf8();
        }
        byte_at.push(b);
        let at = |i: usize| off.map(|o| o + byte_at[i]);

        let mut i = 0;
        let mut run = String::new();
        let mut run_start = 0usize;
        while i < chars.len() {
            // ==highlight==
            if chars[i] == '=' && chars.get(i + 1) == Some(&'=') {
                if let Some(end) = find_pair(&chars, i + 2) {
                    self.push_at(&std::mem::take(&mut run), base, link, at(run_start));
                    let body: String = chars[i + 2..end].iter().collect();
                    self.push_at(&body, base.patch(theme::highlight()), link, at(i + 2));
                    i = end + 2;
                    run_start = i;
                    continue;
                }
            }
            // bare URL, when not already inside a link
            if link.is_none() && starts_url(&chars, i) {
                let mut end = i;
                while end < chars.len() && !chars[end].is_whitespace() {
                    end += 1;
                }
                while end > i && matches!(chars[end - 1], '.' | ',' | ')' | ']' | '!' | '?') {
                    end -= 1;
                }
                let url: String = chars[i..end].iter().collect();
                self.push_at(&std::mem::take(&mut run), base, None, at(run_start));
                let idx = self.out.urls.len();
                self.out.urls.push(url.clone());
                self.push_at(&url, base.patch(theme::link()), Some(idx), at(i));
                i = end;
                run_start = i;
                continue;
            }
            if run.is_empty() {
                run_start = i;
            }
            run.push(chars[i]);
            i += 1;
        }
        self.push_at(&run, base, link, at(run_start));
    }

    fn run(&mut self, markdown: &str) {
        for (event, range) in Parser::new_ext(markdown, options()).into_offset_iter() {
            let src_line = self.line_of(range.start);
            if self.cells.is_empty() && matches!(self.sink, Sink::Page) {
                self.src_line = Some(src_line);
            }
            self.event(event, src_line, range);
        }
        self.flush();
    }

    fn event(&mut self, event: Event<'_>, src_line: usize, range: std::ops::Range<usize>) {
        match event {
            Event::Start(Tag::Heading { level, .. }) => {
                self.blank();
                self.src_line = Some(src_line);
                self.line_prefix();
                self.styles.push(theme::heading(level as usize));
            }
            Event::End(TagEnd::Heading(_)) => {
                self.styles.pop();
                self.flush();
            }
            Event::Start(Tag::Paragraph) => {
                if self.list_depth == 0 && self.table.is_none() {
                    self.blank();
                    self.src_line = Some(src_line);
                }
                self.line_prefix();
            }
            Event::End(TagEnd::Paragraph) => self.flush(),
            Event::Start(Tag::BlockQuote(_)) => {
                self.blank();
                self.prefix.push_str("");
                self.styles.push(theme::quote());
            }
            Event::End(TagEnd::BlockQuote(_)) => {
                self.styles.pop();
                let n = self.prefix.len().saturating_sub("".len());
                self.prefix.truncate(n);
                self.flush();
            }
            Event::Start(Tag::List(_)) => {
                if self.list_depth == 0 {
                    self.blank();
                }
                self.list_depth += 1;
            }
            Event::End(TagEnd::List(_)) => {
                self.list_depth = self.list_depth.saturating_sub(1);
                self.flush();
            }
            Event::Start(Tag::Item) => {
                self.flush();
                self.src_line = Some(src_line);
                let text = format!("{}{} ", self.indent(), theme::BULLET);
                self.push(&text, theme::marker(), None);
            }
            Event::End(TagEnd::Item) => {
                if self.done_item {
                    self.styles.pop();
                    self.done_item = false;
                }
                self.flush()
            }
            Event::TaskListMarker(done) => {
                // replace the bullet we pushed at the start of the item
                self.cells.clear();
                let (mark, style) = if done {
                    (theme::CHECKED, theme::done())
                } else {
                    (theme::UNCHECKED, theme::marker())
                };
                let text = format!("{}{mark} ", self.indent());
                self.push(&text, style, None);
                self.pending_checkbox = Some(src_line);
                if done {
                    // done items read as struck-through and dim until the item ends
                    self.styles.push(self.style().patch(theme::done_text()));
                    self.done_item = true;
                }
            }
            Event::Start(Tag::CodeBlock(_)) => {
                self.blank();
                self.src_line = Some(src_line);
                self.in_code_block = true;
            }
            Event::End(TagEnd::CodeBlock) => {
                self.in_code_block = false;
                self.flush();
            }
            Event::Start(Tag::Emphasis) => self
                .styles
                .push(self.style().add_modifier(Modifier::ITALIC)),
            Event::Start(Tag::Strong) => {
                self.styles.push(self.style().add_modifier(Modifier::BOLD))
            }
            Event::Start(Tag::Strikethrough) => self
                .styles
                .push(self.style().add_modifier(Modifier::CROSSED_OUT)),
            Event::End(TagEnd::Emphasis)
            | Event::End(TagEnd::Strong)
            | Event::End(TagEnd::Strikethrough) => {
                self.styles.pop();
            }
            Event::Start(Tag::Link { dest_url, .. }) => {
                let idx = self.out.urls.len();
                self.out.urls.push(dest_url.into_string());
                self.link = Some(idx);
                self.styles.push(self.style().patch(theme::link()));
            }
            Event::End(TagEnd::Link) => {
                self.styles.pop();
                self.link = None;
            }
            Event::Start(Tag::Image { dest_url, .. }) => {
                self.image_alt = Some((String::new(), dest_url.into_string()));
            }
            Event::End(TagEnd::Image) => {
                if let Some((alt, url)) = self.image_alt.take() {
                    self.flush();
                    let idx = self.out.images.len();
                    self.out.images.push(ImageSpec {
                        alt: alt.clone(),
                        url: url.clone(),
                    });
                    let label = if alt.is_empty() {
                        format!("🖼 {url}")
                    } else {
                        format!("🖼 {alt} ({url})")
                    };
                    self.push(&label, theme::marker(), None);
                    let cells = std::mem::take(&mut self.cells);
                    self.out.lines.push(PLine {
                        cells,
                        checkbox: None,
                        image: Some(idx),
                        src_line: self.src_line,
                        wide: false,
                    });
                }
            }
            // tables
            Event::Start(Tag::Table(aligns)) => {
                self.blank();
                self.src_line = Some(src_line);
                self.table = Some(Table {
                    aligns,
                    ..Table::default()
                });
            }
            Event::End(TagEnd::Table) => self.emit_table(),
            Event::Start(Tag::TableHead) => {
                if let Some(t) = self.table.as_mut() {
                    t.in_head = true;
                }
            }
            Event::End(TagEnd::TableHead) | Event::End(TagEnd::TableRow) => {
                if let Some(t) = self.table.as_mut() {
                    let row = std::mem::take(&mut t.row);
                    t.rows.push(row);
                    t.in_head = false;
                }
            }
            Event::Start(Tag::TableRow) => {}
            Event::Start(Tag::TableCell) => {
                self.cell_buf.clear();
                self.sink = Sink::Table;
                if self.table.as_ref().is_some_and(|t| t.in_head) {
                    self.styles.push(self.style().add_modifier(Modifier::BOLD));
                }
            }
            Event::End(TagEnd::TableCell) => {
                if self.table.as_ref().is_some_and(|t| t.in_head) {
                    self.styles.pop();
                }
                self.sink = Sink::Page;
                let cell = std::mem::take(&mut self.cell_buf);
                if let Some(t) = self.table.as_mut() {
                    t.row.push(cell);
                }
            }
            Event::Code(code) => {
                let style = self.style().patch(theme::code());
                let link = self.link;
                // the range spans the backticks too; the content starts after them
                let ticks = self.src[range.clone()]
                    .chars()
                    .take_while(|c| *c == '`')
                    .count();
                self.push_at(&code.into_string(), style, link, Some(range.start + ticks));
            }
            Event::Text(text) => {
                if let Some((alt, _)) = self.image_alt.as_mut() {
                    alt.push_str(&text);
                } else if self.in_code_block {
                    let mut off = range.start;
                    // split_inclusive, not lines(): the line ending has to be
                    // counted as it is in the file, `\r\n` included, or every
                    // later offset in a CRLF note drifts by a byte a line
                    for raw in text.split_inclusive('\n') {
                        let l = raw.trim_end_matches('\n').trim_end_matches('\r');
                        // the two-space indent is ours; the code itself is the file's
                        self.push("  ", theme::code(), None);
                        self.push_at(l, theme::code(), None, Some(off));
                        off += raw.len();
                        let cells = std::mem::take(&mut self.cells);
                        self.out.lines.push(PLine {
                            cells,
                            checkbox: None,
                            image: None,
                            src_line: self.src_line,
                            wide: false,
                        });
                    }
                } else {
                    self.emit_text(&text, Some(range.start));
                }
            }
            Event::SoftBreak => {
                if matches!(self.sink, Sink::Table) {
                    self.push(" ", self.style(), self.link);
                } else {
                    self.flush();
                    self.src_line = Some(src_line);
                    if !self.prefix.is_empty() {
                        let p = self.prefix.clone();
                        self.push(&p, theme::marker(), None);
                    }
                }
            }
            Event::HardBreak => self.flush(),
            Event::Rule => {
                self.blank();
                self.push(&"".repeat(40), theme::marker(), None);
                self.flush();
            }
            _ => {}
        }
    }

    /// Lay out the buffered table. Three shapes, because one shape cannot
    /// serve a two-column table and an eight-column one on the same page:
    /// a grid, a grid whose cells wrap, or one labelled block per row.
    fn emit_table(&mut self) {
        let Some(t) = self.table.take() else { return };
        if t.rows.is_empty() {
            return;
        }
        let cols = t.rows.iter().map(|r| r.len()).max().unwrap_or(0);
        let measured: Vec<Vec<usize>> = t
            .rows
            .iter()
            .map(|r| r.iter().map(|c| cells_width(c)).collect())
            .collect();
        let natural = crate::md::column_widths(&measured, cols);
        let seps = crate::md::COL_SEP.chars().count() * cols.saturating_sub(1);
        let fits = natural.iter().sum::<usize>() + seps <= self.width;

        match self.table_shape(cols, seps, fits) {
            Shape::Grid { wrap } => {
                let widths = crate::md::fit_widths(&natural, self.width);
                self.emit_grid(&t, cols, &widths, wrap, false);
            }
            Shape::Scroll => {
                let widths = self.scroll_widths(&natural);
                self.emit_grid(&t, cols, &widths, true, true);
            }
            Shape::Cards => self.emit_cards(&t, cols),
        }
    }

    /// Which shape this table gets. `auto` keeps the grid while its columns are
    /// still wide enough to read a phrase in, and gives up on it — rather than
    /// shaving every column to a stub and an ellipsis — once they are not.
    fn table_shape(&self, cols: usize, seps: usize, fits: bool) -> Shape {
        // below this the columns hit their floor and the grid runs off the
        // page whatever it is told to do, so cards are the only shape left
        let grid_possible = self.width >= cols * crate::md::MIN_COL + seps;
        match self.tables {
            TableStyle::Fit => Shape::Grid { wrap: false },
            TableStyle::Wrap if grid_possible => Shape::Grid { wrap: !fits },
            TableStyle::Wrap => Shape::Cards,
            TableStyle::Cards => Shape::Cards,
            TableStyle::Scroll => Shape::Scroll,
            // a table that already fits is left exactly as it was; one that
            // does not keeps its columns readable and pans instead
            TableStyle::Auto if fits => Shape::Grid { wrap: false },
            TableStyle::Auto => Shape::Scroll,
        }
    }

    /// Column widths for a scrolling table: each column as wide as its widest
    /// cell, capped so a single long URL cannot push every other column off
    /// the far side. The cap is a share of the page, not a fixed number, so it
    /// scales with the window the way Obsidian's does.
    fn scroll_widths(&self, natural: &[usize]) -> Vec<usize> {
        /// Narrowest a column is ever capped to, and the share of the page a
        /// single column may claim before it starts wrapping.
        const FLOOR: usize = 12;
        let cap = (self.width / 3).clamp(FLOOR, 44);
        natural.iter().map(|w| (*w).min(cap).max(1)).collect()
    }

    /// Aligned columns with a light rule under the head. `wrap` lets a cell
    /// that does not fit run onto further lines instead of being cut.
    fn emit_grid(&mut self, t: &Table, cols: usize, widths: &[usize], wrap: bool, wide: bool) {
        let src_line = self.src_line;
        // a rule between body rows only earns its keep once rows are taller
        // than one line, where without it the eye loses which row it is on
        let mut ruled = false;
        for (ri, row) in t.rows.iter().enumerate() {
            let empty: Vec<PCell> = Vec::new();
            // every cell, already broken into the lines it will occupy
            let parts: Vec<Vec<Vec<PCell>>> = (0..cols)
                .map(|ci| {
                    let cell = row.get(ci).unwrap_or(&empty);
                    let w = widths.get(ci).copied().unwrap_or(0);
                    if wrap {
                        wrap_pcells(cell, w.max(1))
                    } else {
                        vec![truncate_cells(cell, w)]
                    }
                })
                .collect();
            let height = parts.iter().map(|p| p.len()).max().unwrap_or(1);
            if height > 1 {
                ruled = true;
            }
            for line in 0..height {
                let mut cells: Vec<PCell> = Vec::new();
                for (ci, w) in widths.iter().enumerate().take(cols) {
                    if ci > 0 {
                        cells.extend(str_cells(crate::md::COL_SEP, theme::marker()));
                    }
                    let blank: Vec<PCell> = Vec::new();
                    let part = parts[ci].get(line).unwrap_or(&blank);
                    let align = align_of(t.aligns.get(ci).copied().unwrap_or(Alignment::None));
                    let (left, right) = crate::md::pad_for(cells_width(part), *w, align);
                    cells.extend(str_cells(&" ".repeat(left), theme::PLAIN));
                    cells.extend(part.iter().cloned());
                    cells.extend(str_cells(&" ".repeat(right), theme::PLAIN));
                }
                self.out.lines.push(PLine {
                    cells,
                    checkbox: None,
                    image: None,
                    src_line,
                    wide,
                });
            }
            // under the head always; between wrapped body rows as well
            let last = ri + 1 == t.rows.len();
            if ri == 0 || (ruled && !last) {
                let rule = crate::md::table_rule(widths);
                self.out.lines.push(PLine {
                    cells: str_cells(&rule, theme::marker()),
                    checkbox: None,
                    image: None,
                    src_line,
                    wide,
                });
            }
        }
    }

    /// One block per row: the row's first cells as a heading, then every other
    /// column as `label  value` under it. Nothing is truncated, so a table
    /// twenty columns wide is still readable on an eighty-column terminal —
    /// it is simply taller.
    fn emit_cards(&mut self, t: &Table, cols: usize) {
        let src_line = self.src_line;
        let empty: Vec<PCell> = Vec::new();
        let head: Vec<String> = (0..cols)
            .map(|ci| {
                t.rows
                    .first()
                    .and_then(|r| r.get(ci))
                    .map(|c| c.iter().map(|p| p.ch).collect::<String>())
                    .unwrap_or_default()
                    .trim()
                    .to_string()
            })
            .collect();
        // the label column is as wide as the widest heading, so the values
        // line up down the whole table and can be read as a column
        let labelw = head
            .iter()
            .skip(1)
            .map(|h| crate::md::str_width(h))
            .max()
            .unwrap_or(0);

        let push = |cells: Vec<PCell>, out: &mut Rendered| {
            out.lines.push(PLine {
                cells,
                checkbox: None,
                image: None,
                src_line,
                wide: false,
            });
        };

        for (ri, row) in t.rows.iter().enumerate().skip(1) {
            if ri > 1 {
                push(Vec::new(), &mut self.out);
            }
            // the heading: the first column, which is nearly always the row's
            // name or date, marked with the same bar a blockquote uses
            let mut title = str_cells(&format!("{} ", crate::md::theme::QUOTE_BAR), theme::state());
            let first = truncate_cells(row.first().unwrap_or(&empty), self.width.saturating_sub(2));
            title.extend(first.iter().map(|c| {
                let mut c = c.clone();
                c.style = c.style.patch(theme::heading(3)).fg(theme::palette().accent);
                c
            }));
            push(title, &mut self.out);

            for ci in 1..cols {
                let value = row.get(ci).unwrap_or(&empty);
                // an empty cell says nothing worth a line of its own
                if value.iter().all(|c| c.ch.is_whitespace()) {
                    continue;
                }
                let label = head.get(ci).cloned().unwrap_or_default();
                let pad = labelw.saturating_sub(crate::md::str_width(&label));
                let indent = 2 + labelw + 2;
                let avail = self.width.saturating_sub(indent).max(8);
                for (i, part) in wrap_pcells(value, avail).into_iter().enumerate() {
                    let mut cells = if i == 0 {
                        let mut c = str_cells("  ", theme::PLAIN);
                        c.extend(str_cells(&label, theme::marker()));
                        c.extend(str_cells(&" ".repeat(pad + 2), theme::PLAIN));
                        c
                    } else {
                        // continuation lines hang under the value, not the label
                        str_cells(&" ".repeat(indent), theme::PLAIN)
                    };
                    cells.extend(part);
                    push(cells, &mut self.out);
                }
            }
        }
    }

    fn finish(mut self) -> Rendered {
        self.flush();
        self.out
    }
}

/// The three ways a table can be laid out, once `auto` has made up its mind.
enum Shape {
    Grid {
        wrap: bool,
    },
    /// Natural column widths, capped so no one column runs away with the
    /// table, and the page pans across whatever that adds up to.
    Scroll,
    Cards,
}

/// Word-wrap a run of rendered cells into rows no wider than `width` display
/// columns. Shared by the preview's own soft wrap and by table cells, so a
/// wrapped cell breaks where a wrapped paragraph would.
pub fn wrap_pcells(cells: &[PCell], width: usize) -> Vec<Vec<PCell>> {
    if width == 0 || cells_width(cells) <= width {
        return vec![cells.to_vec()];
    }
    let chars: Vec<char> = cells.iter().map(|c| c.ch).collect();
    crate::md::wrap_breaks(&chars, width, width)
        .into_iter()
        .map(|(s, e)| cells[s..e].to_vec())
        .collect()
}

/// pulldown's alignment in the shared vocabulary.
fn align_of(a: Alignment) -> crate::md::Align {
    match a {
        Alignment::Right => crate::md::Align::Right,
        Alignment::Center => crate::md::Align::Center,
        _ => crate::md::Align::Left,
    }
}

fn str_cells(s: &str, style: Style) -> Vec<PCell> {
    s.chars()
        .map(|ch| PCell {
            ch,
            style,
            link: None,
            src: None,
        })
        .collect()
}

/// A cell run cut to `width` columns, ellipsis included when it was cut.
fn truncate_cells(cells: &[PCell], width: usize) -> Vec<PCell> {
    if cells_width(cells) <= width {
        return cells.to_vec();
    }
    let mut out: Vec<PCell> = Vec::new();
    let mut used = 0;
    for c in cells {
        let cw = crate::md::char_width(c.ch);
        if used + cw > width.saturating_sub(1) {
            break;
        }
        out.push(c.clone());
        used += cw;
    }
    let style = out.last().map(|c| c.style).unwrap_or(theme::PLAIN);
    out.push(PCell {
        ch: '',
        style,
        link: None,
        src: None,
    });
    out
}

/// Display width of a run of cells, in terminal columns.
pub fn cells_width(cells: &[PCell]) -> usize {
    cells.iter().map(|c| crate::md::char_width(c.ch)).sum()
}

fn starts_url(chars: &[char], i: usize) -> bool {
    let rest: String = chars[i..].iter().take(8).collect();
    (rest.starts_with("http://") || rest.starts_with("https://"))
        && (i == 0 || !chars[i - 1].is_alphanumeric())
}

fn find_pair(chars: &[char], from: usize) -> Option<usize> {
    (from..chars.len().saturating_sub(1)).find(|&k| chars[k] == '=' && chars[k + 1] == '=')
}

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

    fn flat(r: &Rendered) -> String {
        r.lines
            .iter()
            .map(|l| l.text())
            .collect::<Vec<_>>()
            .join("\n")
    }

    #[test]
    fn renders_without_panic() {
        let md = "# Title\n\nSome **bold** and *italic* and `code`.\n\n- one\n- [ ] task\n- [x] done\n\n> quote\n\n```\nlet x = 1;\n```\n\n---\n";
        let r = render(md);
        assert!(r.lines.len() > 5);
        let flat = flat(&r);
        assert!(flat.contains("Title"));
        assert!(flat.contains("bold"));
        assert!(flat.contains("let x = 1;"));
    }

    #[test]
    fn code_block_offsets_survive_crlf() {
        for md in [
            "# T\n\n```\nlet x = 1;\nlet y = 2;\n```\n\ntail\n",
            "# T\r\n\r\n```\r\nlet x = 1;\r\nlet y = 2;\r\n```\r\n\r\ntail\r\n",
        ] {
            let src_lines: Vec<&str> = md.lines().collect();
            for line in &render(md).lines {
                for c in &line.cells {
                    // every mapped cell points at its own character
                    if let Some((l, col)) = c.src {
                        let at = src_lines[l].chars().nth(col);
                        assert_eq!(at, Some(c.ch), "{md:?} at ({l},{col})");
                    }
                }
            }
        }
    }

    const WIDE: &str = "| a | bbbbbbbbbbbbbbbbbbbb |\n| --- | --- |\n| 1 | 2 |\n";

    /// The table this whole feature exists for: eight columns of real content.
    const JOB_LOG: &str = concat!(
        "| date | company | title | comp | location | path | doc | status |\n",
        "|---|---|---|---|---|---|---|---|\n",
        "| 2026-08-25 | Harrison Consulting | Director of Product | $220K/yr | ",
        "Seattle, WA | LinkedIn Easy Apply | doc | applied |\n",
    );

    #[test]
    fn a_wide_table_is_squeezed_into_the_page_width() {
        let r = render_page(WIDE, 16, TableStyle::Fit);
        for l in &r.lines {
            assert!(cells_width(&l.cells) <= 16);
        }
        let head: String = r.lines[0].cells.iter().map(|c| c.ch).collect();
        assert_eq!(head, "a │ bbbbbbbbbbb…");
    }

    #[test]
    fn a_line_is_either_inside_the_page_or_marked_wide() {
        // the whole contract in one assertion: a shape either fits the page,
        // or says it does not so the view pans across it instead of wrapping
        for width in [24usize, 40, 80, 100] {
            for style in [
                TableStyle::Auto,
                TableStyle::Scroll,
                TableStyle::Wrap,
                TableStyle::Cards,
            ] {
                for l in &render_page(JOB_LOG, width, style).lines {
                    assert!(
                        l.wide || cells_width(&l.cells) <= width,
                        "{style:?} at {width}: {:?}",
                        l.text()
                    );
                }
            }
        }
    }

    #[test]
    fn a_scrolling_table_keeps_its_columns_and_cuts_nothing() {
        let r = render_page(JOB_LOG, 60, TableStyle::Scroll);
        let table: Vec<&PLine> = r.lines.iter().filter(|l| l.wide).collect();
        assert!(!table.is_empty());
        let text: String = table.iter().map(|l| l.text()).collect();
        // no column was shaved down to an ellipsis
        assert!(!text.contains(''), "{text}");
        // and the words are whole, not broken across a nine-column cell
        assert!(text.contains("Harrison"), "{text}");
        assert!(text.contains("applied"), "{text}");
        // the table is genuinely wider than the page — that is the point
        assert!(table.iter().any(|l| cells_width(&l.cells) > 60));
        // every row of it is the same width, so the columns line up while it pans
        let widths: Vec<usize> = table.iter().map(|l| cells_width(&l.cells)).collect();
        assert!(widths.windows(2).all(|w| w[0] == w[1]), "{widths:?}");
    }

    #[test]
    fn one_runaway_column_cannot_push_the_others_off_the_far_side() {
        let md = concat!(
            "| a | b |\n|---|---|\n",
            "| short | https://example.com/an/extremely/long/url/that/goes/on/and/on/forever |\n",
        );
        let r = render_page(md, 60, TableStyle::Scroll);
        // capped at a third of the page, so the long cell wraps rather than
        // making the table hundreds of columns wide
        for l in r.lines.iter().filter(|l| l.wide) {
            assert!(cells_width(&l.cells) <= 60 + 60 / 3, "{:?}", l.text());
        }
    }

    #[test]
    fn wrapping_keeps_every_word_a_squeezed_grid_would_have_cut() {
        let r = render_page(WIDE, 16, TableStyle::Wrap);
        let text: String = r.lines.iter().map(|l| l.text()).collect();
        assert!(text.contains("bbbbbbbb"), "{text:?}");
        // nothing was cut, so no ellipsis was needed
        assert!(!text.contains(''), "{text:?}");
    }

    #[test]
    fn cards_label_every_value_and_truncate_nothing() {
        let md = concat!(
            "| date | company | status |\n|---|---|---|\n",
            "| 2026-08-25 | Harrison Consulting | applied |\n",
        );
        let r = render_page(md, 30, TableStyle::Cards);
        let text: String = r.lines.iter().map(|l| format!("{}\n", l.text())).collect();
        // the first column heads the block; the rest are labelled under it
        assert!(text.contains("2026-08-25"), "{text}");
        assert!(text.contains("company"), "{text}");
        assert!(text.contains("Harrison Consulting"), "{text}");
        assert!(text.contains("status"), "{text}");
        assert!(text.contains("applied"), "{text}");
        // the header row is the labels, never a card of its own
        assert!(!text.contains("▌ date"), "{text}");
        assert!(!text.contains(''), "{text}");
    }

    #[test]
    fn auto_leaves_a_table_that_fits_alone_and_scrolls_one_that_does_not() {
        // two roomy columns: still a grid, with the head rule under it
        let narrow = "| a | b |\n|---|---|\n| 1 | 2 |\n";
        let grid: String = render_page(narrow, 80, TableStyle::Auto)
            .lines
            .iter()
            .map(|l| format!("{}\n", l.text()))
            .collect();
        assert!(grid.contains(''), "{grid}");
        assert!(!grid.contains(''), "{grid}");

        // one that does not fit keeps its columns and pans instead
        let r = render_page(JOB_LOG, 60, TableStyle::Auto);
        assert!(r.lines.iter().any(|l| l.wide));
        let text: String = r.lines.iter().map(|l| l.text()).collect();
        assert!(!text.contains(''), "{text}");
    }

    #[test]
    fn tables_get_aligned_columns_and_a_head_rule() {
        let md = "| a | bbbb |\n| --- | ---: |\n| 1 | 2 |\n";
        let r = render(md);
        let rows: Vec<String> = r
            .lines
            .iter()
            .map(|l| l.text())
            .filter(|t| !t.trim().is_empty())
            .collect();
        assert_eq!(rows[0], "a │ bbbb");
        assert_eq!(rows[1], "──┼─────");
        assert_eq!(rows[2], "1 │    2"); // right aligned
                                         // the header is bold
        assert!(r.lines[0].cells[0]
            .style
            .add_modifier
            .contains(Modifier::BOLD));
    }

    #[test]
    fn table_columns_are_measured_in_display_columns() {
        let r = render("| 漢字 | b |\n| --- | --- |\n| x | y |\n");
        let rows: Vec<&PLine> = r
            .lines
            .iter()
            .filter(|l| !l.text().trim().is_empty())
            .collect();
        let widths: Vec<usize> = rows.iter().map(|l| cells_width(&l.cells)).collect();
        // every row, rule included, lines up at the same width
        assert!(widths.windows(2).all(|w| w[0] == w[1]), "{widths:?}");
    }

    #[test]
    fn every_quoted_line_gets_its_bar() {
        // the first line of a quote needs the bar as much as its continuations
        let r = render("> first line\n> second line\n\nafter\n");
        let quoted: Vec<String> = r
            .lines
            .iter()
            .map(|l| l.text())
            .filter(|t| t.contains("line"))
            .collect();
        assert_eq!(quoted, vec!["▌ first line", "▌ second line"]);
        // text outside the quote keeps its bar off
        assert!(r.lines.iter().any(|l| l.text() == "after"));
    }

    #[test]
    fn highlight_gets_the_highlight_style() {
        let r = render("a ==wow== b");
        let line = r.lines.iter().find(|l| l.text().contains("wow")).unwrap();
        assert_eq!(line.text(), "a wow b");
        let cell = line.cells.iter().find(|c| c.ch == 'w').unwrap();
        assert_eq!(cell.style.bg, theme::highlight().bg);
    }

    #[test]
    fn checkboxes_render_and_remember_their_source_line() {
        let r = render("# t\n\n- [ ] todo\n- [x] done\n");
        let todo = r.lines.iter().find(|l| l.text().contains("todo")).unwrap();
        assert_eq!(todo.text(), "☐ todo");
        assert_eq!(todo.checkbox, Some(2));
        let done = r.lines.iter().find(|l| l.text().contains("done")).unwrap();
        assert_eq!(done.text(), "✓ done");
        assert_eq!(done.checkbox, Some(3));
        assert!(done.cells[0].style.fg == theme::done().fg);
    }

    #[test]
    fn links_and_bare_urls_are_recorded() {
        let r = render("see [docs](http://x.y) and https://z.example/p now");
        let line = r.lines.iter().find(|l| l.text().contains("docs")).unwrap();
        let docs = line.cells.iter().find(|c| c.ch == 'd').unwrap();
        assert_eq!(r.url(docs.link.unwrap()), Some("http://x.y"));
        let bare = line
            .cells
            .iter()
            .find(|c| c.link.map(|i| r.urls[i].starts_with("https://z")) == Some(true))
            .unwrap();
        assert_eq!(r.url(bare.link.unwrap()), Some("https://z.example/p"));
        assert!(line.text().contains("https://z.example/p"));
    }

    #[test]
    fn images_become_their_own_line() {
        let r = render("![a cat](cat.png)\n");
        let line = r.lines.iter().find(|l| l.image.is_some()).unwrap();
        assert_eq!(line.text(), "🖼 a cat (cat.png)");
        assert_eq!(
            r.images[line.image.unwrap()],
            ImageSpec {
                alt: "a cat".into(),
                url: "cat.png".into()
            }
        );
    }
}