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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
//! TeX Lexer/Tokenizer
//!
//! Converts a LaTeX source string into a stream of TeX tokens.
//! This follows standard TeX tokenization rules including:
//! - Control sequence recognition
//! - Comment handling
//! - Space normalization after control sequences
//! - Parameter token parsing
use super::token::{TexToken, TokenList};
/// The TeX Lexer that converts source text to tokens
pub struct Lexer<'a> {
chars: std::iter::Peekable<std::str::CharIndices<'a>>,
/// Track if we just emitted a control sequence (for space swallowing)
after_cs: bool,
/// Phantom data to hold lifetime
_marker: std::marker::PhantomData<&'a str>,
}
impl<'a> Lexer<'a> {
/// Create a new lexer for the given input
pub fn new(input: &'a str) -> Self {
Lexer {
chars: input.char_indices().peekable(),
after_cs: false,
_marker: std::marker::PhantomData,
}
}
/// Peek at the next character without consuming it
fn peek_char(&mut self) -> Option<char> {
self.chars.peek().map(|(_, c)| *c)
}
/// Consume and return the next character
fn next_char(&mut self) -> Option<char> {
self.chars.next().map(|(_, c)| c)
}
/// Skip whitespace, returns true if any was skipped
fn skip_whitespace(&mut self) -> bool {
let mut skipped = false;
while let Some(c) = self.peek_char() {
if c.is_ascii_whitespace() {
self.next_char();
skipped = true;
} else {
break;
}
}
skipped
}
/// Read a control sequence name (letters only, or single non-letter)
fn read_control_seq(&mut self) -> String {
let mut name = String::new();
// Check first character
if let Some(c) = self.peek_char() {
if c.is_ascii_alphabetic() {
// Multi-letter control sequence
while let Some(c) = self.peek_char() {
if c.is_ascii_alphabetic() {
name.push(c);
self.next_char();
} else {
break;
}
}
// TeX swallows spaces after alphabetic control sequences
self.after_cs = true;
} else {
// Single non-letter control sequence like \% \{ \}
name.push(c);
self.next_char();
self.after_cs = false;
}
}
name
}
/// Read a comment (everything until end of line)
fn read_comment(&mut self) -> String {
let mut comment = String::new();
while let Some(c) = self.peek_char() {
if c == '\n' || c == '\r' {
break;
}
comment.push(c);
self.next_char();
}
// Consume the newline
if let Some(c) = self.peek_char() {
if c == '\r' {
self.next_char();
}
}
if let Some(c) = self.peek_char() {
if c == '\n' {
self.next_char();
}
}
comment
}
/// Read the next token
fn next_token(&mut self) -> Option<TexToken> {
// Handle space swallowing after control sequences
if self.after_cs {
self.skip_whitespace();
self.after_cs = false;
}
let c = self.next_char()?;
match c {
// Escape character - start of control sequence
'\\' => {
let name = self.read_control_seq();
if name.is_empty() {
// Lone backslash at end of input
Some(TexToken::Char('\\'))
} else {
Some(TexToken::ControlSeq(name))
}
}
// Begin group
'{' => Some(TexToken::BeginGroup),
// End group
'}' => Some(TexToken::EndGroup),
// Parameter token
'#' => {
if let Some(next) = self.peek_char() {
if next.is_ascii_digit() && next != '0' {
self.next_char();
Some(TexToken::Param(next.to_digit(10).unwrap() as u8))
} else if next == '#' {
// ## - check if followed by digit for DeferredParam
self.next_char();
if let Some(digit) = self.peek_char() {
if digit.is_ascii_digit() && digit != '0' {
self.next_char();
Some(TexToken::DeferredParam(digit.to_digit(10).unwrap() as u8))
} else {
// ## not followed by digit produces a single #
Some(TexToken::Char('#'))
}
} else {
// ## at end of input produces a single #
Some(TexToken::Char('#'))
}
} else {
// Invalid parameter, treat as char
Some(TexToken::Char('#'))
}
} else {
Some(TexToken::Char('#'))
}
}
// Comment
'%' => {
let comment = self.read_comment();
Some(TexToken::Comment(comment))
}
// Math shift
'$' => Some(TexToken::MathShift),
// Alignment tab
'&' => Some(TexToken::AlignTab),
// Superscript
'^' => Some(TexToken::Superscript),
// Subscript
'_' => Some(TexToken::Subscript),
// Active character (tilde for non-breaking space)
'~' => Some(TexToken::ActiveChar('~')),
// Whitespace - normalize to single space
' ' | '\t' => {
// Skip any additional whitespace
while let Some(next) = self.peek_char() {
if next == ' ' || next == '\t' {
self.next_char();
} else {
break;
}
}
Some(TexToken::Space)
}
// Newlines - can be significant in TeX
'\n' | '\r' => {
// Check for paragraph break (blank line)
let mut blank_line = false;
while let Some(next) = self.peek_char() {
if next == ' ' || next == '\t' {
self.next_char();
} else if next == '\n' || next == '\r' {
self.next_char();
blank_line = true;
} else {
break;
}
}
if blank_line {
// Paragraph break becomes \par
Some(TexToken::ControlSeq("par".into()))
} else {
// Single newline becomes space
Some(TexToken::Space)
}
}
// Regular character
_ => Some(TexToken::Char(c)),
}
}
/// Tokenize the entire input
pub fn tokenize(self) -> TokenList {
let tokens: Vec<TexToken> = self.collect();
TokenList::from_vec(tokens)
}
}
impl<'a> Iterator for Lexer<'a> {
type Item = TexToken;
fn next(&mut self) -> Option<Self::Item> {
self.next_token()
}
}
/// Convenience function to tokenize a string
pub fn tokenize(input: &str) -> TokenList {
Lexer::new(input).tokenize()
}
/// Convert a token list back to a string (detokenize)
pub fn detokenize(tokens: &TokenList) -> String {
let mut result = String::new();
let slice = tokens.as_slice();
for (i, token) in slice.iter().enumerate() {
match token {
TexToken::ControlSeq(name) => {
result.push('\\');
result.push_str(name);
// Add space after alphabetic control sequences if next token
// is a letter or another control sequence
if name.chars().all(|c| c.is_ascii_alphabetic()) {
if let Some(next) = slice.get(i + 1) {
match next {
TexToken::Char(c) if c.is_ascii_alphabetic() => {
result.push(' ');
}
TexToken::ControlSeq(_) => {
result.push(' ');
}
_ => {}
}
}
}
}
TexToken::BeginGroup => {
result.push('{');
}
TexToken::EndGroup => {
result.push('}');
}
TexToken::Param(n) => {
result.push('#');
result.push(char::from_digit(*n as u32, 10).unwrap());
}
TexToken::DeferredParam(n) => {
result.push('#');
result.push('#');
result.push(char::from_digit(*n as u32, 10).unwrap());
}
TexToken::Char(c) => {
result.push(*c);
}
TexToken::Space => {
result.push(' ');
}
TexToken::Comment(text) => {
result.push('%');
result.push_str(text);
result.push('\n');
}
TexToken::MathShift => {
result.push('$');
}
TexToken::AlignTab => {
result.push('&');
}
TexToken::Superscript => {
result.push('^');
}
TexToken::Subscript => {
result.push('_');
}
TexToken::ActiveChar(c) => {
result.push(*c);
}
TexToken::EndOfInput => {}
}
}
result
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_simple_tokenize() {
let tokens = tokenize("hello");
assert_eq!(tokens.len(), 5);
assert_eq!(tokens.as_slice()[0], TexToken::Char('h'));
}
#[test]
fn test_control_sequence() {
let tokens = tokenize("\\frac{a}{b}");
assert_eq!(tokens.as_slice()[0], TexToken::ControlSeq("frac".into()));
assert_eq!(tokens.as_slice()[1], TexToken::BeginGroup);
assert_eq!(tokens.as_slice()[2], TexToken::Char('a'));
assert_eq!(tokens.as_slice()[3], TexToken::EndGroup);
}
#[test]
fn test_space_swallowing() {
// Space after \frac should be swallowed
let tokens = tokenize("\\frac {a}");
assert_eq!(tokens.as_slice()[0], TexToken::ControlSeq("frac".into()));
assert_eq!(tokens.as_slice()[1], TexToken::BeginGroup);
}
#[test]
fn test_parameter_tokens() {
let tokens = tokenize("#1 #2");
assert_eq!(tokens.as_slice()[0], TexToken::Param(1));
assert_eq!(tokens.as_slice()[1], TexToken::Space);
assert_eq!(tokens.as_slice()[2], TexToken::Param(2));
}
#[test]
fn test_comment() {
let tokens = tokenize("a%comment\nb");
assert_eq!(tokens.as_slice()[0], TexToken::Char('a'));
assert_eq!(tokens.as_slice()[1], TexToken::Comment("comment".into()));
assert_eq!(tokens.as_slice()[2], TexToken::Char('b'));
}
#[test]
fn test_escaped_chars() {
let tokens = tokenize("\\% \\{");
assert_eq!(tokens.as_slice()[0], TexToken::ControlSeq("%".into()));
assert_eq!(tokens.as_slice()[1], TexToken::Space);
assert_eq!(tokens.as_slice()[2], TexToken::ControlSeq("{".into()));
}
#[test]
fn test_double_hash() {
let tokens = tokenize("##");
assert_eq!(tokens.as_slice()[0], TexToken::Char('#'));
}
#[test]
fn test_deferred_param() {
let tokens = tokenize("##1 ##2");
assert_eq!(tokens.as_slice()[0], TexToken::DeferredParam(1));
assert_eq!(tokens.as_slice()[1], TexToken::Space);
assert_eq!(tokens.as_slice()[2], TexToken::DeferredParam(2));
}
#[test]
fn test_roundtrip() {
let input = "\\frac{a^2}{b_1}";
let tokens = tokenize(input);
let output = detokenize(&tokens);
assert_eq!(output, input);
}
#[test]
fn test_newcommand_body() {
let tokens = tokenize("\\langle #1, #2\\rangle");
assert_eq!(tokens.as_slice()[0], TexToken::ControlSeq("langle".into()));
assert_eq!(tokens.as_slice()[1], TexToken::Param(1));
assert_eq!(tokens.as_slice()[2], TexToken::Char(','));
assert_eq!(tokens.as_slice()[3], TexToken::Space);
assert_eq!(tokens.as_slice()[4], TexToken::Param(2));
assert_eq!(tokens.as_slice()[5], TexToken::ControlSeq("rangle".into()));
}
}