1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
use nom::branch::alt;
use nom::bytes::complete::is_not;
use nom::bytes::complete::tag_no_case;
use nom::character::complete::line_ending;
use nom::character::complete::space0;
use nom::character::complete::space1;
use nom::combinator::eof;
use nom::combinator::not;
use nom::combinator::opt;
use nom::combinator::recognize;
use nom::multi::many_till;
use nom::sequence::tuple;

use super::org_source::OrgSource;
use crate::context::parser_with_context;
use crate::context::ContextElement;
use crate::context::ExitClass;
use crate::context::ExitMatcherNode;
use crate::context::RefContext;
use crate::error::CustomError;
use crate::error::MyError;
use crate::error::Res;
use crate::parser::element_parser::element;
use crate::parser::util::blank_line;
use crate::parser::util::exit_matcher_parser;
use crate::parser::util::get_consumed;
use crate::parser::util::immediate_in_section;
use crate::parser::util::start_of_line;
use crate::types::DynamicBlock;
use crate::types::Element;
use crate::types::Paragraph;
use crate::types::SetSource;

#[cfg_attr(feature = "tracing", tracing::instrument(ret, level = "debug"))]
pub fn dynamic_block<'b, 'g, 'r, 's>(
    context: RefContext<'b, 'g, 'r, 's>,
    input: OrgSource<'s>,
) -> Res<OrgSource<'s>, DynamicBlock<'s>> {
    // TODO: Do I need to differentiate between different dynamic block types.
    if immediate_in_section(context, "dynamic block") {
        return Err(nom::Err::Error(CustomError::MyError(MyError(
            "Cannot nest objects of the same element".into(),
        ))));
    }
    start_of_line(input)?;
    let (remaining, _leading_whitespace) = space0(input)?;
    let (remaining, (_begin, name, parameters, _ws)) = tuple((
        recognize(tuple((tag_no_case("#+begin:"), space1))),
        name,
        opt(tuple((space1, parameters))),
        line_ending,
    ))(remaining)?;
    let contexts = [
        ContextElement::ConsumeTrailingWhitespace(true),
        ContextElement::Context("dynamic block"),
        ContextElement::ExitMatcherNode(ExitMatcherNode {
            class: ExitClass::Alpha,
            exit_matcher: &dynamic_block_end,
        }),
    ];
    let parser_context = context.with_additional_node(&contexts[0]);
    let parser_context = parser_context.with_additional_node(&contexts[1]);
    let parser_context = parser_context.with_additional_node(&contexts[2]);
    let parameters = match parameters {
        Some((_ws, parameters)) => Some(parameters),
        None => None,
    };
    let element_matcher = parser_with_context!(element(true))(&parser_context);
    let exit_matcher = parser_with_context!(exit_matcher_parser)(&parser_context);
    let (remaining, children) = match tuple((
        not(exit_matcher),
        blank_line,
        many_till(blank_line, exit_matcher),
    ))(remaining)
    {
        Ok((remain, (_not_immediate_exit, first_line, (_trailing_whitespace, _exit_contents)))) => {
            let mut element = Element::Paragraph(Paragraph::of_text(first_line.into()));
            let source = get_consumed(remaining, remain);
            element.set_source(source.into());
            (remain, vec![element])
        }
        Err(_) => {
            let (remaining, (children, _exit_contents)) =
                many_till(element_matcher, exit_matcher)(remaining)?;
            (remaining, children)
        }
    };
    let (remaining, _end) = dynamic_block_end(&parser_context, remaining)?;

    let source = get_consumed(input, remaining);
    Ok((
        remaining,
        DynamicBlock {
            source: source.into(),
            name: name.into(),
            parameters: parameters.map(|val| val.into()),
            children,
        },
    ))
}

#[cfg_attr(feature = "tracing", tracing::instrument(ret, level = "debug"))]
fn name<'s>(input: OrgSource<'s>) -> Res<OrgSource<'s>, OrgSource<'s>> {
    is_not(" \t\r\n")(input)
}

#[cfg_attr(feature = "tracing", tracing::instrument(ret, level = "debug"))]
fn parameters<'s>(input: OrgSource<'s>) -> Res<OrgSource<'s>, OrgSource<'s>> {
    is_not("\r\n")(input)
}

#[cfg_attr(feature = "tracing", tracing::instrument(ret, level = "debug"))]
fn dynamic_block_end<'b, 'g, 'r, 's>(
    _context: RefContext<'b, 'g, 'r, 's>,
    input: OrgSource<'s>,
) -> Res<OrgSource<'s>, OrgSource<'s>> {
    start_of_line(input)?;
    let (remaining, source) = recognize(tuple((
        space0,
        tag_no_case("#+end:"),
        alt((eof, line_ending)),
    )))(input)?;
    Ok((remaining, source))
}