organic/src/parser/line_break.rs

69 lines
2.3 KiB
Rust
Raw Normal View History

2023-07-22 00:00:53 -04:00
use nom::bytes::complete::tag;
use nom::character::complete::line_ending;
use nom::character::complete::one_of;
use nom::combinator::recognize;
use nom::multi::many0;
use super::org_source::OrgSource;
2023-07-21 23:48:37 -04:00
use super::Context;
2023-07-22 00:00:53 -04:00
use crate::error::CustomError;
use crate::error::MyError;
2023-07-21 23:48:37 -04:00
use crate::error::Res;
2023-07-22 00:00:53 -04:00
use crate::parser::util::get_consumed;
use crate::parser::util::get_current_line_before_position;
2023-07-22 00:00:53 -04:00
use crate::parser::util::get_one_before;
use crate::parser::LineBreak;
2023-08-10 20:04:59 -04:00
#[cfg_attr(feature = "tracing", tracing::instrument(ret, level = "debug"))]
pub fn line_break<'r, 's>(
context: Context<'r, 's>,
input: OrgSource<'s>,
) -> Res<OrgSource<'s>, LineBreak<'s>> {
2023-07-22 00:00:53 -04:00
let (remaining, _) = pre(context, input)?;
let (remaining, _) = tag(r#"\\"#)(remaining)?;
let (remaining, _) = recognize(many0(one_of(" \t")))(remaining)?;
let (remaining, _) = line_ending(remaining)?;
let source = get_consumed(input, remaining);
Ok((
remaining,
LineBreak {
source: source.into(),
},
))
2023-07-22 00:00:53 -04:00
}
2023-07-21 23:48:37 -04:00
2023-08-10 20:04:59 -04:00
#[cfg_attr(feature = "tracing", tracing::instrument(ret, level = "debug"))]
fn pre<'r, 's>(context: Context<'r, 's>, input: OrgSource<'s>) -> Res<OrgSource<'s>, ()> {
2023-07-22 00:00:53 -04:00
let document_root = context.get_document_root().unwrap();
let preceding_character = get_one_before(document_root, input)
.map(|slice| slice.chars().next())
.flatten();
match preceding_character {
// If None, we are at the start of the file
None | Some('\\') => {
return Err(nom::Err::Error(CustomError::MyError(MyError(
"Not a valid pre character for line break.".into(),
2023-07-22 00:00:53 -04:00
))));
}
_ => {}
};
let current_line = get_current_line_before_position(document_root, input);
match current_line {
Some(line) => {
let is_non_empty_line = Into::<&str>::into(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.".into(),
))));
}
}
None => {
return Err(nom::Err::Error(CustomError::MyError(MyError(
"No preceding line for line break.".into(),
))));
}
}
2023-07-22 00:00:53 -04:00
Ok((input, ()))
2023-07-21 23:48:37 -04:00
}