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
use lazy_static::lazy_static;
use std::iter::FromIterator;
use std::collections::HashSet;
use std::rc::Rc;
use std::borrow::Cow;
use crate::backend::data::{
Atom,
Text,
Enclosure,
EnclosureKind,
INLINE_MATH_TAG,
};
use crate::backend::{Ast, Tag};
pub static LATEX_ENVIRONMENT_NAME_LIST: &'static [&'static str] = &[
"equation",
"split",
];
lazy_static! {
pub static ref LATEX_ENV_NAMES: HashSet<&'static str> = {
HashSet::from_iter(
LATEX_ENVIRONMENT_NAME_LIST.to_vec()
)
};
}
fn to_valid_latex_math<'a>(node: Ast<'a>) -> Ast<'a> {
fn init_env<'a>(env_name: &'a str, tag_name: Cow<'a, str>, children: Vec<Ast<'a>>) -> Ast<'a> {
Ast::new_fragment(vec![
Ast::Tag(Tag::new("begin", vec![
Ast::Enclosure(Enclosure::new_curly_brace(vec![
Ast::Content(Cow::Borrowed(env_name))
]))
])),
Ast::new_fragment(children),
Ast::Tag(Tag::new("end", vec![
Ast::Enclosure(Enclosure::new_curly_brace(vec![
Ast::Content(Cow::Borrowed(env_name))
]))
])),
])
}
fn f<'a>(x: Ast<'a>) -> Ast<'a> {
match x {
Ast::Tag(tag) if LATEX_ENV_NAMES.contains(tag.name()) => {
let env_name = *LATEX_ENV_NAMES.get(tag.name()).unwrap();
init_env(
env_name,
tag.name.clone(),
tag.children
)
}
Ast::Tag(mut tag) => {
tag.children = tag.children
.into_iter()
.collect();
Ast::Tag(tag)
}
x => x,
}
}
node.transform(Rc::new(f))
}
pub fn latex_pass<'a>(node: Ast<'a>) -> Ast<'a> {
match node {
Ast::Tag(tag) if tag.has_name("equation") => {
let node = tag.children
.into_iter()
.flat_map(Ast::unblock)
.map(to_valid_latex_math)
.map(Ast::to_string)
.collect::<Vec<_>>()
.join("");
let start = "\\begin{equation}\\begin{split}";
let end = "\\end{split}\\end{equation}";
Ast::Content(Cow::Owned(format!(
"\\[{}{}{}\\]",
start,
node,
end,
)))
}
Ast::Tag(tag) if tag.has_name(INLINE_MATH_TAG) => {
let node = tag.children
.into_iter()
.map(to_valid_latex_math)
.map(Ast::to_string)
.collect::<Vec<_>>()
.join("");
Ast::Content(Cow::Owned(format!(
"\\({}\\)",
node,
)))
}
Ast::Tag(mut tag) => {
tag.children = tag.children
.into_iter()
.map(latex_pass)
.collect();
Ast::Tag(tag)
}
Ast::Enclosure(mut block) => {
block.children = block.children
.into_iter()
.map(latex_pass)
.collect();
Ast::Enclosure(block)
}
node @ Ast::Ident(_) => node,
node @ Ast::Content(_) => node,
node @ Ast::Token(_) => node,
}
}