mirror of
https://github.com/TxtDot/dalet-rs.git
synced 2025-03-15 03:57:50 +03:00
feat: gemtext parser, pre tag
This commit is contained in:
parent
856534c22f
commit
6265701499
9 changed files with 258 additions and 1 deletions
src/parsers
68
src/parsers/gemtext.rs
Normal file
68
src/parsers/gemtext.rs
Normal file
|
@ -0,0 +1,68 @@
|
|||
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)
|
||||
}
|
1
src/parsers/mod.rs
Normal file
1
src/parsers/mod.rs
Normal file
|
@ -0,0 +1 @@
|
|||
pub mod gemtext;
|
Loading…
Add table
Add a link
Reference in a new issue