mdfrier 1.0.1

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
#![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 mapper;
mod markdown;
mod wrap;

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

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::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, Clone, 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,
}

/// 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),
    /// Blank line.
    Blank,
}

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

impl std::fmt::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 std::fmt::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 iter = MdIterator::new(tree, &mut self.inline_parser, text);
        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| {
                if matches!(line.kind, LineKind::Blank) {
                    String::new()
                } else {
                    line.spans.iter().map(|s| s.content.as_str()).collect()
                }
            })
            .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(), 2);
        assert_eq!(lines[0].spans[0].content, "This");
        // Second line: "*" (open) + "is" (emphasis) + "*" (close) + " a test."
        assert_eq!(lines[1].spans[0].content, "*");
        assert!(
            lines[1].spans[0]
                .modifiers
                .contains(Modifier::EmphasisWrapper)
        );
        assert_eq!(lines[1].spans[1].content, "is");
        assert!(lines[1].spans[1].modifiers.contains(Modifier::Emphasis));
        assert_eq!(lines[1].spans[2].content, "*");
        assert!(
            lines[1].spans[2]
                .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 spans: Vec<_> = frier
            .parse(15, "See https://example.com/path ok?", &DefaultMapper)
            .unwrap()
            .flat_map(|l| l.spans)
            .collect();
        assert_eq!(
            spans,
            vec![
                Span::from("See "),
                Span::with("(", Modifier::LinkURLWrapper),
                Span::with("https://", Modifier::LinkURL | Modifier::BareLink),
                Span::with("example.com/", Modifier::LinkURL | Modifier::BareLink,),
                Span::with("path", Modifier::LinkURL | Modifier::BareLink,),
                Span::with(")", Modifier::LinkURLWrapper),
                Span::with(" ok?", Modifier::empty()),
            ]
        );
    }

    #[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);
    }

    #[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 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,),
            ]
        );
    }
}