mirror of
https://github.com/TxtDot/dalet-rs.git
synced 2025-03-14 11:44:38 +03:00
69 lines
2.5 KiB
Rust
69 lines
2.5 KiB
Rust
|
use crate::abstractions::{Body, HeadingLevel, NotNullBody, Tag};
|
||
|
|
||
|
#[derive(Debug)]
|
||
|
pub enum GemTextParseError {
|
||
|
InvalidLink,
|
||
|
}
|
||
|
|
||
|
pub fn parse_gemtext(s: String) -> Result<Vec<Tag>, GemTextParseError> {
|
||
|
let mut page: Vec<Tag> = Vec::new();
|
||
|
let mut preformatted = false;
|
||
|
let mut preformatted_text = String::new();
|
||
|
|
||
|
let mut before_is_ordered_list = false;
|
||
|
let mut ordered_list: Vec<Tag> = Vec::new();
|
||
|
|
||
|
for line in s.lines() {
|
||
|
let mut line = line.trim().to_owned();
|
||
|
|
||
|
if before_is_ordered_list && !line.starts_with("* ") {
|
||
|
page.push(Tag::Ul(ordered_list.clone()));
|
||
|
before_is_ordered_list = false;
|
||
|
ordered_list.clear();
|
||
|
} else if preformatted && !line.starts_with("```") {
|
||
|
preformatted_text.push_str(&line);
|
||
|
preformatted_text.push('\n');
|
||
|
} else if line.starts_with("=>") {
|
||
|
let body = line.split_off(2);
|
||
|
let mut body = body.trim().splitn(2, " ");
|
||
|
|
||
|
let url = body.next().ok_or(GemTextParseError::InvalidLink)?.trim();
|
||
|
|
||
|
match body.next() {
|
||
|
Some(label) => page.push(Tag::Link(
|
||
|
Body::Text(label.trim().to_owned()),
|
||
|
url.to_owned(),
|
||
|
)),
|
||
|
None => page.push(Tag::Link(Body::Null, url.to_owned())),
|
||
|
};
|
||
|
} else if line.starts_with("# ") {
|
||
|
let body = line.split_off(2);
|
||
|
page.push(Tag::H(body.trim().to_owned(), HeadingLevel::One));
|
||
|
} else if line.starts_with("## ") {
|
||
|
let body = line.split_off(3);
|
||
|
page.push(Tag::H(body.trim().to_owned(), HeadingLevel::Two));
|
||
|
} else if line.starts_with("### ") {
|
||
|
let body = line.split_off(4);
|
||
|
page.push(Tag::H(body.trim().to_owned(), HeadingLevel::Three));
|
||
|
} else if line.starts_with("* ") {
|
||
|
before_is_ordered_list = true;
|
||
|
let body = line.split_off(2);
|
||
|
ordered_list.push(Tag::El(NotNullBody::Text(body)));
|
||
|
} else if line.starts_with("> ") {
|
||
|
let body = line.split_off(2);
|
||
|
page.push(Tag::Bq(NotNullBody::Text(body)));
|
||
|
} else if line.starts_with("```") {
|
||
|
if preformatted {
|
||
|
page.push(Tag::Pre(preformatted_text.clone()));
|
||
|
preformatted_text.clear();
|
||
|
}
|
||
|
|
||
|
preformatted = !preformatted;
|
||
|
} else if !line.is_empty() {
|
||
|
page.push(Tag::P(NotNullBody::Text(line)));
|
||
|
}
|
||
|
}
|
||
|
|
||
|
Ok(page)
|
||
|
}
|