use super::Node;
#[derive(Clone)]
pub struct Ast {
inner: Vec<Node>,
}
impl Ast {
#[must_use]
pub fn from_string(source: &str) -> Self {
let mut ast = vec![];
let mut in_preformatted = false;
let mut in_list = false;
let mut lines = source.lines();
while let Some(line) = lines.next() {
ast.append(&mut Self::evaluate(
line,
&mut lines,
&mut in_preformatted,
&mut in_list,
));
}
Self {
inner: ast
}
}
#[must_use]
pub fn to_gemtext(&self) -> String {
let mut gemtext = "".to_string();
for node in &self.inner {
match node {
Node::Text(text) => gemtext.push_str(&format!("{}\n", text)),
Node::Link {
to,
text,
} =>
gemtext.push_str(&format!(
"=> {}{}\n",
to,
text
.clone()
.map_or_else(|| "".to_string(), |text| format!(" {}", text)),
)),
Node::Heading {
level,
text,
} =>
gemtext.push_str(&format!(
"{} {}\n",
match level {
1 => "#",
2 => "##",
3 => "###",
_ => "",
},
text
)),
Node::List(items) =>
gemtext.push_str(&format!(
"{}\n",
items
.iter()
.map(|i| format!("* {}", i))
.collect::<Vec<String>>()
.join("\n"),
)),
Node::Blockquote(text) => gemtext.push_str(&format!("> {}\n", text)),
Node::PreformattedText {
alt_text,
text,
} =>
gemtext.push_str(&format!(
"```{}\n{}```\n",
alt_text.clone().unwrap_or_else(|| "".to_string()),
text
)),
Node::Whitespace => gemtext.push('\n'),
}
}
gemtext
}
#[must_use]
pub const fn inner(&self) -> &Vec<Node> { &self.inner }
#[allow(clippy::too_many_lines)]
fn evaluate(
line: &str,
lines: &mut std::str::Lines<'_>,
in_preformatted: &mut bool,
in_list: &mut bool,
) -> Vec<Node> {
let mut preformatted = String::new();
let mut alt_text = String::new();
let mut nodes = vec![];
let mut line = line;
let mut list_items = vec![];
loop {
match line.get(0..1).unwrap_or("") {
"=" => {
let line = line.get(2..).unwrap();
let mut split = line
.split_whitespace()
.map(String::from)
.collect::<Vec<String>>()
.into_iter();
nodes.push(Node::Link {
to: split.next().expect("no location in link"),
text: {
let rest = split.collect::<Vec<String>>().join(" ");
if rest.is_empty() {
None
} else {
Some(rest)
}
},
});
break;
}
"#" => {
let level = match line.get(0..3) {
Some(root) =>
if root.contains("###") {
3
} else if root.contains("##") {
2
} else if root.contains('#') {
1
} else {
0
},
None => 0,
};
nodes.push(Node::Heading {
level,
text: line.get(level..).unwrap_or("").trim_start().to_string(),
});
break;
}
"*" => {
if !*in_list {
*in_list = true;
}
list_items.push(line.get(1..).unwrap_or("").trim_start().to_string());
if let Some(next_line) = lines.next() {
line = next_line;
} else {
break;
}
}
">" => {
nodes.push(Node::Blockquote(
line.get(1..).unwrap_or("").trim_start().to_string(),
));
break;
}
"`" => {
*in_preformatted = !*in_preformatted;
if *in_preformatted {
alt_text = line.get(3..).unwrap_or("").to_string();
if let Some(next_line) = lines.next() {
line = next_line;
} else {
break;
}
} else {
nodes.push(Node::PreformattedText {
alt_text: if alt_text.is_empty() {
None
} else {
Some(alt_text)
},
text: preformatted,
});
break;
}
}
"" if !*in_preformatted => {
nodes.push(Node::Whitespace);
break;
}
_ => {
if *in_preformatted {
preformatted.push_str(&format!("{}\n", line));
if let Some(next_line) = lines.next() {
line = next_line;
} else {
break;
}
} else {
if *in_list {
*in_list = false;
nodes.push(Node::Text(line.to_string()));
break;
}
nodes.push(Node::Text(line.to_string()));
break;
}
}
}
}
if !list_items.is_empty() {
nodes.reverse();
nodes.push(Node::List(list_items));
nodes.reverse();
}
nodes
}
}