1pub fn is_callout_line(line: &str) -> bool {
2 line.trim_start()
3 .strip_prefix("//")
4 .is_some_and(|body| body.trim_start().starts_with("!callout"))
5}
6
7pub fn drop_callout_lines(text: &str) -> String {
8 text.lines()
9 .filter(|line| !is_callout_line(line))
10 .collect::<Vec<_>>()
11 .join("\n")
12}
13
14pub fn split_example(doc: &str) -> (&str, Option<&str>) {
15 match doc.find("\nExample:\n") {
16 Some(position) => {
17 let prose = doc[..position].trim_end();
18 let example = doc[position + "\nExample:\n".len()..].trim_end();
19 (prose, Some(example))
20 }
21 None => (doc, None),
22 }
23}
24
25pub fn dedent(text: &str) -> String {
26 let indent = text
27 .lines()
28 .filter(|line| !line.trim().is_empty())
29 .map(|line| line.len() - line.trim_start().len())
30 .min()
31 .unwrap_or(0);
32 text.lines()
33 .map(|line| line.get(indent..).unwrap_or(""))
34 .collect::<Vec<_>>()
35 .join("\n")
36}
37
38pub fn to_markdown(doc: &str) -> String {
40 let text = drop_callout_lines(doc);
41 let (prose, example) = split_example(&text);
42 match example {
43 Some(example) => format!(
44 "{prose}\n\nExample:\n\n```lisette\n{}\n```",
45 dedent(example)
46 ),
47 None => prose.to_string(),
48 }
49}
50
51#[cfg(test)]
52mod tests {
53 use super::*;
54
55 const BUFFERED: &str = "Creates a `Channel` with room for `capacity` values.\n\nExample:\n // !callout-right room for `4` values before a send waits\n let jobs = Channel.buffered<int>(4)";
56
57 #[test]
58 fn markdown_drops_callouts_and_fences_the_example() {
59 assert_eq!(
60 to_markdown(BUFFERED),
61 "Creates a `Channel` with room for `capacity` values.\n\nExample:\n\n```lisette\nlet jobs = Channel.buffered<int>(4)\n```"
62 );
63 }
64
65 #[test]
66 fn markdown_without_example_is_the_prose() {
67 assert_eq!(to_markdown("Returns the length."), "Returns the length.");
68 }
69
70 #[test]
71 fn split_example_keeps_prose_and_example_apart() {
72 let (prose, example) = split_example(BUFFERED);
73 assert_eq!(
74 prose,
75 "Creates a `Channel` with room for `capacity` values."
76 );
77 assert_eq!(
78 example,
79 Some(
80 " // !callout-right room for `4` values before a send waits\n let jobs = Channel.buffered<int>(4)"
81 )
82 );
83 }
84
85 #[test]
86 fn dedent_removes_the_shared_indent_only() {
87 assert_eq!(dedent(" a\n\n b"), "a\n\n b");
88 }
89}