From 1835873d7553a413f0d13f14f4dbc2e07d477c45 Mon Sep 17 00:00:00 2001 From: Kjetil Orbekk Date: Fri, 2 Nov 2018 18:27:07 -0400 Subject: Parse and print working for a subset of org docs --- src/org.rs | 45 ++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 42 insertions(+), 3 deletions(-) diff --git a/src/org.rs b/src/org.rs index aa81581..aca0d6b 100644 --- a/src/org.rs +++ b/src/org.rs @@ -21,7 +21,7 @@ macro_rules! matchers { } matchers! { - header <- r"^(\*)+ (.*)"; + header <- r"^(\*+) (.*)"; properties_start <- r"^\s*:PROPERTIES:\s*$"; property <- r"^\s*:([^:]*): (.*)$"; properties_end <- r"^\s*:END:\s*$"; @@ -80,6 +80,31 @@ pub fn parse(input: &str) -> OrgDocument { parser.doc } +pub fn print(doc: OrgDocument) -> String { + let mut result = vec![]; + let mut current_level = 0; + for e in doc { + match e { + Org::Unknown(s) => result.push(s), + + Org::Header(level, s) => { + current_level = level as usize; + result.push(format!("{} {}", "*".repeat(level as usize), s)); + } + + Org::Properties(_ps) => { + let indent = " ".repeat(current_level); + result.push(format!("{}:PROPERTIES:", indent)); + for (key, val) in _ps { + result.push(format!("{}:{}: {}", indent, key, val)); + } + result.push(format!("{}:END:", indent)); + } + } + } + result.join("\n") +} + #[cfg(test)] mod tests { use super::*; @@ -102,8 +127,8 @@ mod tests { #[test] fn parse_header() { - let doc = "* hello"; - assert_eq!(parse(doc), vec![Org::Header(1, "hello".to_string())]); + let doc = "** hello"; + assert_eq!(parse(doc), vec![Org::Header(2, "hello".to_string())]); assert_eq!( parse(" * hello"), vec![Org::Unknown(" * hello".to_string())] @@ -131,4 +156,18 @@ mod tests { ] ); } + + #[test] + fn print_id() { + let doc = "* Hello + :PROPERTIES: + :FOO: 1 + :END: +This is an org document. + +** Another header +This is deep. +"; + assert_eq!(doc, print(parse(doc))); + } } -- cgit v1.2.3