Check that the preceding line for a line break is non-empty.

This commit is contained in:
Tom Alexander 2023-07-22 00:26:54 -04:00
parent a1f3e9ea47
commit 5c1d913c99
Signed by: talexander
GPG Key ID: D3A179C9A53C0EDE
3 changed files with 47 additions and 3 deletions

View File

@ -9,6 +9,7 @@ use crate::error::CustomError;
use crate::error::MyError;
use crate::error::Res;
use crate::parser::util::get_consumed;
use crate::parser::util::get_current_line_before_position;
use crate::parser::util::get_one_before;
use crate::parser::LineBreak;
@ -28,7 +29,6 @@ fn pre<'r, 's>(context: Context<'r, 's>, input: &'s str) -> Res<&'s str, ()> {
let preceding_character = get_one_before(document_root, input)
.map(|slice| slice.chars().next())
.flatten();
// TODO: Must be at the end of a non-empty line so instead of getting one character before, we need to grab the entire line.
match preceding_character {
// If None, we are at the start of the file
None | Some('\\') => {
@ -38,5 +38,22 @@ fn pre<'r, 's>(context: Context<'r, 's>, input: &'s str) -> Res<&'s str, ()> {
}
_ => {}
};
let current_line = get_current_line_before_position(document_root, input);
match current_line {
Some(line) => {
let is_non_empty_line = line.chars().any(|c| !c.is_whitespace());
if !is_non_empty_line {
return Err(nom::Err::Error(CustomError::MyError(MyError(
"Not a valid pre line for line break.",
))));
}
}
None => {
return Err(nom::Err::Error(CustomError::MyError(MyError(
"No preceding line for line break.",
))));
}
}
Ok((input, ()))
}

View File

@ -59,6 +59,32 @@ pub fn get_one_before<'s>(document: &'s str, current_position: &'s str) -> Optio
Some(&document[previous_character_offset..offset])
}
/// Get the line current_position is on up until current_position
pub fn get_current_line_before_position<'s>(
document: &'s str,
current_position: &'s str,
) -> Option<&'s str> {
assert!(is_slice_of(document, current_position));
if document.as_ptr() as usize == current_position.as_ptr() as usize {
return None;
}
let offset = current_position.as_ptr() as usize - document.as_ptr() as usize;
let mut previous_character_offset = offset;
loop {
let new_offset = document.floor_char_boundary(previous_character_offset - 1);
let new_line = &document[new_offset..offset];
let leading_char = new_line
.chars()
.next()
.expect("Impossible to not have at least 1 character to read.");
if "\r\n".contains(leading_char) || new_offset == 0 {
break;
}
previous_character_offset = new_offset;
}
Some(&document[previous_character_offset..offset])
}
/// Check if the child string slice is a slice of the parent string slice.
fn is_slice_of(parent: &str, child: &str) -> bool {
let parent_start = parent.as_ptr() as usize;

View File

@ -1,2 +1,3 @@
before src_foo{ipsum} after
src_bar[lorem]{ipsum}
foo bar baz
lorem ipsum