mdfried 0.20.3

A markdown viewer for the terminal that renders images and big headers
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
//! Section aggregation from Lines.
//!
//! This module provides `SectionIterator` which groups parsed lines into sections
//! for display. Lines are aggregated based on their type:
//! - Header lines become their own section
//! - Image lines become their own section
//! - All other lines are aggregated into text sections

use std::iter::Peekable;

use mdfrier::link_tracker::TrackedUrl;
use mdfrier::ratatui::render_line;
use mdfrier::{Line, LineKind, MarkdownLink, Modifier, SourceContent};
use ratatui::text::Span;

use crate::config::Theme;
use crate::document::{LineExtra, LinkReference, Section, SectionContent, SectionID};

/// Events produced during section iteration that need post-processing.
pub enum SectionEvent {
    Image(SectionID, MarkdownLink),
    Header(SectionID, String, u8),
    ReferenceDefinition { id: String, url: String },
}

/// Iterator that groups lines into sections and renders them.
pub struct SectionIterator<'a, I: Iterator<Item = Line>> {
    inner: Peekable<I>,
    theme: &'a Theme,
    section_id: usize,
}

impl<'a, I: Iterator<Item = Line>> SectionIterator<'a, I> {
    /// Create a new section iterator from a line iterator.
    pub fn new(inner: I, theme: &'a Theme) -> Self {
        SectionIterator {
            inner: inner.peekable(),
            theme,
            section_id: 0,
        }
    }

    /// Get the last section ID that was assigned (for ParseDone).
    pub fn last_section_id(&self) -> Option<usize> {
        if self.section_id == 0 {
            None
        } else {
            Some(self.section_id - 1)
        }
    }

    pub fn next_section_id(&mut self) -> SectionID {
        let id = self.section_id;
        self.section_id += 1;
        id
    }

    /// Render a line to ratatui Line without links, for headers, images, or other non-text
    /// content.
    fn render_simple_line(&self, line: Line) -> ratatui::text::Line<'static> {
        let (line, _) = render_line(line, self.theme);
        line
    }

    /// Process header lines into sections.
    fn process_header(&mut self, first: Line, tier: u8) -> Section {
        let text: String = first.spans.iter().map(|s| s.content.as_str()).collect();
        let id = self.next_section_id();
        if self.theme.has_text_size_protocol.unwrap_or_default() {
            return Section {
                id,
                height: 2,
                content: SectionContent::Header(text.clone(), tier, None),
            };
        }
        let mut lines = vec![self.render_simple_line(first)];
        if let Some(first) = lines.get_mut(0) {
            first.spans.insert(0, Span::from(" "));
            first.spans.insert(0, Span::from("#".repeat(tier as usize)));
        }
        Section {
            id,
            height: 2,
            content: SectionContent::HeaderPlaceholder(
                text.clone(),
                tier,
                lines.into_iter().map(|line| (line, Vec::new())).collect(),
            ),
        }
    }

    /// Process image lines into a section.
    fn process_image(&mut self, first: Line, link: MarkdownLink) -> Section {
        let id = self.next_section_id();
        let mut lines = vec![self.render_simple_line(first)];

        // Include trailing blank line if present (to maintain spacing)
        if let Some(peeked) = self.inner.peek() {
            if matches!(peeked.kind, LineKind::Blank) {
                let blank = self.inner.next().expect("peeked");
                lines.push(self.render_simple_line(blank));
            }
        }

        Section {
            id,
            height: lines.len() as u16,
            content: SectionContent::ImagePlaceholder(
                link,
                lines.into_iter().map(|line| (line, Vec::new())).collect(),
            ),
        }
    }

    /// Process text lines (paragraphs, code blocks, tables, etc.) into a section.
    fn process_text(&mut self, first: Line) -> Option<Section> {
        let mut lines = vec![first];

        // Aggregate consecutive non-header, non-image lines
        while let Some(peeked) = self.inner.peek() {
            match &peeked.kind {
                // Stop aggregating at headers or images
                LineKind::Header(_) | LineKind::Image { .. } => break,
                // Continue aggregating all other lines (including blanks)
                _ => {
                    let line = self.inner.next().expect("peeked value should exist");
                    lines.push(line);
                }
            }
        }

        // Check if a header follows (need to preserve one blank line for spacing)
        let (followed_by_header, followed_by_image) = self
            .inner
            .peek()
            .map(|l| {
                (
                    matches!(l.kind, LineKind::Header(_)),
                    matches!(l.kind, LineKind::Image { .. }),
                )
            })
            .unwrap_or_default();

        // Trim trailing blank lines, unless image
        if !followed_by_image {
            while lines
                .last()
                .is_some_and(|l| matches!(l.kind, LineKind::Blank))
            {
                lines.pop();
            }
        }

        // Skip if section ended up empty after trimming
        if lines.is_empty() {
            return None;
        }

        // Re-add one blank line if needed for spacing before header
        if followed_by_header {
            lines.push(Line {
                kind: LineKind::Blank,
                spans: Vec::new(),
                urls: Vec::new(),
            });
        }

        let rendered_lines: Vec<_> = lines
            .into_iter()
            .map(|line| {
                let mut link_reference_definition =
                    if line.kind == LineKind::LinkReferenceDefinitions {
                        let reference = line.spans.iter().find_map(|span| {
                            span.modifiers
                                .contains(Modifier::LinkDescription)
                                .then(|| span.content.clone())
                        });
                        if reference.is_none() {
                            log::error!("LineKind::LinkReferenceDefinitions but no LinkDescription span for the reference-id");
                            log::debug!("line: {line:?}");
                        }
                        reference
                    } else {
                        None
                    };

                let (ratatui_line, urls) = render_line(line, self.theme);

                let extras: Vec<LineExtra> = urls
                    .into_iter()
                    .filter_map(|tracked_url| {
                        if let TrackedUrl::Link {
                            start,
                            lines,
                            end,
                            url,
                            is_reference,
                        } = tracked_url
                        {
                            Some(LineExtra::Link {
                                source: SourceContent::from(url.as_str()),
                                start,
                                end,
                                lines: if lines == 0 { None } else { Some(lines) },
                                // Build the reference, both on the links that point the reference
                                // definition, and the reference definitions.
                                // The worker emits a special event on definitions for the document
                                // to update all reference links, after all `Parse` events.
                                reference: if is_reference {
                                    LinkReference::Reference { id: url }
                                } else if let Some(id) = link_reference_definition.take() {
                                    // We can take it because there should only be one
                                    // ReferenceDefinition per line.
                                    LinkReference::ReferenceDefinition { id, url }
                                } else {
                                    LinkReference::None
                                },
                            })
                        } else {
                            None
                        }
                    })
                    .collect();

                (ratatui_line, extras)
            })
            .collect();

        let id = self.next_section_id();
        Some(Section {
            id,
            height: rendered_lines.len() as u16,
            content: SectionContent::Lines(rendered_lines),
        })
    }
}

impl<I: Iterator<Item = Line>> Iterator for SectionIterator<'_, I> {
    type Item = Section;

    fn next(&mut self) -> Option<Self::Item> {
        // Return buffered section if available
        loop {
            let first = self.inner.next()?;

            match first.kind {
                // Headers are always their own section
                LineKind::Header(tier) => return Some(self.process_header(first, tier)),

                // Images are always their own section
                #[expect(clippy::ref_patterns)]
                LineKind::Image(ref link) => {
                    let link = link.clone();
                    return Some(self.process_image(first, link));
                }

                // Skip blank lines at the start of a section
                LineKind::Blank => {
                    continue;
                }

                // All other line types get aggregated into text sections
                _ => {
                    if let Some(section) = self.process_text(first) {
                        return Some(section);
                    }
                    // Section was empty after trimming, continue to next
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::document::{LineExtra, SectionContent};
    use mdfrier::{MdFrier, SourceContent};

    #[ctor::ctor]
    fn init_logger() {
        crate::debug::init_test_logger();
    }

    #[expect(clippy::unwrap_used)]
    fn parse_sections(text: &str) -> Vec<Section> {
        let mut frier = MdFrier::new().unwrap();
        let theme = Theme::default();
        let lines = frier.parse(80, text, &theme).unwrap();
        SectionIterator::new(lines, &theme).collect()
    }

    #[test]
    fn header_is_own_section() {
        let sections = parse_sections("# Hello\n\nWorld");
        assert_eq!(sections.len(), 2);
        assert!(matches!(
            sections[0].content,
            SectionContent::HeaderPlaceholder(_, 1, _)
        ));
        assert!(matches!(sections[1].content, SectionContent::Lines(_)));
    }

    #[test]
    fn consecutive_text_aggregated() {
        let sections = parse_sections("Line 1\nLine 2\nLine 3");
        assert_eq!(sections.len(), 1);
        assert!(matches!(sections[0].content, SectionContent::Lines(_)));
    }

    #[test]
    fn image_is_own_section() {
        let sections = parse_sections("Before\n\n![alt](http://example.com/img.png)\n\nAfter");
        assert_eq!(sections.len(), 3);
        assert!(matches!(sections[0].content, SectionContent::Lines(_)));
        assert!(matches!(
            sections[1].content,
            SectionContent::ImagePlaceholder(_, _)
        ));
        assert!(matches!(sections[2].content, SectionContent::Lines(_)));
    }

    #[test]
    fn multiple_headers() {
        let sections = parse_sections("# One\n\n## Two\n\n### Three");
        assert_eq!(sections.len(), 3);
        assert!(matches!(
            sections[0].content,
            SectionContent::HeaderPlaceholder(_, 1, _)
        ));
        assert!(matches!(
            sections[1].content,
            SectionContent::HeaderPlaceholder(_, 2, _)
        ));
        assert!(matches!(
            sections[2].content,
            SectionContent::HeaderPlaceholder(_, 3, _)
        ));
    }

    #[test]
    #[expect(clippy::unwrap_used)]
    fn header_wrapping_tier_1() {
        let mut frier = MdFrier::new().unwrap();
        let theme = Theme {
            has_text_size_protocol: Some(true),
            ..Default::default()
        };
        let lines = frier.parse(10, "# 1234567890", &theme).unwrap();
        let sections: Vec<Section> = SectionIterator::new(lines, &theme).collect();

        assert_eq!(sections.len(), 2);

        let SectionContent::Header(text, tier, _) = &sections[0].content else {
            panic!("expected Header");
        };
        assert_eq!(1, *tier);
        assert_eq!("12345", text);

        let SectionContent::Header(text, tier, _) = &sections[1].content else {
            panic!("expected Header");
        };
        assert_eq!(1, *tier);
        assert_eq!("67890", text);
    }

    #[test]
    fn image_after_blank() {
        let sections = parse_sections("Before\n\n![alt](http://example.com/img.png)");
        assert_eq!(sections.len(), 2);
        assert!(matches!(sections[0].content, SectionContent::Lines(_)));
        assert!(matches!(
            sections[1].content,
            SectionContent::ImagePlaceholder(_, _)
        ));
        let SectionContent::Lines(lines) = &sections[0].content else {
            panic!("expected SectionContent::Lines");
        };
        assert_eq!(lines.len(), 2, "two lines");
    }

    #[test]
    fn md_link_parses_as_section_with_one_link() {
        let sections = parse_sections("[example](https://example.org/)\n");
        assert_eq!(sections.len(), 1);
        assert!(matches!(sections[0].content, SectionContent::Lines(_)));
        let SectionContent::Lines(lines) = &sections[0].content else {
            panic!("expected SectionContent::Lines");
        };
        assert_eq!(lines.len(), 1, "one line");
        assert!(matches!(lines[0].1.as_slice(), [LineExtra::Link { .. }]),);
    }

    #[test]
    fn md_link_with_code_block_parses_as_section_with_one_link() {
        let sections = parse_sections("[example `code`](https://example.org/)\n");
        assert_eq!(sections.len(), 1);
        assert!(matches!(sections[0].content, SectionContent::Lines(_)));
        let SectionContent::Lines(lines) = &sections[0].content else {
            panic!("expected SectionContent::Lines");
        };
        assert_eq!(lines.len(), 1);
        assert!(matches!(lines[0].1.as_slice(), [LineExtra::Link { .. }]),);
    }

    #[test]
    fn link_with_multiple_spans_has_correct_url() {
        let url = "https://example.com/target";
        let markdown = format!("unrelated [text with `code`]({})", url);

        let sections = parse_sections(&markdown);
        assert_eq!(sections.len(), 1);

        let SectionContent::Lines(lines) = &sections[0].content else {
            panic!("expected SectionContent::Lines");
        };
        assert_eq!(lines.len(), 1, "one line");

        let link_extras: Vec<_> = lines[0]
            .1
            .iter()
            .filter_map(|extra| {
                if let LineExtra::Link { source: url, .. } = extra {
                    Some(url)
                } else {
                    None
                }
            })
            .collect();

        log::debug!("TEST LOG");
        assert_eq!(link_extras.len(), 1);
        assert_eq!(link_extras[0].as_ref(), url,);
    }

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

        let sections = parse_sections(markdown);

        let SectionContent::Lines(lines) = &sections[0].content else {
            panic!("expected SectionContent::Lines");
        };

        let link_extras: Vec<_> = lines[0]
            .1
            .iter()
            .filter_map(|extra| {
                if let LineExtra::Link { source: url, .. } = extra {
                    Some(url)
                } else {
                    None
                }
            })
            .collect();

        assert_eq!(
            link_extras,
            vec![&SourceContent::from("http://example.com/link")]
        );
    }

    #[test]
    fn multiple_links() {
        let markdown = r#"Here goes [link one](http://example.com/link1), here goes [link two](http://example.com/link2).  
Definitely on another line (soft-break) goes [link three](http://example.com/link3).  
That's all."#;

        let sections = parse_sections(markdown);

        assert_eq!(1, sections.len());
        let SectionContent::Lines(lines) = &sections[0].content else {
            panic!("expected SectionContent::Lines");
        };

        assert_eq!(
            lines[0].0.to_string(),
            String::from("Here goes link one, here goes link two."),
        );
        assert_eq!(
            lines[0].1,
            vec![
                LineExtra::Link {
                    source: "http://example.com/link1".into(),
                    start: 10,
                    end: 18,
                    lines: None,
                    reference: LinkReference::None,
                },
                LineExtra::Link {
                    source: "http://example.com/link2".into(),
                    start: 30,
                    end: 38,
                    lines: None,
                    reference: LinkReference::None,
                },
            ]
        );
        assert_eq!(
            lines[1].1,
            vec![LineExtra::Link {
                source: "http://example.com/link3".into(),
                start: 45,
                end: 55,
                lines: None,
                reference: LinkReference::None,
            },]
        );
    }
}