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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
use mathml_renderer::{
arena::StringBuilder,
attribute::{HtmlTextSize, HtmlTextStyle},
length::{Length, LengthUnit},
super_char::SuperChar,
symbol,
};
use crate::{
error::{LatexErrKind, LatexError},
parser::{ParseResult, Parser},
specifications::LatexUnit,
token::{EndToken, Mode, TextToken, Token},
};
/// A run of text with uniform style and size.
pub(super) struct TextSnippet<'arena>(
pub Option<HtmlTextStyle>,
pub Option<HtmlTextSize>,
pub &'arena str,
);
impl<'arena> Parser<'_, '_, 'arena> {
pub(super) fn extract_text(
&mut self,
initial_style: Option<HtmlTextStyle>,
text_mode: bool,
) -> ParseResult<Vec<TextSnippet<'arena>>> {
let mut style_stack = vec![(0usize, initial_style)];
let mut str_builder: Option<StringBuilder> = None;
let mut snippets: Vec<TextSnippet<'arena>> = Vec::new();
let mut accent_to_insert: Option<char> = None;
let mut brace_nesting = 0usize;
// Size declarations like `\large`. Each entry records the `style_stack` depth and the
// brace nesting level at which the size was declared, because the size stays in effect
// until either that style scope or that brace group is closed. (`brace_nesting` is
// reset on every style push, so the nesting level alone would be ambiguous.)
let mut size_stack: Vec<(usize, usize, HtmlTextSize)> = Vec::new();
while let Some((previous_nesting, current_style)) = style_stack.last().copied() {
let current_size = size_stack.last().map(|&(_, _, size)| size);
let tokloc = if text_mode {
self.tokens.next_any_token()
} else {
self.tokens.next()
};
let (token, span) = tokloc?.into_parts();
let c: Result<SuperChar, LatexErrKind> = if let Token::TextMode(text_token) = token {
if text_mode {
match text_token {
TextToken::Accent(accent) => {
if str_builder.is_some() {
accent_to_insert = Some(accent);
continue;
} else {
Err(LatexErrKind::ExpectedArgumentGotEOI)
}
}
TextToken::Letter(ch) => Ok(ch.into()),
TextToken::Style(style) => {
if let Some(builder) = str_builder.take()
&& !builder.is_empty()
{
let text = builder.finish(self.arena);
snippets.push(TextSnippet(current_style, current_size, text));
}
style_stack.push((brace_nesting, Some(style)));
brace_nesting = 0;
continue;
}
TextToken::Size(text_size) => {
if let Some(builder) = str_builder.take() {
if builder.is_empty() {
str_builder = Some(builder);
} else {
let text = builder.finish(self.arena);
snippets.push(TextSnippet(current_style, current_size, text));
str_builder = Some(self.buffer.get_builder());
}
size_stack.push((style_stack.len(), brace_nesting, text_size));
} else {
// The size command itself is the argument of the style command,
// e.g. `\text\large x`, which is equivalent to `\text{}x`:
// the text is empty and the size never takes effect.
style_stack.pop();
brace_nesting = previous_nesting;
discard_dead_sizes(
&mut size_stack,
style_stack.len(),
brace_nesting,
);
if !style_stack.is_empty() {
// If there are still styles to process, we must have been within a group.
str_builder = Some(self.buffer.get_builder());
}
}
continue;
}
}
} else {
Err(LatexErrKind::NotValidInMathMode)
}
} else if matches!(
token,
Token::Letter(_, Mode::MathOrText)
| Token::SquareBracketOpen
| Token::SquareBracketClose
| Token::Digit(_)
| Token::Prime
| Token::Whitespace
| Token::NonBreakingSpace
| Token::InternalStringLiteral(_)
| Token::GroupBegin
| Token::GroupEnd
| Token::MathOrTextMode(_, _)
| Token::Text(_)
| Token::Eoi
| Token::Right
| Token::End(_)
) {
// These tokens are valid in both math and text mode.
match token {
Token::Letter(c, Mode::MathOrText) => Ok(c),
Token::SquareBracketOpen => {
Ok(symbol::LEFT_SQUARE_BRACKET.as_op().as_superchar())
}
Token::SquareBracketClose => {
Ok(symbol::RIGHT_SQUARE_BRACKET.as_op().as_superchar())
}
Token::Digit(digit) => Ok(digit.into()),
Token::Prime => Ok(SuperChar::from_char('’')),
Token::Whitespace | Token::NonBreakingSpace => {
Ok(SuperChar::from_char(symbol::NO_BREAK_SPACE))
}
Token::InternalStringLiteral(output) => {
if let Some(str_builder) = &mut str_builder {
str_builder.push_str(output);
continue;
} else {
snippets.push(TextSnippet(current_style, current_size, output));
style_stack.pop();
brace_nesting = previous_nesting;
discard_dead_sizes(&mut size_stack, style_stack.len(), brace_nesting);
if !style_stack.is_empty() {
// If there are still styles to process, we must have been within a group.
str_builder = Some(self.buffer.get_builder());
}
continue;
}
}
Token::GroupBegin => {
if str_builder.is_none() {
str_builder = Some(self.buffer.get_builder());
} else {
brace_nesting += 1;
}
continue;
}
Token::GroupEnd => {
if let Some(builder) = str_builder.take() {
if let Some(new_nesting) = brace_nesting.checked_sub(1) {
brace_nesting = new_nesting;
let group_had_sizes = matches!(
size_stack.last(),
Some(&(depth, nesting, _))
if depth == style_stack.len() && nesting > brace_nesting
);
if group_had_sizes {
// The group that just closed contained size declarations,
// which now go out of scope.
if !builder.is_empty() {
let text = builder.finish(self.arena);
snippets.push(TextSnippet(
current_style,
current_size,
text,
));
}
discard_dead_sizes(
&mut size_stack,
style_stack.len(),
brace_nesting,
);
str_builder = Some(self.buffer.get_builder());
} else {
// TODO: Avoid this back-and-forth with the `str_builder`.
str_builder = Some(builder);
}
continue;
} else {
if !builder.is_empty() {
let text = builder.finish(self.arena);
snippets.push(TextSnippet(current_style, current_size, text));
}
style_stack.pop();
brace_nesting = previous_nesting;
discard_dead_sizes(
&mut size_stack,
style_stack.len(),
brace_nesting,
);
if !style_stack.is_empty() {
str_builder = Some(self.buffer.get_builder());
}
continue;
}
} else {
Err(LatexErrKind::ExpectedArgumentGotClose)
}
}
Token::MathOrTextMode(_, ch) => Ok(ch.into()),
Token::Text(style) => {
if let Some(builder) = str_builder.take()
&& !builder.is_empty()
{
let text = builder.finish(self.arena);
snippets.push(TextSnippet(current_style, current_size, text));
}
style_stack.push((brace_nesting, style));
brace_nesting = 0;
continue;
}
Token::Eoi => {
if str_builder.is_some() {
Err(LatexErrKind::UnclosedGroup(EndToken::GroupClose))
} else {
Err(LatexErrKind::ExpectedArgumentGotEOI)
}
}
Token::Right | Token::End(_) => Err(LatexErrKind::ExpectedArgumentGotClose),
_ => unreachable!(),
}
} else if !text_mode {
// These tokens are only valid in math mode.
match token {
Token::Letter(c, _) | Token::UprightLetter(c) => Ok(c),
Token::Open(op) | Token::Close(op) | Token::Ord(op) => {
Ok(op.as_op().as_superchar())
}
Token::BinaryOp(op) => Ok(op.as_op().as_superchar()),
Token::Relation(op) => Ok(op.as_op().as_superchar()),
Token::ForceRelation(op) => Ok(op.as_superchar()),
Token::Punctuation(op) => Ok(op.as_op().as_superchar()),
Token::PseudoOperator(output) | Token::PseudoOperatorLimits(output) => {
if let Some(str_builder) = &mut str_builder {
str_builder.push_str(output);
continue;
}
snippets.push(TextSnippet(current_style, current_size, output));
style_stack.pop();
brace_nesting = previous_nesting;
discard_dead_sizes(&mut size_stack, style_stack.len(), brace_nesting);
if !style_stack.is_empty() {
// If there are still styles to process, we must have been within a group.
str_builder = Some(self.buffer.get_builder());
}
continue;
}
Token::Space(length) => {
if length == Length::new(1.0, LengthUnit::Em) {
Ok(SuperChar::from_char('\u{2003}'))
} else if length == LatexUnit::Mu.length_with_unit(5.0) {
Ok(SuperChar::from_char('\u{2004}'))
} else if length == LatexUnit::Mu.length_with_unit(4.0) {
Ok(SuperChar::from_char('\u{205F}'))
} else if length == LatexUnit::Mu.length_with_unit(3.0) {
Ok(SuperChar::from_char('\u{2009}'))
} else {
// Ignore other spaces in text mode.
if str_builder.is_none() {
// This space was the only thing after the style change.
// So we need to pop the style stack and restore the previous nesting.
style_stack.pop();
brace_nesting = previous_nesting;
discard_dead_sizes(
&mut size_stack,
style_stack.len(),
brace_nesting,
);
if !style_stack.is_empty() {
// If there are still styles to process, we must have been within a group.
str_builder = Some(self.buffer.get_builder());
}
}
continue;
}
}
_ => Err(LatexErrKind::CouldNotExtractText),
}
} else {
Err(LatexErrKind::NotValidInTextMode)
};
let c = c.map_err(|err| Box::new(LatexError(span.into(), err)))?;
if let Some(builder) = &mut str_builder {
builder.push_superchar(c);
if let Some(accent) = accent_to_insert.take() {
builder.push_char(accent);
}
} else {
let mut b = [0u8; SuperChar::MAX_LEN_UTF8];
let text = self.arena.alloc_str(c.encode_utf8(&mut b));
snippets.push(TextSnippet(current_style, current_size, text));
style_stack.pop();
brace_nesting = previous_nesting;
discard_dead_sizes(&mut size_stack, style_stack.len(), brace_nesting);
if !style_stack.is_empty() {
// If there are still styles to process, we must have been within a group.
str_builder = Some(self.buffer.get_builder());
}
}
}
Ok(snippets)
}
}
/// Remove all size declarations that have gone out of scope, i.e. those declared in a style
/// scope or brace group that has been closed.
fn discard_dead_sizes(
size_stack: &mut Vec<(usize, usize, HtmlTextSize)>,
style_depth: usize,
brace_nesting: usize,
) {
while let Some(&(depth, nesting, _)) = size_stack.last() {
if depth > style_depth || (depth == style_depth && nesting > brace_nesting) {
size_stack.pop();
} else {
break;
}
}
}