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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
use crate::constants::{NEWLINE, RBRACE, STAR};
use crate::node_pool::NodeID;
use crate::types::{Cursor, MatchError, ParseOpts, Parseable, Parser, Result};
use regex::bytes::Regex;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LatexEnv<'a> {
    pub name: &'a str,
    pub contents: &'a str,
}

impl<'a> Parseable<'a> for LatexEnv<'a> {
    fn parse(
        parser: &mut Parser<'a>,
        mut cursor: Cursor<'a>,
        parent: Option<NodeID>,
        parse_opts: ParseOpts,
    ) -> Result<NodeID> {
        let start = cursor.index;
        cursor.word(r"\begin{")?;
        let name_match = cursor.fn_until(|chr| {
            !chr.is_ascii_alphanumeric() && chr != STAR || (chr == NEWLINE || chr == RBRACE)
        })?;

        cursor.index = name_match.end;
        cursor.word("}\n")?;
        let name = name_match.obj;

        let a = format!(r"(?m)^[ \t]*\\end{{{name}}}[\t ]*$");
        // HACK: i simplt cannot figure out how to properly escape the curls in the regex.
        // always getting hit with:
        // error: repetition quantifier expects a valid decimal
        let a = a.replace("{", r"\{");
        let a = a.replace("}", r"\}");

        let ending_re: Regex = Regex::new(&a).unwrap();
        let matched_reg = ending_re
            .find_at(cursor.byte_arr, cursor.index)
            .ok_or(MatchError::InvalidLogic)?;

        Ok(parser.alloc(
            Self {
                name,
                contents: cursor.clamp_forwards(matched_reg.start()),
            },
            start,
            matched_reg.end(),
            parent,
        ))
    }
}

#[cfg(test)]
mod tests {
    use crate::{element::LatexEnv, expr_in_pool, parse_org, types::Expr};

    #[test]
    fn basic_latex_env() {
        let inp = r"
\begin{align*}
\end{align*}
";

        dbg!(parse_org(inp));
    }

    #[test]
    fn latex_env_with_content() {
        let inp = r"
\begin{align*}

\text{latex constructs}\\
\alpha\\
\beta\\

10x + 4 &= 3\\

\end{align*}
";

        dbg!(parse_org(inp));
    }

    #[test]
    fn latex_env_failed_header() {
        // not alpha numeric
        let inp = r"
\begin{star!}
\end{star!}
";

        dbg!(parse_org(inp));

        let inp = r"
\begin{a13214-}
\end{a13214-}
";
        dbg!(parse_org(inp));
        // failed construction
        let inp = r"
\begin{one}more stuff
\end{one}
";
        dbg!(parse_org(inp));
    }

    #[test]
    fn latex_empty_start() {
        let inp = r"
\begin{}
\end{}
";
        dbg!(parse_org(inp));
    }

    #[test]
    fn latex_failed_end() {
        let inp = r"
\begin{start}
\end{notstart}
";
        dbg!(parse_org(inp));
    }

    #[test]
    fn latex_env_indented() {
        let input = r"
             \begin{align}
             we are eating so good?
             \end{align}
";

        let parsed = parse_org(input);

        let l = expr_in_pool!(parsed, LatexEnv).unwrap();

        assert_eq!(
            l,
            &LatexEnv {
                name: "align",
                contents: "             we are eating so good?\n"
            }
        )
    }
}