organic/src/parser/bold.rs

73 lines
2.5 KiB
Rust
Raw Normal View History

2022-12-18 07:30:24 +00:00
use crate::parser::parser_with_context::parser_with_context;
use super::combinator::context_many_till;
use super::error::CustomError;
use super::error::MyError;
use super::parser_context::ChainBehavior;
use super::parser_context::ContextElement;
use super::parser_context::ExitMatcherNode;
use super::text::symbol;
use super::text::Bold;
use super::text::Res;
use super::text::TextElement;
use super::text_element_parser::_preceded_by_whitespace;
use super::text_element_parser::flat_text_element;
2022-12-18 07:39:29 +00:00
use super::text_element_parser::in_section;
2022-12-18 07:30:24 +00:00
use super::Context;
use nom::branch::alt;
use nom::bytes::complete::tag;
use nom::combinator::map;
use nom::combinator::peek;
use nom::combinator::recognize;
use nom::sequence::tuple;
2022-12-18 07:39:29 +00:00
pub fn bold<'s, 'r>(context: Context<'r, 's>, i: &'s str) -> Res<&'s str, Bold<'s>> {
2022-12-18 07:30:24 +00:00
let bold_start = parser_with_context!(context_bold_start)(&context);
let parser_context = context
.with_additional_node(ContextElement::ExitMatcherNode(ExitMatcherNode {
exit_matcher: ChainBehavior::AndParent(Some(&context_bold_end)),
}))
.with_additional_node(ContextElement::Context("bold"));
let (remaining, captured) = recognize(tuple((bold_start, |i| {
context_many_till(&parser_context, flat_text_element, context_bold_end)(i)
})))(i)?;
let ret = Bold { contents: captured };
Ok((remaining, ret))
}
fn can_start_bold<'s, 'r>(context: Context<'r, 's>) -> bool {
2022-12-18 07:39:29 +00:00
_preceded_by_whitespace(context) && !in_section(context, "bold")
2022-12-18 07:30:24 +00:00
}
2022-12-18 07:37:42 +00:00
fn context_bold_start<'s, 'r>(context: Context<'r, 's>, input: &'s str) -> Res<&'s str, &'s str> {
2022-12-18 07:30:24 +00:00
if can_start_bold(context) {
recognize(bold_start)(input)
} else {
// TODO: Make this a specific error instead of just a generic MyError
return Err(nom::Err::Error(CustomError::MyError(MyError(
"Cannot start bold",
))));
}
}
2022-12-18 07:37:42 +00:00
fn context_bold_end<'s, 'r>(context: Context<'r, 's>, input: &'s str) -> Res<&'s str, &'s str> {
2022-12-18 07:30:24 +00:00
let (remaining, actual_match) = recognize(bold_end)(input)?;
peek(alt((
// Must have whitespace after the end asterisk or it must be the end of that section (as checked by the exit matcher)
tag(" "),
tag("\t"),
tag("\n"),
|i| context.check_exit_matcher(i),
)))(remaining)?;
Ok((remaining, actual_match))
}
2022-12-18 07:37:42 +00:00
fn bold_start(input: &str) -> Res<&str, TextElement> {
2022-12-18 07:30:24 +00:00
map(symbol("*"), TextElement::Symbol)(input)
}
2022-12-18 07:37:42 +00:00
fn bold_end(input: &str) -> Res<&str, TextElement> {
2022-12-18 07:30:24 +00:00
map(symbol("*"), TextElement::Symbol)(input)
}