prettify_markdown/format/
heading.rs

1use prettify::{
2    concat, conditional_group, fill, hard_line, join, join_to_vector, line, string, PrettifyDoc,
3};
4
5fn atx_heading_marker(level: usize) -> PrettifyDoc<'static> {
6    let heading_marker = "#";
7    let heading_marker = heading_marker.repeat(level) + " ";
8    string(heading_marker)
9}
10
11pub fn format_atx_heading(level: usize, content: &str) -> PrettifyDoc {
12    concat(vec![
13        atx_heading_marker(level),
14        string(content),
15        hard_line(),
16    ])
17}
18
19pub fn format_setext_heading(level: usize, content: &str) -> PrettifyDoc {
20    let heading_marker = if level == 1 { "=" } else { "-" };
21    let heading_marker = heading_marker.repeat(12);
22
23    let content_words: Vec<PrettifyDoc> =
24        content.replace('\n', " ").split(' ').map(string).collect();
25
26    concat(vec![
27        conditional_group(
28            vec![
29                concat(vec![
30                    atx_heading_marker(level),
31                    join(content_words.clone(), line()),
32                ]),
33                concat(vec![
34                    fill(join_to_vector(content_words, line())),
35                    hard_line(),
36                    string(heading_marker),
37                ]),
38            ],
39            "setext_heading",
40        ),
41        hard_line(),
42    ])
43}
44
45#[cfg(test)]
46mod tests {
47    use super::*;
48    use prettify::print;
49
50    #[test]
51    fn format_atx_heading_test() {
52        assert_eq!(
53            print(format_atx_heading(1, "hello world")),
54            "# hello world\n"
55        );
56        assert_eq!(
57            print(format_atx_heading(2, "hello world")),
58            "## hello world\n"
59        );
60    }
61
62    #[test]
63    fn format_setext_heading_test() {
64        assert_eq!(
65            print(format_setext_heading(1, "hello world")),
66            "# hello world\n"
67        );
68        assert_eq!(
69            print(format_setext_heading(2, "hello world")),
70            "## hello world\n"
71        );
72        assert_eq!(
73            print(format_setext_heading(1, "hello\nworld")),
74            "# hello world\n"
75        );
76        assert_eq!(
77            print(format_setext_heading(2, "hello\nworld")),
78            "## hello world\n"
79        );
80        assert_eq!(print(format_setext_heading(2, "hello")), "## hello\n");
81        assert_eq!(
82            print(format_setext_heading(
83                1,
84                "this is an incredibly long header that definitely cannot fit on one line so this will need to be rendered as a setext heading"
85            )),
86            "this is an incredibly long header that definitely cannot fit on one line so this\nwill need to be rendered as a setext heading\n============\n"
87        );
88    }
89}