diff options
| author | Fuwn <[email protected]> | 2022-06-02 07:31:20 +0000 |
|---|---|---|
| committer | Fuwn <[email protected]> | 2022-06-02 07:31:20 +0000 |
| commit | 53f1753db91fe9347155f8192052e30baaad9cbc (patch) | |
| tree | f7053185a4a2e20a9a086ab96153bc074f7e5672 /src/ast.rs | |
| parent | docs(cargo): bump 0.2.3 -> 0.2.4 (diff) | |
| download | germ-53f1753db91fe9347155f8192052e30baaad9cbc.tar.xz germ-53f1753db91fe9347155f8192052e30baaad9cbc.zip | |
feat(ast): Ast::to_gemtext
Diffstat (limited to 'src/ast.rs')
| -rw-r--r-- | src/ast.rs | 58 |
1 files changed, 58 insertions, 0 deletions
@@ -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::<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 + } + /// The actual AST of `Ast` /// /// # Example |