nvim-neorg / rust-norg

A robust parser for Norg for tools that don't use tree-sitter.
11 stars 3 forks source link

feat(lib): re-export stage2 and stage3 token and node enums to expose them #2

Closed NTBBloodbath closed 2 months ago

NTBBloodbath commented 2 months ago

This change allows token and node enums to be used outside of internal parsing by exposing them in the main public API rust_norg, thus allowing them to be used for external parsing based on the chumsky parser. For example, to create a Norg -> HTML parser.

Any suggestion is welcome :)

Dummy example code for headers and paragraphs w/ preview ```rust use rust_norg::{parse, ParagraphSegmentToken, NorgASTFlat}; trait NorgToHtml { fn to_html(&self) -> String; } fn paragraph_to_string(segment: &[ParagraphSegmentToken]) -> String { let mut paragraph: String = "".to_owned(); segment.iter().for_each(|node| match node { ParagraphSegmentToken::Text(s) => paragraph.push_str(s), ParagraphSegmentToken::Whitespace => paragraph.push(' '), ParagraphSegmentToken::Escape(c) => paragraph.push_str(&c.to_string()), ParagraphSegmentToken::Special(c) => paragraph.push_str(&c.to_string()), }); paragraph } impl NorgToHtml for NorgASTFlat { fn to_html(&self) -> String { match self { NorgASTFlat::Heading {level, title, ..} => { let mut heading_tag: String = "<".to_owned(); match level { 1 => { heading_tag.push_str("h1>") }, _ => todo!() } let heading_title = paragraph_to_string(title); heading_tag.push_str(&heading_title); heading_tag.push_str(""); heading_tag }, NorgASTFlat::Paragraph(s) => { let mut paragraph_tag: String = "

".to_owned(); let paragraph = paragraph_to_string(s); paragraph_tag.push_str(¶graph); paragraph_tag.push_str("

"); paragraph_tag } _ => todo!(), } } } fn norg_to_html(ast: &NorgASTFlat) -> String { ast.to_html() } fn main() -> Result<()> { let norg_code = "* Hello, World\n This is a paragraph lol\n"; println!("Norg code:\n{}\nProduced HTML:", norg_code); let ast = parse(norg_code).unwrap(); for node in ast { let html = norg_to_html(&node); println!("{}", html); } Ok(()) } ``` ![demo showcase](https://github.com/nvim-neorg/rust-norg/assets/36456999/7e7d64b4-f5d3-4348-87e3-1ff605c6b18e)