diff --git a/src/parser/org_source.rs b/src/parser/org_source.rs index db252d41..a9f479fd 100644 --- a/src/parser/org_source.rs +++ b/src/parser/org_source.rs @@ -19,6 +19,9 @@ pub struct OrgSource<'s> { start_of_line: usize, preceding_character: Option, line_number: usize, + bracket_depth: isize, // [] + brace_depth: isize, // {} + parenthesis_depth: isize, // () } impl<'s> OrgSource<'s> { @@ -33,6 +36,9 @@ impl<'s> OrgSource<'s> { start_of_line: 0, preceding_character: None, line_number: 1, + bracket_depth: 0, + brace_depth: 0, + parenthesis_depth: 0, } } @@ -62,6 +68,18 @@ impl<'s> OrgSource<'s> { pub fn get_line_number(&self) -> usize { self.line_number } + + pub fn get_bracket_depth(&self) -> isize { + self.bracket_depth + } + + pub fn get_brace_depth(&self) -> isize { + self.brace_depth + } + + pub fn get_parenthesis_depth(&self) -> isize { + self.parenthesis_depth + } } impl<'s> InputTake for OrgSource<'s> { @@ -127,11 +145,35 @@ where let skipped_text = &self.full_source[self.start..new_start]; let mut start_of_line = self.start_of_line; let mut line_number = self.line_number; + let mut bracket_depth = self.bracket_depth; + let mut brace_depth = self.brace_depth; + let mut parenthesis_depth = self.parenthesis_depth; for (offset, character) in skipped_text.char_indices() { - if character == '\n' { - start_of_line = self.start + offset + 1; - line_number += 1; - } + match character { + '\n' => { + start_of_line = self.start + offset + 1; + line_number += 1; + } + '[' => { + bracket_depth += 1; + } + ']' => { + bracket_depth -= 1; + } + '{' => { + brace_depth += 1; + } + '}' => { + brace_depth -= 1; + } + '(' => { + parenthesis_depth += 1; + } + ')' => { + parenthesis_depth -= 1; + } + _ => {} + }; } OrgSource { @@ -141,6 +183,9 @@ where start_of_line, preceding_character: skipped_text.chars().last(), line_number, + bracket_depth, + brace_depth, + parenthesis_depth, } } } @@ -389,4 +434,19 @@ mod tests { assert_eq!(input.slice(6..).get_line_number(), 2); assert_eq!(input.slice(6..).slice(10..).get_line_number(), 4); } + + #[test] + fn depth() { + let input = OrgSource::new("[][()][({)]}}}}"); + assert_eq!(input.get_bracket_depth(), 0); + assert_eq!(input.get_brace_depth(), 0); + assert_eq!(input.get_parenthesis_depth(), 0); + assert_eq!(input.slice(4..).get_bracket_depth(), 1); + assert_eq!(input.slice(4..).get_brace_depth(), 0); + assert_eq!(input.slice(4..).get_parenthesis_depth(), 1); + assert_eq!(input.slice(4..).slice(6..).get_bracket_depth(), 1); + assert_eq!(input.slice(4..).slice(6..).get_brace_depth(), 1); + assert_eq!(input.slice(4..).slice(6..).get_parenthesis_depth(), 0); + assert_eq!(input.slice(14..).get_brace_depth(), -2); + } }