mdfrier 3.0.6

A markdown parser that produces styled terminal lines
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
#![cfg_attr(docsrs, feature(doc_auto_cfg))]

//! mdfrier - Deep fry markdown for [mdfried](https://crates.io/crates/mdfried).
//!
//! This crate's goal is to render markdown as close to the source text as possible, while also
//! wrapping and also allowing for mapping to a custom style.
//!
//! 1. Parse into raw lines with nodes.
//! 2. Map (or strip) the node's markdown decorator symbols but preserve some internal marker.
//! 3. Wrap the lines of nodes to a maximum width.
//! 4. Apply styles such as emphasis or color.
//!
//! At step 4, the users of this library will typically convert the wrapped lines of nodes with
//! their style information to whatever the target is: ANSI escape sequences, or whatever some
//! their library expects.
//!
//! There is a `ratatui` feature that enables the [`ratatui`] module, which does exactly this, for
//! [ratatui](https://ratatui.rs).
//!
//! The [`Mapper`] trait controls decorator symbols (e.g., blockquote bar, link brackets).
//! The optional `ratatui` feature provides the [`ratatui::Theme`] trait that combines [`Mapper`]
//! with [`ratatui::style::Style`](https://docs.rs/ratatui/latest/ratatui/style/struct.Style.html) conversion.
//!
//! # Examples
//!
//! [`StyledMapper`] is the default goal of this crate. It heavily maps markdown symbols, and
//! strips many, with the intention of adding syles (color, bold, italics...) later, after wrapping.
//! That is, it does not "stylize" the markdown, but is intented *for* stylizing later.
//!
//! The styles should be applied when iterating over the [`Line`]'s [`Span`]s.
//! ```
//! use mdfrier::{MdFrier, Line, Span, Mapper, Modifier, DefaultMapper, StyledMapper};
//!
//! let mut frier = MdFrier::new().unwrap();
//!
//! // StyledMapper removes decorators (for use with colors/bold/italic styling)
//! let text: String = frier.parse(80, "*emphasis* and **strong**", &StyledMapper).unwrap()
//!     .flat_map(|l: Line| l.spans.into_iter().map(|s: Span|
//!         if s.modifiers.contains(Modifier::Emphasis) {
//!             format!("\033[31m{}\033[0m", s.content)
//!         } else if s.modifiers.contains(Modifier::StrongEmphasis) {
//!             format!("\033[33m{}\033[0m", s.content)
//!         } else {
//!             s.content
//!         }
//!     ))
//!     .collect();
//! assert_eq!(text, "\033[31memphasis\033[0m and \033[33mstrong\033[0m");
//! ```
//!
//! A custom mapper should implement the [`Mapper`] trait. For example, here we replace some
//! markdown delimiters with fancy symbols.
//! ```
//! use mdfrier::{MdFrier, Mapper};
//!
//! struct FancyMapper;
//! impl Mapper for FancyMapper {
//!     fn emphasis_open(&self) -> &str { "♥" }
//!     fn emphasis_close(&self) -> &str { "♥" }
//!     fn strong_open(&self) -> &str { "✦" }
//!     fn strong_close(&self) -> &str { "✦" }
//!     fn blockquote_bar(&self) -> &str { "➤ " }
//! }
//!
//! let mut frier = MdFrier::new().unwrap();
//!
//! let lines = frier.parse(80, "Hello *world*!\n\n> Quote\n\n**Bold**", &FancyMapper).unwrap();
//! let mut output = String::new();
//! for line in lines {
//!     for span in line.spans {
//!         output.push_str(&span.content);
//!     }
//!     output.push('\n');
//! }
//! assert_eq!(output, "Hello ♥world♥!\n\n➤ Quote\n\n✦Bold✦\n");
//! ```
//!
//! A [`DefaultMapper`] exists, which *could* be used to only style, preserving the markdown
//! content. It's used only for unit tests.
//! Note that it would be much more efficient to use the
//! [`tree-sitter-md`](https://crates.io/crates/tree-sitter-md) crate directly instead,
//! since it operates with byte-ranges of the original text. Think editor syntax highlighting.
//! ```
//! use mdfrier::{MdFrier, DefaultMapper};
//!
//! let mut frier = MdFrier::new().unwrap();
//!
//! let text: String = frier.parse(80, "*emphasis* and **strong**", &DefaultMapper).unwrap()
//!     .flat_map(|l| l.spans.into_iter().map(|s| s.content))
//!     .collect();
//! assert_eq!(text, "*emphasis* and **strong**");
//!
//! ```

mod lines;
pub mod link_tracker;
pub mod mapper;
mod markdown;
mod wrap;

#[cfg(feature = "ratatui")]
pub mod ratatui;

use std::fmt::Display;

use tree_sitter::Parser;

pub use lines::LineIterator;
pub use mapper::{DefaultMapper, Mapper, StyledMapper};
pub use markdown::BulletStyle;
pub use markdown::{Modifier, SourceContent, Span};

use crate::link_tracker::TrackedUrl;
use crate::markdown::MdIterator;

// ============================================================================
// Public output types
// ============================================================================

/// A single output line from the markdown parser.
///
/// This is the final, flattened representation with all decorators applied
/// and nesting converted to prefix spans.
#[derive(Debug, PartialEq)]
pub struct Line {
    /// The text spans making up this line, including any prefix spans
    /// (blockquote bars, list markers) that were added from nesting.
    pub spans: Vec<Span>,
    /// The kind of content this line represents.
    pub kind: LineKind,
    /// Any links and images found *ending* on this line.
    pub urls: Vec<TrackedUrl>,
}

/// The kind of content a line represents.
#[derive(Debug, Clone, PartialEq)]
pub enum LineKind {
    /// Regular text paragraph.
    Paragraph,
    /// Header line with tier (1-6).
    Header(u8),
    /// Code block line with language.
    CodeBlock { language: String },
    /// Horizontal rule (content is in spans).
    HorizontalRule,
    /// Table data row.
    TableRow { is_header: bool },
    /// Table border/separator.
    TableBorder,
    /// Image reference.
    Image(MarkdownLink),
    /// Link reference definitions, e.g. `[reference]: http://example.com`, has `LinkDescription`
    /// and `LinkUrl` [`Modifier`]s, respectively.
    LinkReferenceDefinitions,
}

#[cfg(test)]
impl Display for Line {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}",
            self.spans
                .iter()
                .map(|s| s.content.clone())
                .collect::<Vec<String>>()
                .join("")
        )
    }
}

#[cfg(test)]
impl Line {
    fn to_strings<T>(lines: T) -> Vec<String>
    where
        T: IntoIterator,
        T::Item: Display,
    {
        lines
            .into_iter()
            .map(|s| s.to_string())
            .collect::<Vec<String>>()
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct MarkdownLink {
    pub url: String,
    pub description: String,
}

impl Display for MarkdownLink {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "[{}]({})", self.description, self.url)
    }
}

/// Failed to parse markdown.
#[derive(Debug)]
pub struct MarkdownParseError;

impl Display for MarkdownParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Failed to parse markdown")
    }
}

impl std::error::Error for MarkdownParseError {}

/// The main markdown parser struct.
///
/// Wraps tree-sitter parsers and provides a simple interface for parsing
/// markdown text into lines.
pub struct MdFrier {
    parser: Parser,
    inline_parser: Parser,
}

impl MdFrier {
    /// Create a new MdFrier instance.
    pub fn new() -> Result<Self, MarkdownParseError> {
        let mut parser = Parser::new();
        parser
            .set_language(&tree_sitter_md::LANGUAGE.into())
            .ok()
            .ok_or(MarkdownParseError)?;

        let mut inline_parser = Parser::new();
        inline_parser
            .set_language(&tree_sitter_md::INLINE_LANGUAGE.into())
            .ok()
            .ok_or(MarkdownParseError)?;

        Ok(Self {
            parser,
            inline_parser,
        })
    }

    /// Parse markdown text and return an iterator of `Line` items.
    ///
    /// The mapper controls how decorators are rendered (link brackets,
    /// blockquote bars, list markers, etc.). Use `DefaultMapper` for
    /// plain ASCII output, or implement your own `Mapper` for custom symbols.
    ///
    /// # Arguments
    ///
    /// * `width` - The terminal width for line wrapping
    /// * `text` - The markdown text to parse
    /// * `mapper` - The mapper to use for content transformation
    pub fn parse<'a, M: Mapper>(
        &'a mut self,
        width: u16,
        text: &'a str,
        mapper: &'a M,
    ) -> Result<LineIterator<'a, M>, MarkdownParseError> {
        let tree = self.parser.parse(text, None).ok_or(MarkdownParseError)?;
        let mut iter = MdIterator::new(tree, &mut self.inline_parser, text);
        iter.preserve_list_ordinals(mapper.preserve_list_ordinals());
        Ok(LineIterator::new(iter, width, mapper))
    }
}

#[cfg(test)]
#[expect(clippy::unwrap_used)]
mod tests {
    use super::*;
    use pretty_assertions::assert_eq;

    /// Convert MdLines to a string representation for testing.
    /// With the new flat API, all prefix spans are included in spans.
    fn lines_to_string(lines: &[Line]) -> String {
        lines
            .iter()
            .map(|line| {
                line.spans
                    .iter()
                    .map(|s| s.content.as_str())
                    .collect::<String>()
            })
            .collect::<Vec<_>>()
            .join("\n")
    }

    #[test]
    fn parse_simple_text() {
        let mut frier = MdFrier::new().unwrap();
        let lines: Vec<_> = frier
            .parse(80, "Hello world!", &DefaultMapper)
            .unwrap()
            .collect();
        assert_eq!(lines.len(), 1);

        let line = &lines[0];
        assert_eq!(line.spans.len(), 1);
        assert_eq!(line.spans[0].content, "Hello world!");
    }

    #[test]
    fn parse_styled_text() {
        let mut frier = MdFrier::new().unwrap();
        // DefaultMapper preserves decorators around emphasis
        let lines: Vec<_> = frier
            .parse(80, "Hello *world*!", &DefaultMapper)
            .unwrap()
            .collect();
        assert_eq!(lines.len(), 1);

        let line = &lines[0];
        // Spans: "Hello " + "*" (open) + "world" (emphasis) + "*" (close) + "!"
        assert_eq!(line.spans.len(), 5);
        assert_eq!(line.spans[0].content, "Hello ");
        assert_eq!(line.spans[1].content, "*");
        assert!(line.spans[1].modifiers.contains(Modifier::EmphasisWrapper));
        assert_eq!(line.spans[2].content, "world");
        assert!(line.spans[2].modifiers.contains(Modifier::Emphasis));
        assert_eq!(line.spans[3].content, "*");
        assert!(line.spans[3].modifiers.contains(Modifier::EmphasisWrapper));
        assert_eq!(line.spans[4].content, "!");
    }

    #[test]
    fn parse_header() {
        let mut frier = MdFrier::new().unwrap();
        let lines: Vec<_> = frier
            .parse(80, "# Hello\n", &DefaultMapper)
            .unwrap()
            .collect();
        assert_eq!(lines.len(), 1);

        let line = &lines[0];
        assert!(matches!(line.kind, LineKind::Header(1)));
    }

    #[test]
    fn parse_code_block() {
        let mut frier = MdFrier::new().unwrap();
        let lines: Vec<_> = frier
            .parse(80, "```rust\nlet x = 1;\n```\n", &DefaultMapper)
            .unwrap()
            .collect();
        assert_eq!(lines.len(), 1);

        let line = &lines[0];
        assert!(matches!(line.kind, LineKind::CodeBlock { .. }));
        // First span is the code content
        assert!(line.spans[0].content.starts_with("let x = 1;"));
    }

    #[test]
    fn parse_blockquote() {
        let mut frier = MdFrier::new().unwrap();
        let lines: Vec<_> = frier
            .parse(80, "> Hello world", &DefaultMapper)
            .unwrap()
            .collect();
        assert_eq!(lines.len(), 1);

        let line = &lines[0];
        // With flat API, first span should be the blockquote bar
        assert!(line.spans[0].modifiers.contains(Modifier::BlockquoteBar));
        assert_eq!(line.spans[0].content, "> ");
    }

    #[test]
    fn parse_list() {
        let mut frier = MdFrier::new().unwrap();
        let lines: Vec<_> = frier
            .parse(80, "- Item 1\n- Item 2", &DefaultMapper)
            .unwrap()
            .collect();
        assert_eq!(lines.len(), 2);
    }

    #[test]
    fn paragraph_breaks() {
        let mut frier = MdFrier::new().unwrap();
        let lines: Vec<_> = frier
            .parse(10, "longline1\nlongline2", &DefaultMapper)
            .unwrap()
            .collect();
        assert_eq!(lines.len(), 2);
        assert_eq!(lines[0].spans[0].content, "longline1");
        assert_eq!(lines[1].spans[0].content, "longline2");
    }

    #[test]
    fn soft_break_with_styling() {
        let mut frier = MdFrier::new().unwrap();
        // DefaultMapper preserves decorators
        let lines: Vec<_> = frier
            .parse(80, "This\n*is* a test.", &DefaultMapper)
            .unwrap()
            .collect();
        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0].spans[0].content, "This");
        assert_eq!(lines[0].spans[1].content, " ");
        // Second line: "*" (open) + "is" (emphasis) + "*" (close) + " a test."
        assert_eq!(lines[0].spans[2].content, "*");
        assert!(
            lines[0].spans[2]
                .modifiers
                .contains(Modifier::EmphasisWrapper)
        );
        assert_eq!(lines[0].spans[3].content, "is");
        assert!(lines[0].spans[3].modifiers.contains(Modifier::Emphasis));
        assert_eq!(lines[0].spans[4].content, "*");
        assert!(
            lines[0].spans[4]
                .modifiers
                .contains(Modifier::EmphasisWrapper)
        );
    }

    #[test]
    fn code_block_spacing() {
        let input = "Paragraph before.
```rust
let x = 1;
```
Paragraph after.";

        let mut frier = MdFrier::new().unwrap();
        let lines: Vec<_> = frier.parse(80, input, &DefaultMapper).unwrap().collect();
        let output = lines_to_string(&lines);
        insta::assert_snapshot!(output);
    }

    #[test]
    fn code_block_before_list_spacing() {
        let input = "```rust
let x = 1;
```
- list item";

        let mut frier = MdFrier::new().unwrap();
        let lines: Vec<_> = frier.parse(80, input, &DefaultMapper).unwrap().collect();
        let output = lines_to_string(&lines);
        insta::assert_snapshot!(output);
    }

    #[test]
    fn separate_blockquotes_have_blank_lines() {
        let input = r#"> Blockquotes are very handy in email to emulate reply text.
> 
> This line is part of the same quote.

Quote break.

> This is a very long line that will still be quoted properly when it wraps. Oh boy let's keep writing to make sure this is long enough to actually wrap for everyone. Oh, you can *put* **Markdown** into a blockquote.

> Blockquotes can also be nested...
>> ...by using additional greater-than signs right next to each other...
> > > ...or with spaces between arrows."#;

        let mut frier = MdFrier::new().unwrap();
        let lines: Vec<_> = frier.parse(80, input, &DefaultMapper).unwrap().collect();
        let output = lines_to_string(&lines);
        insta::assert_snapshot!(output);
    }

    #[test]
    fn bare_url_line_broken() {
        let mut frier = MdFrier::new().unwrap();
        let lines = frier
            .parse(15, "See https://example.com/path ok?", &DefaultMapper)
            .unwrap();

        assert_eq!(
            lines.map(|line| line.spans).collect::<Vec<Vec<Span>>>(),
            vec![
                vec![Span::from("See")],
                vec![
                    Span::with("https://", Modifier::BareLink | Modifier::LinkURL),
                    Span::with("       ", Modifier::BareLink | Modifier::LinkURL),
                ],
                vec![
                    Span::with("example.com/", Modifier::BareLink | Modifier::LinkURL),
                    Span::with("   ", Modifier::BareLink | Modifier::LinkURL),
                ],
                vec![
                    Span::with("path", Modifier::BareLink | Modifier::LinkURL),
                    Span::from(" ok?"),
                ],
            ]
        );
    }

    #[test]
    fn list_marker_mapping() {
        let input = r#"1. First ordered list item
2. Another item
   - Unordered sub-list.
3. Actual numbers don't matter, just that it's a number
   1. Ordered sub-list
4. And another item.

- Create a list by starting a line with `+`, `-`, or `*`
- Sub-lists are made by indenting 2 spaces:
  - Marker character change forces new list start:
    - Ac tristique libero volutpat at
    * Facilisis in pretium nisl aliquet
    - Nulla volutpat aliquam velit
  - Task lists
    - [x] Finish my changes
    - [ ] Push my commits to GitHub
    - [ ] Open a pull request
    - [x] @mentions, #refs, [links](), **formatting**, and <del>tags</del> supported
    - [x] list syntax required (any unordered or ordered list supported)
    - [ ] this is a complete item with a long line that should definitely 100% get wrapped at some point
    - [ ] this is an incomplete item
+ Very easy!
"#;

        let mut frier = MdFrier::new().unwrap();
        struct RomanListMapper;
        impl Mapper for RomanListMapper {
            fn ordered_marker(&self, num: u32) -> String {
                match num {
                    1 => "I.   ",
                    2 => "II.  ",
                    3 => "III. ",
                    4 => "IV.  ",
                    _ => "?.   ",
                }
                .to_owned()
            }
            fn unordered_bullet(&self, _style: BulletStyle) -> &str {
                ""
            }
            fn task_checked(&self) -> &str {
                ""
            }
            fn task_unchecked(&self) -> &str {
                ""
            }
        }
        let mapper = RomanListMapper {};
        let lines: Vec<_> = frier.parse(80, input, &mapper).unwrap().collect();
        let output = lines_to_string(&lines);
        insta::assert_snapshot!(output);
    }

    #[test]
    fn list_preserve_formatting() {
        let input = r#"1. First ordered list item
2. Another item
   - Unordered sub-list.
3. Actual numbers don't matter, just that it's a number
   1. Ordered sub-list
4. And another item.

   You can have properly indented paragraphs within list items. Notice the blank line above, and the leading spaces (at least one, but we'll use three here to also align the raw Markdown).

   To have a line break without a paragraph, you will need to use two trailing spaces.
   Note that this line is separate, but within the same paragraph.
   (This is contrary to the typical GFM line break behaviour, where trailing spaces are not required.)

- Unordered list can use asterisks
  And can also have continuations.

* Or minuses

- Or pluses

1. Make my changes
   1. Fix bug
   2. Improve formatting
      - Make the headings bigger
2. Push my commits to GitHub
3. Open a pull request
   - Describe my changes
   - Mention all the members of my team
     - Ask for feedback

- Create a list by starting a line with `+`, `-`, or `*`
- Sub-lists are made by indenting 2 spaces:
  - Marker character change forces new list start:
    - Ac tristique libero volutpat at
    * Facilisis in pretium nisl aliquet
    - Nulla volutpat aliquam velit
  - Task lists
    - [x] Finish my changes
    - [ ] Push my commits to GitHub
    - [ ] Open a pull request
    - [x] @mentions, #refs, [links](), **formatting**, and <del>tags</del> supported
    - [x] list syntax required (any unordered or ordered list supported)
    - [ ] this is a complete item
    - [ ] this is an incomplete item
- Very easy!
"#;

        let mut frier = MdFrier::new().unwrap();
        let lines: Vec<_> = frier.parse(80, input, &DefaultMapper).unwrap().collect();
        let output = lines_to_string(&lines);
        insta::assert_snapshot!(output);
    }

    #[test]
    fn list_preserve_continuations() {
        let input = r#"1. First ordered list item
2. Another item  

   Continuation of item.
   Carry on.

   Further continuation.
3. Last item
"#;

        let mut frier = MdFrier::new().unwrap();
        let lines: Vec<_> = frier.parse(80, input, &DefaultMapper).unwrap().collect();
        let output = lines_to_string(&lines);
        insta::assert_snapshot!(output);
    }

    struct PreserveMapper;
    impl Mapper for PreserveMapper {
        fn preserve_list_ordinals(&self) -> bool {
            true
        }
    }

    #[test]
    fn ordinals_preserved() {
        // preserve_list_ordinals = true: source numbers are kept exactly as written
        let input = "1. a\n3. b\n5. c\n";
        let mut frier = MdFrier::new().unwrap();
        let lines: Vec<_> = frier.parse(80, input, &PreserveMapper).unwrap().collect();
        assert_eq!(lines_to_string(&lines), "1. a\n3. b\n5. c");
    }

    #[test]
    fn ordinals_preserved_nested() {
        // preserve mode must not renumber items in nested structures
        let input = "3. a\n   - inner\n7. b\n";
        let mut frier = MdFrier::new().unwrap();
        let lines: Vec<_> = frier.parse(80, input, &PreserveMapper).unwrap().collect();
        assert_eq!(lines_to_string(&lines), "3. a\n   - inner\n7. b");
    }

    #[test]
    fn ordinals_sequential_from_1() {
        // Non-sequential source numbers are renumbered starting from the first item's number
        let input = "1. a\n3. b\n5. c\n";
        let mut frier = MdFrier::new().unwrap();
        let lines: Vec<_> = frier.parse(80, input, &DefaultMapper).unwrap().collect();
        assert_eq!(lines_to_string(&lines), "1. a\n2. b\n3. c");
    }

    #[test]
    fn ordinals_sequential_from_first() {
        // Renumbering starts from the first item's number, not always 1
        let input = "2. a\n7. b\n4. c\n";
        let mut frier = MdFrier::new().unwrap();
        let lines: Vec<_> = frier.parse(80, input, &DefaultMapper).unwrap().collect();
        assert_eq!(lines_to_string(&lines), "2. a\n3. b\n4. c");
    }

    #[test]
    fn ordinals_sequential_nested() {
        // Each nested ordered list has its own counter independent of the outer list.
        // Note: tree-sitter-markdown only recognises a tight nested ordered sub-list when
        // it starts at 1. A sub-list starting at any other number is parsed as paragraph
        // continuation text of the parent item, so we use 1 here to get a real sub-list.
        let input = "3. a\n   1. inner-a\n   9. inner-b\n7. b\n";
        let mut frier = MdFrier::new().unwrap();
        let lines: Vec<_> = frier.parse(80, input, &DefaultMapper).unwrap().collect();
        // inner 9 → 2 (continues from 1), outer 7 → 4 (continues from 3)
        assert_eq!(
            lines_to_string(&lines),
            "3. a\n   1. inner-a\n   2. inner-b\n4. b"
        );
    }

    #[test]
    fn ordinals_sequential_nested_unordered() {
        // A nested unordered list must not reset the outer ordered counter.
        let input = "3. a\n   - inner-a\n   - inner-b\n7. b\n";
        let mut frier = MdFrier::new().unwrap();
        let lines: Vec<_> = frier.parse(80, input, &DefaultMapper).unwrap().collect();
        // outer 7 → 4 (continues from 3, despite the nested unordered items)
        assert_eq!(
            lines_to_string(&lines),
            "3. a\n   - inner-a\n   - inner-b\n4. b"
        );
    }

    #[test]
    fn ordinals_complex_nested() {
        // Exercises sequential renumbering and preserve mode together across:
        // - an outer ordered list starting at a non-1 number
        // - a nested unordered sub-list (must not disturb the outer counter)
        // - a nested ordered sub-list with a non-sequential source item (9 → 2)
        // - a two-digit outer item (11 → 5)
        //
        // Inner ordered sub-list starts at 1 because tree-sitter-markdown parses
        // tight nested ordered sub-lists as paragraph continuation when they start
        // at any other number.
        let input = "\
3. outer-a
   - unordered-1
   - unordered-2
7. outer-b
   1. inner-1
   9. inner-2
11. outer-c
";
        let mut frier = MdFrier::new().unwrap();

        let seq_lines: Vec<_> = frier.parse(80, input, &DefaultMapper).unwrap().collect();
        assert_eq!(
            lines_to_string(&seq_lines),
            "3. outer-a\n   - unordered-1\n   - unordered-2\n4. outer-b\n   1. inner-1\n   2. inner-2\n5. outer-c",
        );

        let pre_lines: Vec<_> = frier.parse(80, input, &PreserveMapper).unwrap().collect();
        assert_eq!(
            lines_to_string(&pre_lines),
            "3. outer-a\n   - unordered-1\n   - unordered-2\n7. outer-b\n   1. inner-1\n   9. inner-2\n11. outer-c",
        );
    }

    #[test]
    fn code_block_wrapping() {
        // Test that code blocks wrap at width boundary
        let input = "```\nabcdefghij\n```\n";

        let mut frier = MdFrier::new().unwrap();
        // Width of 5 should wrap "abcdefghij" into two lines
        let lines: Vec<_> = frier.parse(5, input, &DefaultMapper).unwrap().collect();
        assert_eq!(lines.len(), 2);
        // First line should be 5 chars
        assert_eq!(lines[0].spans[0].content, "abcde");
        // Second line should be remaining 5 chars
        assert_eq!(lines[1].spans[0].content, "fghij");
    }

    #[test]
    fn code_block_no_wrap_when_fits() {
        // Test that code blocks don't wrap when they fit
        let input = "```\nabcde\n```\n";

        let mut frier = MdFrier::new().unwrap();
        let lines: Vec<_> = frier.parse(5, input, &DefaultMapper).unwrap().collect();
        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0].spans[0].content, "abcde");
    }

    #[test]
    fn hide_urls() {
        let mut frier = MdFrier::new().unwrap();
        struct HideUrlsMapper;
        impl Mapper for HideUrlsMapper {
            fn hide_urls(&self) -> bool {
                true
            }
        }
        let mapper = HideUrlsMapper {};
        let lines: Vec<_> = frier
            .parse(80, "[desc](https://url)", &mapper)
            .unwrap()
            .collect();
        assert_eq!(lines.len(), 1);

        assert_eq!(
            lines[0].spans,
            vec![
                Span::with("[", Modifier::Link | Modifier::LinkDescriptionWrapper),
                Span::with("desc", Modifier::Link | Modifier::LinkDescription,),
                Span::with("]", Modifier::Link | Modifier::LinkDescriptionWrapper),
                Span::with("", Modifier::Link | Modifier::LinkURLWrapper,),
                Span::with("https://url", Modifier::Link | Modifier::LinkURL),
                Span::with("", Modifier::Link | Modifier::LinkURLWrapper,),
            ]
        );
    }

    #[test]
    fn inline_image_surrounding_text() {
        let input = r#"This a paragraph.  
Here we have an "inline" image, ![inline](./notfound.img), and trailing text.  
Should be split up nicely.
"#;

        let mut frier = MdFrier::new().unwrap();
        let lines: Vec<_> = frier.parse(80, input, &DefaultMapper).unwrap().collect();
        let output = lines_to_string(&lines);
        insta::assert_snapshot!(output);
    }

    #[test]
    fn html() {
        let input = r#"<div style="color: green">
    I want to put in HTML in markdown for some reason.
</div>
"#;

        let mut frier = MdFrier::new().unwrap();
        let lines: Vec<_> = frier.parse(80, input, &DefaultMapper).unwrap().collect();
        let output = lines_to_string(&lines);
        insta::assert_snapshot!(output);
    }

    #[test]
    fn wrapping_indented_list_continuation() {
        let input = "\
- Mermaid diagram rendering.  
  A code block annotated as `mermaid` gets rendered either via builtin `mermaid-rs-renderer` (can
  be disabled with the `mermaid` feature), or via external command in config,
  e.g. `mermaid = \"mmdc -i - -o - -e png\"`.";

        let mut frier = MdFrier::new().unwrap();
        let lines: Vec<_> = frier.parse(88, input, &StyledMapper).unwrap().collect();
        let output = lines_to_string(&lines);
        assert_eq!(
            output,
            "- Mermaid diagram rendering.\
\n  A code block annotated as mermaid gets rendered either via builtin mermaid-rs-renderer\
\n  (can be disabled with the mermaid feature), or via external command in config, e.g.\
\n  mermaid = \"mmdc -i - -o - -e png\"."
        );
    }

    #[test]
    fn non_wrapping_simple_list_items() {
        let input = "\
* A
  * B
  * C";

        let mut frier = MdFrier::new().unwrap();
        let lines: Vec<_> = frier.parse(88, input, &StyledMapper).unwrap().collect();
        let output = lines_to_string(&lines);
        assert_eq!(
            output,
            "* A\
\n  * B\
\n  * C"
        );
    }

    #[test]
    fn wrapping_indented_sublist_inline_code() {
        let input = "\
* Rust cargo: `cargo install mdfried`
  * Needs a chafa package with development headers, usually called something like `libchafa-dev`, `libchafa-devel`, or just `libchafa`, or even just `chafa`.";

        let mut frier = MdFrier::new().unwrap();
        let lines: Vec<_> = frier.parse(88, input, &StyledMapper).unwrap().collect();
        let output = lines_to_string(&lines);
        assert_eq!(
            output,
            "* Rust cargo: cargo install mdfried\
\n  * Needs a chafa package with development headers, usually called something like\
\n    libchafa-dev, libchafa-devel, or just libchafa, or even just chafa."
        );
    }

    #[test]
    fn nested_image_link() {
        let input = "[![test image](http://example.com/image.png)](http://example.com/link)";

        let mut frier = MdFrier::new().unwrap();
        let lines: Vec<_> = frier.parse(80, input, &DefaultMapper).unwrap().collect();

        assert_eq!(
            lines[0].spans,
            vec![
                Span::with("[", Modifier::Link | Modifier::LinkDescriptionWrapper),
                Span::with(
                    "![",
                    Modifier::Link | Modifier::LinkDescription | Modifier::Image
                ),
                Span::with(
                    "test image",
                    Modifier::Link | Modifier::LinkDescription | Modifier::Image
                ),
                Span::with(
                    "](",
                    Modifier::Link | Modifier::LinkDescription | Modifier::Image
                ),
                Span::with(
                    "http://example.com/image.png",
                    Modifier::Link
                        | Modifier::LinkDescription
                        | Modifier::LinkURL
                        | Modifier::Image,
                ),
                Span::with(
                    ")",
                    Modifier::Link | Modifier::LinkDescription | Modifier::Image
                ),
                Span::with("]", Modifier::Link | Modifier::LinkDescriptionWrapper),
                Span::with("(", Modifier::Link | Modifier::LinkURLWrapper,),
                Span::with(
                    "http://example.com/link",
                    Modifier::Link | Modifier::LinkURL
                ),
                Span::with(")", Modifier::Link | Modifier::LinkURLWrapper,),
            ]
        );
    }
}