1use std::borrow::Cow;
2
3use comrak::nodes::{AstNode, NodeCodeBlock, NodeValue};
4
5use super::context::Context;
6use super::layout::{self, Spacing};
7use super::{footnote, list, raw};
8use crate::document::Block;
9
10#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
12#[non_exhaustive]
13pub enum SectionKind {
14 FrontMatter,
15 Heading {
16 level: u8,
17 },
18 Paragraph,
19 ListItem {
21 task: Option<bool>,
22 },
23 Quote,
24 Alert,
25 Code {
26 language: Option<String>,
27 },
28 Mermaid,
29 Table,
30 Rule,
31 Html,
32 Footnotes,
33}
34
35#[derive(Clone, Debug, PartialEq, Eq)]
40#[non_exhaustive]
41pub struct Section {
42 pub first_line: usize,
43 pub last_line: usize,
44 pub kind: SectionKind,
45 pub blocks: Vec<Block>,
46}
47
48pub(super) enum Group {
50 Sections {
51 spacing: Spacing,
52 sections: Vec<Section>,
53 },
54 Unsectioned(Vec<Block>),
56}
57
58impl Group {
59 fn single(section: Section) -> Self {
60 Self::Sections { spacing: Spacing::Loose, sections: vec![section] }
61 }
62
63 pub fn stacked(self) -> Vec<Block> {
65 match self {
66 Self::Sections { spacing, sections } => layout::stack(sections.into_iter().map(|section| section.blocks), spacing),
67 Self::Unsectioned(blocks) => blocks,
68 }
69 }
70
71 pub fn sections(self) -> Vec<Section> {
72 match self {
73 Self::Sections { sections, .. } => sections,
74 Self::Unsectioned(_) => Vec::new(),
75 }
76 }
77}
78
79fn is_footnote_definition<'a>(node: &'a AstNode<'a>) -> bool {
80 matches!(node.data().value, NodeValue::FootnoteDefinition(_))
81}
82
83fn code_kind(code: &NodeCodeBlock) -> SectionKind {
84 match raw::language(code) {
85 Some(language) if language == raw::MERMAID => SectionKind::Mermaid,
86 language => SectionKind::Code { language },
87 }
88}
89
90fn kind<'a>(node: &'a AstNode<'a>) -> Option<SectionKind> {
92 let kind = match &node.data().value {
93 NodeValue::FrontMatter(_) => SectionKind::FrontMatter,
94 NodeValue::Heading(heading) => SectionKind::Heading { level: heading.level },
95 NodeValue::BlockQuote => SectionKind::Quote,
96 NodeValue::Alert(_) => SectionKind::Alert,
97 NodeValue::CodeBlock(code) => code_kind(code),
98 NodeValue::HtmlBlock(_) => SectionKind::Html,
99 NodeValue::ThematicBreak => SectionKind::Rule,
100 NodeValue::Table(_) => SectionKind::Table,
101 NodeValue::Paragraph => SectionKind::Paragraph,
102 _ => return None,
103 };
104 Some(kind)
105}
106
107fn written_lines(source: &str) -> Vec<bool> {
109 let source = if source.contains('\r') { Cow::Owned(source.replace("\r\n", "\n")) } else { Cow::Borrowed(source) };
110 source.split(['\n', '\r']).map(|line| !line.trim().is_empty()).collect()
111}
112
113fn last_written_line(first_line: usize, last_line: usize, written: &[bool]) -> usize {
115 let is_written = |line: &usize| written.get(line - 1).copied().unwrap_or(false);
116 (first_line..=last_line).rev().find(is_written).unwrap_or(first_line)
117}
118
119fn section<'a>(node: &'a AstNode<'a>, kind: SectionKind, blocks: Vec<Block>, written: &[bool]) -> Section {
120 let position = node.data().sourcepos;
121 let last_line = last_written_line(position.start.line, position.end.line, written);
122 Section { first_line: position.start.line, last_line, kind, blocks }
123}
124
125fn group<'a>(node: &'a AstNode<'a>, written: &[bool], context: &Context) -> Group {
126 if let NodeValue::List(list) = &node.data().value {
127 let items = node.children().zip(list::items(node, list, context));
128 let sections =
129 items.map(|(item, blocks)| section(item, SectionKind::ListItem { task: list::task(item) }, blocks, written)).collect();
130 return Group::Sections { spacing: list::spacing(list), sections };
131 }
132 let blocks = super::block(node, context);
133 match kind(node) {
134 Some(kind) => Group::single(section(node, kind, blocks, written)),
135 None => Group::Unsectioned(blocks),
136 }
137}
138
139fn footnotes<'a>(definitions: &[&'a AstNode<'a>], written: &[bool], context: &Context) -> Option<Group> {
142 let first_line = definitions.iter().map(|definition| definition.data().sourcepos.start.line).min()?;
143 let last_line = definitions.iter().map(|definition| definition.data().sourcepos.end.line).max()?;
144 let last_line = last_written_line(first_line, last_line, written);
145 let blocks = footnote::section(definitions, context);
146 Some(Group::single(Section { first_line, last_line, kind: SectionKind::Footnotes, blocks }))
147}
148
149pub(super) fn groups<'a>(root: &'a AstNode<'a>, source: &str, context: &Context) -> Vec<Group> {
151 let written = written_lines(source);
152 let (notes, body): (Vec<&AstNode>, Vec<&AstNode>) = root.children().partition(|node| is_footnote_definition(node));
153 let body = body.into_iter().map(|node| group(node, &written, context));
154 body.chain(footnotes(¬es, &written, context)).collect()
155}
156
157#[cfg(test)]
158mod tests {
159 use super::*;
160 use crate::document::{CellSize, Line, Settings, test_settings};
161 use crate::markdown::{render, render_sections};
162
163 const SHOWCASE: &str = include_str!("../../tests/fixtures/showcase.md");
164 const CELL: CellSize = CellSize { width_px: 10, height_px: 22 };
165 const EVERY_KIND: &str = "---\ntitle: T\n---\n\n# Heading\n\nA paragraph\nover two lines\n\n- item one\n - nested\n- [x] item two\n\n```rust\nfn a() {}\n```\n\n| a | b |\n|---|---|\n| 1 | 2 |\n\n```mermaid\ngraph TD\n A --> B\n```\n\n> [!NOTE]\n> Noted.\n\nNote[^n].\n\n[^n]: The note.\n";
166
167 fn content(blocks: Vec<Block>) -> Vec<Block> {
169 blocks
170 .into_iter()
171 .flat_map(|block| match block {
172 Block::Lines(lines) => {
173 lines.into_iter().filter(|line| *line != Line::blank()).map(|line| Block::Lines(vec![line])).collect()
174 }
175 other => vec![other],
176 })
177 .collect()
178 }
179
180 fn outline(source: &str) -> Vec<(usize, usize, SectionKind)> {
181 render_sections(source, &test_settings()).into_iter().map(|section| (section.first_line, section.last_line, section.kind)).collect()
182 }
183
184 #[test]
185 fn sections_hold_what_render_draws_less_the_spacing() {
186 for width in [20, 40, 80, 100] {
187 for cell in [None, Some(CELL)] {
188 let settings = Settings { width, cell, ..test_settings() };
189 let blocks: Vec<Block> = render_sections(SHOWCASE, &settings).into_iter().flat_map(|section| section.blocks).collect();
190
191 assert_eq!(content(blocks), content(render(SHOWCASE, &settings).blocks), "width {width}, cell {cell:?}");
192 }
193 }
194 }
195
196 #[test]
197 fn no_section_starts_or_ends_with_a_blank_line() {
198 let is_blank_edge =
199 |block: &Block, edge: fn(&[Line]) -> Option<&Line>| matches!(block, Block::Lines(lines) if edge(lines) == Some(&Line::blank()));
200 for section in render_sections(EVERY_KIND, &test_settings()).into_iter().chain(render_sections(SHOWCASE, &test_settings())) {
201 assert!(!section.blocks.first().is_some_and(|first| is_blank_edge(first, <[Line]>::first)), "{:?}", section.kind);
202 assert!(!section.blocks.last().is_some_and(|last| is_blank_edge(last, <[Line]>::last)), "{:?}", section.kind);
203 }
204 }
205
206 #[test]
207 fn each_section_points_at_its_source_lines() {
208 assert_eq!(
209 outline(EVERY_KIND),
210 [
211 (1, 3, SectionKind::FrontMatter),
212 (5, 5, SectionKind::Heading { level: 1 }),
213 (7, 8, SectionKind::Paragraph),
214 (10, 11, SectionKind::ListItem { task: None }),
215 (12, 12, SectionKind::ListItem { task: Some(true) }),
216 (14, 16, SectionKind::Code { language: Some("rust".to_owned()) }),
217 (18, 20, SectionKind::Table),
218 (22, 25, SectionKind::Mermaid),
219 (27, 28, SectionKind::Alert),
220 (30, 30, SectionKind::Paragraph),
221 (32, 32, SectionKind::Footnotes),
222 ]
223 );
224 }
225
226 #[test]
227 fn lines_end_where_comrak_ends_them_whatever_the_line_ending() {
228 for ending in ["\n", "\r\n", "\r"] {
229 let source = ["- one", " more", "", "- two", "", "", "text"].join(ending) + ending;
230
231 assert_eq!(
232 outline(&source),
233 [
234 (1, 2, SectionKind::ListItem { task: None }),
235 (4, 4, SectionKind::ListItem { task: None }),
236 (7, 7, SectionKind::Paragraph)
237 ],
238 "{ending:?}"
239 );
240 }
241 }
242
243 #[test]
244 fn the_notes_span_every_definition_in_source_order() {
245 let source = "b[^b] a[^a]\n\n[^a]: A.\n\ntext\n\n[^b]: B.\n";
246
247 assert_eq!(outline(source).last(), Some(&(3, 7, SectionKind::Footnotes)));
248 }
249
250 #[test]
251 fn a_list_splits_into_its_items_and_other_containers_stay_whole() {
252 let kinds: Vec<SectionKind> =
253 outline("1. one\n2. two\n\n> quote\n>\n> more\n\n---\n\n<div>x</div>\n").into_iter().map(|(.., kind)| kind).collect();
254
255 assert_eq!(
256 kinds,
257 [
258 SectionKind::ListItem { task: None },
259 SectionKind::ListItem { task: None },
260 SectionKind::Quote,
261 SectionKind::Rule,
262 SectionKind::Html
263 ]
264 );
265 }
266
267 #[test]
268 fn a_fence_without_language_is_code_without_one() {
269 assert_eq!(outline("```\nx\n```\n"), [(1, 3, SectionKind::Code { language: None })]);
270 }
271
272 #[test]
273 fn a_fence_names_its_language_by_its_first_word_lowercased() {
274 let kinds: Vec<SectionKind> = ["Rust,ignore", "{.mermaid}", "Mermaid", "mermaid,ignore"]
275 .iter()
276 .flat_map(|info| outline(&format!("```{info}\ngraph TD\n```\n")))
277 .map(|(.., kind)| kind)
278 .collect();
279
280 assert_eq!(
281 kinds,
282 [SectionKind::Code { language: Some("rust".to_owned()) }, SectionKind::Mermaid, SectionKind::Mermaid, SectionKind::Mermaid]
283 );
284 }
285
286 #[test]
287 fn a_mermaid_section_is_its_picture_when_the_terminal_can_draw() {
288 let settings = Settings { cell: Some(CELL), ..test_settings() };
289 let sections = render_sections("```mermaid\ngraph TD\n A --> B\n```\n", &settings);
290
291 assert!(
292 matches!(sections[..], [Section { kind: SectionKind::Mermaid, ref blocks, .. }] if matches!(blocks[..], [Block::Picture(_)]))
293 );
294 }
295}