Skip to main content

microcad_lang_markdown/
section.rs

1// Copyright © 2026 The µcad authors <info@ucad.xyz>
2// SPDX-License-Identifier: AGPL-3.0-or-later
3
4//! Markdown section
5
6use crate::Paragraph;
7
8/// A markdown section with heading and paragraphs.
9#[derive(Debug, Clone, Default)]
10pub struct Section {
11    /// A heading, displayed with a `#` prefix in markdown.
12    pub heading: String,
13    /// Section level.
14    pub level: i64,
15    /// The section content, consisting of paragraphs.
16    pub content: Vec<Paragraph>,
17}
18
19impl Section {
20    /// A section with `n` levels deeper.
21    pub fn nested(&self, n: i64) -> Section {
22        Section {
23            heading: self.heading.clone(),
24            level: self.level + n,
25            content: self.content.clone(),
26        }
27    }
28
29    /// Returns `false` if this section has a heading and a content.
30    pub fn is_empty(&self) -> bool {
31        self.heading.is_empty() && self.content.is_empty()
32    }
33}
34
35impl std::fmt::Display for Section {
36    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
37        writeln!(f, "{} {}", "#".repeat(self.level as usize), self.heading)?;
38        if self.content.is_empty() {
39            Ok(())
40        } else {
41            writeln!(f)?;
42            self.content
43                .iter()
44                .enumerate()
45                .try_for_each(|(i, paragraph)| {
46                    if i > 0 {
47                        writeln!(f)?;
48                    }
49                    write!(f, "{paragraph}")
50                })
51        }
52    }
53}