From 53f1753db91fe9347155f8192052e30baaad9cbc Mon Sep 17 00:00:00 2001 From: Fuwn Date: Thu, 2 Jun 2022 07:31:20 +0000 Subject: feat(ast): Ast::to_gemtext --- src/ast.rs | 58 +++++++++++++++++++++++++++++++++++++++++++++++++ src/convert/markdown.rs | 2 +- 2 files changed, 59 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/ast.rs b/src/ast.rs index f432666..49ee1f6 100644 --- a/src/ast.rs +++ b/src/ast.rs @@ -215,6 +215,64 @@ impl 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::>() + .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 + } + /// The actual AST of `Ast` /// /// # Example diff --git a/src/convert/markdown.rs b/src/convert/markdown.rs index c6899b7..a38da9f 100644 --- a/src/convert/markdown.rs +++ b/src/convert/markdown.rs @@ -69,7 +69,7 @@ pub fn convert(source: &[Node]) -> String { text )); } - Node::Whitespace => markdown.push_str("\n"), + Node::Whitespace => markdown.push('\n'), } } -- cgit v1.2.3