twrite-core 0.9.0

Headless buffer, movement, syntax, and hook primitives for twrite
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
use std::ops::Range;
use std::sync::{Arc, RwLock};

use crate::{
    ConcealedLine, DisplayPad, EditorBuffer, HighlightTag, StyleSpan, SyntaxHighlighter,
    display_width,
};

use super::config::{ConcealMode, MarkdownConfig};
use super::links::extract_markdown_links;
use super::table::{
    TABLE_CELL_TAG, TABLE_DELIMITER_TAG, TABLE_HEADER_TAG, TableAlignment, TableBlock, TableLayout,
    TableRowKind, clean_table_line, find_unescaped_pipes, is_fenced_row, split_table_cells,
    table_layouts_with_fences,
};

/// Cached table display layouts and associated document version.
type TableCache = Arc<RwLock<Option<(usize, Vec<TableLayout>)>>>;

/// Cached fence line row indices and associated document version.
type FenceCache = Arc<RwLock<Option<(usize, Vec<usize>)>>>;

/// A syntax highlighter for CommonMark and GFM Markdown documents using `pulldown-cmark`.
#[derive(Debug, Clone)]
pub struct MarkdownHighlighter {
    config: MarkdownConfig,
    cached_fences: FenceCache,
    cached_tables: TableCache,
}

impl Default for MarkdownHighlighter {
    fn default() -> Self {
        Self::new()
    }
}

impl MarkdownHighlighter {
    /// Creates a new Markdown syntax highlighter with default configuration.
    pub fn new() -> Self {
        Self::with_config(MarkdownConfig::default())
    }

    /// Creates a new Markdown syntax highlighter with custom configuration.
    pub fn with_config(config: MarkdownConfig) -> Self {
        Self {
            config,
            cached_fences: Arc::new(RwLock::new(None)),
            cached_tables: Arc::new(RwLock::new(None)),
        }
    }

    /// Returns the active Markdown configuration.
    pub fn config(&self) -> &MarkdownConfig {
        &self.config
    }

    /// Updates the Markdown configuration.
    pub fn set_config(&mut self, config: MarkdownConfig) {
        self.config = config;
    }

    fn is_in_fenced_code_block(&self, buffer: &EditorBuffer, current_row: usize) -> bool {
        let fences = self.cached_fence_rows(buffer);
        is_fenced_row(&fences, current_row)
    }

    /// Returns the fence-marker rows for this document version, scanning once
    /// and sharing the result across all per-row queries in the epoch.
    ///
    /// This is the single `O(N)` fence pass per version: `highlight_line`,
    /// table-block lookup, and table-layout building all share it instead of
    /// each rescanning `0..row` per visible row per frame.
    fn cached_fence_rows(&self, buffer: &EditorBuffer) -> Vec<usize> {
        let version = buffer.version();
        if let Ok(guard) = self.cached_fences.read()
            && let Some((v, ref fences)) = *guard
            && v == version
        {
            return fences.clone();
        }

        if let Ok(mut guard) = self.cached_fences.write() {
            if let Some((v, ref fences)) = *guard
                && v == version
            {
                return fences.clone();
            }

            let fences = scan_fence_rows(buffer);
            *guard = Some((version, fences.clone()));
            fences
        } else {
            scan_fence_rows(buffer)
        }
    }

    /// Locates the table block for `row` from the version-cached layouts.
    ///
    /// Point queries never walk the buffer: the one linear sweep per version
    /// lives in [`Self::cached_layouts`], and every per-row call
    /// (`highlight_line`, `should_wrap_line`, `expand_line`) shares it.
    /// Previously each call re-walked up to the whole table (upward search +
    /// body extension with a `line_to_string` alloc per row), costing
    /// milliseconds per row inside large tables on every selection frame.
    fn cached_table_block(&self, buffer: &EditorBuffer, row: usize) -> Option<TableBlock> {
        if row >= buffer.len_lines() {
            return None;
        }
        self.cached_layouts(buffer)
            .into_iter()
            .find(|l| l.block.contains(row))
            .map(|l| l.block)
    }

    /// Returns the table layout containing `row`, if any.
    fn layout_for_row(&self, buffer: &EditorBuffer, row: usize) -> Option<TableLayout> {
        self.cached_layouts(buffer)
            .into_iter()
            .find(|l| l.block.contains(row))
    }

    /// Returns all table layouts for this document version, sweeping once
    /// and sharing the result across every per-row query in the epoch.
    fn cached_layouts(&self, buffer: &EditorBuffer) -> Vec<TableLayout> {
        let version = buffer.version();
        if let Ok(guard) = self.cached_tables.read()
            && let Some((v, ref layouts)) = *guard
            && v == version
        {
            return layouts.clone();
        }
        if let Ok(mut guard) = self.cached_tables.write() {
            if let Some((v, ref layouts)) = *guard
                && v == version
            {
                return layouts.clone();
            }
            // Build layouts with the shared fence index: one linear sweep,
            // not one `O(row)` fence rescan per row.
            let fences = self.cached_fence_rows(buffer);
            let layouts = table_layouts_with_fences(buffer, &fences);
            *guard = Some((version, layouts.clone()));
            layouts
        } else {
            let fences = self.cached_fence_rows(buffer);
            table_layouts_with_fences(buffer, &fences)
        }
    }
}

/// Single linear fence-marker scan shared by every table query in an epoch.
fn scan_fence_rows(buffer: &EditorBuffer) -> Vec<usize> {
    let mut fences = Vec::new();
    let total_lines = buffer.len_lines();
    let rope = buffer.text();
    for r in 0..total_lines {
        let line = rope.line(r);
        let mut chars = line.chars();
        while let Some(c) = chars.next() {
            if !c.is_whitespace() {
                if (c == '`' && chars.next() == Some('`') && chars.next() == Some('`'))
                    || (c == '~' && chars.next() == Some('~') && chars.next() == Some('~'))
                {
                    fences.push(r);
                }
                break;
            }
        }
    }
    fences
}

/// Snaps a display byte offset forward to a char boundary.
fn snap_display_fwd(display: &str, mut i: usize) -> usize {
    i = i.min(display.len());
    while i < display.len() && !display.is_char_boundary(i) {
        i += 1;
    }
    i
}

/// Snaps a display byte offset backward to a char boundary.
fn snap_display_back(display: &str, mut i: usize) -> usize {
    i = i.min(display.len());
    while i > 0 && !display.is_char_boundary(i) {
        i -= 1;
    }
    i
}

/// Computes display-only padding aligning one table row's cells to the
/// block's column widths.
///
/// `source` is the stripped source line, `concealed` its collapsed display
/// form. Column widths are measured on unconcealed source text (see
/// [`TableLayout`]); per-row padding absorbs concealment shrinkage so pipes
/// align on active and inactive rows alike. Delimiter dashes are extended
/// with `-` fill; body/header cells are space-padded honoring the column's
/// delimiter alignment.
fn table_row_pads(
    layout: &TableLayout,
    kind: TableRowKind,
    source: &str,
    concealed: &ConcealedLine,
) -> Vec<DisplayPad> {
    let display = &concealed.display_text;
    let (_, cells) = split_table_cells(source);
    let mut pads = Vec::new();
    for (i, cell) in cells.iter().enumerate().take(layout.col_widths.len()) {
        let width = layout.col_widths[i];
        let ds = snap_display_fwd(
            display,
            concealed.source_to_display(cell.start.min(source.len())),
        );
        let de = snap_display_back(
            display,
            concealed.source_to_display(cell.end.min(source.len())),
        );
        if ds >= de {
            continue;
        }
        // Trim padding already present in the display slice.
        let bytes = display.as_bytes();
        let mut cs = ds;
        while cs < de && (bytes[cs] == b' ' || bytes[cs] == b'\t') {
            cs += 1;
        }
        let mut ce = de;
        while ce > cs && (bytes[ce - 1] == b' ' || bytes[ce - 1] == b'\t') {
            ce -= 1;
        }
        let content_width = display_width(&display[cs..ce]);
        if content_width >= width {
            continue;
        }
        let need = width - content_width;
        if kind == TableRowKind::Delimiter {
            // Extend the dash run, keeping a trailing alignment colon last.
            let at = if display[cs..ce].ends_with(':') {
                ce - 1
            } else {
                ce
            };
            pads.push(DisplayPad {
                display_at: at,
                fill: '-',
                len: need,
            });
            continue;
        }
        match layout
            .block
            .aligns
            .get(i)
            .copied()
            .unwrap_or(TableAlignment::None)
        {
            TableAlignment::Right => pads.push(DisplayPad {
                display_at: cs,
                fill: ' ',
                len: need,
            }),
            TableAlignment::Center => {
                let left = need / 2;
                let right = need - left;
                if left > 0 {
                    pads.push(DisplayPad {
                        display_at: cs,
                        fill: ' ',
                        len: left,
                    });
                }
                if right > 0 {
                    pads.push(DisplayPad {
                        display_at: ce,
                        fill: ' ',
                        len: right,
                    });
                }
            }
            TableAlignment::Left | TableAlignment::None => pads.push(DisplayPad {
                display_at: ce,
                fill: ' ',
                len: need,
            }),
        }
    }
    pads
}

impl SyntaxHighlighter for MarkdownHighlighter {
    fn highlight_line(&self, buffer: &EditorBuffer, row: usize, line_text: &str) -> Vec<StyleSpan> {
        let mut spans = Vec::new();
        let trimmed_start = line_text.trim_start();

        let delimiter_tag = match self.config.conceal_mode {
            ConcealMode::Off => None,
            ConcealMode::Dimmed => Some(HighlightTag::Dimmed),
            ConcealMode::Hidden => Some(HighlightTag::Hidden),
        };

        let is_cursor_row = row == buffer.cursor_point().row;

        if trimmed_start.starts_with("```") || trimmed_start.starts_with("~~~") {
            spans.push(StyleSpan::tag(0..line_text.len(), HighlightTag::Code));
            return spans;
        }

        if self.is_in_fenced_code_block(buffer, row) {
            spans.push(StyleSpan::tag(0..line_text.len(), HighlightTag::Code));
            return spans;
        }

        // GFM pipe tables. Runs before the thematic-break check so a
        // single-column `---` delimiter is not mistaken for an `<hr>`.
        // Pipes stay visible in every conceal mode (Hidden maps to Dimmed)
        // to preserve `ConcealedLine` source/display column alignment.
        if self.config.visual_tables
            && let Some(block) = self.cached_table_block(buffer, row)
            && let Some(kind) = block.kind_at(row)
        {
            // Pipes dim on inactive rows but are never concealed.
            let pipe_dim = match self.config.conceal_mode {
                ConcealMode::Off => None,
                ConcealMode::Dimmed | ConcealMode::Hidden => Some(HighlightTag::Dimmed),
            };
            let pipes = find_unescaped_pipes(line_text);
            match kind {
                TableRowKind::Delimiter => {
                    spans.push(StyleSpan::tag(
                        0..line_text.len(),
                        HighlightTag::Custom(TABLE_DELIMITER_TAG),
                    ));
                    for p in &pipes {
                        spans.push(StyleSpan::tag(*p..*p + 1, HighlightTag::Punctuation));
                    }
                    if !is_cursor_row {
                        let tag = delimiter_tag.unwrap_or(HighlightTag::Comment);
                        // Map Hidden -> Dimmed: concealing dashes would collapse
                        // the row to nothing and break cursor mapping.
                        let tag = if tag == HighlightTag::Hidden {
                            HighlightTag::Dimmed
                        } else {
                            tag
                        };
                        spans.push(StyleSpan::tag(0..line_text.len(), tag));
                    }
                    return spans;
                }
                TableRowKind::Header | TableRowKind::Body => {
                    let cell_tag = if kind == TableRowKind::Header {
                        HighlightTag::Custom(TABLE_HEADER_TAG)
                    } else {
                        HighlightTag::Custom(TABLE_CELL_TAG)
                    };
                    let (_, cells) = split_table_cells(line_text);
                    for cell in &cells {
                        let end = cell.end.min(line_text.len());
                        if cell.start < end {
                            spans.push(StyleSpan::tag(cell.start..end, cell_tag));
                            if kind == TableRowKind::Header
                                && let Some(content) = line_text.get(cell.start..end)
                                && !content.trim().is_empty()
                            {
                                spans.push(StyleSpan::tag(cell.start..end, HighlightTag::Bold));
                            }
                        }
                    }
                    for p in &pipes {
                        spans.push(StyleSpan::tag(*p..*p + 1, HighlightTag::Punctuation));
                        if !is_cursor_row && let Some(dim) = pipe_dim {
                            spans.push(StyleSpan::tag(*p..*p + 1, dim));
                        }
                    }
                    // Fall through to the inline pulldown pass so emphasis,
                    // code spans, and links inside cells keep working.
                }
            }
        }

        if self.config.visual_thematic_breaks {
            let trimmed_break = trimmed_start.trim_end();
            if (trimmed_break == "---" || trimmed_break == "***" || trimmed_break == "___")
                && line_text.len() >= 3
            {
                // Structural tag first so tag-driven layout survives concealment;
                // visual span last so text colors are unchanged.
                spans.push(StyleSpan::tag(
                    0..line_text.len(),
                    HighlightTag::HorizontalRule,
                ));
                let tag = delimiter_tag.unwrap_or(HighlightTag::Comment);
                spans.push(StyleSpan::tag(0..line_text.len(), tag));
                return spans;
            }
        }

        let heading_prefix = if trimmed_start.starts_with("# ") {
            Some((2, HighlightTag::Heading(1)))
        } else if trimmed_start.starts_with("## ") {
            Some((3, HighlightTag::Heading(2)))
        } else if trimmed_start.starts_with("### ") {
            Some((4, HighlightTag::Heading(3)))
        } else if trimmed_start.starts_with("#### ") {
            Some((5, HighlightTag::Heading(4)))
        } else if trimmed_start.starts_with("##### ") {
            Some((6, HighlightTag::Heading(5)))
        } else if trimmed_start.starts_with("###### ") {
            Some((7, HighlightTag::Heading(6)))
        } else {
            None
        };

        if let Some((prefix_len, tag)) = heading_prefix {
            let indent = line_text.len() - trimmed_start.len();
            if !is_cursor_row && let Some(delim_tag) = delimiter_tag {
                spans.push(StyleSpan::tag(indent..indent + prefix_len, delim_tag));
                if indent + prefix_len < line_text.len() {
                    spans.push(StyleSpan::tag(indent + prefix_len..line_text.len(), tag));
                }
            } else {
                spans.push(StyleSpan::tag(0..line_text.len(), tag));
            }
            return spans;
        }

        if trimmed_start.starts_with("> ") || trimmed_start == ">" {
            let indent = line_text.len() - trimmed_start.len();
            let quote_len = if trimmed_start.starts_with("> ") {
                2
            } else {
                1
            };
            // Structural tag first; visual span last so colors are unchanged.
            spans.push(StyleSpan::tag(
                indent..indent + quote_len,
                HighlightTag::Blockquote,
            ));
            if !is_cursor_row && let Some(delim_tag) = delimiter_tag {
                let delim_len = if trimmed_start.starts_with("> ") {
                    2
                } else {
                    1
                };
                spans.push(StyleSpan::tag(indent..indent + delim_len, delim_tag));
            } else {
                spans.push(StyleSpan::tag(indent..indent + 1, HighlightTag::Comment));
            }
        }

        let is_task_unchecked = trimmed_start.starts_with("- [ ] ")
            || trimmed_start == "- [ ]"
            || trimmed_start.starts_with("* [ ] ")
            || trimmed_start == "* [ ]";
        let is_task_checked = trimmed_start.starts_with("- [x] ")
            || trimmed_start == "- [x]"
            || trimmed_start.starts_with("- [X] ")
            || trimmed_start == "- [X]"
            || trimmed_start.starts_with("* [x] ")
            || trimmed_start == "* [x]"
            || trimmed_start.starts_with("* [X] ")
            || trimmed_start == "* [X]";
        let is_task_list = is_task_unchecked || is_task_checked;

        if is_task_list {
            let indent = line_text.len() - trimmed_start.len();
            // Structural tag first so tag-driven layout works even when the
            // marker bytes are concealed; visual span last so colors stay.
            let marker_len = if trimmed_start.len() >= 6 {
                6
            } else {
                trimmed_start.len()
            };
            let task_tag = if is_task_checked {
                HighlightTag::TaskChecked
            } else {
                HighlightTag::TaskUnchecked
            };
            spans.push(StyleSpan::tag(indent..indent + marker_len, task_tag));
            if !is_cursor_row && let Some(delim_tag) = delimiter_tag {
                if delim_tag == HighlightTag::Hidden {
                    spans.push(StyleSpan::tag(
                        indent..indent + marker_len,
                        HighlightTag::Hidden,
                    ));
                } else {
                    spans.push(StyleSpan::tag(indent..indent + 2, delim_tag));
                }
            }
        }

        super::inline::highlight_inline_markdown(
            line_text,
            is_cursor_row,
            delimiter_tag,
            &mut spans,
        );

        spans
    }

    fn extract_links(
        &self,
        _buffer: &EditorBuffer,
        _row: usize,
        line_text: &str,
    ) -> Vec<(Range<usize>, String)> {
        if !(line_text.contains('[') || line_text.contains('<')) {
            return Vec::new();
        }
        extract_markdown_links(line_text)
    }

    fn expand_line(
        &self,
        buffer: &EditorBuffer,
        row: usize,
        concealed: &ConcealedLine,
    ) -> Vec<DisplayPad> {
        if !(self.config.visual_tables && self.config.table_alignment) {
            return Vec::new();
        }
        let layout = match self.layout_for_row(buffer, row) {
            Some(layout) => layout,
            None => return Vec::new(),
        };
        let kind = match layout.block.kind_at(row) {
            Some(kind) => kind,
            None => return Vec::new(),
        };
        let source = clean_table_line(&buffer.line_to_string(row)).to_string();
        table_row_pads(&layout, kind, &source, concealed)
    }

    fn should_wrap_line(&self, buffer: &EditorBuffer, row: usize) -> bool {
        if !(self.config.visual_tables && self.config.table_alignment) {
            return true;
        }
        !self
            .cached_table_block(buffer, row)
            .is_some_and(|b| b.contains(row))
    }
}

#[cfg(test)]
mod tests {
    use super::super::links::extract_markdown_links;
    use super::*;
    use crate::{ConcealedLine, StyleValue};

    #[test]
    fn test_markdown_heading_spans() {
        let buffer = EditorBuffer::new("# Heading 1\n## Heading 2\nplain text\n---");
        let highlighter = MarkdownHighlighter::new();

        let spans1 = highlighter.highlight_line(&buffer, 0, "# Heading 1");
        assert_eq!(spans1.len(), 1);
        assert_eq!(spans1[0].style, StyleValue::Tag(HighlightTag::Heading(1)));

        let spans2 = highlighter.highlight_line(&buffer, 1, "## Heading 2");
        assert_eq!(spans2.len(), 2);
        assert_eq!(spans2[0].style, StyleValue::Tag(HighlightTag::Dimmed));
        assert_eq!(spans2[1].style, StyleValue::Tag(HighlightTag::Heading(2)));

        let spans3 = highlighter.highlight_line(&buffer, 2, "plain text");
        assert!(spans3.is_empty());

        let spans4 = highlighter.highlight_line(&buffer, 3, "---");
        assert_eq!(spans4.len(), 2);
        assert_eq!(
            spans4[0].style,
            StyleValue::Tag(HighlightTag::HorizontalRule)
        );
        assert_eq!(spans4[1].style, StyleValue::Tag(HighlightTag::Dimmed));
    }

    #[test]
    fn test_markdown_heading_levels_4_to_6() {
        let buffer = EditorBuffer::new("#### H4\n##### H5\n###### H6");
        let highlighter = MarkdownHighlighter::new();

        for (row, text, level) in [
            (0, "#### H4", 4u8),
            (1, "##### H5", 5u8),
            (2, "###### H6", 6u8),
        ] {
            let spans = highlighter.highlight_line(&buffer, row, text);
            assert!(
                spans
                    .iter()
                    .any(|s| s.style == StyleValue::Tag(HighlightTag::Heading(level))),
                "row {row} must emit Heading({level})"
            );
        }
    }

    #[test]
    fn test_markdown_inline_bold_and_code() {
        let buffer = EditorBuffer::new("This is **bold** and `code` here.");
        let highlighter = MarkdownHighlighter::new();

        let spans = highlighter.highlight_line(&buffer, 0, "This is **bold** and `code` here.");
        let bold_span = spans
            .iter()
            .find(|s| s.style == StyleValue::Tag(HighlightTag::Bold));
        assert!(bold_span.is_some());

        let code_span = spans
            .iter()
            .find(|s| s.style == StyleValue::Tag(HighlightTag::Code));
        assert!(code_span.is_some());
    }

    #[test]
    fn test_markdown_conceal_modes() {
        let buffer = EditorBuffer::new("# Heading 1\n## Heading 2");

        let hidden_highlighter = MarkdownHighlighter::with_config(MarkdownConfig {
            conceal_mode: ConcealMode::Hidden,
            ..Default::default()
        });
        let spans_hidden = hidden_highlighter.highlight_line(&buffer, 1, "## Heading 2");
        assert_eq!(spans_hidden.len(), 2);
        assert_eq!(spans_hidden[0].style, StyleValue::Tag(HighlightTag::Hidden));
        assert_eq!(
            spans_hidden[1].style,
            StyleValue::Tag(HighlightTag::Heading(2))
        );

        let off_highlighter = MarkdownHighlighter::with_config(MarkdownConfig {
            conceal_mode: ConcealMode::Off,
            ..Default::default()
        });
        let spans_off = off_highlighter.highlight_line(&buffer, 1, "## Heading 2");
        assert_eq!(spans_off.len(), 1);
        assert_eq!(
            spans_off[0].style,
            StyleValue::Tag(HighlightTag::Heading(2))
        );
    }

    #[test]
    fn test_markdown_task_list_and_quote_concealment() {
        let buffer = EditorBuffer::new("- [ ] Task 1\n> Quote line\n```rust\nfn main() {}\n```");
        let hidden_highlighter = MarkdownHighlighter::with_config(MarkdownConfig {
            conceal_mode: ConcealMode::Hidden,
            ..Default::default()
        });

        // Row 0 is cursor row (buffer cursor is at 0)
        // Row 1 (Quote) is inactive
        let spans_quote = hidden_highlighter.highlight_line(&buffer, 1, "> Quote line");
        assert!(!spans_quote.is_empty());
        // Structural tag first, visual concealment last.
        assert_eq!(spans_quote[0].range, 0..2);
        assert_eq!(
            spans_quote[0].style,
            StyleValue::Tag(HighlightTag::Blockquote)
        );
        assert_eq!(spans_quote[1].range, 0..2);
        assert_eq!(spans_quote[1].style, StyleValue::Tag(HighlightTag::Hidden));
        let concealed_quote = ConcealedLine::build("> Quote line", &spans_quote);
        assert_eq!(concealed_quote.display_text, "Quote line");

        // Row 2 (Opening fence) remains visible with HighlightTag::Code
        let spans_fence = hidden_highlighter.highlight_line(&buffer, 2, "```rust");
        assert_eq!(spans_fence.len(), 1);
        assert_eq!(spans_fence[0].range, 0..7);
        assert_eq!(spans_fence[0].style, StyleValue::Tag(HighlightTag::Code));
        let concealed_fence = ConcealedLine::build("```rust", &spans_fence);
        assert_eq!(concealed_fence.display_text, "```rust");

        // When buffer cursor moves to row 1, row 0 becomes inactive
        let mut buffer_moved = buffer;
        buffer_moved.set_cursor_offset(13); // on row 1
        let spans_task = hidden_highlighter.highlight_line(&buffer_moved, 0, "- [ ] Task 1");
        assert!(!spans_task.is_empty());
        assert_eq!(spans_task[0].range, 0..6);
        assert_eq!(
            spans_task[0].style,
            StyleValue::Tag(HighlightTag::TaskUnchecked)
        );
        assert_eq!(spans_task[1].range, 0..6);
        assert_eq!(spans_task[1].style, StyleValue::Tag(HighlightTag::Hidden));
        let concealed_task = ConcealedLine::build("- [ ] Task 1", &spans_task);
        assert_eq!(concealed_task.display_text, "Task 1");
    }

    #[test]
    fn test_markdown_link_concealment() {
        let buffer = EditorBuffer::new("[Google](https://google.com)\nActive line");
        let hidden_highlighter = MarkdownHighlighter::with_config(MarkdownConfig {
            conceal_mode: ConcealMode::Hidden,
            ..Default::default()
        });

        // Buffer cursor is at 0 (row 0), so row 0 is active, full link visible
        let spans_active =
            hidden_highlighter.highlight_line(&buffer, 0, "[Google](https://google.com)");
        let concealed_active = ConcealedLine::build("[Google](https://google.com)", &spans_active);
        assert_eq!(
            concealed_active.display_text,
            "[Google](https://google.com)"
        );

        // Move cursor to row 1, row 0 becomes inactive
        let mut buffer_moved = buffer;
        buffer_moved.set_cursor_offset(30);
        let spans_hidden =
            hidden_highlighter.highlight_line(&buffer_moved, 0, "[Google](https://google.com)");
        let concealed_hidden = ConcealedLine::build("[Google](https://google.com)", &spans_hidden);
        assert_eq!(concealed_hidden.display_text, "Google");

        let extracted = extract_markdown_links("[Google](https://google.com)");
        assert_eq!(extracted.len(), 1);
        assert_eq!(extracted[0].0, 1..7);
        assert_eq!(extracted[0].1, "https://google.com");
    }

    #[test]
    fn test_markdown_structural_tags_in_dimmed_mode() {
        let buffer = EditorBuffer::new("- [ ] Todo\n- [x] Done\n> Quote\n---");
        let highlighter = MarkdownHighlighter::new();
        // Move cursor away so no row is the active cursor row side-effect... row 3 check
        // uses default cursor at row 0, so rows 1-3 are inactive.
        let unchecked = highlighter.highlight_line(&buffer, 0, "- [ ] Todo");
        // Row 0 is the cursor row: structural tag still emitted, no concealment.
        assert!(
            unchecked
                .iter()
                .any(|s| s.style == StyleValue::Tag(HighlightTag::TaskUnchecked))
        );

        let mut moved = buffer;
        moved.set_cursor_offset(30);
        let unchecked_inactive = highlighter.highlight_line(&moved, 0, "- [ ] Todo");
        assert!(
            unchecked_inactive
                .iter()
                .any(|s| s.style == StyleValue::Tag(HighlightTag::TaskUnchecked))
        );
        let checked = highlighter.highlight_line(&moved, 1, "- [x] Done");
        assert!(
            checked
                .iter()
                .any(|s| s.style == StyleValue::Tag(HighlightTag::TaskChecked))
        );
        let quote = highlighter.highlight_line(&moved, 2, "> Quote");
        assert!(
            quote
                .iter()
                .any(|s| s.style == StyleValue::Tag(HighlightTag::Blockquote))
        );
        let hr = highlighter.highlight_line(&moved, 3, "---");
        assert!(
            hr.iter()
                .any(|s| s.style == StyleValue::Tag(HighlightTag::HorizontalRule))
        );
    }

    #[test]
    fn test_table_highlight_uses_existing_tags_only() {
        let buffer = EditorBuffer::new("| Name | Age |\n| --- | ---: |\n| Ada | 36 |");
        let highlighter = MarkdownHighlighter::new();

        let header = highlighter.highlight_line(&buffer, 0, "| Name | Age |");
        assert!(
            header
                .iter()
                .any(|s| s.style == StyleValue::Tag(HighlightTag::Punctuation))
        );
        assert!(
            header
                .iter()
                .any(|s| s.style == StyleValue::Tag(HighlightTag::Bold))
        );
        assert!(
            header
                .iter()
                .any(|s| s.style == StyleValue::Tag(HighlightTag::Custom(TABLE_HEADER_TAG)))
        );

        let body = highlighter.highlight_line(&buffer, 2, "| Ada | 36 |");
        assert!(
            body.iter()
                .any(|s| s.style == StyleValue::Tag(HighlightTag::Custom(TABLE_CELL_TAG)))
        );
        assert!(
            body.iter()
                .all(|s| s.style != StyleValue::Tag(HighlightTag::Bold))
        );

        let delim = highlighter.highlight_line(&buffer, 1, "| --- | ---: |");
        assert!(
            delim
                .iter()
                .any(|s| s.style == StyleValue::Tag(HighlightTag::Custom(TABLE_DELIMITER_TAG)))
        );

        // Inline code inside cells still highlights.
        let code_row = EditorBuffer::new("| `x|y` | b |\n| --- | --- |\n| c | d |");
        let code_spans = highlighter.highlight_line(&code_row, 0, "| `x|y` | b |");
        assert!(
            code_spans
                .iter()
                .any(|s| s.style == StyleValue::Tag(HighlightTag::Code))
        );

        // Pipes are never fully concealed: Hidden maps to Dimmed.
        let hidden = MarkdownHighlighter::with_config(MarkdownConfig {
            conceal_mode: ConcealMode::Hidden,
            ..Default::default()
        });
        let mut moved = EditorBuffer::new("| Name | Age |\n| --- | ---: |\n| Ada | 36 |");
        moved.set_cursor_offset(40);
        let inactive = hidden.highlight_line(&moved, 0, "| Name | Age |");
        assert!(
            inactive
                .iter()
                .all(|s| s.style != StyleValue::Tag(HighlightTag::Hidden))
        );
        assert!(
            inactive
                .iter()
                .any(|s| s.style == StyleValue::Tag(HighlightTag::Dimmed))
        );
        let concealed = ConcealedLine::build("| Name | Age |", &inactive);
        assert_eq!(concealed.display_text, "| Name | Age |");

        // Opt-out flag disables everything.
        let off = MarkdownHighlighter::with_config(MarkdownConfig {
            visual_tables: false,
            ..Default::default()
        });
        let plain = off.highlight_line(&buffer, 0, "| Name | Age |");
        assert!(plain.iter().all(|s| !matches!(
            s.style,
            StyleValue::Tag(
                HighlightTag::Custom(TABLE_HEADER_TAG)
                    | HighlightTag::Custom(TABLE_CELL_TAG)
                    | HighlightTag::Custom(TABLE_DELIMITER_TAG)
            )
        )));
    }

    /// Renders one row through highlight + conceal + expand, like the canvas does.
    fn expanded_display(
        highlighter: &MarkdownHighlighter,
        buffer: &EditorBuffer,
        row: usize,
        line: &str,
    ) -> String {
        let spans = highlighter.highlight_line(buffer, row, line);
        let concealed = ConcealedLine::build(line, &spans);
        let pads = highlighter.expand_line(buffer, row, &concealed);
        concealed.expanded(&pads).display_text
    }

    #[test]
    fn test_table_columns_share_widths_when_a_cell_grows() {
        let buffer = EditorBuffer::new("| a | b |\n| --- | --- |\n| looong | c |\n| d | e |");
        let highlighter = MarkdownHighlighter::new();

        let header = expanded_display(&highlighter, &buffer, 0, "| a | b |");
        let body_long = expanded_display(&highlighter, &buffer, 2, "| looong | c |");
        let body_short = expanded_display(&highlighter, &buffer, 3, "| d | e |");
        let delim = expanded_display(&highlighter, &buffer, 1, "| --- | --- |");

        // Pipes land on the same display columns in every row.
        let pipe_cols = |s: &str| {
            s.char_indices()
                .filter(|(_, c)| *c == '|')
                .map(|(i, _)| i)
                .collect::<Vec<_>>()
        };
        assert_eq!(pipe_cols(&header), pipe_cols(&body_long));
        assert_eq!(pipe_cols(&header), pipe_cols(&body_short));
        assert_eq!(pipe_cols(&header), pipe_cols(&delim));
        assert_eq!(header, "| a      | b   |");
        assert_eq!(body_long, "| looong | c   |");
        assert_eq!(delim, "| ------ | --- |");
    }

    #[test]
    fn test_table_alignment_honors_delimiter_sides() {
        let buffer = EditorBuffer::new("| ab | c |\n| ---: | --- |\n| d | ef |");
        let highlighter = MarkdownHighlighter::new();

        // Right-aligned column pads before the content, plain column after.
        let body = expanded_display(&highlighter, &buffer, 2, "| d | ef |");
        assert_eq!(body, "|    d | ef  |");
        // The delimiter already fits, so it renders unchanged and aligned.
        let delim = expanded_display(&highlighter, &buffer, 1, "| ---: | --- |");
        assert_eq!(delim, "| ---: | --- |");
        let pipe_cols = |s: &str| {
            s.char_indices()
                .filter(|(_, c)| *c == '|')
                .map(|(i, _)| i)
                .collect::<Vec<_>>()
        };
        assert_eq!(pipe_cols(&body), pipe_cols(&delim));
    }

    #[test]
    fn test_table_rows_opt_out_of_wrapping() {
        let buffer = EditorBuffer::new("| a | b |\n| --- | --- |\n| c | d |\nplain");
        let highlighter = MarkdownHighlighter::new();
        assert!(!highlighter.should_wrap_line(&buffer, 0));
        assert!(!highlighter.should_wrap_line(&buffer, 1));
        assert!(!highlighter.should_wrap_line(&buffer, 2));
        assert!(highlighter.should_wrap_line(&buffer, 3));

        let off = MarkdownHighlighter::with_config(MarkdownConfig {
            table_alignment: false,
            ..Default::default()
        });
        assert!(off.should_wrap_line(&buffer, 0));
        assert!(
            off.expand_line(&buffer, 0, &ConcealedLine::build("| a | b |", &[]))
                .is_empty()
        );
    }

    #[test]
    fn test_table_layout_cache_invalidates_on_edit() {
        let mut buffer = EditorBuffer::new("| a |\n| --- |\n| b |");
        let highlighter = MarkdownHighlighter::new();
        assert_eq!(
            expanded_display(&highlighter, &buffer, 2, "| b |"),
            "| b   |"
        );
        buffer.replace_range(16..17, "much-longer");
        assert_eq!(
            expanded_display(&highlighter, &buffer, 2, "| much-longer |"),
            "| much-longer |"
        );
    }

    #[test]
    fn test_large_table_body_rows_stay_detected() {
        // The cached block lookup must keep working hundreds of rows deep in
        // one table (a per-row upward walk with a bounded budget would give
        // up before reaching the delimiter and drop table styling mid-table).
        let mut s = String::from("| a | b |\n| --- | --- |\n");
        for i in 0..700 {
            s.push_str(&format!("| c{i} | d |\n"));
        }
        let buffer = EditorBuffer::new(&s);
        let highlighter = MarkdownHighlighter::new();

        for row in [10usize, 300, 699, 701] {
            let line = buffer.line_to_string(row);
            let text = line.trim_end_matches(['\r', '\n']);
            let spans = highlighter.highlight_line(&buffer, row, text);
            assert!(
                spans
                    .iter()
                    .any(|sp| sp.style == StyleValue::Tag(HighlightTag::Custom(TABLE_CELL_TAG))),
                "deep body row {row} must keep its table cell tag"
            );
            assert!(
                !highlighter.should_wrap_line(&buffer, row),
                "deep body row {row} must opt out of wrapping"
            );
            let concealed = ConcealedLine::build(text, &spans);
            assert!(
                !highlighter.expand_line(&buffer, row, &concealed).is_empty(),
                "deep body row {row} must get alignment padding"
            );
        }
    }
    #[test]
    fn test_deep_table_rows_highlight_with_fence_at_top() {
        // Guards the version-cached fence index: a fence pair far above must
        // not hide a real table 1000+ lines below, and fenced pipe rows must
        // still highlight as code, not table cells.
        let mut s = String::from("```rust\nfn f() {}\n```\n");
        for i in 0..1000 {
            s.push_str(&format!("plain filler line {i}\n"));
        }
        let header_row = 1003;
        s.push_str("| a | b |\n| --- | --- |\n| c | d |\n");
        s.push_str("```\n| x |\n| --- |\n```\n");
        let buffer = EditorBuffer::new(&s);
        let highlighter = MarkdownHighlighter::new();

        let header = highlighter.highlight_line(&buffer, header_row, "| a | b |");
        assert!(
            header
                .iter()
                .any(|sp| sp.style == StyleValue::Tag(HighlightTag::Custom(TABLE_HEADER_TAG))),
            "deep header row must keep its table tag"
        );
        assert!(
            header
                .iter()
                .any(|sp| sp.style == StyleValue::Tag(HighlightTag::Bold)),
            "deep header cells must stay bold"
        );
        let body = highlighter.highlight_line(&buffer, header_row + 2, "| c | d |");
        assert!(
            body.iter()
                .any(|sp| sp.style == StyleValue::Tag(HighlightTag::Custom(TABLE_CELL_TAG)))
        );
        assert!(!highlighter.should_wrap_line(&buffer, header_row));
        assert!(!highlighter.should_wrap_line(&buffer, header_row + 2));

        // Pipe rows inside the trailing fence are code, never table cells.
        let total = buffer.len_lines();
        let fenced_pipe_row = total - 3;
        let fenced = highlighter.highlight_line(&buffer, fenced_pipe_row, "| x |");
        assert!(
            fenced
                .iter()
                .any(|sp| sp.style == StyleValue::Tag(HighlightTag::Code)),
            "fenced pipe row must highlight as code"
        );
        assert!(
            fenced
                .iter()
                .all(|sp| sp.style != StyleValue::Tag(HighlightTag::Custom(TABLE_CELL_TAG))),
            "fenced pipe row must not emit table cell tags"
        );
    }
}