2022-12-18 07:37:42 +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;
|
2022-12-18 07:59:41 +00:00
|
|
|
use super::error::Res;
|
2022-12-18 07:37:42 +00:00
|
|
|
use super::parser_context::ChainBehavior;
|
|
|
|
use super::parser_context::ContextElement;
|
|
|
|
use super::parser_context::ExitMatcherNode;
|
|
|
|
use super::text::symbol;
|
2022-12-18 08:11:56 +00:00
|
|
|
use super::text::text_element;
|
2022-12-18 08:24:35 +00:00
|
|
|
use super::token::Link;
|
|
|
|
use super::token::TextElement;
|
2022-12-18 08:18:43 +00:00
|
|
|
use super::util::in_section;
|
2022-12-18 07:37:42 +00:00
|
|
|
use super::Context;
|
|
|
|
use nom::combinator::map;
|
|
|
|
use nom::combinator::recognize;
|
|
|
|
use nom::sequence::tuple;
|
|
|
|
|
2022-12-18 08:30:28 +00:00
|
|
|
pub fn link<'r, 's>(context: Context<'r, 's>, i: &'s str) -> Res<&'s str, Link<'s>> {
|
2022-12-18 07:37:42 +00:00
|
|
|
let link_start = parser_with_context!(context_link_start)(&context);
|
|
|
|
let parser_context = context
|
|
|
|
.with_additional_node(ContextElement::ExitMatcherNode(ExitMatcherNode {
|
|
|
|
exit_matcher: ChainBehavior::AndParent(Some(&context_link_end)),
|
|
|
|
}))
|
|
|
|
.with_additional_node(ContextElement::Context("link"));
|
|
|
|
let (remaining, captured) = recognize(tuple((link_start, |i| {
|
2022-12-18 08:11:56 +00:00
|
|
|
context_many_till(&parser_context, text_element, context_link_end)(i)
|
2022-12-18 07:37:42 +00:00
|
|
|
})))(i)?;
|
|
|
|
let ret = Link { contents: captured };
|
|
|
|
Ok((remaining, ret))
|
|
|
|
}
|
|
|
|
|
2022-12-18 08:30:28 +00:00
|
|
|
fn can_start_link<'r, 's>(context: Context<'r, 's>) -> bool {
|
2022-12-18 07:39:29 +00:00
|
|
|
!in_section(context, "link")
|
2022-12-18 07:37:42 +00:00
|
|
|
}
|
|
|
|
|
2022-12-18 08:30:28 +00:00
|
|
|
fn context_link_start<'r, 's>(context: Context<'r, 's>, input: &'s str) -> Res<&'s str, &'s str> {
|
2022-12-18 07:37:42 +00:00
|
|
|
if can_start_link(context) {
|
|
|
|
recognize(link_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 link",
|
|
|
|
))));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-12-18 08:30:28 +00:00
|
|
|
fn context_link_end<'r, 's>(context: Context<'r, 's>, input: &'s str) -> Res<&'s str, &'s str> {
|
2022-12-18 07:37:42 +00:00
|
|
|
let (remaining, actual_match) = recognize(link_end)(input)?;
|
|
|
|
Ok((remaining, actual_match))
|
|
|
|
}
|
|
|
|
|
|
|
|
fn link_start(input: &str) -> Res<&str, TextElement> {
|
|
|
|
map(symbol("["), TextElement::Symbol)(input)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn link_end(input: &str) -> Res<&str, TextElement> {
|
|
|
|
map(symbol("]"), TextElement::Symbol)(input)
|
|
|
|
}
|